1//===- ASTReaderDecl.cpp - Decl Deserialization ---------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the ASTReader::readDeclRecord method, which is the
10// entrypoint for loading a decl.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTCommon.h"
15#include "ASTReaderInternals.h"
16#include "clang/AST/ASTConcept.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/ASTStructuralEquivalence.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/AttrIterator.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclFriend.h"
25#include "clang/AST/DeclObjC.h"
26#include "clang/AST/DeclOpenMP.h"
27#include "clang/AST/DeclTemplate.h"
28#include "clang/AST/DeclVisitor.h"
29#include "clang/AST/DeclarationName.h"
30#include "clang/AST/Expr.h"
31#include "clang/AST/ExternalASTSource.h"
32#include "clang/AST/LambdaCapture.h"
33#include "clang/AST/NestedNameSpecifier.h"
34#include "clang/AST/OpenMPClause.h"
35#include "clang/AST/Redeclarable.h"
36#include "clang/AST/Stmt.h"
37#include "clang/AST/TemplateBase.h"
38#include "clang/AST/Type.h"
39#include "clang/AST/UnresolvedSet.h"
40#include "clang/Basic/AttrKinds.h"
41#include "clang/Basic/DiagnosticSema.h"
42#include "clang/Basic/ExceptionSpecificationType.h"
43#include "clang/Basic/IdentifierTable.h"
44#include "clang/Basic/LLVM.h"
45#include "clang/Basic/Lambda.h"
46#include "clang/Basic/LangOptions.h"
47#include "clang/Basic/Linkage.h"
48#include "clang/Basic/Module.h"
49#include "clang/Basic/PragmaKinds.h"
50#include "clang/Basic/SourceLocation.h"
51#include "clang/Basic/Specifiers.h"
52#include "clang/Sema/IdentifierResolver.h"
53#include "clang/Serialization/ASTBitCodes.h"
54#include "clang/Serialization/ASTRecordReader.h"
55#include "clang/Serialization/ContinuousRangeMap.h"
56#include "clang/Serialization/ModuleFile.h"
57#include "llvm/ADT/DenseMap.h"
58#include "llvm/ADT/FoldingSet.h"
59#include "llvm/ADT/SmallPtrSet.h"
60#include "llvm/ADT/SmallVector.h"
61#include "llvm/ADT/iterator_range.h"
62#include "llvm/Bitstream/BitstreamReader.h"
63#include "llvm/Support/ErrorHandling.h"
64#include "llvm/Support/SaveAndRestore.h"
65#include <algorithm>
66#include <cassert>
67#include <cstdint>
68#include <cstring>
69#include <string>
70#include <utility>
71
72using namespace clang;
73using namespace serialization;
74
75//===----------------------------------------------------------------------===//
76// Declaration Merging
77//===----------------------------------------------------------------------===//
78
79namespace {
80/// Results from loading a RedeclarableDecl.
81class RedeclarableResult {
82 Decl *MergeWith;
83 GlobalDeclID FirstID;
84 bool IsKeyDecl;
85
86public:
87 RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
88 : MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}
89
90 /// Retrieve the first ID.
91 GlobalDeclID getFirstID() const { return FirstID; }
92
93 /// Is this declaration a key declaration?
94 bool isKeyDecl() const { return IsKeyDecl; }
95
96 /// Get a known declaration that this should be merged with, if
97 /// any.
98 Decl *getKnownMergeTarget() const { return MergeWith; }
99};
100} // namespace
101
102namespace clang {
103class ASTDeclMerger {
104 ASTReader &Reader;
105
106public:
107 ASTDeclMerger(ASTReader &Reader) : Reader(Reader) {}
108
109 void mergeLambda(CXXRecordDecl *D, RedeclarableResult &Redecl, Decl &Context,
110 unsigned Number);
111
112 /// \param KeyDeclID the decl ID of the key declaration \param D.
113 /// GlobalDeclID() if \param is not a key declaration.
114 /// See the comments of ASTReader::KeyDecls for the explanation
115 /// of key declaration.
116 template <typename T>
117 void mergeRedeclarableImpl(Redeclarable<T> *D, T *Existing,
118 GlobalDeclID KeyDeclID);
119
120 template <typename T>
121 void mergeRedeclarable(Redeclarable<T> *D, T *Existing,
122 RedeclarableResult &Redecl) {
123 mergeRedeclarableImpl(
124 D, Existing, Redecl.isKeyDecl() ? Redecl.getFirstID() : GlobalDeclID());
125 }
126
127 void mergeTemplatePattern(RedeclarableTemplateDecl *D,
128 RedeclarableTemplateDecl *Existing, bool IsKeyDecl);
129
130 void MergeDefinitionData(CXXRecordDecl *D,
131 struct CXXRecordDecl::DefinitionData &&NewDD);
132 void MergeDefinitionData(ObjCInterfaceDecl *D,
133 struct ObjCInterfaceDecl::DefinitionData &&NewDD);
134 void MergeDefinitionData(ObjCProtocolDecl *D,
135 struct ObjCProtocolDecl::DefinitionData &&NewDD);
136};
137} // namespace clang
138
139//===----------------------------------------------------------------------===//
140// Declaration deserialization
141//===----------------------------------------------------------------------===//
142
143namespace clang {
144class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
145 ASTReader &Reader;
146 ASTDeclMerger MergeImpl;
147 ASTRecordReader &Record;
148 ASTReader::RecordLocation Loc;
149 const GlobalDeclID ThisDeclID;
150 const SourceLocation ThisDeclLoc;
151
152 using RecordData = ASTReader::RecordData;
153
154 TypeID DeferredTypeID = 0;
155 unsigned AnonymousDeclNumber = 0;
156 GlobalDeclID NamedDeclForTagDecl = GlobalDeclID();
157 IdentifierInfo *TypedefNameForLinkage = nullptr;
158
159 /// A flag to carry the information for a decl from the entity is
160 /// used. We use it to delay the marking of the canonical decl as used until
161 /// the entire declaration is deserialized and merged.
162 bool IsDeclMarkedUsed = false;
163
164 uint64_t GetCurrentCursorOffset();
165
166 uint64_t ReadLocalOffset() {
167 uint64_t LocalOffset = Record.readInt();
168 assert(LocalOffset < Loc.Offset && "offset point after current record");
169 return LocalOffset ? Loc.Offset - LocalOffset : 0;
170 }
171
172 uint64_t ReadGlobalOffset() {
173 uint64_t Local = ReadLocalOffset();
174 return Local ? Record.getGlobalBitOffset(LocalOffset: Local) : 0;
175 }
176
177 SourceLocation readSourceLocation() { return Record.readSourceLocation(); }
178
179 SourceRange readSourceRange() { return Record.readSourceRange(); }
180
181 TypeSourceInfo *readTypeSourceInfo() { return Record.readTypeSourceInfo(); }
182
183 GlobalDeclID readDeclID() { return Record.readDeclID(); }
184
185 std::string readString() { return Record.readString(); }
186
187 Decl *readDecl() { return Record.readDecl(); }
188
189 template <typename T> T *readDeclAs() { return Record.readDeclAs<T>(); }
190
191 serialization::SubmoduleID readSubmoduleID() {
192 if (Record.getIdx() == Record.size())
193 return 0;
194
195 return Record.getGlobalSubmoduleID(LocalID: Record.readInt());
196 }
197
198 Module *readModule() { return Record.getSubmodule(GlobalID: readSubmoduleID()); }
199
200 void ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update,
201 Decl *LambdaContext = nullptr,
202 unsigned IndexInLambdaContext = 0);
203 void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
204 const CXXRecordDecl *D, Decl *LambdaContext,
205 unsigned IndexInLambdaContext);
206 void ReadObjCDefinitionData(struct ObjCInterfaceDecl::DefinitionData &Data);
207 void ReadObjCDefinitionData(struct ObjCProtocolDecl::DefinitionData &Data);
208
209 static DeclContext *getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC);
210
211 static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader,
212 DeclContext *DC, unsigned Index);
213 static void setAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC,
214 unsigned Index, NamedDecl *D);
215
216 /// Commit to a primary definition of the class RD, which is known to be
217 /// a definition of the class. We might not have read the definition data
218 /// for it yet. If we haven't then allocate placeholder definition data
219 /// now too.
220 static CXXRecordDecl *getOrFakePrimaryClassDefinition(ASTReader &Reader,
221 CXXRecordDecl *RD);
222
223 /// Class used to capture the result of searching for an existing
224 /// declaration of a specific kind and name, along with the ability
225 /// to update the place where this result was found (the declaration
226 /// chain hanging off an identifier or the DeclContext we searched in)
227 /// if requested.
228 class FindExistingResult {
229 ASTReader &Reader;
230 NamedDecl *New = nullptr;
231 NamedDecl *Existing = nullptr;
232 bool AddResult = false;
233 unsigned AnonymousDeclNumber = 0;
234 IdentifierInfo *TypedefNameForLinkage = nullptr;
235
236 public:
237 FindExistingResult(ASTReader &Reader) : Reader(Reader) {}
238
239 FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing,
240 unsigned AnonymousDeclNumber,
241 IdentifierInfo *TypedefNameForLinkage)
242 : Reader(Reader), New(New), Existing(Existing), AddResult(true),
243 AnonymousDeclNumber(AnonymousDeclNumber),
244 TypedefNameForLinkage(TypedefNameForLinkage) {}
245
246 FindExistingResult(FindExistingResult &&Other)
247 : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
248 AddResult(Other.AddResult),
249 AnonymousDeclNumber(Other.AnonymousDeclNumber),
250 TypedefNameForLinkage(Other.TypedefNameForLinkage) {
251 Other.AddResult = false;
252 }
253
254 FindExistingResult &operator=(FindExistingResult &&) = delete;
255 ~FindExistingResult();
256
257 /// Suppress the addition of this result into the known set of
258 /// names.
259 void suppress() { AddResult = false; }
260
261 operator NamedDecl *() const { return Existing; }
262
263 template <typename T> operator T *() const {
264 return dyn_cast_or_null<T>(Existing);
265 }
266 };
267
268 static DeclContext *getPrimaryContextForMerging(ASTReader &Reader,
269 DeclContext *DC);
270 FindExistingResult findExisting(NamedDecl *D);
271
272public:
273 ASTDeclReader(ASTReader &Reader, ASTRecordReader &Record,
274 ASTReader::RecordLocation Loc, GlobalDeclID thisDeclID,
275 SourceLocation ThisDeclLoc)
276 : Reader(Reader), MergeImpl(Reader), Record(Record), Loc(Loc),
277 ThisDeclID(thisDeclID), ThisDeclLoc(ThisDeclLoc) {}
278
279 template <typename DeclT>
280 static Decl *getMostRecentDeclImpl(Redeclarable<DeclT> *D);
281 static Decl *getMostRecentDeclImpl(...);
282 static Decl *getMostRecentDecl(Decl *D);
283
284 template <typename DeclT>
285 static void attachPreviousDeclImpl(ASTReader &Reader, Redeclarable<DeclT> *D,
286 Decl *Previous, Decl *Canon);
287 static void attachPreviousDeclImpl(ASTReader &Reader, ...);
288 static void attachPreviousDecl(ASTReader &Reader, Decl *D, Decl *Previous,
289 Decl *Canon);
290
291 static void checkMultipleDefinitionInNamedModules(ASTReader &Reader, Decl *D,
292 Decl *Previous);
293
294 template <typename DeclT>
295 static void attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest);
296 static void attachLatestDeclImpl(...);
297 static void attachLatestDecl(Decl *D, Decl *latest);
298
299 template <typename DeclT>
300 static void markIncompleteDeclChainImpl(Redeclarable<DeclT> *D);
301 static void markIncompleteDeclChainImpl(...);
302
303 void ReadSpecializations(ModuleFile &M, Decl *D,
304 llvm::BitstreamCursor &DeclsCursor, bool IsPartial);
305
306 void ReadFunctionDefinition(FunctionDecl *FD);
307 void Visit(Decl *D);
308
309 void UpdateDecl(Decl *D);
310
311 static void setNextObjCCategory(ObjCCategoryDecl *Cat,
312 ObjCCategoryDecl *Next) {
313 Cat->NextClassCategory = Next;
314 }
315
316 void VisitDecl(Decl *D);
317 void VisitPragmaCommentDecl(PragmaCommentDecl *D);
318 void VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D);
319 void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
320 void VisitNamedDecl(NamedDecl *ND);
321 void VisitLabelDecl(LabelDecl *LD);
322 void VisitNamespaceDecl(NamespaceDecl *D);
323 void VisitHLSLBufferDecl(HLSLBufferDecl *D);
324 void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
325 void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
326 void VisitTypeDecl(TypeDecl *TD);
327 RedeclarableResult VisitTypedefNameDecl(TypedefNameDecl *TD);
328 void VisitTypedefDecl(TypedefDecl *TD);
329 void VisitTypeAliasDecl(TypeAliasDecl *TD);
330 void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
331 void VisitUnresolvedUsingIfExistsDecl(UnresolvedUsingIfExistsDecl *D);
332 RedeclarableResult VisitTagDecl(TagDecl *TD);
333 void VisitEnumDecl(EnumDecl *ED);
334 RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD);
335 void VisitRecordDecl(RecordDecl *RD);
336 RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D);
337 void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); }
338 RedeclarableResult
339 VisitClassTemplateSpecializationDeclImpl(ClassTemplateSpecializationDecl *D);
340
341 void
342 VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D) {
343 VisitClassTemplateSpecializationDeclImpl(D);
344 }
345
346 void VisitClassTemplatePartialSpecializationDecl(
347 ClassTemplatePartialSpecializationDecl *D);
348 RedeclarableResult
349 VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D);
350
351 void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
352 VisitVarTemplateSpecializationDeclImpl(D);
353 }
354
355 void VisitVarTemplatePartialSpecializationDecl(
356 VarTemplatePartialSpecializationDecl *D);
357 void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
358 void VisitValueDecl(ValueDecl *VD);
359 void VisitEnumConstantDecl(EnumConstantDecl *ECD);
360 void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
361 void VisitDeclaratorDecl(DeclaratorDecl *DD);
362 void VisitFunctionDecl(FunctionDecl *FD);
363 void VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *GD);
364 void VisitCXXMethodDecl(CXXMethodDecl *D);
365 void VisitCXXConstructorDecl(CXXConstructorDecl *D);
366 void VisitCXXDestructorDecl(CXXDestructorDecl *D);
367 void VisitCXXConversionDecl(CXXConversionDecl *D);
368 void VisitFieldDecl(FieldDecl *FD);
369 void VisitMSPropertyDecl(MSPropertyDecl *FD);
370 void VisitMSGuidDecl(MSGuidDecl *D);
371 void VisitUnnamedGlobalConstantDecl(UnnamedGlobalConstantDecl *D);
372 void VisitTemplateParamObjectDecl(TemplateParamObjectDecl *D);
373 void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
374 RedeclarableResult VisitVarDeclImpl(VarDecl *D);
375 void ReadVarDeclInit(VarDecl *VD);
376 void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(D: VD); }
377 void VisitImplicitParamDecl(ImplicitParamDecl *PD);
378 void VisitParmVarDecl(ParmVarDecl *PD);
379 void VisitDecompositionDecl(DecompositionDecl *DD);
380 void VisitBindingDecl(BindingDecl *BD);
381 void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
382 void VisitTemplateDecl(TemplateDecl *D);
383 void VisitConceptDecl(ConceptDecl *D);
384 void
385 VisitImplicitConceptSpecializationDecl(ImplicitConceptSpecializationDecl *D);
386 void VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D);
387 RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
388 void VisitClassTemplateDecl(ClassTemplateDecl *D);
389 void VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
390 void VisitVarTemplateDecl(VarTemplateDecl *D);
391 void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
392 void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
393 void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
394 void VisitUsingDecl(UsingDecl *D);
395 void VisitUsingEnumDecl(UsingEnumDecl *D);
396 void VisitUsingPackDecl(UsingPackDecl *D);
397 void VisitUsingShadowDecl(UsingShadowDecl *D);
398 void VisitConstructorUsingShadowDecl(ConstructorUsingShadowDecl *D);
399 void VisitLinkageSpecDecl(LinkageSpecDecl *D);
400 void VisitExportDecl(ExportDecl *D);
401 void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
402 void VisitTopLevelStmtDecl(TopLevelStmtDecl *D);
403 void VisitImportDecl(ImportDecl *D);
404 void VisitAccessSpecDecl(AccessSpecDecl *D);
405 void VisitFriendDecl(FriendDecl *D);
406 void VisitFriendTemplateDecl(FriendTemplateDecl *D);
407 void VisitStaticAssertDecl(StaticAssertDecl *D);
408 void VisitBlockDecl(BlockDecl *BD);
409 void VisitOutlinedFunctionDecl(OutlinedFunctionDecl *D);
410 void VisitCapturedDecl(CapturedDecl *CD);
411 void VisitEmptyDecl(EmptyDecl *D);
412 void VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D);
413
414 void VisitOpenACCDeclareDecl(OpenACCDeclareDecl *D);
415 void VisitOpenACCRoutineDecl(OpenACCRoutineDecl *D);
416
417 void VisitDeclContext(DeclContext *DC, LookupBlockOffsets &Offsets);
418
419 template <typename T>
420 RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
421
422 template <typename T>
423 void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl);
424
425 void mergeRedeclarableTemplate(RedeclarableTemplateDecl *D,
426 RedeclarableResult &Redecl);
427
428 template <typename T> void mergeMergeable(Mergeable<T> *D);
429
430 void mergeMergeable(LifetimeExtendedTemporaryDecl *D);
431
432 ObjCTypeParamList *ReadObjCTypeParamList();
433
434 // FIXME: Reorder according to DeclNodes.td?
435 void VisitObjCMethodDecl(ObjCMethodDecl *D);
436 void VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
437 void VisitObjCContainerDecl(ObjCContainerDecl *D);
438 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
439 void VisitObjCIvarDecl(ObjCIvarDecl *D);
440 void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
441 void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
442 void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
443 void VisitObjCImplDecl(ObjCImplDecl *D);
444 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
445 void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
446 void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
447 void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
448 void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
449 void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
450 void VisitOMPAllocateDecl(OMPAllocateDecl *D);
451 void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
452 void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D);
453 void VisitOMPRequiresDecl(OMPRequiresDecl *D);
454 void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
455};
456} // namespace clang
457
458namespace {
459
460/// Iterator over the redeclarations of a declaration that have already
461/// been merged into the same redeclaration chain.
462template <typename DeclT> class MergedRedeclIterator {
463 DeclT *Start = nullptr;
464 DeclT *Canonical = nullptr;
465 DeclT *Current = nullptr;
466
467public:
468 MergedRedeclIterator() = default;
469 MergedRedeclIterator(DeclT *Start) : Start(Start), Current(Start) {}
470
471 DeclT *operator*() { return Current; }
472
473 MergedRedeclIterator &operator++() {
474 if (Current->isFirstDecl()) {
475 Canonical = Current;
476 Current = Current->getMostRecentDecl();
477 } else
478 Current = Current->getPreviousDecl();
479
480 // If we started in the merged portion, we'll reach our start position
481 // eventually. Otherwise, we'll never reach it, but the second declaration
482 // we reached was the canonical declaration, so stop when we see that one
483 // again.
484 if (Current == Start || Current == Canonical)
485 Current = nullptr;
486 return *this;
487 }
488
489 friend bool operator!=(const MergedRedeclIterator &A,
490 const MergedRedeclIterator &B) {
491 return A.Current != B.Current;
492 }
493};
494
495} // namespace
496
497template <typename DeclT>
498static llvm::iterator_range<MergedRedeclIterator<DeclT>>
499merged_redecls(DeclT *D) {
500 return llvm::make_range(MergedRedeclIterator<DeclT>(D),
501 MergedRedeclIterator<DeclT>());
502}
503
504uint64_t ASTDeclReader::GetCurrentCursorOffset() {
505 return Loc.F->DeclsCursor.GetCurrentBitNo() + Loc.F->GlobalBitOffset;
506}
507
508void ASTDeclReader::ReadFunctionDefinition(FunctionDecl *FD) {
509 if (Record.readInt()) {
510 Reader.DefinitionSource[FD] =
511 Loc.F->Kind == ModuleKind::MK_MainFile ||
512 Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;
513 }
514 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: FD)) {
515 CD->setNumCtorInitializers(Record.readInt());
516 if (CD->getNumCtorInitializers())
517 CD->CtorInitializers = ReadGlobalOffset();
518 }
519 // Store the offset of the body so we can lazily load it later.
520 Reader.PendingBodies[FD] = GetCurrentCursorOffset();
521 // For now remember ThisDeclarationWasADefinition only for friend functions.
522 if (FD->getFriendObjectKind())
523 Reader.ThisDeclarationWasADefinitionSet.insert(V: FD);
524}
525
526void ASTDeclReader::Visit(Decl *D) {
527 DeclVisitor<ASTDeclReader, void>::Visit(D);
528
529 // At this point we have deserialized and merged the decl and it is safe to
530 // update its canonical decl to signal that the entire entity is used.
531 D->getCanonicalDecl()->Used |= IsDeclMarkedUsed;
532 IsDeclMarkedUsed = false;
533
534 if (auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
535 if (auto *TInfo = DD->getTypeSourceInfo())
536 Record.readTypeLoc(TL: TInfo->getTypeLoc());
537 }
538
539 if (auto *TD = dyn_cast<TypeDecl>(Val: D)) {
540 // We have a fully initialized TypeDecl. Read its type now.
541 TD->setTypeForDecl(Reader.GetType(ID: DeferredTypeID).getTypePtrOrNull());
542
543 // If this is a tag declaration with a typedef name for linkage, it's safe
544 // to load that typedef now.
545 if (NamedDeclForTagDecl.isValid())
546 cast<TagDecl>(Val: D)->TypedefNameDeclOrQualifier =
547 cast<TypedefNameDecl>(Val: Reader.GetDecl(ID: NamedDeclForTagDecl));
548 } else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(Val: D)) {
549 // if we have a fully initialized TypeDecl, we can safely read its type now.
550 ID->TypeForDecl = Reader.GetType(ID: DeferredTypeID).getTypePtrOrNull();
551 } else if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
552 // FunctionDecl's body was written last after all other Stmts/Exprs.
553 if (Record.readInt())
554 ReadFunctionDefinition(FD);
555 } else if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
556 ReadVarDeclInit(VD);
557 } else if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
558 if (FD->hasInClassInitializer() && Record.readInt()) {
559 FD->setLazyInClassInitializer(LazyDeclStmtPtr(GetCurrentCursorOffset()));
560 }
561 }
562}
563
564void ASTDeclReader::VisitDecl(Decl *D) {
565 BitsUnpacker DeclBits(Record.readInt());
566 auto ModuleOwnership =
567 (Decl::ModuleOwnershipKind)DeclBits.getNextBits(/*Width=*/3);
568 D->setReferenced(DeclBits.getNextBit());
569 D->Used = DeclBits.getNextBit();
570 IsDeclMarkedUsed |= D->Used;
571 D->setAccess((AccessSpecifier)DeclBits.getNextBits(/*Width=*/2));
572 D->setImplicit(DeclBits.getNextBit());
573 bool HasStandaloneLexicalDC = DeclBits.getNextBit();
574 bool HasAttrs = DeclBits.getNextBit();
575 D->setTopLevelDeclInObjCContainer(DeclBits.getNextBit());
576 D->InvalidDecl = DeclBits.getNextBit();
577 D->FromASTFile = true;
578
579 if (D->isTemplateParameter() || D->isTemplateParameterPack() ||
580 isa<ParmVarDecl, ObjCTypeParamDecl>(Val: D)) {
581 // We don't want to deserialize the DeclContext of a template
582 // parameter or of a parameter of a function template immediately. These
583 // entities might be used in the formulation of its DeclContext (for
584 // example, a function parameter can be used in decltype() in trailing
585 // return type of the function). Use the translation unit DeclContext as a
586 // placeholder.
587 GlobalDeclID SemaDCIDForTemplateParmDecl = readDeclID();
588 GlobalDeclID LexicalDCIDForTemplateParmDecl =
589 HasStandaloneLexicalDC ? readDeclID() : GlobalDeclID();
590 if (LexicalDCIDForTemplateParmDecl.isInvalid())
591 LexicalDCIDForTemplateParmDecl = SemaDCIDForTemplateParmDecl;
592 Reader.addPendingDeclContextInfo(D,
593 SemaDC: SemaDCIDForTemplateParmDecl,
594 LexicalDC: LexicalDCIDForTemplateParmDecl);
595 D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
596 } else {
597 auto *SemaDC = readDeclAs<DeclContext>();
598 auto *LexicalDC =
599 HasStandaloneLexicalDC ? readDeclAs<DeclContext>() : nullptr;
600 if (!LexicalDC)
601 LexicalDC = SemaDC;
602 // If the context is a class, we might not have actually merged it yet, in
603 // the case where the definition comes from an update record.
604 DeclContext *MergedSemaDC;
605 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: SemaDC))
606 MergedSemaDC = getOrFakePrimaryClassDefinition(Reader, RD);
607 else
608 MergedSemaDC = Reader.MergedDeclContexts.lookup(Val: SemaDC);
609 // Avoid calling setLexicalDeclContext() directly because it uses
610 // Decl::getASTContext() internally which is unsafe during derialization.
611 D->setDeclContextsImpl(SemaDC: MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
612 Ctx&: Reader.getContext());
613 }
614 D->setLocation(ThisDeclLoc);
615
616 if (HasAttrs) {
617 AttrVec Attrs;
618 Record.readAttributes(Attrs);
619 // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
620 // internally which is unsafe during derialization.
621 D->setAttrsImpl(Attrs, Ctx&: Reader.getContext());
622 }
623
624 // Determine whether this declaration is part of a (sub)module. If so, it
625 // may not yet be visible.
626 bool ModulePrivate =
627 (ModuleOwnership == Decl::ModuleOwnershipKind::ModulePrivate);
628 if (unsigned SubmoduleID = readSubmoduleID()) {
629 switch (ModuleOwnership) {
630 case Decl::ModuleOwnershipKind::Visible:
631 ModuleOwnership = Decl::ModuleOwnershipKind::VisibleWhenImported;
632 break;
633 case Decl::ModuleOwnershipKind::Unowned:
634 case Decl::ModuleOwnershipKind::VisibleWhenImported:
635 case Decl::ModuleOwnershipKind::ReachableWhenImported:
636 case Decl::ModuleOwnershipKind::ModulePrivate:
637 break;
638 }
639
640 D->setModuleOwnershipKind(ModuleOwnership);
641 // Store the owning submodule ID in the declaration.
642 D->setOwningModuleID(SubmoduleID);
643
644 if (ModulePrivate) {
645 // Module-private declarations are never visible, so there is no work to
646 // do.
647 } else if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
648 // If local visibility is being tracked, this declaration will become
649 // hidden and visible as the owning module does.
650 } else if (Module *Owner = Reader.getSubmodule(GlobalID: SubmoduleID)) {
651 // Mark the declaration as visible when its owning module becomes visible.
652 if (Owner->NameVisibility == Module::AllVisible)
653 D->setVisibleDespiteOwningModule();
654 else
655 Reader.HiddenNamesMap[Owner].push_back(Elt: D);
656 }
657 } else if (ModulePrivate) {
658 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
659 }
660}
661
662void ASTDeclReader::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
663 VisitDecl(D);
664 D->setLocation(readSourceLocation());
665 D->CommentKind = (PragmaMSCommentKind)Record.readInt();
666 std::string Arg = readString();
667 memcpy(dest: D->getTrailingObjects(), src: Arg.data(), n: Arg.size());
668 D->getTrailingObjects()[Arg.size()] = '\0';
669}
670
671void ASTDeclReader::VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D) {
672 VisitDecl(D);
673 D->setLocation(readSourceLocation());
674 std::string Name = readString();
675 memcpy(dest: D->getTrailingObjects(), src: Name.data(), n: Name.size());
676 D->getTrailingObjects()[Name.size()] = '\0';
677
678 D->ValueStart = Name.size() + 1;
679 std::string Value = readString();
680 memcpy(dest: D->getTrailingObjects() + D->ValueStart, src: Value.data(), n: Value.size());
681 D->getTrailingObjects()[D->ValueStart + Value.size()] = '\0';
682}
683
684void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
685 llvm_unreachable("Translation units are not serialized");
686}
687
688void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
689 VisitDecl(D: ND);
690 ND->setDeclName(Record.readDeclarationName());
691 AnonymousDeclNumber = Record.readInt();
692}
693
694void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
695 VisitNamedDecl(ND: TD);
696 TD->setLocStart(readSourceLocation());
697 // Delay type reading until after we have fully initialized the decl.
698 DeferredTypeID = Record.getGlobalTypeID(LocalID: Record.readInt());
699}
700
701RedeclarableResult ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
702 RedeclarableResult Redecl = VisitRedeclarable(D: TD);
703 VisitTypeDecl(TD);
704 TypeSourceInfo *TInfo = readTypeSourceInfo();
705 if (Record.readInt()) { // isModed
706 QualType modedT = Record.readType();
707 TD->setModedTypeSourceInfo(unmodedTSI: TInfo, modedTy: modedT);
708 } else
709 TD->setTypeSourceInfo(TInfo);
710 // Read and discard the declaration for which this is a typedef name for
711 // linkage, if it exists. We cannot rely on our type to pull in this decl,
712 // because it might have been merged with a type from another module and
713 // thus might not refer to our version of the declaration.
714 readDecl();
715 return Redecl;
716}
717
718void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
719 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
720 mergeRedeclarable(DBase: TD, Redecl);
721}
722
723void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
724 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
725 if (auto *Template = readDeclAs<TypeAliasTemplateDecl>())
726 // Merged when we merge the template.
727 TD->setDescribedAliasTemplate(Template);
728 else
729 mergeRedeclarable(DBase: TD, Redecl);
730}
731
732RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {
733 RedeclarableResult Redecl = VisitRedeclarable(D: TD);
734 VisitTypeDecl(TD);
735
736 TD->IdentifierNamespace = Record.readInt();
737
738 BitsUnpacker TagDeclBits(Record.readInt());
739 TD->setTagKind(
740 static_cast<TagTypeKind>(TagDeclBits.getNextBits(/*Width=*/3)));
741 TD->setCompleteDefinition(TagDeclBits.getNextBit());
742 TD->setEmbeddedInDeclarator(TagDeclBits.getNextBit());
743 TD->setFreeStanding(TagDeclBits.getNextBit());
744 TD->setCompleteDefinitionRequired(TagDeclBits.getNextBit());
745 TD->setBraceRange(readSourceRange());
746
747 switch (TagDeclBits.getNextBits(/*Width=*/2)) {
748 case 0:
749 break;
750 case 1: { // ExtInfo
751 auto *Info = new (Reader.getContext()) TagDecl::ExtInfo();
752 Record.readQualifierInfo(Info&: *Info);
753 TD->TypedefNameDeclOrQualifier = Info;
754 break;
755 }
756 case 2: // TypedefNameForAnonDecl
757 NamedDeclForTagDecl = readDeclID();
758 TypedefNameForLinkage = Record.readIdentifier();
759 break;
760 default:
761 llvm_unreachable("unexpected tag info kind");
762 }
763
764 if (!isa<CXXRecordDecl>(Val: TD))
765 mergeRedeclarable(DBase: TD, Redecl);
766 return Redecl;
767}
768
769void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
770 VisitTagDecl(TD: ED);
771 if (TypeSourceInfo *TI = readTypeSourceInfo())
772 ED->setIntegerTypeSourceInfo(TI);
773 else
774 ED->setIntegerType(Record.readType());
775 ED->setPromotionType(Record.readType());
776
777 BitsUnpacker EnumDeclBits(Record.readInt());
778 ED->setNumPositiveBits(EnumDeclBits.getNextBits(/*Width=*/8));
779 ED->setNumNegativeBits(EnumDeclBits.getNextBits(/*Width=*/8));
780 ED->setScoped(EnumDeclBits.getNextBit());
781 ED->setScopedUsingClassTag(EnumDeclBits.getNextBit());
782 ED->setFixed(EnumDeclBits.getNextBit());
783
784 ED->setHasODRHash(true);
785 ED->ODRHash = Record.readInt();
786
787 // If this is a definition subject to the ODR, and we already have a
788 // definition, merge this one into it.
789 if (ED->isCompleteDefinition() && Reader.getContext().getLangOpts().Modules) {
790 EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()];
791 if (!OldDef) {
792 // This is the first time we've seen an imported definition. Look for a
793 // local definition before deciding that we are the first definition.
794 for (auto *D : merged_redecls(D: ED->getCanonicalDecl())) {
795 if (!D->isFromASTFile() && D->isCompleteDefinition()) {
796 OldDef = D;
797 break;
798 }
799 }
800 }
801 if (OldDef) {
802 Reader.MergedDeclContexts.insert(KV: std::make_pair(x&: ED, y&: OldDef));
803 ED->demoteThisDefinitionToDeclaration();
804 Reader.mergeDefinitionVisibility(Def: OldDef, MergedDef: ED);
805 // We don't want to check the ODR hash value for declarations from global
806 // module fragment.
807 if (!shouldSkipCheckingODR(D: ED) && !shouldSkipCheckingODR(D: OldDef) &&
808 OldDef->getODRHash() != ED->getODRHash())
809 Reader.PendingEnumOdrMergeFailures[OldDef].push_back(Elt: ED);
810 } else {
811 OldDef = ED;
812 }
813 }
814
815 if (auto *InstED = readDeclAs<EnumDecl>()) {
816 auto TSK = (TemplateSpecializationKind)Record.readInt();
817 SourceLocation POI = readSourceLocation();
818 ED->setInstantiationOfMemberEnum(C&: Reader.getContext(), ED: InstED, TSK);
819 ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
820 }
821}
822
823RedeclarableResult ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
824 RedeclarableResult Redecl = VisitTagDecl(TD: RD);
825
826 BitsUnpacker RecordDeclBits(Record.readInt());
827 RD->setHasFlexibleArrayMember(RecordDeclBits.getNextBit());
828 RD->setAnonymousStructOrUnion(RecordDeclBits.getNextBit());
829 RD->setHasObjectMember(RecordDeclBits.getNextBit());
830 RD->setHasVolatileMember(RecordDeclBits.getNextBit());
831 RD->setNonTrivialToPrimitiveDefaultInitialize(RecordDeclBits.getNextBit());
832 RD->setNonTrivialToPrimitiveCopy(RecordDeclBits.getNextBit());
833 RD->setNonTrivialToPrimitiveDestroy(RecordDeclBits.getNextBit());
834 RD->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(
835 RecordDeclBits.getNextBit());
836 RD->setHasNonTrivialToPrimitiveDestructCUnion(RecordDeclBits.getNextBit());
837 RD->setHasNonTrivialToPrimitiveCopyCUnion(RecordDeclBits.getNextBit());
838 RD->setHasUninitializedExplicitInitFields(RecordDeclBits.getNextBit());
839 RD->setParamDestroyedInCallee(RecordDeclBits.getNextBit());
840 RD->setArgPassingRestrictions(
841 (RecordArgPassingKind)RecordDeclBits.getNextBits(/*Width=*/2));
842 return Redecl;
843}
844
845void ASTDeclReader::VisitRecordDecl(RecordDecl *RD) {
846 VisitRecordDeclImpl(RD);
847 RD->setODRHash(Record.readInt());
848
849 // Maintain the invariant of a redeclaration chain containing only
850 // a single definition.
851 if (RD->isCompleteDefinition()) {
852 RecordDecl *Canon = static_cast<RecordDecl *>(RD->getCanonicalDecl());
853 RecordDecl *&OldDef = Reader.RecordDefinitions[Canon];
854 if (!OldDef) {
855 // This is the first time we've seen an imported definition. Look for a
856 // local definition before deciding that we are the first definition.
857 for (auto *D : merged_redecls(D: Canon)) {
858 if (!D->isFromASTFile() && D->isCompleteDefinition()) {
859 OldDef = D;
860 break;
861 }
862 }
863 }
864 if (OldDef) {
865 Reader.MergedDeclContexts.insert(KV: std::make_pair(x&: RD, y&: OldDef));
866 RD->demoteThisDefinitionToDeclaration();
867 Reader.mergeDefinitionVisibility(Def: OldDef, MergedDef: RD);
868 if (OldDef->getODRHash() != RD->getODRHash())
869 Reader.PendingRecordOdrMergeFailures[OldDef].push_back(Elt: RD);
870 } else {
871 OldDef = RD;
872 }
873 }
874}
875
876void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
877 VisitNamedDecl(ND: VD);
878 // For function or variable declarations, defer reading the type in case the
879 // declaration has a deduced type that references an entity declared within
880 // the function definition or variable initializer.
881 if (isa<FunctionDecl, VarDecl>(Val: VD))
882 DeferredTypeID = Record.getGlobalTypeID(LocalID: Record.readInt());
883 else
884 VD->setType(Record.readType());
885}
886
887void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
888 VisitValueDecl(VD: ECD);
889 if (Record.readInt())
890 ECD->setInitExpr(Record.readExpr());
891 ECD->setInitVal(C: Reader.getContext(), V: Record.readAPSInt());
892 mergeMergeable(D: ECD);
893}
894
895void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
896 VisitValueDecl(VD: DD);
897 DD->setInnerLocStart(readSourceLocation());
898 if (Record.readInt()) { // hasExtInfo
899 auto *Info = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
900 Record.readQualifierInfo(Info&: *Info);
901 Info->TrailingRequiresClause = AssociatedConstraint(
902 Record.readExpr(),
903 UnsignedOrNone::fromInternalRepresentation(Rep: Record.readUInt32()));
904 DD->DeclInfo = Info;
905 }
906 QualType TSIType = Record.readType();
907 DD->setTypeSourceInfo(
908 TSIType.isNull() ? nullptr
909 : Reader.getContext().CreateTypeSourceInfo(T: TSIType));
910}
911
912void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
913 RedeclarableResult Redecl = VisitRedeclarable(D: FD);
914
915 FunctionDecl *Existing = nullptr;
916
917 switch ((FunctionDecl::TemplatedKind)Record.readInt()) {
918 case FunctionDecl::TK_NonTemplate:
919 break;
920 case FunctionDecl::TK_DependentNonTemplate:
921 FD->setInstantiatedFromDecl(readDeclAs<FunctionDecl>());
922 break;
923 case FunctionDecl::TK_FunctionTemplate: {
924 auto *Template = readDeclAs<FunctionTemplateDecl>();
925 Template->init(NewTemplatedDecl: FD);
926 FD->setDescribedFunctionTemplate(Template);
927 break;
928 }
929 case FunctionDecl::TK_MemberSpecialization: {
930 auto *InstFD = readDeclAs<FunctionDecl>();
931 auto TSK = (TemplateSpecializationKind)Record.readInt();
932 SourceLocation POI = readSourceLocation();
933 FD->setInstantiationOfMemberFunction(C&: Reader.getContext(), FD: InstFD, TSK);
934 FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
935 break;
936 }
937 case FunctionDecl::TK_FunctionTemplateSpecialization: {
938 auto *Template = readDeclAs<FunctionTemplateDecl>();
939 auto TSK = (TemplateSpecializationKind)Record.readInt();
940
941 // Template arguments.
942 SmallVector<TemplateArgument, 8> TemplArgs;
943 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
944
945 // Template args as written.
946 TemplateArgumentListInfo TemplArgsWritten;
947 bool HasTemplateArgumentsAsWritten = Record.readBool();
948 if (HasTemplateArgumentsAsWritten)
949 Record.readTemplateArgumentListInfo(Result&: TemplArgsWritten);
950
951 SourceLocation POI = readSourceLocation();
952
953 ASTContext &C = Reader.getContext();
954 TemplateArgumentList *TemplArgList =
955 TemplateArgumentList::CreateCopy(Context&: C, Args: TemplArgs);
956
957 MemberSpecializationInfo *MSInfo = nullptr;
958 if (Record.readInt()) {
959 auto *FD = readDeclAs<FunctionDecl>();
960 auto TSK = (TemplateSpecializationKind)Record.readInt();
961 SourceLocation POI = readSourceLocation();
962
963 MSInfo = new (C) MemberSpecializationInfo(FD, TSK);
964 MSInfo->setPointOfInstantiation(POI);
965 }
966
967 FunctionTemplateSpecializationInfo *FTInfo =
968 FunctionTemplateSpecializationInfo::Create(
969 C, FD, Template, TSK, TemplateArgs: TemplArgList,
970 TemplateArgsAsWritten: HasTemplateArgumentsAsWritten ? &TemplArgsWritten : nullptr, POI,
971 MSInfo);
972 FD->TemplateOrSpecialization = FTInfo;
973
974 if (FD->isCanonicalDecl()) { // if canonical add to template's set.
975 // The template that contains the specializations set. It's not safe to
976 // use getCanonicalDecl on Template since it may still be initializing.
977 auto *CanonTemplate = readDeclAs<FunctionTemplateDecl>();
978 // Get the InsertPos by FindNodeOrInsertPos() instead of calling
979 // InsertNode(FTInfo) directly to avoid the getASTContext() call in
980 // FunctionTemplateSpecializationInfo's Profile().
981 // We avoid getASTContext because a decl in the parent hierarchy may
982 // be initializing.
983 llvm::FoldingSetNodeID ID;
984 FunctionTemplateSpecializationInfo::Profile(ID, TemplateArgs: TemplArgs, Context: C);
985 void *InsertPos = nullptr;
986 FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();
987 FunctionTemplateSpecializationInfo *ExistingInfo =
988 CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);
989 if (InsertPos)
990 CommonPtr->Specializations.InsertNode(N: FTInfo, InsertPos);
991 else {
992 assert(Reader.getContext().getLangOpts().Modules &&
993 "already deserialized this template specialization");
994 Existing = ExistingInfo->getFunction();
995 }
996 }
997 break;
998 }
999 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
1000 // Templates.
1001 UnresolvedSet<8> Candidates;
1002 unsigned NumCandidates = Record.readInt();
1003 while (NumCandidates--)
1004 Candidates.addDecl(D: readDeclAs<NamedDecl>());
1005
1006 // Templates args.
1007 TemplateArgumentListInfo TemplArgsWritten;
1008 bool HasTemplateArgumentsAsWritten = Record.readBool();
1009 if (HasTemplateArgumentsAsWritten)
1010 Record.readTemplateArgumentListInfo(Result&: TemplArgsWritten);
1011
1012 FD->setDependentTemplateSpecialization(
1013 Context&: Reader.getContext(), Templates: Candidates,
1014 TemplateArgs: HasTemplateArgumentsAsWritten ? &TemplArgsWritten : nullptr);
1015 // These are not merged; we don't need to merge redeclarations of dependent
1016 // template friends.
1017 break;
1018 }
1019 }
1020
1021 VisitDeclaratorDecl(DD: FD);
1022
1023 // Attach a type to this function. Use the real type if possible, but fall
1024 // back to the type as written if it involves a deduced return type.
1025 if (FD->getTypeSourceInfo() && FD->getTypeSourceInfo()
1026 ->getType()
1027 ->castAs<FunctionType>()
1028 ->getReturnType()
1029 ->getContainedAutoType()) {
1030 // We'll set up the real type in Visit, once we've finished loading the
1031 // function.
1032 FD->setType(FD->getTypeSourceInfo()->getType());
1033 Reader.PendingDeducedFunctionTypes.push_back(Elt: {FD, DeferredTypeID});
1034 } else {
1035 FD->setType(Reader.GetType(ID: DeferredTypeID));
1036 }
1037 DeferredTypeID = 0;
1038
1039 FD->DNLoc = Record.readDeclarationNameLoc(Name: FD->getDeclName());
1040 FD->IdentifierNamespace = Record.readInt();
1041
1042 // FunctionDecl's body is handled last at ASTDeclReader::Visit,
1043 // after everything else is read.
1044 BitsUnpacker FunctionDeclBits(Record.readInt());
1045
1046 FD->setCachedLinkage((Linkage)FunctionDeclBits.getNextBits(/*Width=*/3));
1047 FD->setStorageClass((StorageClass)FunctionDeclBits.getNextBits(/*Width=*/3));
1048 FD->setInlineSpecified(FunctionDeclBits.getNextBit());
1049 FD->setImplicitlyInline(FunctionDeclBits.getNextBit());
1050 FD->setHasSkippedBody(FunctionDeclBits.getNextBit());
1051 FD->setVirtualAsWritten(FunctionDeclBits.getNextBit());
1052 // We defer calling `FunctionDecl::setPure()` here as for methods of
1053 // `CXXTemplateSpecializationDecl`s, we may not have connected up the
1054 // definition (which is required for `setPure`).
1055 const bool Pure = FunctionDeclBits.getNextBit();
1056 FD->setHasInheritedPrototype(FunctionDeclBits.getNextBit());
1057 FD->setHasWrittenPrototype(FunctionDeclBits.getNextBit());
1058 FD->setDeletedAsWritten(D: FunctionDeclBits.getNextBit());
1059 FD->setTrivial(FunctionDeclBits.getNextBit());
1060 FD->setTrivialForCall(FunctionDeclBits.getNextBit());
1061 FD->setDefaulted(FunctionDeclBits.getNextBit());
1062 FD->setExplicitlyDefaulted(FunctionDeclBits.getNextBit());
1063 FD->setIneligibleOrNotSelected(FunctionDeclBits.getNextBit());
1064 FD->setConstexprKind(
1065 (ConstexprSpecKind)FunctionDeclBits.getNextBits(/*Width=*/2));
1066 FD->setHasImplicitReturnZero(FunctionDeclBits.getNextBit());
1067 FD->setIsMultiVersion(FunctionDeclBits.getNextBit());
1068 FD->setLateTemplateParsed(FunctionDeclBits.getNextBit());
1069 FD->setInstantiatedFromMemberTemplate(FunctionDeclBits.getNextBit());
1070 FD->setFriendConstraintRefersToEnclosingTemplate(
1071 FunctionDeclBits.getNextBit());
1072 FD->setUsesSEHTry(FunctionDeclBits.getNextBit());
1073 FD->setIsDestroyingOperatorDelete(FunctionDeclBits.getNextBit());
1074 FD->setIsTypeAwareOperatorNewOrDelete(FunctionDeclBits.getNextBit());
1075
1076 FD->EndRangeLoc = readSourceLocation();
1077 if (FD->isExplicitlyDefaulted())
1078 FD->setDefaultLoc(readSourceLocation());
1079
1080 FD->ODRHash = Record.readInt();
1081 FD->setHasODRHash(true);
1082
1083 if (FD->isDefaulted() || FD->isDeletedAsWritten()) {
1084 // If 'Info' is nonzero, we need to read an DefaultedOrDeletedInfo; if,
1085 // additionally, the second bit is also set, we also need to read
1086 // a DeletedMessage for the DefaultedOrDeletedInfo.
1087 if (auto Info = Record.readInt()) {
1088 bool HasMessage = Info & 2;
1089 StringLiteral *DeletedMessage =
1090 HasMessage ? cast<StringLiteral>(Val: Record.readExpr()) : nullptr;
1091
1092 unsigned NumLookups = Record.readInt();
1093 SmallVector<DeclAccessPair, 8> Lookups;
1094 for (unsigned I = 0; I != NumLookups; ++I) {
1095 NamedDecl *ND = Record.readDeclAs<NamedDecl>();
1096 AccessSpecifier AS = (AccessSpecifier)Record.readInt();
1097 Lookups.push_back(Elt: DeclAccessPair::make(D: ND, AS));
1098 }
1099
1100 FD->setDefaultedOrDeletedInfo(
1101 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
1102 Context&: Reader.getContext(), Lookups, DeletedMessage));
1103 }
1104 }
1105
1106 if (Existing)
1107 MergeImpl.mergeRedeclarable(D: FD, Existing, Redecl);
1108 else if (auto Kind = FD->getTemplatedKind();
1109 Kind == FunctionDecl::TK_FunctionTemplate ||
1110 Kind == FunctionDecl::TK_FunctionTemplateSpecialization) {
1111 // Function Templates have their FunctionTemplateDecls merged instead of
1112 // their FunctionDecls.
1113 auto merge = [this, &Redecl, FD](auto &&F) {
1114 auto *Existing = cast_or_null<FunctionDecl>(Val: Redecl.getKnownMergeTarget());
1115 RedeclarableResult NewRedecl(Existing ? F(Existing) : nullptr,
1116 Redecl.getFirstID(), Redecl.isKeyDecl());
1117 mergeRedeclarableTemplate(D: F(FD), Redecl&: NewRedecl);
1118 };
1119 if (Kind == FunctionDecl::TK_FunctionTemplate)
1120 merge(
1121 [](FunctionDecl *FD) { return FD->getDescribedFunctionTemplate(); });
1122 else
1123 merge([](FunctionDecl *FD) {
1124 return FD->getTemplateSpecializationInfo()->getTemplate();
1125 });
1126 } else
1127 mergeRedeclarable(DBase: FD, Redecl);
1128
1129 // Defer calling `setPure` until merging above has guaranteed we've set
1130 // `DefinitionData` (as this will need to access it).
1131 FD->setIsPureVirtual(Pure);
1132
1133 // Read in the parameters.
1134 unsigned NumParams = Record.readInt();
1135 SmallVector<ParmVarDecl *, 16> Params;
1136 Params.reserve(N: NumParams);
1137 for (unsigned I = 0; I != NumParams; ++I)
1138 Params.push_back(Elt: readDeclAs<ParmVarDecl>());
1139 FD->setParams(C&: Reader.getContext(), NewParamInfo: Params);
1140
1141 // If the declaration is a SYCL kernel entry point function as indicated by
1142 // the presence of a sycl_kernel_entry_point attribute, register it so that
1143 // associated metadata is recreated.
1144 if (FD->hasAttr<SYCLKernelEntryPointAttr>()) {
1145 auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
1146 ASTContext &C = Reader.getContext();
1147 const SYCLKernelInfo *SKI = C.findSYCLKernelInfo(T: SKEPAttr->getKernelName());
1148 if (SKI) {
1149 if (!declaresSameEntity(D1: FD, D2: SKI->getKernelEntryPointDecl())) {
1150 Reader.Diag(Loc: FD->getLocation(), DiagID: diag::err_sycl_kernel_name_conflict);
1151 Reader.Diag(Loc: SKI->getKernelEntryPointDecl()->getLocation(),
1152 DiagID: diag::note_previous_declaration);
1153 SKEPAttr->setInvalidAttr();
1154 }
1155 } else {
1156 C.registerSYCLEntryPointFunction(FD);
1157 }
1158 }
1159}
1160
1161void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
1162 VisitNamedDecl(ND: MD);
1163 if (Record.readInt()) {
1164 // Load the body on-demand. Most clients won't care, because method
1165 // definitions rarely show up in headers.
1166 Reader.PendingBodies[MD] = GetCurrentCursorOffset();
1167 }
1168 MD->setSelfDecl(readDeclAs<ImplicitParamDecl>());
1169 MD->setCmdDecl(readDeclAs<ImplicitParamDecl>());
1170 MD->setInstanceMethod(Record.readInt());
1171 MD->setVariadic(Record.readInt());
1172 MD->setPropertyAccessor(Record.readInt());
1173 MD->setSynthesizedAccessorStub(Record.readInt());
1174 MD->setDefined(Record.readInt());
1175 MD->setOverriding(Record.readInt());
1176 MD->setHasSkippedBody(Record.readInt());
1177
1178 MD->setIsRedeclaration(Record.readInt());
1179 MD->setHasRedeclaration(Record.readInt());
1180 if (MD->hasRedeclaration())
1181 Reader.getContext().setObjCMethodRedeclaration(MD,
1182 Redecl: readDeclAs<ObjCMethodDecl>());
1183
1184 MD->setDeclImplementation(
1185 static_cast<ObjCImplementationControl>(Record.readInt()));
1186 MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record.readInt());
1187 MD->setRelatedResultType(Record.readInt());
1188 MD->setReturnType(Record.readType());
1189 MD->setReturnTypeSourceInfo(readTypeSourceInfo());
1190 MD->DeclEndLoc = readSourceLocation();
1191 unsigned NumParams = Record.readInt();
1192 SmallVector<ParmVarDecl *, 16> Params;
1193 Params.reserve(N: NumParams);
1194 for (unsigned I = 0; I != NumParams; ++I)
1195 Params.push_back(Elt: readDeclAs<ParmVarDecl>());
1196
1197 MD->setSelLocsKind((SelectorLocationsKind)Record.readInt());
1198 unsigned NumStoredSelLocs = Record.readInt();
1199 SmallVector<SourceLocation, 16> SelLocs;
1200 SelLocs.reserve(N: NumStoredSelLocs);
1201 for (unsigned i = 0; i != NumStoredSelLocs; ++i)
1202 SelLocs.push_back(Elt: readSourceLocation());
1203
1204 MD->setParamsAndSelLocs(C&: Reader.getContext(), Params, SelLocs);
1205}
1206
1207void ASTDeclReader::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
1208 VisitTypedefNameDecl(TD: D);
1209
1210 D->Variance = Record.readInt();
1211 D->Index = Record.readInt();
1212 D->VarianceLoc = readSourceLocation();
1213 D->ColonLoc = readSourceLocation();
1214}
1215
1216void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
1217 VisitNamedDecl(ND: CD);
1218 CD->setAtStartLoc(readSourceLocation());
1219 CD->setAtEndRange(readSourceRange());
1220}
1221
1222ObjCTypeParamList *ASTDeclReader::ReadObjCTypeParamList() {
1223 unsigned numParams = Record.readInt();
1224 if (numParams == 0)
1225 return nullptr;
1226
1227 SmallVector<ObjCTypeParamDecl *, 4> typeParams;
1228 typeParams.reserve(N: numParams);
1229 for (unsigned i = 0; i != numParams; ++i) {
1230 auto *typeParam = readDeclAs<ObjCTypeParamDecl>();
1231 if (!typeParam)
1232 return nullptr;
1233
1234 typeParams.push_back(Elt: typeParam);
1235 }
1236
1237 SourceLocation lAngleLoc = readSourceLocation();
1238 SourceLocation rAngleLoc = readSourceLocation();
1239
1240 return ObjCTypeParamList::create(ctx&: Reader.getContext(), lAngleLoc,
1241 typeParams, rAngleLoc);
1242}
1243
1244void ASTDeclReader::ReadObjCDefinitionData(
1245 struct ObjCInterfaceDecl::DefinitionData &Data) {
1246 // Read the superclass.
1247 Data.SuperClassTInfo = readTypeSourceInfo();
1248
1249 Data.EndLoc = readSourceLocation();
1250 Data.HasDesignatedInitializers = Record.readInt();
1251 Data.ODRHash = Record.readInt();
1252 Data.HasODRHash = true;
1253
1254 // Read the directly referenced protocols and their SourceLocations.
1255 unsigned NumProtocols = Record.readInt();
1256 SmallVector<ObjCProtocolDecl *, 16> Protocols;
1257 Protocols.reserve(N: NumProtocols);
1258 for (unsigned I = 0; I != NumProtocols; ++I)
1259 Protocols.push_back(Elt: readDeclAs<ObjCProtocolDecl>());
1260 SmallVector<SourceLocation, 16> ProtoLocs;
1261 ProtoLocs.reserve(N: NumProtocols);
1262 for (unsigned I = 0; I != NumProtocols; ++I)
1263 ProtoLocs.push_back(Elt: readSourceLocation());
1264 Data.ReferencedProtocols.set(InList: Protocols.data(), Elts: NumProtocols, Locs: ProtoLocs.data(),
1265 Ctx&: Reader.getContext());
1266
1267 // Read the transitive closure of protocols referenced by this class.
1268 NumProtocols = Record.readInt();
1269 Protocols.clear();
1270 Protocols.reserve(N: NumProtocols);
1271 for (unsigned I = 0; I != NumProtocols; ++I)
1272 Protocols.push_back(Elt: readDeclAs<ObjCProtocolDecl>());
1273 Data.AllReferencedProtocols.set(InList: Protocols.data(), Elts: NumProtocols,
1274 Ctx&: Reader.getContext());
1275}
1276
1277void ASTDeclMerger::MergeDefinitionData(
1278 ObjCInterfaceDecl *D, struct ObjCInterfaceDecl::DefinitionData &&NewDD) {
1279 struct ObjCInterfaceDecl::DefinitionData &DD = D->data();
1280 if (DD.Definition == NewDD.Definition)
1281 return;
1282
1283 Reader.MergedDeclContexts.insert(
1284 KV: std::make_pair(x&: NewDD.Definition, y&: DD.Definition));
1285 Reader.mergeDefinitionVisibility(Def: DD.Definition, MergedDef: NewDD.Definition);
1286
1287 if (D->getODRHash() != NewDD.ODRHash)
1288 Reader.PendingObjCInterfaceOdrMergeFailures[DD.Definition].push_back(
1289 Elt: {NewDD.Definition, &NewDD});
1290}
1291
1292void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
1293 RedeclarableResult Redecl = VisitRedeclarable(D: ID);
1294 VisitObjCContainerDecl(CD: ID);
1295 DeferredTypeID = Record.getGlobalTypeID(LocalID: Record.readInt());
1296 mergeRedeclarable(DBase: ID, Redecl);
1297
1298 ID->TypeParamList = ReadObjCTypeParamList();
1299 if (Record.readInt()) {
1300 // Read the definition.
1301 ID->allocateDefinitionData();
1302
1303 ReadObjCDefinitionData(Data&: ID->data());
1304 ObjCInterfaceDecl *Canon = ID->getCanonicalDecl();
1305 if (Canon->Data.getPointer()) {
1306 // If we already have a definition, keep the definition invariant and
1307 // merge the data.
1308 MergeImpl.MergeDefinitionData(D: Canon, NewDD: std::move(ID->data()));
1309 ID->Data = Canon->Data;
1310 } else {
1311 // Set the definition data of the canonical declaration, so other
1312 // redeclarations will see it.
1313 ID->getCanonicalDecl()->Data = ID->Data;
1314
1315 // We will rebuild this list lazily.
1316 ID->setIvarList(nullptr);
1317 }
1318
1319 // Note that we have deserialized a definition.
1320 Reader.PendingDefinitions.insert(Ptr: ID);
1321
1322 // Note that we've loaded this Objective-C class.
1323 Reader.ObjCClassesLoaded.push_back(Elt: ID);
1324 } else {
1325 ID->Data = ID->getCanonicalDecl()->Data;
1326 }
1327}
1328
1329void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
1330 VisitFieldDecl(FD: IVD);
1331 IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record.readInt());
1332 // This field will be built lazily.
1333 IVD->setNextIvar(nullptr);
1334 bool synth = Record.readInt();
1335 IVD->setSynthesize(synth);
1336
1337 // Check ivar redeclaration.
1338 if (IVD->isInvalidDecl())
1339 return;
1340 // Don't check ObjCInterfaceDecl as interfaces are named and mismatches can be
1341 // detected in VisitObjCInterfaceDecl. Here we are looking for redeclarations
1342 // in extensions.
1343 if (isa<ObjCInterfaceDecl>(Val: IVD->getDeclContext()))
1344 return;
1345 ObjCInterfaceDecl *CanonIntf =
1346 IVD->getContainingInterface()->getCanonicalDecl();
1347 IdentifierInfo *II = IVD->getIdentifier();
1348 ObjCIvarDecl *PrevIvar = CanonIntf->lookupInstanceVariable(IVarName: II);
1349 if (PrevIvar && PrevIvar != IVD) {
1350 auto *ParentExt = dyn_cast<ObjCCategoryDecl>(Val: IVD->getDeclContext());
1351 auto *PrevParentExt =
1352 dyn_cast<ObjCCategoryDecl>(Val: PrevIvar->getDeclContext());
1353 if (ParentExt && PrevParentExt) {
1354 // Postpone diagnostic as we should merge identical extensions from
1355 // different modules.
1356 Reader
1357 .PendingObjCExtensionIvarRedeclarations[std::make_pair(x&: ParentExt,
1358 y&: PrevParentExt)]
1359 .push_back(Elt: std::make_pair(x&: IVD, y&: PrevIvar));
1360 } else if (ParentExt || PrevParentExt) {
1361 // Duplicate ivars in extension + implementation are never compatible.
1362 // Compatibility of implementation + implementation should be handled in
1363 // VisitObjCImplementationDecl.
1364 Reader.Diag(Loc: IVD->getLocation(), DiagID: diag::err_duplicate_ivar_declaration)
1365 << II;
1366 Reader.Diag(Loc: PrevIvar->getLocation(), DiagID: diag::note_previous_definition);
1367 }
1368 }
1369}
1370
1371void ASTDeclReader::ReadObjCDefinitionData(
1372 struct ObjCProtocolDecl::DefinitionData &Data) {
1373 unsigned NumProtoRefs = Record.readInt();
1374 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1375 ProtoRefs.reserve(N: NumProtoRefs);
1376 for (unsigned I = 0; I != NumProtoRefs; ++I)
1377 ProtoRefs.push_back(Elt: readDeclAs<ObjCProtocolDecl>());
1378 SmallVector<SourceLocation, 16> ProtoLocs;
1379 ProtoLocs.reserve(N: NumProtoRefs);
1380 for (unsigned I = 0; I != NumProtoRefs; ++I)
1381 ProtoLocs.push_back(Elt: readSourceLocation());
1382 Data.ReferencedProtocols.set(InList: ProtoRefs.data(), Elts: NumProtoRefs,
1383 Locs: ProtoLocs.data(), Ctx&: Reader.getContext());
1384 Data.ODRHash = Record.readInt();
1385 Data.HasODRHash = true;
1386}
1387
1388void ASTDeclMerger::MergeDefinitionData(
1389 ObjCProtocolDecl *D, struct ObjCProtocolDecl::DefinitionData &&NewDD) {
1390 struct ObjCProtocolDecl::DefinitionData &DD = D->data();
1391 if (DD.Definition == NewDD.Definition)
1392 return;
1393
1394 Reader.MergedDeclContexts.insert(
1395 KV: std::make_pair(x&: NewDD.Definition, y&: DD.Definition));
1396 Reader.mergeDefinitionVisibility(Def: DD.Definition, MergedDef: NewDD.Definition);
1397
1398 if (D->getODRHash() != NewDD.ODRHash)
1399 Reader.PendingObjCProtocolOdrMergeFailures[DD.Definition].push_back(
1400 Elt: {NewDD.Definition, &NewDD});
1401}
1402
1403void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
1404 RedeclarableResult Redecl = VisitRedeclarable(D: PD);
1405 VisitObjCContainerDecl(CD: PD);
1406 mergeRedeclarable(DBase: PD, Redecl);
1407
1408 if (Record.readInt()) {
1409 // Read the definition.
1410 PD->allocateDefinitionData();
1411
1412 ReadObjCDefinitionData(Data&: PD->data());
1413
1414 ObjCProtocolDecl *Canon = PD->getCanonicalDecl();
1415 if (Canon->Data.getPointer()) {
1416 // If we already have a definition, keep the definition invariant and
1417 // merge the data.
1418 MergeImpl.MergeDefinitionData(D: Canon, NewDD: std::move(PD->data()));
1419 PD->Data = Canon->Data;
1420 } else {
1421 // Set the definition data of the canonical declaration, so other
1422 // redeclarations will see it.
1423 PD->getCanonicalDecl()->Data = PD->Data;
1424 }
1425 // Note that we have deserialized a definition.
1426 Reader.PendingDefinitions.insert(Ptr: PD);
1427 } else {
1428 PD->Data = PD->getCanonicalDecl()->Data;
1429 }
1430}
1431
1432void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
1433 VisitFieldDecl(FD);
1434}
1435
1436void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
1437 VisitObjCContainerDecl(CD);
1438 CD->setCategoryNameLoc(readSourceLocation());
1439 CD->setIvarLBraceLoc(readSourceLocation());
1440 CD->setIvarRBraceLoc(readSourceLocation());
1441
1442 // Note that this category has been deserialized. We do this before
1443 // deserializing the interface declaration, so that it will consider this
1444 /// category.
1445 Reader.CategoriesDeserialized.insert(Ptr: CD);
1446
1447 CD->ClassInterface = readDeclAs<ObjCInterfaceDecl>();
1448 CD->TypeParamList = ReadObjCTypeParamList();
1449 unsigned NumProtoRefs = Record.readInt();
1450 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1451 ProtoRefs.reserve(N: NumProtoRefs);
1452 for (unsigned I = 0; I != NumProtoRefs; ++I)
1453 ProtoRefs.push_back(Elt: readDeclAs<ObjCProtocolDecl>());
1454 SmallVector<SourceLocation, 16> ProtoLocs;
1455 ProtoLocs.reserve(N: NumProtoRefs);
1456 for (unsigned I = 0; I != NumProtoRefs; ++I)
1457 ProtoLocs.push_back(Elt: readSourceLocation());
1458 CD->setProtocolList(List: ProtoRefs.data(), Num: NumProtoRefs, Locs: ProtoLocs.data(),
1459 C&: Reader.getContext());
1460
1461 // Protocols in the class extension belong to the class.
1462 if (NumProtoRefs > 0 && CD->ClassInterface && CD->IsClassExtension())
1463 CD->ClassInterface->mergeClassExtensionProtocolList(
1464 List: (ObjCProtocolDecl *const *)ProtoRefs.data(), Num: NumProtoRefs,
1465 C&: Reader.getContext());
1466}
1467
1468void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
1469 VisitNamedDecl(ND: CAD);
1470 CAD->setClassInterface(readDeclAs<ObjCInterfaceDecl>());
1471}
1472
1473void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
1474 VisitNamedDecl(ND: D);
1475 D->setAtLoc(readSourceLocation());
1476 D->setLParenLoc(readSourceLocation());
1477 QualType T = Record.readType();
1478 TypeSourceInfo *TSI = readTypeSourceInfo();
1479 D->setType(T, TSI);
1480 D->setPropertyAttributes((ObjCPropertyAttribute::Kind)Record.readInt());
1481 D->setPropertyAttributesAsWritten(
1482 (ObjCPropertyAttribute::Kind)Record.readInt());
1483 D->setPropertyImplementation(
1484 (ObjCPropertyDecl::PropertyControl)Record.readInt());
1485 DeclarationName GetterName = Record.readDeclarationName();
1486 SourceLocation GetterLoc = readSourceLocation();
1487 D->setGetterName(Sel: GetterName.getObjCSelector(), Loc: GetterLoc);
1488 DeclarationName SetterName = Record.readDeclarationName();
1489 SourceLocation SetterLoc = readSourceLocation();
1490 D->setSetterName(Sel: SetterName.getObjCSelector(), Loc: SetterLoc);
1491 D->setGetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1492 D->setSetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1493 D->setPropertyIvarDecl(readDeclAs<ObjCIvarDecl>());
1494}
1495
1496void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
1497 VisitObjCContainerDecl(CD: D);
1498 D->setClassInterface(readDeclAs<ObjCInterfaceDecl>());
1499}
1500
1501void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1502 VisitObjCImplDecl(D);
1503 D->CategoryNameLoc = readSourceLocation();
1504}
1505
1506void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1507 VisitObjCImplDecl(D);
1508 D->setSuperClass(readDeclAs<ObjCInterfaceDecl>());
1509 D->SuperLoc = readSourceLocation();
1510 D->setIvarLBraceLoc(readSourceLocation());
1511 D->setIvarRBraceLoc(readSourceLocation());
1512 D->setHasNonZeroConstructors(Record.readInt());
1513 D->setHasDestructors(Record.readInt());
1514 D->NumIvarInitializers = Record.readInt();
1515 if (D->NumIvarInitializers)
1516 D->IvarInitializers = ReadGlobalOffset();
1517}
1518
1519void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
1520 VisitDecl(D);
1521 D->setAtLoc(readSourceLocation());
1522 D->setPropertyDecl(readDeclAs<ObjCPropertyDecl>());
1523 D->PropertyIvarDecl = readDeclAs<ObjCIvarDecl>();
1524 D->IvarLoc = readSourceLocation();
1525 D->setGetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1526 D->setSetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1527 D->setGetterCXXConstructor(Record.readExpr());
1528 D->setSetterCXXAssignment(Record.readExpr());
1529}
1530
1531void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
1532 VisitDeclaratorDecl(DD: FD);
1533 FD->Mutable = Record.readInt();
1534
1535 unsigned Bits = Record.readInt();
1536 FD->StorageKind = Bits >> 1;
1537 if (FD->StorageKind == FieldDecl::ISK_CapturedVLAType)
1538 FD->CapturedVLAType =
1539 cast<VariableArrayType>(Val: Record.readType().getTypePtr());
1540 else if (Bits & 1)
1541 FD->setBitWidth(Record.readExpr());
1542
1543 if (!FD->getDeclName() ||
1544 FD->isPlaceholderVar(LangOpts: Reader.getContext().getLangOpts())) {
1545 if (auto *Tmpl = readDeclAs<FieldDecl>())
1546 Reader.getContext().setInstantiatedFromUnnamedFieldDecl(Inst: FD, Tmpl);
1547 }
1548 mergeMergeable(D: FD);
1549}
1550
1551void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
1552 VisitDeclaratorDecl(DD: PD);
1553 PD->GetterId = Record.readIdentifier();
1554 PD->SetterId = Record.readIdentifier();
1555}
1556
1557void ASTDeclReader::VisitMSGuidDecl(MSGuidDecl *D) {
1558 VisitValueDecl(VD: D);
1559 D->PartVal.Part1 = Record.readInt();
1560 D->PartVal.Part2 = Record.readInt();
1561 D->PartVal.Part3 = Record.readInt();
1562 for (auto &C : D->PartVal.Part4And5)
1563 C = Record.readInt();
1564
1565 // Add this GUID to the AST context's lookup structure, and merge if needed.
1566 if (MSGuidDecl *Existing = Reader.getContext().MSGuidDecls.GetOrInsertNode(N: D))
1567 Reader.getContext().setPrimaryMergedDecl(D, Primary: Existing->getCanonicalDecl());
1568}
1569
1570void ASTDeclReader::VisitUnnamedGlobalConstantDecl(
1571 UnnamedGlobalConstantDecl *D) {
1572 VisitValueDecl(VD: D);
1573 D->Value = Record.readAPValue();
1574
1575 // Add this to the AST context's lookup structure, and merge if needed.
1576 if (UnnamedGlobalConstantDecl *Existing =
1577 Reader.getContext().UnnamedGlobalConstantDecls.GetOrInsertNode(N: D))
1578 Reader.getContext().setPrimaryMergedDecl(D, Primary: Existing->getCanonicalDecl());
1579}
1580
1581void ASTDeclReader::VisitTemplateParamObjectDecl(TemplateParamObjectDecl *D) {
1582 VisitValueDecl(VD: D);
1583 D->Value = Record.readAPValue();
1584
1585 // Add this template parameter object to the AST context's lookup structure,
1586 // and merge if needed.
1587 if (TemplateParamObjectDecl *Existing =
1588 Reader.getContext().TemplateParamObjectDecls.GetOrInsertNode(N: D))
1589 Reader.getContext().setPrimaryMergedDecl(D, Primary: Existing->getCanonicalDecl());
1590}
1591
1592void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
1593 VisitValueDecl(VD: FD);
1594
1595 FD->ChainingSize = Record.readInt();
1596 assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
1597 FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
1598
1599 for (unsigned I = 0; I != FD->ChainingSize; ++I)
1600 FD->Chaining[I] = readDeclAs<NamedDecl>();
1601
1602 mergeMergeable(D: FD);
1603}
1604
1605RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
1606 RedeclarableResult Redecl = VisitRedeclarable(D: VD);
1607 VisitDeclaratorDecl(DD: VD);
1608
1609 BitsUnpacker VarDeclBits(Record.readInt());
1610 auto VarLinkage = Linkage(VarDeclBits.getNextBits(/*Width=*/3));
1611 bool DefGeneratedInModule = VarDeclBits.getNextBit();
1612 VD->VarDeclBits.SClass = (StorageClass)VarDeclBits.getNextBits(/*Width=*/3);
1613 VD->VarDeclBits.TSCSpec = VarDeclBits.getNextBits(/*Width=*/2);
1614 VD->VarDeclBits.InitStyle = VarDeclBits.getNextBits(/*Width=*/2);
1615 VD->VarDeclBits.ARCPseudoStrong = VarDeclBits.getNextBit();
1616 bool HasDeducedType = false;
1617 if (!isa<ParmVarDecl>(Val: VD)) {
1618 VD->NonParmVarDeclBits.IsThisDeclarationADemotedDefinition =
1619 VarDeclBits.getNextBit();
1620 VD->NonParmVarDeclBits.ExceptionVar = VarDeclBits.getNextBit();
1621 VD->NonParmVarDeclBits.NRVOVariable = VarDeclBits.getNextBit();
1622 VD->NonParmVarDeclBits.CXXForRangeDecl = VarDeclBits.getNextBit();
1623
1624 VD->NonParmVarDeclBits.IsInline = VarDeclBits.getNextBit();
1625 VD->NonParmVarDeclBits.IsInlineSpecified = VarDeclBits.getNextBit();
1626 VD->NonParmVarDeclBits.IsConstexpr = VarDeclBits.getNextBit();
1627 VD->NonParmVarDeclBits.IsInitCapture = VarDeclBits.getNextBit();
1628 VD->NonParmVarDeclBits.PreviousDeclInSameBlockScope =
1629 VarDeclBits.getNextBit();
1630
1631 VD->NonParmVarDeclBits.EscapingByref = VarDeclBits.getNextBit();
1632 HasDeducedType = VarDeclBits.getNextBit();
1633 VD->NonParmVarDeclBits.ImplicitParamKind =
1634 VarDeclBits.getNextBits(/*Width*/ 3);
1635
1636 VD->NonParmVarDeclBits.ObjCForDecl = VarDeclBits.getNextBit();
1637 VD->NonParmVarDeclBits.IsCXXForRangeImplicitVar = VarDeclBits.getNextBit();
1638 }
1639
1640 // If this variable has a deduced type, defer reading that type until we are
1641 // done deserializing this variable, because the type might refer back to the
1642 // variable.
1643 if (HasDeducedType)
1644 Reader.PendingDeducedVarTypes.push_back(Elt: {VD, DeferredTypeID});
1645 else
1646 VD->setType(Reader.GetType(ID: DeferredTypeID));
1647 DeferredTypeID = 0;
1648
1649 VD->setCachedLinkage(VarLinkage);
1650
1651 // Reconstruct the one piece of the IdentifierNamespace that we need.
1652 if (VD->getStorageClass() == SC_Extern && VarLinkage != Linkage::None &&
1653 VD->getLexicalDeclContext()->isFunctionOrMethod())
1654 VD->setLocalExternDecl();
1655
1656 if (DefGeneratedInModule) {
1657 Reader.DefinitionSource[VD] =
1658 Loc.F->Kind == ModuleKind::MK_MainFile ||
1659 Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;
1660 }
1661
1662 if (VD->hasAttr<BlocksAttr>()) {
1663 Expr *CopyExpr = Record.readExpr();
1664 if (CopyExpr)
1665 Reader.getContext().setBlockVarCopyInit(VD, CopyExpr, CanThrow: Record.readInt());
1666 }
1667
1668 enum VarKind {
1669 VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
1670 };
1671 switch ((VarKind)Record.readInt()) {
1672 case VarNotTemplate:
1673 // Only true variables (not parameters or implicit parameters) can be
1674 // merged; the other kinds are not really redeclarable at all.
1675 if (!isa<ParmVarDecl>(Val: VD) && !isa<ImplicitParamDecl>(Val: VD) &&
1676 !isa<VarTemplateSpecializationDecl>(Val: VD))
1677 mergeRedeclarable(DBase: VD, Redecl);
1678 break;
1679 case VarTemplate:
1680 // Merged when we merge the template.
1681 VD->setDescribedVarTemplate(readDeclAs<VarTemplateDecl>());
1682 break;
1683 case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
1684 auto *Tmpl = readDeclAs<VarDecl>();
1685 auto TSK = (TemplateSpecializationKind)Record.readInt();
1686 SourceLocation POI = readSourceLocation();
1687 Reader.getContext().setInstantiatedFromStaticDataMember(Inst: VD, Tmpl, TSK,PointOfInstantiation: POI);
1688 mergeRedeclarable(DBase: VD, Redecl);
1689 break;
1690 }
1691 }
1692
1693 return Redecl;
1694}
1695
1696void ASTDeclReader::ReadVarDeclInit(VarDecl *VD) {
1697 if (uint64_t Val = Record.readInt()) {
1698 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
1699 Eval->HasConstantInitialization = (Val & 2) != 0;
1700 Eval->HasConstantDestruction = (Val & 4) != 0;
1701 Eval->WasEvaluated = (Val & 8) != 0;
1702 Eval->HasSideEffects = (Val & 16) != 0;
1703 Eval->CheckedForSideEffects = true;
1704 if (Eval->WasEvaluated) {
1705 Eval->Evaluated = Record.readAPValue();
1706 if (Eval->Evaluated.needsCleanup())
1707 Reader.getContext().addDestruction(Ptr: &Eval->Evaluated);
1708 }
1709
1710 // Store the offset of the initializer. Don't deserialize it yet: it might
1711 // not be needed, and might refer back to the variable, for example if it
1712 // contains a lambda.
1713 Eval->Value = GetCurrentCursorOffset();
1714 }
1715}
1716
1717void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1718 VisitVarDecl(VD: PD);
1719}
1720
1721void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1722 VisitVarDecl(VD: PD);
1723
1724 unsigned scopeIndex = Record.readInt();
1725 BitsUnpacker ParmVarDeclBits(Record.readInt());
1726 unsigned isObjCMethodParam = ParmVarDeclBits.getNextBit();
1727 unsigned scopeDepth = ParmVarDeclBits.getNextBits(/*Width=*/7);
1728 unsigned declQualifier = ParmVarDeclBits.getNextBits(/*Width=*/7);
1729 if (isObjCMethodParam) {
1730 assert(scopeDepth == 0);
1731 PD->setObjCMethodScopeInfo(scopeIndex);
1732 PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1733 } else {
1734 PD->setScopeInfo(scopeDepth, parameterIndex: scopeIndex);
1735 }
1736 PD->ParmVarDeclBits.IsKNRPromoted = ParmVarDeclBits.getNextBit();
1737
1738 PD->ParmVarDeclBits.HasInheritedDefaultArg = ParmVarDeclBits.getNextBit();
1739 if (ParmVarDeclBits.getNextBit()) // hasUninstantiatedDefaultArg.
1740 PD->setUninstantiatedDefaultArg(Record.readExpr());
1741
1742 if (ParmVarDeclBits.getNextBit()) // Valid explicit object parameter
1743 PD->ExplicitObjectParameterIntroducerLoc = Record.readSourceLocation();
1744
1745 // FIXME: If this is a redeclaration of a function from another module, handle
1746 // inheritance of default arguments.
1747}
1748
1749void ASTDeclReader::VisitDecompositionDecl(DecompositionDecl *DD) {
1750 VisitVarDecl(VD: DD);
1751 auto **BDs = DD->getTrailingObjects();
1752 for (unsigned I = 0; I != DD->NumBindings; ++I) {
1753 BDs[I] = readDeclAs<BindingDecl>();
1754 BDs[I]->setDecomposedDecl(DD);
1755 }
1756}
1757
1758void ASTDeclReader::VisitBindingDecl(BindingDecl *BD) {
1759 VisitValueDecl(VD: BD);
1760 BD->Binding = Record.readExpr();
1761}
1762
1763void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1764 VisitDecl(D: AD);
1765 AD->setAsmString(cast<StringLiteral>(Val: Record.readExpr()));
1766 AD->setRParenLoc(readSourceLocation());
1767}
1768
1769void ASTDeclReader::VisitTopLevelStmtDecl(TopLevelStmtDecl *D) {
1770 VisitDecl(D);
1771 D->Statement = Record.readStmt();
1772}
1773
1774void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1775 VisitDecl(D: BD);
1776 BD->setBody(cast_or_null<CompoundStmt>(Val: Record.readStmt()));
1777 BD->setSignatureAsWritten(readTypeSourceInfo());
1778 unsigned NumParams = Record.readInt();
1779 SmallVector<ParmVarDecl *, 16> Params;
1780 Params.reserve(N: NumParams);
1781 for (unsigned I = 0; I != NumParams; ++I)
1782 Params.push_back(Elt: readDeclAs<ParmVarDecl>());
1783 BD->setParams(Params);
1784
1785 BD->setIsVariadic(Record.readInt());
1786 BD->setBlockMissingReturnType(Record.readInt());
1787 BD->setIsConversionFromLambda(Record.readInt());
1788 BD->setDoesNotEscape(Record.readInt());
1789 BD->setCanAvoidCopyToHeap(Record.readInt());
1790
1791 bool capturesCXXThis = Record.readInt();
1792 unsigned numCaptures = Record.readInt();
1793 SmallVector<BlockDecl::Capture, 16> captures;
1794 captures.reserve(N: numCaptures);
1795 for (unsigned i = 0; i != numCaptures; ++i) {
1796 auto *decl = readDeclAs<VarDecl>();
1797 unsigned flags = Record.readInt();
1798 bool byRef = (flags & 1);
1799 bool nested = (flags & 2);
1800 Expr *copyExpr = ((flags & 4) ? Record.readExpr() : nullptr);
1801
1802 captures.push_back(Elt: BlockDecl::Capture(decl, byRef, nested, copyExpr));
1803 }
1804 BD->setCaptures(Context&: Reader.getContext(), Captures: captures, CapturesCXXThis: capturesCXXThis);
1805}
1806
1807void ASTDeclReader::VisitOutlinedFunctionDecl(OutlinedFunctionDecl *D) {
1808 // NumParams is deserialized by OutlinedFunctionDecl::CreateDeserialized().
1809 VisitDecl(D);
1810 for (unsigned I = 0; I < D->NumParams; ++I)
1811 D->setParam(i: I, P: readDeclAs<ImplicitParamDecl>());
1812 D->setNothrow(Record.readInt() != 0);
1813 D->setBody(cast_or_null<Stmt>(Val: Record.readStmt()));
1814}
1815
1816void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1817 VisitDecl(D: CD);
1818 unsigned ContextParamPos = Record.readInt();
1819 CD->setNothrow(Record.readInt() != 0);
1820 // Body is set by VisitCapturedStmt.
1821 for (unsigned I = 0; I < CD->NumParams; ++I) {
1822 if (I != ContextParamPos)
1823 CD->setParam(i: I, P: readDeclAs<ImplicitParamDecl>());
1824 else
1825 CD->setContextParam(i: I, P: readDeclAs<ImplicitParamDecl>());
1826 }
1827}
1828
1829void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1830 VisitDecl(D);
1831 D->setLanguage(static_cast<LinkageSpecLanguageIDs>(Record.readInt()));
1832 D->setExternLoc(readSourceLocation());
1833 D->setRBraceLoc(readSourceLocation());
1834}
1835
1836void ASTDeclReader::VisitExportDecl(ExportDecl *D) {
1837 VisitDecl(D);
1838 D->RBraceLoc = readSourceLocation();
1839}
1840
1841void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1842 VisitNamedDecl(ND: D);
1843 D->setLocStart(readSourceLocation());
1844}
1845
1846void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1847 RedeclarableResult Redecl = VisitRedeclarable(D);
1848 VisitNamedDecl(ND: D);
1849
1850 BitsUnpacker NamespaceDeclBits(Record.readInt());
1851 D->setInline(NamespaceDeclBits.getNextBit());
1852 D->setNested(NamespaceDeclBits.getNextBit());
1853 D->LocStart = readSourceLocation();
1854 D->RBraceLoc = readSourceLocation();
1855
1856 // Defer loading the anonymous namespace until we've finished merging
1857 // this namespace; loading it might load a later declaration of the
1858 // same namespace, and we have an invariant that older declarations
1859 // get merged before newer ones try to merge.
1860 GlobalDeclID AnonNamespace;
1861 if (Redecl.getFirstID() == ThisDeclID)
1862 AnonNamespace = readDeclID();
1863
1864 mergeRedeclarable(DBase: D, Redecl);
1865
1866 if (AnonNamespace.isValid()) {
1867 // Each module has its own anonymous namespace, which is disjoint from
1868 // any other module's anonymous namespaces, so don't attach the anonymous
1869 // namespace at all.
1870 auto *Anon = cast<NamespaceDecl>(Val: Reader.GetDecl(ID: AnonNamespace));
1871 if (!Record.isModule())
1872 D->setAnonymousNamespace(Anon);
1873 }
1874}
1875
1876void ASTDeclReader::VisitHLSLBufferDecl(HLSLBufferDecl *D) {
1877 VisitNamedDecl(ND: D);
1878 LookupBlockOffsets Offsets;
1879 VisitDeclContext(DC: D, Offsets);
1880 D->IsCBuffer = Record.readBool();
1881 D->KwLoc = readSourceLocation();
1882 D->LBraceLoc = readSourceLocation();
1883 D->RBraceLoc = readSourceLocation();
1884}
1885
1886void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1887 RedeclarableResult Redecl = VisitRedeclarable(D);
1888 VisitNamedDecl(ND: D);
1889 D->NamespaceLoc = readSourceLocation();
1890 D->IdentLoc = readSourceLocation();
1891 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1892 D->Namespace = readDeclAs<NamedDecl>();
1893 mergeRedeclarable(DBase: D, Redecl);
1894}
1895
1896void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1897 VisitNamedDecl(ND: D);
1898 D->setUsingLoc(readSourceLocation());
1899 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1900 D->DNLoc = Record.readDeclarationNameLoc(Name: D->getDeclName());
1901 D->FirstUsingShadow.setPointer(readDeclAs<UsingShadowDecl>());
1902 D->setTypename(Record.readInt());
1903 if (auto *Pattern = readDeclAs<NamedDecl>())
1904 Reader.getContext().setInstantiatedFromUsingDecl(Inst: D, Pattern);
1905 mergeMergeable(D);
1906}
1907
1908void ASTDeclReader::VisitUsingEnumDecl(UsingEnumDecl *D) {
1909 VisitNamedDecl(ND: D);
1910 D->setUsingLoc(readSourceLocation());
1911 D->setEnumLoc(readSourceLocation());
1912 D->setEnumType(Record.readTypeSourceInfo());
1913 D->FirstUsingShadow.setPointer(readDeclAs<UsingShadowDecl>());
1914 if (auto *Pattern = readDeclAs<UsingEnumDecl>())
1915 Reader.getContext().setInstantiatedFromUsingEnumDecl(Inst: D, Pattern);
1916 mergeMergeable(D);
1917}
1918
1919void ASTDeclReader::VisitUsingPackDecl(UsingPackDecl *D) {
1920 VisitNamedDecl(ND: D);
1921 D->InstantiatedFrom = readDeclAs<NamedDecl>();
1922 auto **Expansions = D->getTrailingObjects();
1923 for (unsigned I = 0; I != D->NumExpansions; ++I)
1924 Expansions[I] = readDeclAs<NamedDecl>();
1925 mergeMergeable(D);
1926}
1927
1928void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1929 RedeclarableResult Redecl = VisitRedeclarable(D);
1930 VisitNamedDecl(ND: D);
1931 D->Underlying = readDeclAs<NamedDecl>();
1932 D->IdentifierNamespace = Record.readInt();
1933 D->UsingOrNextShadow = readDeclAs<NamedDecl>();
1934 auto *Pattern = readDeclAs<UsingShadowDecl>();
1935 if (Pattern)
1936 Reader.getContext().setInstantiatedFromUsingShadowDecl(Inst: D, Pattern);
1937 mergeRedeclarable(DBase: D, Redecl);
1938}
1939
1940void ASTDeclReader::VisitConstructorUsingShadowDecl(
1941 ConstructorUsingShadowDecl *D) {
1942 VisitUsingShadowDecl(D);
1943 D->NominatedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1944 D->ConstructedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1945 D->IsVirtual = Record.readInt();
1946}
1947
1948void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1949 VisitNamedDecl(ND: D);
1950 D->UsingLoc = readSourceLocation();
1951 D->NamespaceLoc = readSourceLocation();
1952 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1953 D->NominatedNamespace = readDeclAs<NamedDecl>();
1954 D->CommonAncestor = readDeclAs<DeclContext>();
1955}
1956
1957void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1958 VisitValueDecl(VD: D);
1959 D->setUsingLoc(readSourceLocation());
1960 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1961 D->DNLoc = Record.readDeclarationNameLoc(Name: D->getDeclName());
1962 D->EllipsisLoc = readSourceLocation();
1963 mergeMergeable(D);
1964}
1965
1966void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1967 UnresolvedUsingTypenameDecl *D) {
1968 VisitTypeDecl(TD: D);
1969 D->TypenameLocation = readSourceLocation();
1970 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1971 D->EllipsisLoc = readSourceLocation();
1972 mergeMergeable(D);
1973}
1974
1975void ASTDeclReader::VisitUnresolvedUsingIfExistsDecl(
1976 UnresolvedUsingIfExistsDecl *D) {
1977 VisitNamedDecl(ND: D);
1978}
1979
1980void ASTDeclReader::ReadCXXDefinitionData(
1981 struct CXXRecordDecl::DefinitionData &Data, const CXXRecordDecl *D,
1982 Decl *LambdaContext, unsigned IndexInLambdaContext) {
1983
1984 BitsUnpacker CXXRecordDeclBits = Record.readInt();
1985
1986#define FIELD(Name, Width, Merge) \
1987 if (!CXXRecordDeclBits.canGetNextNBits(Width)) \
1988 CXXRecordDeclBits.updateValue(Record.readInt()); \
1989 Data.Name = CXXRecordDeclBits.getNextBits(Width);
1990
1991#include "clang/AST/CXXRecordDeclDefinitionBits.def"
1992#undef FIELD
1993
1994 // Note: the caller has deserialized the IsLambda bit already.
1995 Data.ODRHash = Record.readInt();
1996 Data.HasODRHash = true;
1997
1998 if (Record.readInt()) {
1999 Reader.DefinitionSource[D] =
2000 Loc.F->Kind == ModuleKind::MK_MainFile ||
2001 Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;
2002 }
2003
2004 Record.readUnresolvedSet(Set&: Data.Conversions);
2005 Data.ComputedVisibleConversions = Record.readInt();
2006 if (Data.ComputedVisibleConversions)
2007 Record.readUnresolvedSet(Set&: Data.VisibleConversions);
2008 assert(Data.Definition && "Data.Definition should be already set!");
2009
2010 if (!Data.IsLambda) {
2011 assert(!LambdaContext && !IndexInLambdaContext &&
2012 "given lambda context for non-lambda");
2013
2014 Data.NumBases = Record.readInt();
2015 if (Data.NumBases)
2016 Data.Bases = ReadGlobalOffset();
2017
2018 Data.NumVBases = Record.readInt();
2019 if (Data.NumVBases)
2020 Data.VBases = ReadGlobalOffset();
2021
2022 Data.FirstFriend = readDeclID().getRawValue();
2023 } else {
2024 using Capture = LambdaCapture;
2025
2026 auto &Lambda = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
2027
2028 BitsUnpacker LambdaBits(Record.readInt());
2029 Lambda.DependencyKind = LambdaBits.getNextBits(/*Width=*/2);
2030 Lambda.IsGenericLambda = LambdaBits.getNextBit();
2031 Lambda.CaptureDefault = LambdaBits.getNextBits(/*Width=*/2);
2032 Lambda.NumCaptures = LambdaBits.getNextBits(/*Width=*/15);
2033 Lambda.HasKnownInternalLinkage = LambdaBits.getNextBit();
2034
2035 Lambda.NumExplicitCaptures = Record.readInt();
2036 Lambda.ManglingNumber = Record.readInt();
2037 if (unsigned DeviceManglingNumber = Record.readInt())
2038 Reader.getContext().DeviceLambdaManglingNumbers[D] = DeviceManglingNumber;
2039 Lambda.IndexInContext = IndexInLambdaContext;
2040 Lambda.ContextDecl = LambdaContext;
2041 Capture *ToCapture = nullptr;
2042 if (Lambda.NumCaptures) {
2043 ToCapture = (Capture *)Reader.getContext().Allocate(Size: sizeof(Capture) *
2044 Lambda.NumCaptures);
2045 Lambda.AddCaptureList(Ctx&: Reader.getContext(), CaptureList: ToCapture);
2046 }
2047 Lambda.MethodTyInfo = readTypeSourceInfo();
2048 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
2049 SourceLocation Loc = readSourceLocation();
2050 BitsUnpacker CaptureBits(Record.readInt());
2051 bool IsImplicit = CaptureBits.getNextBit();
2052 auto Kind =
2053 static_cast<LambdaCaptureKind>(CaptureBits.getNextBits(/*Width=*/3));
2054 switch (Kind) {
2055 case LCK_StarThis:
2056 case LCK_This:
2057 case LCK_VLAType:
2058 new (ToCapture)
2059 Capture(Loc, IsImplicit, Kind, nullptr, SourceLocation());
2060 ToCapture++;
2061 break;
2062 case LCK_ByCopy:
2063 case LCK_ByRef:
2064 auto *Var = readDeclAs<ValueDecl>();
2065 SourceLocation EllipsisLoc = readSourceLocation();
2066 new (ToCapture) Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
2067 ToCapture++;
2068 break;
2069 }
2070 }
2071 }
2072}
2073
2074void ASTDeclMerger::MergeDefinitionData(
2075 CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {
2076 assert(D->DefinitionData &&
2077 "merging class definition into non-definition");
2078 auto &DD = *D->DefinitionData;
2079
2080 if (DD.Definition != MergeDD.Definition) {
2081 // Track that we merged the definitions.
2082 Reader.MergedDeclContexts.insert(KV: std::make_pair(x&: MergeDD.Definition,
2083 y&: DD.Definition));
2084 Reader.PendingDefinitions.erase(Ptr: MergeDD.Definition);
2085 MergeDD.Definition->demoteThisDefinitionToDeclaration();
2086 Reader.mergeDefinitionVisibility(Def: DD.Definition, MergedDef: MergeDD.Definition);
2087 assert(!Reader.Lookups.contains(MergeDD.Definition) &&
2088 "already loaded pending lookups for merged definition");
2089 }
2090
2091 auto PFDI = Reader.PendingFakeDefinitionData.find(Val: &DD);
2092 if (PFDI != Reader.PendingFakeDefinitionData.end() &&
2093 PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) {
2094 // We faked up this definition data because we found a class for which we'd
2095 // not yet loaded the definition. Replace it with the real thing now.
2096 assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?");
2097 PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded;
2098
2099 // Don't change which declaration is the definition; that is required
2100 // to be invariant once we select it.
2101 auto *Def = DD.Definition;
2102 DD = std::move(MergeDD);
2103 DD.Definition = Def;
2104 return;
2105 }
2106
2107 bool DetectedOdrViolation = false;
2108
2109 #define FIELD(Name, Width, Merge) Merge(Name)
2110 #define MERGE_OR(Field) DD.Field |= MergeDD.Field;
2111 #define NO_MERGE(Field) \
2112 DetectedOdrViolation |= DD.Field != MergeDD.Field; \
2113 MERGE_OR(Field)
2114 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
2115 NO_MERGE(IsLambda)
2116 #undef NO_MERGE
2117 #undef MERGE_OR
2118
2119 if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
2120 DetectedOdrViolation = true;
2121 // FIXME: Issue a diagnostic if the base classes don't match when we come
2122 // to lazily load them.
2123
2124 // FIXME: Issue a diagnostic if the list of conversion functions doesn't
2125 // match when we come to lazily load them.
2126 if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
2127 DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
2128 DD.ComputedVisibleConversions = true;
2129 }
2130
2131 // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
2132 // lazily load it.
2133
2134 if (DD.IsLambda) {
2135 auto &Lambda1 = static_cast<CXXRecordDecl::LambdaDefinitionData &>(DD);
2136 auto &Lambda2 = static_cast<CXXRecordDecl::LambdaDefinitionData &>(MergeDD);
2137 DetectedOdrViolation |= Lambda1.DependencyKind != Lambda2.DependencyKind;
2138 DetectedOdrViolation |= Lambda1.IsGenericLambda != Lambda2.IsGenericLambda;
2139 DetectedOdrViolation |= Lambda1.CaptureDefault != Lambda2.CaptureDefault;
2140 DetectedOdrViolation |= Lambda1.NumCaptures != Lambda2.NumCaptures;
2141 DetectedOdrViolation |=
2142 Lambda1.NumExplicitCaptures != Lambda2.NumExplicitCaptures;
2143 DetectedOdrViolation |=
2144 Lambda1.HasKnownInternalLinkage != Lambda2.HasKnownInternalLinkage;
2145 DetectedOdrViolation |= Lambda1.ManglingNumber != Lambda2.ManglingNumber;
2146
2147 if (Lambda1.NumCaptures && Lambda1.NumCaptures == Lambda2.NumCaptures) {
2148 for (unsigned I = 0, N = Lambda1.NumCaptures; I != N; ++I) {
2149 LambdaCapture &Cap1 = Lambda1.Captures.front()[I];
2150 LambdaCapture &Cap2 = Lambda2.Captures.front()[I];
2151 DetectedOdrViolation |= Cap1.getCaptureKind() != Cap2.getCaptureKind();
2152 }
2153 Lambda1.AddCaptureList(Ctx&: Reader.getContext(), CaptureList: Lambda2.Captures.front());
2154 }
2155 }
2156
2157 // We don't want to check ODR for decls in the global module fragment.
2158 if (shouldSkipCheckingODR(D: MergeDD.Definition) || shouldSkipCheckingODR(D))
2159 return;
2160
2161 if (D->getODRHash() != MergeDD.ODRHash) {
2162 DetectedOdrViolation = true;
2163 }
2164
2165 if (DetectedOdrViolation)
2166 Reader.PendingOdrMergeFailures[DD.Definition].push_back(
2167 Elt: {MergeDD.Definition, &MergeDD});
2168}
2169
2170void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update,
2171 Decl *LambdaContext,
2172 unsigned IndexInLambdaContext) {
2173 struct CXXRecordDecl::DefinitionData *DD;
2174 ASTContext &C = Reader.getContext();
2175
2176 // Determine whether this is a lambda closure type, so that we can
2177 // allocate the appropriate DefinitionData structure.
2178 bool IsLambda = Record.readInt();
2179 assert(!(IsLambda && Update) &&
2180 "lambda definition should not be added by update record");
2181 if (IsLambda)
2182 DD = new (C) CXXRecordDecl::LambdaDefinitionData(
2183 D, nullptr, CXXRecordDecl::LDK_Unknown, false, LCD_None);
2184 else
2185 DD = new (C) struct CXXRecordDecl::DefinitionData(D);
2186
2187 CXXRecordDecl *Canon = D->getCanonicalDecl();
2188 // Set decl definition data before reading it, so that during deserialization
2189 // when we read CXXRecordDecl, it already has definition data and we don't
2190 // set fake one.
2191 if (!Canon->DefinitionData)
2192 Canon->DefinitionData = DD;
2193 D->DefinitionData = Canon->DefinitionData;
2194 ReadCXXDefinitionData(Data&: *DD, D, LambdaContext, IndexInLambdaContext);
2195
2196 // Mark this declaration as being a definition.
2197 D->setCompleteDefinition(true);
2198
2199 // We might already have a different definition for this record. This can
2200 // happen either because we're reading an update record, or because we've
2201 // already done some merging. Either way, just merge into it.
2202 if (Canon->DefinitionData != DD) {
2203 MergeImpl.MergeDefinitionData(D: Canon, MergeDD: std::move(*DD));
2204 return;
2205 }
2206
2207 // If this is not the first declaration or is an update record, we can have
2208 // other redeclarations already. Make a note that we need to propagate the
2209 // DefinitionData pointer onto them.
2210 if (Update || Canon != D)
2211 Reader.PendingDefinitions.insert(Ptr: D);
2212}
2213
2214RedeclarableResult ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
2215 RedeclarableResult Redecl = VisitRecordDeclImpl(RD: D);
2216
2217 ASTContext &C = Reader.getContext();
2218
2219 enum CXXRecKind {
2220 CXXRecNotTemplate = 0,
2221 CXXRecTemplate,
2222 CXXRecMemberSpecialization,
2223 CXXLambda
2224 };
2225
2226 Decl *LambdaContext = nullptr;
2227 unsigned IndexInLambdaContext = 0;
2228
2229 switch ((CXXRecKind)Record.readInt()) {
2230 case CXXRecNotTemplate:
2231 // Merged when we merge the folding set entry in the primary template.
2232 if (!isa<ClassTemplateSpecializationDecl>(Val: D))
2233 mergeRedeclarable(DBase: D, Redecl);
2234 break;
2235 case CXXRecTemplate: {
2236 // Merged when we merge the template.
2237 auto *Template = readDeclAs<ClassTemplateDecl>();
2238 D->TemplateOrInstantiation = Template;
2239 if (!Template->getTemplatedDecl()) {
2240 // We've not actually loaded the ClassTemplateDecl yet, because we're
2241 // currently being loaded as its pattern. Rely on it to set up our
2242 // TypeForDecl (see VisitClassTemplateDecl).
2243 //
2244 // Beware: we do not yet know our canonical declaration, and may still
2245 // get merged once the surrounding class template has got off the ground.
2246 DeferredTypeID = 0;
2247 }
2248 break;
2249 }
2250 case CXXRecMemberSpecialization: {
2251 auto *RD = readDeclAs<CXXRecordDecl>();
2252 auto TSK = (TemplateSpecializationKind)Record.readInt();
2253 SourceLocation POI = readSourceLocation();
2254 MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
2255 MSI->setPointOfInstantiation(POI);
2256 D->TemplateOrInstantiation = MSI;
2257 mergeRedeclarable(DBase: D, Redecl);
2258 break;
2259 }
2260 case CXXLambda: {
2261 LambdaContext = readDecl();
2262 if (LambdaContext)
2263 IndexInLambdaContext = Record.readInt();
2264 if (LambdaContext)
2265 MergeImpl.mergeLambda(D, Redecl, Context&: *LambdaContext, Number: IndexInLambdaContext);
2266 else
2267 // If we don't have a mangling context, treat this like any other
2268 // declaration.
2269 mergeRedeclarable(DBase: D, Redecl);
2270 break;
2271 }
2272 }
2273
2274 bool WasDefinition = Record.readInt();
2275 if (WasDefinition)
2276 ReadCXXRecordDefinition(D, /*Update=*/false, LambdaContext,
2277 IndexInLambdaContext);
2278 else
2279 // Propagate DefinitionData pointer from the canonical declaration.
2280 D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
2281
2282 // Lazily load the key function to avoid deserializing every method so we can
2283 // compute it.
2284 if (WasDefinition) {
2285 GlobalDeclID KeyFn = readDeclID();
2286 if (KeyFn.isValid() && D->isCompleteDefinition())
2287 // FIXME: This is wrong for the ARM ABI, where some other module may have
2288 // made this function no longer be a key function. We need an update
2289 // record or similar for that case.
2290 C.KeyFunctions[D] = KeyFn.getRawValue();
2291 }
2292
2293 return Redecl;
2294}
2295
2296void ASTDeclReader::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
2297 D->setExplicitSpecifier(Record.readExplicitSpec());
2298 D->Ctor = readDeclAs<CXXConstructorDecl>();
2299 VisitFunctionDecl(FD: D);
2300 D->setDeductionCandidateKind(
2301 static_cast<DeductionCandidate>(Record.readInt()));
2302 D->setSourceDeductionGuide(readDeclAs<CXXDeductionGuideDecl>());
2303 D->setSourceDeductionGuideKind(
2304 static_cast<CXXDeductionGuideDecl::SourceDeductionGuideKind>(
2305 Record.readInt()));
2306}
2307
2308void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
2309 VisitFunctionDecl(FD: D);
2310
2311 unsigned NumOverridenMethods = Record.readInt();
2312 if (D->isCanonicalDecl()) {
2313 while (NumOverridenMethods--) {
2314 // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
2315 // MD may be initializing.
2316 if (auto *MD = readDeclAs<CXXMethodDecl>())
2317 Reader.getContext().addOverriddenMethod(Method: D, Overridden: MD->getCanonicalDecl());
2318 }
2319 } else {
2320 // We don't care about which declarations this used to override; we get
2321 // the relevant information from the canonical declaration.
2322 Record.skipInts(N: NumOverridenMethods);
2323 }
2324}
2325
2326void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2327 // We need the inherited constructor information to merge the declaration,
2328 // so we have to read it before we call VisitCXXMethodDecl.
2329 D->setExplicitSpecifier(Record.readExplicitSpec());
2330 if (D->isInheritingConstructor()) {
2331 auto *Shadow = readDeclAs<ConstructorUsingShadowDecl>();
2332 auto *Ctor = readDeclAs<CXXConstructorDecl>();
2333 *D->getTrailingObjects<InheritedConstructor>() =
2334 InheritedConstructor(Shadow, Ctor);
2335 }
2336
2337 VisitCXXMethodDecl(D);
2338}
2339
2340void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2341 VisitCXXMethodDecl(D);
2342
2343 if (auto *OperatorDelete = readDeclAs<FunctionDecl>()) {
2344 CXXDestructorDecl *Canon = D->getCanonicalDecl();
2345 auto *ThisArg = Record.readExpr();
2346 // FIXME: Check consistency if we have an old and new operator delete.
2347 if (!Canon->OperatorDelete) {
2348 Canon->OperatorDelete = OperatorDelete;
2349 Canon->OperatorDeleteThisArg = ThisArg;
2350 }
2351 }
2352}
2353
2354void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
2355 D->setExplicitSpecifier(Record.readExplicitSpec());
2356 VisitCXXMethodDecl(D);
2357}
2358
2359void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
2360 VisitDecl(D);
2361 D->ImportedModule = readModule();
2362 D->setImportComplete(Record.readInt());
2363 auto *StoredLocs = D->getTrailingObjects();
2364 for (unsigned I = 0, N = Record.back(); I != N; ++I)
2365 StoredLocs[I] = readSourceLocation();
2366 Record.skipInts(N: 1); // The number of stored source locations.
2367}
2368
2369void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
2370 VisitDecl(D);
2371 D->setColonLoc(readSourceLocation());
2372}
2373
2374void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
2375 VisitDecl(D);
2376 if (Record.readInt()) // hasFriendDecl
2377 D->Friend = readDeclAs<NamedDecl>();
2378 else
2379 D->Friend = readTypeSourceInfo();
2380 for (unsigned i = 0; i != D->NumTPLists; ++i)
2381 D->getTrailingObjects()[i] = Record.readTemplateParameterList();
2382 D->NextFriend = readDeclID().getRawValue();
2383 D->UnsupportedFriend = (Record.readInt() != 0);
2384 D->FriendLoc = readSourceLocation();
2385 D->EllipsisLoc = readSourceLocation();
2386}
2387
2388void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2389 VisitDecl(D);
2390 unsigned NumParams = Record.readInt();
2391 D->NumParams = NumParams;
2392 D->Params = new (Reader.getContext()) TemplateParameterList *[NumParams];
2393 for (unsigned i = 0; i != NumParams; ++i)
2394 D->Params[i] = Record.readTemplateParameterList();
2395 if (Record.readInt()) // HasFriendDecl
2396 D->Friend = readDeclAs<NamedDecl>();
2397 else
2398 D->Friend = readTypeSourceInfo();
2399 D->FriendLoc = readSourceLocation();
2400}
2401
2402void ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
2403 VisitNamedDecl(ND: D);
2404
2405 assert(!D->TemplateParams && "TemplateParams already set!");
2406 D->TemplateParams = Record.readTemplateParameterList();
2407 D->init(NewTemplatedDecl: readDeclAs<NamedDecl>());
2408}
2409
2410void ASTDeclReader::VisitConceptDecl(ConceptDecl *D) {
2411 VisitTemplateDecl(D);
2412 D->ConstraintExpr = Record.readExpr();
2413 mergeMergeable(D);
2414}
2415
2416void ASTDeclReader::VisitImplicitConceptSpecializationDecl(
2417 ImplicitConceptSpecializationDecl *D) {
2418 // The size of the template list was read during creation of the Decl, so we
2419 // don't have to re-read it here.
2420 VisitDecl(D);
2421 llvm::SmallVector<TemplateArgument, 4> Args;
2422 for (unsigned I = 0; I < D->NumTemplateArgs; ++I)
2423 Args.push_back(Elt: Record.readTemplateArgument(/*Canonicalize=*/true));
2424 D->setTemplateArguments(Args);
2425}
2426
2427void ASTDeclReader::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
2428}
2429
2430void ASTDeclReader::ReadSpecializations(ModuleFile &M, Decl *D,
2431 llvm::BitstreamCursor &DeclsCursor,
2432 bool IsPartial) {
2433 uint64_t Offset = ReadLocalOffset();
2434 bool Failed =
2435 Reader.ReadSpecializations(M, Cursor&: DeclsCursor, Offset, D, IsPartial);
2436 (void)Failed;
2437 assert(!Failed);
2438}
2439
2440RedeclarableResult
2441ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
2442 RedeclarableResult Redecl = VisitRedeclarable(D);
2443
2444 // Make sure we've allocated the Common pointer first. We do this before
2445 // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
2446 RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
2447 if (!CanonD->Common) {
2448 CanonD->Common = CanonD->newCommon(C&: Reader.getContext());
2449 Reader.PendingDefinitions.insert(Ptr: CanonD);
2450 }
2451 D->Common = CanonD->Common;
2452
2453 // If this is the first declaration of the template, fill in the information
2454 // for the 'common' pointer.
2455 if (ThisDeclID == Redecl.getFirstID()) {
2456 if (auto *RTD = readDeclAs<RedeclarableTemplateDecl>()) {
2457 assert(RTD->getKind() == D->getKind() &&
2458 "InstantiatedFromMemberTemplate kind mismatch");
2459 D->setInstantiatedFromMemberTemplate(RTD);
2460 if (Record.readInt())
2461 D->setMemberSpecialization();
2462 }
2463 }
2464
2465 VisitTemplateDecl(D);
2466 D->IdentifierNamespace = Record.readInt();
2467
2468 return Redecl;
2469}
2470
2471void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
2472 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2473 mergeRedeclarableTemplate(D, Redecl);
2474
2475 if (ThisDeclID == Redecl.getFirstID()) {
2476 // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
2477 // the specializations.
2478 ReadSpecializations(M&: *Loc.F, D, DeclsCursor&: Loc.F->DeclsCursor, /*IsPartial=*/false);
2479 ReadSpecializations(M&: *Loc.F, D, DeclsCursor&: Loc.F->DeclsCursor, /*IsPartial=*/true);
2480 }
2481
2482 if (D->getTemplatedDecl()->TemplateOrInstantiation) {
2483 // We were loaded before our templated declaration was. We've not set up
2484 // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
2485 // it now.
2486 Reader.getContext().getInjectedClassNameType(
2487 Decl: D->getTemplatedDecl(), TST: D->getInjectedClassNameSpecialization());
2488 }
2489}
2490
2491void ASTDeclReader::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
2492 llvm_unreachable("BuiltinTemplates are not serialized");
2493}
2494
2495/// TODO: Unify with ClassTemplateDecl version?
2496/// May require unifying ClassTemplateDecl and
2497/// VarTemplateDecl beyond TemplateDecl...
2498void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
2499 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2500 mergeRedeclarableTemplate(D, Redecl);
2501
2502 if (ThisDeclID == Redecl.getFirstID()) {
2503 // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
2504 // the specializations.
2505 ReadSpecializations(M&: *Loc.F, D, DeclsCursor&: Loc.F->DeclsCursor, /*IsPartial=*/false);
2506 ReadSpecializations(M&: *Loc.F, D, DeclsCursor&: Loc.F->DeclsCursor, /*IsPartial=*/true);
2507 }
2508}
2509
2510RedeclarableResult ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
2511 ClassTemplateSpecializationDecl *D) {
2512 RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
2513
2514 ASTContext &C = Reader.getContext();
2515 if (Decl *InstD = readDecl()) {
2516 if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: InstD)) {
2517 D->SpecializedTemplate = CTD;
2518 } else {
2519 SmallVector<TemplateArgument, 8> TemplArgs;
2520 Record.readTemplateArgumentList(TemplArgs);
2521 TemplateArgumentList *ArgList
2522 = TemplateArgumentList::CreateCopy(Context&: C, Args: TemplArgs);
2523 auto *PS =
2524 new (C) ClassTemplateSpecializationDecl::
2525 SpecializedPartialSpecialization();
2526 PS->PartialSpecialization
2527 = cast<ClassTemplatePartialSpecializationDecl>(Val: InstD);
2528 PS->TemplateArgs = ArgList;
2529 D->SpecializedTemplate = PS;
2530 }
2531 }
2532
2533 SmallVector<TemplateArgument, 8> TemplArgs;
2534 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2535 D->TemplateArgs = TemplateArgumentList::CreateCopy(Context&: C, Args: TemplArgs);
2536 D->PointOfInstantiation = readSourceLocation();
2537 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2538 D->StrictPackMatch = Record.readBool();
2539
2540 bool writtenAsCanonicalDecl = Record.readInt();
2541 if (writtenAsCanonicalDecl) {
2542 auto *CanonPattern = readDeclAs<ClassTemplateDecl>();
2543 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2544 // Set this as, or find, the canonical declaration for this specialization
2545 ClassTemplateSpecializationDecl *CanonSpec;
2546 if (auto *Partial = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: D)) {
2547 CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
2548 .GetOrInsertNode(N: Partial);
2549 } else {
2550 CanonSpec =
2551 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(N: D);
2552 }
2553 // If there was already a canonical specialization, merge into it.
2554 if (CanonSpec != D) {
2555 MergeImpl.mergeRedeclarable<TagDecl>(D, Existing: CanonSpec, Redecl);
2556
2557 // This declaration might be a definition. Merge with any existing
2558 // definition.
2559 if (auto *DDD = D->DefinitionData) {
2560 if (CanonSpec->DefinitionData)
2561 MergeImpl.MergeDefinitionData(D: CanonSpec, MergeDD: std::move(*DDD));
2562 else
2563 CanonSpec->DefinitionData = D->DefinitionData;
2564 }
2565 D->DefinitionData = CanonSpec->DefinitionData;
2566 }
2567 }
2568 }
2569
2570 // extern/template keyword locations for explicit instantiations
2571 if (Record.readBool()) {
2572 auto *ExplicitInfo = new (C) ExplicitInstantiationInfo;
2573 ExplicitInfo->ExternKeywordLoc = readSourceLocation();
2574 ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2575 D->ExplicitInfo = ExplicitInfo;
2576 }
2577
2578 if (Record.readBool())
2579 D->setTemplateArgsAsWritten(Record.readASTTemplateArgumentListInfo());
2580
2581 return Redecl;
2582}
2583
2584void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
2585 ClassTemplatePartialSpecializationDecl *D) {
2586 // We need to read the template params first because redeclarable is going to
2587 // need them for profiling
2588 TemplateParameterList *Params = Record.readTemplateParameterList();
2589 D->TemplateParams = Params;
2590
2591 RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
2592
2593 // These are read/set from/to the first declaration.
2594 if (ThisDeclID == Redecl.getFirstID()) {
2595 D->InstantiatedFromMember.setPointer(
2596 readDeclAs<ClassTemplatePartialSpecializationDecl>());
2597 D->InstantiatedFromMember.setInt(Record.readInt());
2598 }
2599}
2600
2601void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2602 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2603
2604 if (ThisDeclID == Redecl.getFirstID()) {
2605 // This FunctionTemplateDecl owns a CommonPtr; read it.
2606 ReadSpecializations(M&: *Loc.F, D, DeclsCursor&: Loc.F->DeclsCursor, /*IsPartial=*/false);
2607 }
2608}
2609
2610/// TODO: Unify with ClassTemplateSpecializationDecl version?
2611/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2612/// VarTemplate(Partial)SpecializationDecl with a new data
2613/// structure Template(Partial)SpecializationDecl, and
2614/// using Template(Partial)SpecializationDecl as input type.
2615RedeclarableResult ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
2616 VarTemplateSpecializationDecl *D) {
2617 ASTContext &C = Reader.getContext();
2618 if (Decl *InstD = readDecl()) {
2619 if (auto *VTD = dyn_cast<VarTemplateDecl>(Val: InstD)) {
2620 D->SpecializedTemplate = VTD;
2621 } else {
2622 SmallVector<TemplateArgument, 8> TemplArgs;
2623 Record.readTemplateArgumentList(TemplArgs);
2624 TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
2625 Context&: C, Args: TemplArgs);
2626 auto *PS =
2627 new (C)
2628 VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
2629 PS->PartialSpecialization =
2630 cast<VarTemplatePartialSpecializationDecl>(Val: InstD);
2631 PS->TemplateArgs = ArgList;
2632 D->SpecializedTemplate = PS;
2633 }
2634 }
2635
2636 // extern/template keyword locations for explicit instantiations
2637 if (Record.readBool()) {
2638 auto *ExplicitInfo = new (C) ExplicitInstantiationInfo;
2639 ExplicitInfo->ExternKeywordLoc = readSourceLocation();
2640 ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2641 D->ExplicitInfo = ExplicitInfo;
2642 }
2643
2644 if (Record.readBool())
2645 D->setTemplateArgsAsWritten(Record.readASTTemplateArgumentListInfo());
2646
2647 SmallVector<TemplateArgument, 8> TemplArgs;
2648 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2649 D->TemplateArgs = TemplateArgumentList::CreateCopy(Context&: C, Args: TemplArgs);
2650 D->PointOfInstantiation = readSourceLocation();
2651 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2652 D->IsCompleteDefinition = Record.readInt();
2653
2654 RedeclarableResult Redecl = VisitVarDeclImpl(VD: D);
2655
2656 bool writtenAsCanonicalDecl = Record.readInt();
2657 if (writtenAsCanonicalDecl) {
2658 auto *CanonPattern = readDeclAs<VarTemplateDecl>();
2659 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2660 VarTemplateSpecializationDecl *CanonSpec;
2661 if (auto *Partial = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: D)) {
2662 CanonSpec = CanonPattern->getCommonPtr()
2663 ->PartialSpecializations.GetOrInsertNode(N: Partial);
2664 } else {
2665 CanonSpec =
2666 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(N: D);
2667 }
2668 // If we already have a matching specialization, merge it.
2669 if (CanonSpec != D)
2670 MergeImpl.mergeRedeclarable<VarDecl>(D, Existing: CanonSpec, Redecl);
2671 }
2672 }
2673
2674 return Redecl;
2675}
2676
2677/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2678/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2679/// VarTemplate(Partial)SpecializationDecl with a new data
2680/// structure Template(Partial)SpecializationDecl, and
2681/// using Template(Partial)SpecializationDecl as input type.
2682void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
2683 VarTemplatePartialSpecializationDecl *D) {
2684 TemplateParameterList *Params = Record.readTemplateParameterList();
2685 D->TemplateParams = Params;
2686
2687 RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
2688
2689 // These are read/set from/to the first declaration.
2690 if (ThisDeclID == Redecl.getFirstID()) {
2691 D->InstantiatedFromMember.setPointer(
2692 readDeclAs<VarTemplatePartialSpecializationDecl>());
2693 D->InstantiatedFromMember.setInt(Record.readInt());
2694 }
2695}
2696
2697void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
2698 VisitTypeDecl(TD: D);
2699
2700 D->setDeclaredWithTypename(Record.readInt());
2701
2702 bool TypeConstraintInitialized = D->hasTypeConstraint() && Record.readBool();
2703 if (TypeConstraintInitialized) {
2704 ConceptReference *CR = nullptr;
2705 if (Record.readBool())
2706 CR = Record.readConceptReference();
2707 Expr *ImmediatelyDeclaredConstraint = Record.readExpr();
2708 UnsignedOrNone ArgPackSubstIndex = Record.readUnsignedOrNone();
2709
2710 D->setTypeConstraint(CR, ImmediatelyDeclaredConstraint, ArgPackSubstIndex);
2711 D->NumExpanded = Record.readUnsignedOrNone();
2712 }
2713
2714 if (Record.readInt())
2715 D->setDefaultArgument(C: Reader.getContext(),
2716 DefArg: Record.readTemplateArgumentLoc());
2717}
2718
2719void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
2720 VisitDeclaratorDecl(DD: D);
2721 // TemplateParmPosition.
2722 D->setDepth(Record.readInt());
2723 D->setPosition(Record.readInt());
2724 if (D->hasPlaceholderTypeConstraint())
2725 D->setPlaceholderTypeConstraint(Record.readExpr());
2726 if (D->isExpandedParameterPack()) {
2727 auto TypesAndInfos =
2728 D->getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
2729 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2730 new (&TypesAndInfos[I].first) QualType(Record.readType());
2731 TypesAndInfos[I].second = readTypeSourceInfo();
2732 }
2733 } else {
2734 // Rest of NonTypeTemplateParmDecl.
2735 D->ParameterPack = Record.readInt();
2736 if (Record.readInt())
2737 D->setDefaultArgument(C: Reader.getContext(),
2738 DefArg: Record.readTemplateArgumentLoc());
2739 }
2740}
2741
2742void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
2743 VisitTemplateDecl(D);
2744 D->setDeclaredWithTypename(Record.readBool());
2745 // TemplateParmPosition.
2746 D->setDepth(Record.readInt());
2747 D->setPosition(Record.readInt());
2748 if (D->isExpandedParameterPack()) {
2749 auto **Data = D->getTrailingObjects();
2750 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2751 I != N; ++I)
2752 Data[I] = Record.readTemplateParameterList();
2753 } else {
2754 // Rest of TemplateTemplateParmDecl.
2755 D->ParameterPack = Record.readInt();
2756 if (Record.readInt())
2757 D->setDefaultArgument(C: Reader.getContext(),
2758 DefArg: Record.readTemplateArgumentLoc());
2759 }
2760}
2761
2762void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2763 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2764 mergeRedeclarableTemplate(D, Redecl);
2765}
2766
2767void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
2768 VisitDecl(D);
2769 D->AssertExprAndFailed.setPointer(Record.readExpr());
2770 D->AssertExprAndFailed.setInt(Record.readInt());
2771 D->Message = cast_or_null<StringLiteral>(Val: Record.readExpr());
2772 D->RParenLoc = readSourceLocation();
2773}
2774
2775void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
2776 VisitDecl(D);
2777}
2778
2779void ASTDeclReader::VisitLifetimeExtendedTemporaryDecl(
2780 LifetimeExtendedTemporaryDecl *D) {
2781 VisitDecl(D);
2782 D->ExtendingDecl = readDeclAs<ValueDecl>();
2783 D->ExprWithTemporary = Record.readStmt();
2784 if (Record.readInt()) {
2785 D->Value = new (D->getASTContext()) APValue(Record.readAPValue());
2786 D->getASTContext().addDestruction(Ptr: D->Value);
2787 }
2788 D->ManglingNumber = Record.readInt();
2789 mergeMergeable(D);
2790}
2791
2792void ASTDeclReader::VisitDeclContext(DeclContext *DC,
2793 LookupBlockOffsets &Offsets) {
2794 Offsets.LexicalOffset = ReadLocalOffset();
2795 Offsets.VisibleOffset = ReadLocalOffset();
2796 Offsets.ModuleLocalOffset = ReadLocalOffset();
2797 Offsets.TULocalOffset = ReadLocalOffset();
2798}
2799
2800template <typename T>
2801RedeclarableResult ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
2802 GlobalDeclID FirstDeclID = readDeclID();
2803 Decl *MergeWith = nullptr;
2804
2805 bool IsKeyDecl = ThisDeclID == FirstDeclID;
2806 bool IsFirstLocalDecl = false;
2807
2808 uint64_t RedeclOffset = 0;
2809
2810 // invalid FirstDeclID indicates that this declaration was the only
2811 // declaration of its entity, and is used for space optimization.
2812 if (FirstDeclID.isInvalid()) {
2813 FirstDeclID = ThisDeclID;
2814 IsKeyDecl = true;
2815 IsFirstLocalDecl = true;
2816 } else if (unsigned N = Record.readInt()) {
2817 // This declaration was the first local declaration, but may have imported
2818 // other declarations.
2819 IsKeyDecl = N == 1;
2820 IsFirstLocalDecl = true;
2821
2822 // We have some declarations that must be before us in our redeclaration
2823 // chain. Read them now, and remember that we ought to merge with one of
2824 // them.
2825 // FIXME: Provide a known merge target to the second and subsequent such
2826 // declaration.
2827 for (unsigned I = 0; I != N - 1; ++I)
2828 MergeWith = readDecl();
2829
2830 RedeclOffset = ReadLocalOffset();
2831 } else {
2832 // This declaration was not the first local declaration. Read the first
2833 // local declaration now, to trigger the import of other redeclarations.
2834 (void)readDecl();
2835 }
2836
2837 auto *FirstDecl = cast_or_null<T>(Reader.GetDecl(ID: FirstDeclID));
2838 if (FirstDecl != D) {
2839 // We delay loading of the redeclaration chain to avoid deeply nested calls.
2840 // We temporarily set the first (canonical) declaration as the previous one
2841 // which is the one that matters and mark the real previous DeclID to be
2842 // loaded & attached later on.
2843 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
2844 D->First = FirstDecl->getCanonicalDecl();
2845 }
2846
2847 auto *DAsT = static_cast<T *>(D);
2848
2849 // Note that we need to load local redeclarations of this decl and build a
2850 // decl chain for them. This must happen *after* we perform the preloading
2851 // above; this ensures that the redeclaration chain is built in the correct
2852 // order.
2853 if (IsFirstLocalDecl)
2854 Reader.PendingDeclChains.push_back(Elt: std::make_pair(DAsT, RedeclOffset));
2855
2856 return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
2857}
2858
2859/// Attempts to merge the given declaration (D) with another declaration
2860/// of the same entity.
2861template <typename T>
2862void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
2863 RedeclarableResult &Redecl) {
2864 // If modules are not available, there is no reason to perform this merge.
2865 if (!Reader.getContext().getLangOpts().Modules)
2866 return;
2867
2868 // If we're not the canonical declaration, we don't need to merge.
2869 if (!DBase->isFirstDecl())
2870 return;
2871
2872 auto *D = static_cast<T *>(DBase);
2873
2874 if (auto *Existing = Redecl.getKnownMergeTarget())
2875 // We already know of an existing declaration we should merge with.
2876 MergeImpl.mergeRedeclarable(D, cast<T>(Existing), Redecl);
2877 else if (FindExistingResult ExistingRes = findExisting(D))
2878 if (T *Existing = ExistingRes)
2879 MergeImpl.mergeRedeclarable(D, Existing, Redecl);
2880}
2881
2882/// Attempt to merge D with a previous declaration of the same lambda, which is
2883/// found by its index within its context declaration, if it has one.
2884///
2885/// We can't look up lambdas in their enclosing lexical or semantic context in
2886/// general, because for lambdas in variables, both of those might be a
2887/// namespace or the translation unit.
2888void ASTDeclMerger::mergeLambda(CXXRecordDecl *D, RedeclarableResult &Redecl,
2889 Decl &Context, unsigned IndexInContext) {
2890 // If modules are not available, there is no reason to perform this merge.
2891 if (!Reader.getContext().getLangOpts().Modules)
2892 return;
2893
2894 // If we're not the canonical declaration, we don't need to merge.
2895 if (!D->isFirstDecl())
2896 return;
2897
2898 if (auto *Existing = Redecl.getKnownMergeTarget())
2899 // We already know of an existing declaration we should merge with.
2900 mergeRedeclarable(D, Existing: cast<TagDecl>(Val: Existing), Redecl);
2901
2902 // Look up this lambda to see if we've seen it before. If so, merge with the
2903 // one we already loaded.
2904 NamedDecl *&Slot = Reader.LambdaDeclarationsForMerging[{
2905 Context.getCanonicalDecl(), IndexInContext}];
2906 if (Slot)
2907 mergeRedeclarable(D, Existing: cast<TagDecl>(Val: Slot), Redecl);
2908 else
2909 Slot = D;
2910}
2911
2912void ASTDeclReader::mergeRedeclarableTemplate(RedeclarableTemplateDecl *D,
2913 RedeclarableResult &Redecl) {
2914 mergeRedeclarable(DBase: D, Redecl);
2915 // If we merged the template with a prior declaration chain, merge the
2916 // common pointer.
2917 // FIXME: Actually merge here, don't just overwrite.
2918 D->Common = D->getCanonicalDecl()->Common;
2919}
2920
2921/// "Cast" to type T, asserting if we don't have an implicit conversion.
2922/// We use this to put code in a template that will only be valid for certain
2923/// instantiations.
2924template<typename T> static T assert_cast(T t) { return t; }
2925template<typename T> static T assert_cast(...) {
2926 llvm_unreachable("bad assert_cast");
2927}
2928
2929/// Merge together the pattern declarations from two template
2930/// declarations.
2931void ASTDeclMerger::mergeTemplatePattern(RedeclarableTemplateDecl *D,
2932 RedeclarableTemplateDecl *Existing,
2933 bool IsKeyDecl) {
2934 auto *DPattern = D->getTemplatedDecl();
2935 auto *ExistingPattern = Existing->getTemplatedDecl();
2936 RedeclarableResult Result(
2937 /*MergeWith*/ ExistingPattern,
2938 DPattern->getCanonicalDecl()->getGlobalID(), IsKeyDecl);
2939
2940 if (auto *DClass = dyn_cast<CXXRecordDecl>(Val: DPattern)) {
2941 // Merge with any existing definition.
2942 // FIXME: This is duplicated in several places. Refactor.
2943 auto *ExistingClass =
2944 cast<CXXRecordDecl>(Val: ExistingPattern)->getCanonicalDecl();
2945 if (auto *DDD = DClass->DefinitionData) {
2946 if (ExistingClass->DefinitionData) {
2947 MergeDefinitionData(D: ExistingClass, MergeDD: std::move(*DDD));
2948 } else {
2949 ExistingClass->DefinitionData = DClass->DefinitionData;
2950 // We may have skipped this before because we thought that DClass
2951 // was the canonical declaration.
2952 Reader.PendingDefinitions.insert(Ptr: DClass);
2953 }
2954 }
2955 DClass->DefinitionData = ExistingClass->DefinitionData;
2956
2957 return mergeRedeclarable(D: DClass, Existing: cast<TagDecl>(Val: ExistingPattern),
2958 Redecl&: Result);
2959 }
2960 if (auto *DFunction = dyn_cast<FunctionDecl>(Val: DPattern))
2961 return mergeRedeclarable(D: DFunction, Existing: cast<FunctionDecl>(Val: ExistingPattern),
2962 Redecl&: Result);
2963 if (auto *DVar = dyn_cast<VarDecl>(Val: DPattern))
2964 return mergeRedeclarable(D: DVar, Existing: cast<VarDecl>(Val: ExistingPattern), Redecl&: Result);
2965 if (auto *DAlias = dyn_cast<TypeAliasDecl>(Val: DPattern))
2966 return mergeRedeclarable(D: DAlias, Existing: cast<TypedefNameDecl>(Val: ExistingPattern),
2967 Redecl&: Result);
2968 llvm_unreachable("merged an unknown kind of redeclarable template");
2969}
2970
2971/// Attempts to merge the given declaration (D) with another declaration
2972/// of the same entity.
2973template <typename T>
2974void ASTDeclMerger::mergeRedeclarableImpl(Redeclarable<T> *DBase, T *Existing,
2975 GlobalDeclID KeyDeclID) {
2976 auto *D = static_cast<T *>(DBase);
2977 T *ExistingCanon = Existing->getCanonicalDecl();
2978 T *DCanon = D->getCanonicalDecl();
2979 if (ExistingCanon != DCanon) {
2980 // Have our redeclaration link point back at the canonical declaration
2981 // of the existing declaration, so that this declaration has the
2982 // appropriate canonical declaration.
2983 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
2984 D->First = ExistingCanon;
2985 ExistingCanon->Used |= D->Used;
2986 D->Used = false;
2987
2988 bool IsKeyDecl = KeyDeclID.isValid();
2989
2990 // When we merge a template, merge its pattern.
2991 if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
2992 mergeTemplatePattern(
2993 D: DTemplate, Existing: assert_cast<RedeclarableTemplateDecl *>(ExistingCanon),
2994 IsKeyDecl);
2995
2996 // If this declaration is a key declaration, make a note of that.
2997 if (IsKeyDecl)
2998 Reader.KeyDecls[ExistingCanon].push_back(KeyDeclID);
2999 }
3000}
3001
3002/// ODR-like semantics for C/ObjC allow us to merge tag types and a structural
3003/// check in Sema guarantees the types can be merged (see C11 6.2.7/1 or C89
3004/// 6.1.2.6/1). Although most merging is done in Sema, we need to guarantee
3005/// that some types are mergeable during deserialization, otherwise name
3006/// lookup fails. This is the case for EnumConstantDecl.
3007static bool allowODRLikeMergeInC(NamedDecl *ND) {
3008 if (!ND)
3009 return false;
3010 // TODO: implement merge for other necessary decls.
3011 if (isa<EnumConstantDecl, FieldDecl, IndirectFieldDecl>(Val: ND))
3012 return true;
3013 return false;
3014}
3015
3016/// Attempts to merge LifetimeExtendedTemporaryDecl with
3017/// identical class definitions from two different modules.
3018void ASTDeclReader::mergeMergeable(LifetimeExtendedTemporaryDecl *D) {
3019 // If modules are not available, there is no reason to perform this merge.
3020 if (!Reader.getContext().getLangOpts().Modules)
3021 return;
3022
3023 LifetimeExtendedTemporaryDecl *LETDecl = D;
3024
3025 LifetimeExtendedTemporaryDecl *&LookupResult =
3026 Reader.LETemporaryForMerging[std::make_pair(
3027 x: LETDecl->getExtendingDecl(), y: LETDecl->getManglingNumber())];
3028 if (LookupResult)
3029 Reader.getContext().setPrimaryMergedDecl(D: LETDecl,
3030 Primary: LookupResult->getCanonicalDecl());
3031 else
3032 LookupResult = LETDecl;
3033}
3034
3035/// Attempts to merge the given declaration (D) with another declaration
3036/// of the same entity, for the case where the entity is not actually
3037/// redeclarable. This happens, for instance, when merging the fields of
3038/// identical class definitions from two different modules.
3039template<typename T>
3040void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
3041 // If modules are not available, there is no reason to perform this merge.
3042 if (!Reader.getContext().getLangOpts().Modules)
3043 return;
3044
3045 // ODR-based merging is performed in C++ and in some cases (tag types) in C.
3046 // Note that C identically-named things in different translation units are
3047 // not redeclarations, but may still have compatible types, where ODR-like
3048 // semantics may apply.
3049 if (!Reader.getContext().getLangOpts().CPlusPlus &&
3050 !allowODRLikeMergeInC(dyn_cast<NamedDecl>(static_cast<T*>(D))))
3051 return;
3052
3053 if (FindExistingResult ExistingRes = findExisting(D: static_cast<T*>(D)))
3054 if (T *Existing = ExistingRes)
3055 Reader.getContext().setPrimaryMergedDecl(D: static_cast<T *>(D),
3056 Primary: Existing->getCanonicalDecl());
3057}
3058
3059void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
3060 Record.readOMPChildren(Data: D->Data);
3061 VisitDecl(D);
3062}
3063
3064void ASTDeclReader::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3065 Record.readOMPChildren(Data: D->Data);
3066 VisitDecl(D);
3067}
3068
3069void ASTDeclReader::VisitOMPRequiresDecl(OMPRequiresDecl * D) {
3070 Record.readOMPChildren(Data: D->Data);
3071 VisitDecl(D);
3072}
3073
3074void ASTDeclReader::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
3075 VisitValueDecl(VD: D);
3076 D->setLocation(readSourceLocation());
3077 Expr *In = Record.readExpr();
3078 Expr *Out = Record.readExpr();
3079 D->setCombinerData(InE: In, OutE: Out);
3080 Expr *Combiner = Record.readExpr();
3081 D->setCombiner(Combiner);
3082 Expr *Orig = Record.readExpr();
3083 Expr *Priv = Record.readExpr();
3084 D->setInitializerData(OrigE: Orig, PrivE: Priv);
3085 Expr *Init = Record.readExpr();
3086 auto IK = static_cast<OMPDeclareReductionInitKind>(Record.readInt());
3087 D->setInitializer(E: Init, IK);
3088 D->PrevDeclInScope = readDeclID().getRawValue();
3089}
3090
3091void ASTDeclReader::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3092 Record.readOMPChildren(Data: D->Data);
3093 VisitValueDecl(VD: D);
3094 D->VarName = Record.readDeclarationName();
3095 D->PrevDeclInScope = readDeclID().getRawValue();
3096}
3097
3098void ASTDeclReader::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
3099 VisitVarDecl(VD: D);
3100}
3101
3102void ASTDeclReader::VisitOpenACCDeclareDecl(OpenACCDeclareDecl *D) {
3103 VisitDecl(D);
3104 D->DirKind = Record.readEnum<OpenACCDirectiveKind>();
3105 D->DirectiveLoc = Record.readSourceLocation();
3106 D->EndLoc = Record.readSourceLocation();
3107 Record.readOpenACCClauseList(Clauses: D->Clauses);
3108}
3109void ASTDeclReader::VisitOpenACCRoutineDecl(OpenACCRoutineDecl *D) {
3110 VisitDecl(D);
3111 D->DirKind = Record.readEnum<OpenACCDirectiveKind>();
3112 D->DirectiveLoc = Record.readSourceLocation();
3113 D->EndLoc = Record.readSourceLocation();
3114 D->ParensLoc = Record.readSourceRange();
3115 D->FuncRef = Record.readExpr();
3116 Record.readOpenACCClauseList(Clauses: D->Clauses);
3117}
3118
3119//===----------------------------------------------------------------------===//
3120// Attribute Reading
3121//===----------------------------------------------------------------------===//
3122
3123namespace {
3124class AttrReader {
3125 ASTRecordReader &Reader;
3126
3127public:
3128 AttrReader(ASTRecordReader &Reader) : Reader(Reader) {}
3129
3130 uint64_t readInt() {
3131 return Reader.readInt();
3132 }
3133
3134 bool readBool() { return Reader.readBool(); }
3135
3136 SourceRange readSourceRange() {
3137 return Reader.readSourceRange();
3138 }
3139
3140 SourceLocation readSourceLocation() {
3141 return Reader.readSourceLocation();
3142 }
3143
3144 Expr *readExpr() { return Reader.readExpr(); }
3145
3146 Attr *readAttr() { return Reader.readAttr(); }
3147
3148 std::string readString() {
3149 return Reader.readString();
3150 }
3151
3152 TypeSourceInfo *readTypeSourceInfo() {
3153 return Reader.readTypeSourceInfo();
3154 }
3155
3156 IdentifierInfo *readIdentifier() {
3157 return Reader.readIdentifier();
3158 }
3159
3160 VersionTuple readVersionTuple() {
3161 return Reader.readVersionTuple();
3162 }
3163
3164 OMPTraitInfo *readOMPTraitInfo() { return Reader.readOMPTraitInfo(); }
3165
3166 template <typename T> T *readDeclAs() { return Reader.readDeclAs<T>(); }
3167};
3168}
3169
3170Attr *ASTRecordReader::readAttr() {
3171 AttrReader Record(*this);
3172 auto V = Record.readInt();
3173 if (!V)
3174 return nullptr;
3175
3176 Attr *New = nullptr;
3177 // Kind is stored as a 1-based integer because 0 is used to indicate a null
3178 // Attr pointer.
3179 auto Kind = static_cast<attr::Kind>(V - 1);
3180 ASTContext &Context = getContext();
3181
3182 IdentifierInfo *AttrName = Record.readIdentifier();
3183 IdentifierInfo *ScopeName = Record.readIdentifier();
3184 SourceRange AttrRange = Record.readSourceRange();
3185 SourceLocation ScopeLoc = Record.readSourceLocation();
3186 unsigned ParsedKind = Record.readInt();
3187 unsigned Syntax = Record.readInt();
3188 unsigned SpellingIndex = Record.readInt();
3189 bool IsAlignas = (ParsedKind == AttributeCommonInfo::AT_Aligned &&
3190 Syntax == AttributeCommonInfo::AS_Keyword &&
3191 SpellingIndex == AlignedAttr::Keyword_alignas);
3192 bool IsRegularKeywordAttribute = Record.readBool();
3193
3194 AttributeCommonInfo Info(AttrName, AttributeScopeInfo(ScopeName, ScopeLoc),
3195 AttrRange, AttributeCommonInfo::Kind(ParsedKind),
3196 {AttributeCommonInfo::Syntax(Syntax), SpellingIndex,
3197 IsAlignas, IsRegularKeywordAttribute});
3198
3199#include "clang/Serialization/AttrPCHRead.inc"
3200
3201 assert(New && "Unable to decode attribute?");
3202 return New;
3203}
3204
3205/// Reads attributes from the current stream position.
3206void ASTRecordReader::readAttributes(AttrVec &Attrs) {
3207 for (unsigned I = 0, E = readInt(); I != E; ++I)
3208 if (auto *A = readAttr())
3209 Attrs.push_back(Elt: A);
3210}
3211
3212//===----------------------------------------------------------------------===//
3213// ASTReader Implementation
3214//===----------------------------------------------------------------------===//
3215
3216/// Note that we have loaded the declaration with the given
3217/// Index.
3218///
3219/// This routine notes that this declaration has already been loaded,
3220/// so that future GetDecl calls will return this declaration rather
3221/// than trying to load a new declaration.
3222inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
3223 assert(!DeclsLoaded[Index] && "Decl loaded twice?");
3224 DeclsLoaded[Index] = D;
3225}
3226
3227/// Determine whether the consumer will be interested in seeing
3228/// this declaration (via HandleTopLevelDecl).
3229///
3230/// This routine should return true for anything that might affect
3231/// code generation, e.g., inline function definitions, Objective-C
3232/// declarations with metadata, etc.
3233bool ASTReader::isConsumerInterestedIn(Decl *D) {
3234 // An ObjCMethodDecl is never considered as "interesting" because its
3235 // implementation container always is.
3236
3237 // An ImportDecl or VarDecl imported from a module map module will get
3238 // emitted when we import the relevant module.
3239 if (isPartOfPerModuleInitializer(D)) {
3240 auto *M = D->getImportedOwningModule();
3241 if (M && M->Kind == Module::ModuleMapModule &&
3242 getContext().DeclMustBeEmitted(D))
3243 return false;
3244 }
3245
3246 if (isa<FileScopeAsmDecl, TopLevelStmtDecl, ObjCProtocolDecl, ObjCImplDecl,
3247 ImportDecl, PragmaCommentDecl, PragmaDetectMismatchDecl>(Val: D))
3248 return true;
3249 if (isa<OMPThreadPrivateDecl, OMPDeclareReductionDecl, OMPDeclareMapperDecl,
3250 OMPAllocateDecl, OMPRequiresDecl>(Val: D))
3251 return !D->getDeclContext()->isFunctionOrMethod();
3252 if (const auto *Var = dyn_cast<VarDecl>(Val: D))
3253 return Var->isFileVarDecl() &&
3254 (Var->isThisDeclarationADefinition() == VarDecl::Definition ||
3255 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD: Var));
3256 if (const auto *Func = dyn_cast<FunctionDecl>(Val: D))
3257 return Func->doesThisDeclarationHaveABody() || PendingBodies.count(Key: D);
3258
3259 if (auto *ES = D->getASTContext().getExternalSource())
3260 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
3261 return true;
3262
3263 return false;
3264}
3265
3266/// Get the correct cursor and offset for loading a declaration.
3267ASTReader::RecordLocation ASTReader::DeclCursorForID(GlobalDeclID ID,
3268 SourceLocation &Loc) {
3269 ModuleFile *M = getOwningModuleFile(ID);
3270 assert(M);
3271 unsigned LocalDeclIndex = ID.getLocalDeclIndex();
3272 const DeclOffset &DOffs = M->DeclOffsets[LocalDeclIndex];
3273 Loc = ReadSourceLocation(MF&: *M, Raw: DOffs.getRawLoc());
3274 return RecordLocation(M, DOffs.getBitOffset(DeclTypesBlockStartOffset: M->DeclsBlockStartOffset));
3275}
3276
3277ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
3278 auto I = GlobalBitOffsetsMap.find(K: GlobalOffset);
3279
3280 assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
3281 return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
3282}
3283
3284uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint64_t LocalOffset) {
3285 return LocalOffset + M.GlobalBitOffset;
3286}
3287
3288CXXRecordDecl *
3289ASTDeclReader::getOrFakePrimaryClassDefinition(ASTReader &Reader,
3290 CXXRecordDecl *RD) {
3291 // Try to dig out the definition.
3292 auto *DD = RD->DefinitionData;
3293 if (!DD)
3294 DD = RD->getCanonicalDecl()->DefinitionData;
3295
3296 // If there's no definition yet, then DC's definition is added by an update
3297 // record, but we've not yet loaded that update record. In this case, we
3298 // commit to DC being the canonical definition now, and will fix this when
3299 // we load the update record.
3300 if (!DD) {
3301 DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);
3302 RD->setCompleteDefinition(true);
3303 RD->DefinitionData = DD;
3304 RD->getCanonicalDecl()->DefinitionData = DD;
3305
3306 // Track that we did this horrible thing so that we can fix it later.
3307 Reader.PendingFakeDefinitionData.insert(
3308 KV: std::make_pair(x&: DD, y: ASTReader::PendingFakeDefinitionKind::Fake));
3309 }
3310
3311 return DD->Definition;
3312}
3313
3314/// Find the context in which we should search for previous declarations when
3315/// looking for declarations to merge.
3316DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
3317 DeclContext *DC) {
3318 if (auto *ND = dyn_cast<NamespaceDecl>(Val: DC))
3319 return ND->getFirstDecl();
3320
3321 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
3322 return getOrFakePrimaryClassDefinition(Reader, RD);
3323
3324 if (auto *RD = dyn_cast<RecordDecl>(Val: DC))
3325 return RD->getDefinition();
3326
3327 if (auto *ED = dyn_cast<EnumDecl>(Val: DC))
3328 return ED->getDefinition();
3329
3330 if (auto *OID = dyn_cast<ObjCInterfaceDecl>(Val: DC))
3331 return OID->getDefinition();
3332
3333 // We can see the TU here only if we have no Sema object. It is possible
3334 // we're in clang-repl so we still need to get the primary context.
3335 if (auto *TU = dyn_cast<TranslationUnitDecl>(Val: DC))
3336 return TU->getPrimaryContext();
3337
3338 return nullptr;
3339}
3340
3341ASTDeclReader::FindExistingResult::~FindExistingResult() {
3342 // Record that we had a typedef name for linkage whether or not we merge
3343 // with that declaration.
3344 if (TypedefNameForLinkage) {
3345 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3346 Reader.ImportedTypedefNamesForLinkage.insert(
3347 KV: std::make_pair(x: std::make_pair(x&: DC, y&: TypedefNameForLinkage), y&: New));
3348 return;
3349 }
3350
3351 if (!AddResult || Existing)
3352 return;
3353
3354 DeclarationName Name = New->getDeclName();
3355 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3356 if (needsAnonymousDeclarationNumber(D: New)) {
3357 setAnonymousDeclForMerging(Reader, DC: New->getLexicalDeclContext(),
3358 Index: AnonymousDeclNumber, D: New);
3359 } else if (DC->isTranslationUnit() &&
3360 !Reader.getContext().getLangOpts().CPlusPlus) {
3361 if (Reader.getIdResolver().tryAddTopLevelDecl(D: New, Name))
3362 Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
3363 .push_back(Elt: New);
3364 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3365 // Add the declaration to its redeclaration context so later merging
3366 // lookups will find it.
3367 MergeDC->makeDeclVisibleInContextImpl(D: New, /*Internal*/true);
3368 }
3369}
3370
3371/// Find the declaration that should be merged into, given the declaration found
3372/// by name lookup. If we're merging an anonymous declaration within a typedef,
3373/// we need a matching typedef, and we merge with the type inside it.
3374static NamedDecl *getDeclForMerging(NamedDecl *Found,
3375 bool IsTypedefNameForLinkage) {
3376 if (!IsTypedefNameForLinkage)
3377 return Found;
3378
3379 // If we found a typedef declaration that gives a name to some other
3380 // declaration, then we want that inner declaration. Declarations from
3381 // AST files are handled via ImportedTypedefNamesForLinkage.
3382 if (Found->isFromASTFile())
3383 return nullptr;
3384
3385 if (auto *TND = dyn_cast<TypedefNameDecl>(Val: Found))
3386 return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
3387
3388 return nullptr;
3389}
3390
3391/// Find the declaration to use to populate the anonymous declaration table
3392/// for the given lexical DeclContext. We only care about finding local
3393/// definitions of the context; we'll merge imported ones as we go.
3394DeclContext *
3395ASTDeclReader::getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC) {
3396 // For classes, we track the definition as we merge.
3397 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: LexicalDC)) {
3398 auto *DD = RD->getCanonicalDecl()->DefinitionData;
3399 return DD ? DD->Definition : nullptr;
3400 } else if (auto *OID = dyn_cast<ObjCInterfaceDecl>(Val: LexicalDC)) {
3401 return OID->getCanonicalDecl()->getDefinition();
3402 }
3403
3404 // For anything else, walk its merged redeclarations looking for a definition.
3405 // Note that we can't just call getDefinition here because the redeclaration
3406 // chain isn't wired up.
3407 for (auto *D : merged_redecls(D: cast<Decl>(Val: LexicalDC))) {
3408 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
3409 if (FD->isThisDeclarationADefinition())
3410 return FD;
3411 if (auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
3412 if (MD->isThisDeclarationADefinition())
3413 return MD;
3414 if (auto *RD = dyn_cast<RecordDecl>(Val: D))
3415 if (RD->isThisDeclarationADefinition())
3416 return RD;
3417 }
3418
3419 // No merged definition yet.
3420 return nullptr;
3421}
3422
3423NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
3424 DeclContext *DC,
3425 unsigned Index) {
3426 // If the lexical context has been merged, look into the now-canonical
3427 // definition.
3428 auto *CanonDC = cast<Decl>(Val: DC)->getCanonicalDecl();
3429
3430 // If we've seen this before, return the canonical declaration.
3431 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3432 if (Index < Previous.size() && Previous[Index])
3433 return Previous[Index];
3434
3435 // If this is the first time, but we have parsed a declaration of the context,
3436 // build the anonymous declaration list from the parsed declaration.
3437 auto *PrimaryDC = getPrimaryDCForAnonymousDecl(LexicalDC: DC);
3438 if (PrimaryDC && !cast<Decl>(Val: PrimaryDC)->isFromASTFile()) {
3439 numberAnonymousDeclsWithin(DC: PrimaryDC, Visit: [&](NamedDecl *ND, unsigned Number) {
3440 if (Previous.size() == Number)
3441 Previous.push_back(Elt: cast<NamedDecl>(Val: ND->getCanonicalDecl()));
3442 else
3443 Previous[Number] = cast<NamedDecl>(Val: ND->getCanonicalDecl());
3444 });
3445 }
3446
3447 return Index < Previous.size() ? Previous[Index] : nullptr;
3448}
3449
3450void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
3451 DeclContext *DC, unsigned Index,
3452 NamedDecl *D) {
3453 auto *CanonDC = cast<Decl>(Val: DC)->getCanonicalDecl();
3454
3455 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3456 if (Index >= Previous.size())
3457 Previous.resize(N: Index + 1);
3458 if (!Previous[Index])
3459 Previous[Index] = D;
3460}
3461
3462ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
3463 DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
3464 : D->getDeclName();
3465
3466 if (!Name && !needsAnonymousDeclarationNumber(D)) {
3467 // Don't bother trying to find unnamed declarations that are in
3468 // unmergeable contexts.
3469 FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
3470 AnonymousDeclNumber, TypedefNameForLinkage);
3471 Result.suppress();
3472 return Result;
3473 }
3474
3475 ASTContext &C = Reader.getContext();
3476 DeclContext *DC = D->getDeclContext()->getRedeclContext();
3477 if (TypedefNameForLinkage) {
3478 auto It = Reader.ImportedTypedefNamesForLinkage.find(
3479 Val: std::make_pair(x&: DC, y&: TypedefNameForLinkage));
3480 if (It != Reader.ImportedTypedefNamesForLinkage.end())
3481 if (C.isSameEntity(X: It->second, Y: D))
3482 return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
3483 TypedefNameForLinkage);
3484 // Go on to check in other places in case an existing typedef name
3485 // was not imported.
3486 }
3487
3488 if (needsAnonymousDeclarationNumber(D)) {
3489 // This is an anonymous declaration that we may need to merge. Look it up
3490 // in its context by number.
3491 if (auto *Existing = getAnonymousDeclForMerging(
3492 Reader, DC: D->getLexicalDeclContext(), Index: AnonymousDeclNumber))
3493 if (C.isSameEntity(X: Existing, Y: D))
3494 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3495 TypedefNameForLinkage);
3496 } else if (DC->isTranslationUnit() &&
3497 !Reader.getContext().getLangOpts().CPlusPlus) {
3498 IdentifierResolver &IdResolver = Reader.getIdResolver();
3499
3500 // Temporarily consider the identifier to be up-to-date. We don't want to
3501 // cause additional lookups here.
3502 class UpToDateIdentifierRAII {
3503 IdentifierInfo *II;
3504 bool WasOutToDate = false;
3505
3506 public:
3507 explicit UpToDateIdentifierRAII(IdentifierInfo *II) : II(II) {
3508 if (II) {
3509 WasOutToDate = II->isOutOfDate();
3510 if (WasOutToDate)
3511 II->setOutOfDate(false);
3512 }
3513 }
3514
3515 ~UpToDateIdentifierRAII() {
3516 if (WasOutToDate)
3517 II->setOutOfDate(true);
3518 }
3519 } UpToDate(Name.getAsIdentifierInfo());
3520
3521 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
3522 IEnd = IdResolver.end();
3523 I != IEnd; ++I) {
3524 if (NamedDecl *Existing = getDeclForMerging(Found: *I, IsTypedefNameForLinkage: TypedefNameForLinkage))
3525 if (C.isSameEntity(X: Existing, Y: D))
3526 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3527 TypedefNameForLinkage);
3528 }
3529 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3530 DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
3531 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
3532 if (NamedDecl *Existing = getDeclForMerging(Found: *I, IsTypedefNameForLinkage: TypedefNameForLinkage))
3533 if (C.isSameEntity(X: Existing, Y: D))
3534 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3535 TypedefNameForLinkage);
3536 }
3537 } else {
3538 // Not in a mergeable context.
3539 return FindExistingResult(Reader);
3540 }
3541
3542 // If this declaration is from a merged context, make a note that we need to
3543 // check that the canonical definition of that context contains the decl.
3544 //
3545 // Note that we don't perform ODR checks for decls from the global module
3546 // fragment.
3547 //
3548 // FIXME: We should do something similar if we merge two definitions of the
3549 // same template specialization into the same CXXRecordDecl.
3550 auto MergedDCIt = Reader.MergedDeclContexts.find(Val: D->getLexicalDeclContext());
3551 if (MergedDCIt != Reader.MergedDeclContexts.end() &&
3552 !shouldSkipCheckingODR(D) && MergedDCIt->second == D->getDeclContext() &&
3553 !shouldSkipCheckingODR(D: cast<Decl>(Val: D->getDeclContext())))
3554 Reader.PendingOdrMergeChecks.push_back(Elt: D);
3555
3556 return FindExistingResult(Reader, D, /*Existing=*/nullptr,
3557 AnonymousDeclNumber, TypedefNameForLinkage);
3558}
3559
3560template<typename DeclT>
3561Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
3562 return D->RedeclLink.getLatestNotUpdated();
3563}
3564
3565Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
3566 llvm_unreachable("getMostRecentDecl on non-redeclarable declaration");
3567}
3568
3569Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
3570 assert(D);
3571
3572 switch (D->getKind()) {
3573#define ABSTRACT_DECL(TYPE)
3574#define DECL(TYPE, BASE) \
3575 case Decl::TYPE: \
3576 return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
3577#include "clang/AST/DeclNodes.inc"
3578 }
3579 llvm_unreachable("unknown decl kind");
3580}
3581
3582Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
3583 return ASTDeclReader::getMostRecentDecl(D: D->getCanonicalDecl());
3584}
3585
3586namespace {
3587void mergeInheritableAttributes(ASTReader &Reader, Decl *D, Decl *Previous) {
3588 InheritableAttr *NewAttr = nullptr;
3589 ASTContext &Context = Reader.getContext();
3590 const auto *IA = Previous->getAttr<MSInheritanceAttr>();
3591
3592 if (IA && !D->hasAttr<MSInheritanceAttr>()) {
3593 NewAttr = cast<InheritableAttr>(Val: IA->clone(C&: Context));
3594 NewAttr->setInherited(true);
3595 D->addAttr(A: NewAttr);
3596 }
3597
3598 const auto *AA = Previous->getAttr<AvailabilityAttr>();
3599 if (AA && !D->hasAttr<AvailabilityAttr>()) {
3600 NewAttr = AA->clone(C&: Context);
3601 NewAttr->setInherited(true);
3602 D->addAttr(A: NewAttr);
3603 }
3604}
3605} // namespace
3606
3607template<typename DeclT>
3608void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3609 Redeclarable<DeclT> *D,
3610 Decl *Previous, Decl *Canon) {
3611 D->RedeclLink.setPrevious(cast<DeclT>(Previous));
3612 D->First = cast<DeclT>(Previous)->First;
3613}
3614
3615namespace clang {
3616
3617template<>
3618void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3619 Redeclarable<VarDecl> *D,
3620 Decl *Previous, Decl *Canon) {
3621 auto *VD = static_cast<VarDecl *>(D);
3622 auto *PrevVD = cast<VarDecl>(Val: Previous);
3623 D->RedeclLink.setPrevious(PrevVD);
3624 D->First = PrevVD->First;
3625
3626 // We should keep at most one definition on the chain.
3627 // FIXME: Cache the definition once we've found it. Building a chain with
3628 // N definitions currently takes O(N^2) time here.
3629 if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {
3630 for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {
3631 if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {
3632 Reader.mergeDefinitionVisibility(Def: CurD, MergedDef: VD);
3633 VD->demoteThisDefinitionToDeclaration();
3634 break;
3635 }
3636 }
3637 }
3638}
3639
3640static bool isUndeducedReturnType(QualType T) {
3641 auto *DT = T->getContainedDeducedType();
3642 return DT && !DT->isDeduced();
3643}
3644
3645template<>
3646void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3647 Redeclarable<FunctionDecl> *D,
3648 Decl *Previous, Decl *Canon) {
3649 auto *FD = static_cast<FunctionDecl *>(D);
3650 auto *PrevFD = cast<FunctionDecl>(Val: Previous);
3651
3652 FD->RedeclLink.setPrevious(PrevFD);
3653 FD->First = PrevFD->First;
3654
3655 // If the previous declaration is an inline function declaration, then this
3656 // declaration is too.
3657 if (PrevFD->isInlined() != FD->isInlined()) {
3658 // FIXME: [dcl.fct.spec]p4:
3659 // If a function with external linkage is declared inline in one
3660 // translation unit, it shall be declared inline in all translation
3661 // units in which it appears.
3662 //
3663 // Be careful of this case:
3664 //
3665 // module A:
3666 // template<typename T> struct X { void f(); };
3667 // template<typename T> inline void X<T>::f() {}
3668 //
3669 // module B instantiates the declaration of X<int>::f
3670 // module C instantiates the definition of X<int>::f
3671 //
3672 // If module B and C are merged, we do not have a violation of this rule.
3673 FD->setImplicitlyInline(true);
3674 }
3675
3676 auto *FPT = FD->getType()->getAs<FunctionProtoType>();
3677 auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
3678 if (FPT && PrevFPT) {
3679 // If we need to propagate an exception specification along the redecl
3680 // chain, make a note of that so that we can do so later.
3681 bool IsUnresolved = isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType());
3682 bool WasUnresolved =
3683 isUnresolvedExceptionSpec(ESpecType: PrevFPT->getExceptionSpecType());
3684 if (IsUnresolved != WasUnresolved)
3685 Reader.PendingExceptionSpecUpdates.insert(
3686 KV: {Canon, IsUnresolved ? PrevFD : FD});
3687
3688 // If we need to propagate a deduced return type along the redecl chain,
3689 // make a note of that so that we can do it later.
3690 bool IsUndeduced = isUndeducedReturnType(T: FPT->getReturnType());
3691 bool WasUndeduced = isUndeducedReturnType(T: PrevFPT->getReturnType());
3692 if (IsUndeduced != WasUndeduced)
3693 Reader.PendingDeducedTypeUpdates.insert(
3694 KV: {cast<FunctionDecl>(Val: Canon),
3695 (IsUndeduced ? PrevFPT : FPT)->getReturnType()});
3696 }
3697}
3698
3699} // namespace clang
3700
3701void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
3702 llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
3703}
3704
3705/// Inherit the default template argument from \p From to \p To. Returns
3706/// \c false if there is no default template for \p From.
3707template <typename ParmDecl>
3708static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,
3709 Decl *ToD) {
3710 auto *To = cast<ParmDecl>(ToD);
3711 if (!From->hasDefaultArgument())
3712 return false;
3713 To->setInheritedDefaultArgument(Context, From);
3714 return true;
3715}
3716
3717static void inheritDefaultTemplateArguments(ASTContext &Context,
3718 TemplateDecl *From,
3719 TemplateDecl *To) {
3720 auto *FromTP = From->getTemplateParameters();
3721 auto *ToTP = To->getTemplateParameters();
3722 assert(FromTP->size() == ToTP->size() && "merged mismatched templates?");
3723
3724 for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {
3725 NamedDecl *FromParam = FromTP->getParam(Idx: I);
3726 NamedDecl *ToParam = ToTP->getParam(Idx: I);
3727
3728 if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(Val: FromParam))
3729 inheritDefaultTemplateArgument(Context, From: FTTP, ToD: ToParam);
3730 else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: FromParam))
3731 inheritDefaultTemplateArgument(Context, From: FNTTP, ToD: ToParam);
3732 else
3733 inheritDefaultTemplateArgument(
3734 Context, From: cast<TemplateTemplateParmDecl>(Val: FromParam), ToD: ToParam);
3735 }
3736}
3737
3738// [basic.link]/p10:
3739// If two declarations of an entity are attached to different modules,
3740// the program is ill-formed;
3741void ASTDeclReader::checkMultipleDefinitionInNamedModules(ASTReader &Reader,
3742 Decl *D,
3743 Decl *Previous) {
3744 // If it is previous implcitly introduced, it is not meaningful to
3745 // diagnose it.
3746 if (Previous->isImplicit())
3747 return;
3748
3749 // FIXME: Get rid of the enumeration of decl types once we have an appropriate
3750 // abstract for decls of an entity. e.g., the namespace decl and using decl
3751 // doesn't introduce an entity.
3752 if (!isa<VarDecl, FunctionDecl, TagDecl, RedeclarableTemplateDecl>(Val: Previous))
3753 return;
3754
3755 // Skip implicit instantiations since it may give false positive diagnostic
3756 // messages.
3757 // FIXME: Maybe this shows the implicit instantiations may have incorrect
3758 // module owner ships. But given we've finished the compilation of a module,
3759 // how can we add new entities to that module?
3760 if (isa<VarTemplateSpecializationDecl>(Val: Previous))
3761 return;
3762 if (isa<ClassTemplateSpecializationDecl>(Val: Previous))
3763 return;
3764 if (auto *Func = dyn_cast<FunctionDecl>(Val: Previous);
3765 Func && Func->getTemplateSpecializationInfo())
3766 return;
3767
3768 // The module ownership of in-class friend declaration is not straightforward.
3769 // Avoid diagnosing such cases.
3770 if (D->getFriendObjectKind() || Previous->getFriendObjectKind())
3771 return;
3772
3773 // Skip diagnosing in-class declarations.
3774 if (!Previous->getLexicalDeclContext()
3775 ->getNonTransparentContext()
3776 ->isFileContext() ||
3777 !D->getLexicalDeclContext()->getNonTransparentContext()->isFileContext())
3778 return;
3779
3780 Module *M = Previous->getOwningModule();
3781 if (!M)
3782 return;
3783
3784 // We only forbids merging decls within named modules.
3785 if (!M->isNamedModule()) {
3786 // Try to warn the case that we merged decls from global module.
3787 if (!M->isGlobalModule())
3788 return;
3789
3790 if (D->getOwningModule() &&
3791 M->getTopLevelModule() == D->getOwningModule()->getTopLevelModule())
3792 return;
3793
3794 Reader.PendingWarningForDuplicatedDefsInModuleUnits.push_back(
3795 Elt: {D, Previous});
3796 return;
3797 }
3798
3799 // It is fine if they are in the same module.
3800 if (Reader.getContext().isInSameModule(M1: M, M2: D->getOwningModule()))
3801 return;
3802
3803 Reader.Diag(Loc: Previous->getLocation(),
3804 DiagID: diag::err_multiple_decl_in_different_modules)
3805 << cast<NamedDecl>(Val: Previous) << M->Name;
3806 Reader.Diag(Loc: D->getLocation(), DiagID: diag::note_also_found);
3807}
3808
3809void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
3810 Decl *Previous, Decl *Canon) {
3811 assert(D && Previous);
3812
3813 switch (D->getKind()) {
3814#define ABSTRACT_DECL(TYPE)
3815#define DECL(TYPE, BASE) \
3816 case Decl::TYPE: \
3817 attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
3818 break;
3819#include "clang/AST/DeclNodes.inc"
3820 }
3821
3822 checkMultipleDefinitionInNamedModules(Reader, D, Previous);
3823
3824 // If the declaration was visible in one module, a redeclaration of it in
3825 // another module remains visible even if it wouldn't be visible by itself.
3826 //
3827 // FIXME: In this case, the declaration should only be visible if a module
3828 // that makes it visible has been imported.
3829 D->IdentifierNamespace |=
3830 Previous->IdentifierNamespace &
3831 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3832
3833 // If the declaration declares a template, it may inherit default arguments
3834 // from the previous declaration.
3835 if (auto *TD = dyn_cast<TemplateDecl>(Val: D))
3836 inheritDefaultTemplateArguments(Context&: Reader.getContext(),
3837 From: cast<TemplateDecl>(Val: Previous), To: TD);
3838
3839 // If any of the declaration in the chain contains an Inheritable attribute,
3840 // it needs to be added to all the declarations in the redeclarable chain.
3841 // FIXME: Only the logic of merging MSInheritableAttr is present, it should
3842 // be extended for all inheritable attributes.
3843 mergeInheritableAttributes(Reader, D, Previous);
3844}
3845
3846template<typename DeclT>
3847void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
3848 D->RedeclLink.setLatest(cast<DeclT>(Latest));
3849}
3850
3851void ASTDeclReader::attachLatestDeclImpl(...) {
3852 llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
3853}
3854
3855void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
3856 assert(D && Latest);
3857
3858 switch (D->getKind()) {
3859#define ABSTRACT_DECL(TYPE)
3860#define DECL(TYPE, BASE) \
3861 case Decl::TYPE: \
3862 attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
3863 break;
3864#include "clang/AST/DeclNodes.inc"
3865 }
3866}
3867
3868template<typename DeclT>
3869void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
3870 D->RedeclLink.markIncomplete();
3871}
3872
3873void ASTDeclReader::markIncompleteDeclChainImpl(...) {
3874 llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
3875}
3876
3877void ASTReader::markIncompleteDeclChain(Decl *D) {
3878 switch (D->getKind()) {
3879#define ABSTRACT_DECL(TYPE)
3880#define DECL(TYPE, BASE) \
3881 case Decl::TYPE: \
3882 ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
3883 break;
3884#include "clang/AST/DeclNodes.inc"
3885 }
3886}
3887
3888/// Read the declaration at the given offset from the AST file.
3889Decl *ASTReader::ReadDeclRecord(GlobalDeclID ID) {
3890 SourceLocation DeclLoc;
3891 RecordLocation Loc = DeclCursorForID(ID, Loc&: DeclLoc);
3892 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3893 // Keep track of where we are in the stream, then jump back there
3894 // after reading this declaration.
3895 SavedStreamPosition SavedPosition(DeclsCursor);
3896
3897 ReadingKindTracker ReadingKind(Read_Decl, *this);
3898
3899 // Note that we are loading a declaration record.
3900 Deserializing ADecl(this);
3901
3902 auto Fail = [](const char *what, llvm::Error &&Err) {
3903 llvm::report_fatal_error(reason: Twine("ASTReader::readDeclRecord failed ") + what +
3904 ": " + toString(E: std::move(Err)));
3905 };
3906
3907 if (llvm::Error JumpFailed = DeclsCursor.JumpToBit(BitNo: Loc.Offset))
3908 Fail("jumping", std::move(JumpFailed));
3909 ASTRecordReader Record(*this, *Loc.F);
3910 ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);
3911 Expected<unsigned> MaybeCode = DeclsCursor.ReadCode();
3912 if (!MaybeCode)
3913 Fail("reading code", MaybeCode.takeError());
3914 unsigned Code = MaybeCode.get();
3915
3916 ASTContext &Context = getContext();
3917 Decl *D = nullptr;
3918 Expected<unsigned> MaybeDeclCode = Record.readRecord(Cursor&: DeclsCursor, AbbrevID: Code);
3919 if (!MaybeDeclCode)
3920 llvm::report_fatal_error(
3921 reason: Twine("ASTReader::readDeclRecord failed reading decl code: ") +
3922 toString(E: MaybeDeclCode.takeError()));
3923
3924 switch ((DeclCode)MaybeDeclCode.get()) {
3925 case DECL_CONTEXT_LEXICAL:
3926 case DECL_CONTEXT_VISIBLE:
3927 case DECL_CONTEXT_MODULE_LOCAL_VISIBLE:
3928 case DECL_CONTEXT_TU_LOCAL_VISIBLE:
3929 case DECL_SPECIALIZATIONS:
3930 case DECL_PARTIAL_SPECIALIZATIONS:
3931 llvm_unreachable("Record cannot be de-serialized with readDeclRecord");
3932 case DECL_TYPEDEF:
3933 D = TypedefDecl::CreateDeserialized(C&: Context, ID);
3934 break;
3935 case DECL_TYPEALIAS:
3936 D = TypeAliasDecl::CreateDeserialized(C&: Context, ID);
3937 break;
3938 case DECL_ENUM:
3939 D = EnumDecl::CreateDeserialized(C&: Context, ID);
3940 break;
3941 case DECL_RECORD:
3942 D = RecordDecl::CreateDeserialized(C: Context, ID);
3943 break;
3944 case DECL_ENUM_CONSTANT:
3945 D = EnumConstantDecl::CreateDeserialized(C&: Context, ID);
3946 break;
3947 case DECL_FUNCTION:
3948 D = FunctionDecl::CreateDeserialized(C&: Context, ID);
3949 break;
3950 case DECL_LINKAGE_SPEC:
3951 D = LinkageSpecDecl::CreateDeserialized(C&: Context, ID);
3952 break;
3953 case DECL_EXPORT:
3954 D = ExportDecl::CreateDeserialized(C&: Context, ID);
3955 break;
3956 case DECL_LABEL:
3957 D = LabelDecl::CreateDeserialized(C&: Context, ID);
3958 break;
3959 case DECL_NAMESPACE:
3960 D = NamespaceDecl::CreateDeserialized(C&: Context, ID);
3961 break;
3962 case DECL_NAMESPACE_ALIAS:
3963 D = NamespaceAliasDecl::CreateDeserialized(C&: Context, ID);
3964 break;
3965 case DECL_USING:
3966 D = UsingDecl::CreateDeserialized(C&: Context, ID);
3967 break;
3968 case DECL_USING_PACK:
3969 D = UsingPackDecl::CreateDeserialized(C&: Context, ID, NumExpansions: Record.readInt());
3970 break;
3971 case DECL_USING_SHADOW:
3972 D = UsingShadowDecl::CreateDeserialized(C&: Context, ID);
3973 break;
3974 case DECL_USING_ENUM:
3975 D = UsingEnumDecl::CreateDeserialized(C&: Context, ID);
3976 break;
3977 case DECL_CONSTRUCTOR_USING_SHADOW:
3978 D = ConstructorUsingShadowDecl::CreateDeserialized(C&: Context, ID);
3979 break;
3980 case DECL_USING_DIRECTIVE:
3981 D = UsingDirectiveDecl::CreateDeserialized(C&: Context, ID);
3982 break;
3983 case DECL_UNRESOLVED_USING_VALUE:
3984 D = UnresolvedUsingValueDecl::CreateDeserialized(C&: Context, ID);
3985 break;
3986 case DECL_UNRESOLVED_USING_TYPENAME:
3987 D = UnresolvedUsingTypenameDecl::CreateDeserialized(C&: Context, ID);
3988 break;
3989 case DECL_UNRESOLVED_USING_IF_EXISTS:
3990 D = UnresolvedUsingIfExistsDecl::CreateDeserialized(Ctx&: Context, ID);
3991 break;
3992 case DECL_CXX_RECORD:
3993 D = CXXRecordDecl::CreateDeserialized(C: Context, ID);
3994 break;
3995 case DECL_CXX_DEDUCTION_GUIDE:
3996 D = CXXDeductionGuideDecl::CreateDeserialized(C&: Context, ID);
3997 break;
3998 case DECL_CXX_METHOD:
3999 D = CXXMethodDecl::CreateDeserialized(C&: Context, ID);
4000 break;
4001 case DECL_CXX_CONSTRUCTOR:
4002 D = CXXConstructorDecl::CreateDeserialized(C&: Context, ID, AllocKind: Record.readInt());
4003 break;
4004 case DECL_CXX_DESTRUCTOR:
4005 D = CXXDestructorDecl::CreateDeserialized(C&: Context, ID);
4006 break;
4007 case DECL_CXX_CONVERSION:
4008 D = CXXConversionDecl::CreateDeserialized(C&: Context, ID);
4009 break;
4010 case DECL_ACCESS_SPEC:
4011 D = AccessSpecDecl::CreateDeserialized(C&: Context, ID);
4012 break;
4013 case DECL_FRIEND:
4014 D = FriendDecl::CreateDeserialized(C&: Context, ID, FriendTypeNumTPLists: Record.readInt());
4015 break;
4016 case DECL_FRIEND_TEMPLATE:
4017 D = FriendTemplateDecl::CreateDeserialized(C&: Context, ID);
4018 break;
4019 case DECL_CLASS_TEMPLATE:
4020 D = ClassTemplateDecl::CreateDeserialized(C&: Context, ID);
4021 break;
4022 case DECL_CLASS_TEMPLATE_SPECIALIZATION:
4023 D = ClassTemplateSpecializationDecl::CreateDeserialized(C&: Context, ID);
4024 break;
4025 case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
4026 D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(C&: Context, ID);
4027 break;
4028 case DECL_VAR_TEMPLATE:
4029 D = VarTemplateDecl::CreateDeserialized(C&: Context, ID);
4030 break;
4031 case DECL_VAR_TEMPLATE_SPECIALIZATION:
4032 D = VarTemplateSpecializationDecl::CreateDeserialized(C&: Context, ID);
4033 break;
4034 case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
4035 D = VarTemplatePartialSpecializationDecl::CreateDeserialized(C&: Context, ID);
4036 break;
4037 case DECL_FUNCTION_TEMPLATE:
4038 D = FunctionTemplateDecl::CreateDeserialized(C&: Context, ID);
4039 break;
4040 case DECL_TEMPLATE_TYPE_PARM: {
4041 bool HasTypeConstraint = Record.readInt();
4042 D = TemplateTypeParmDecl::CreateDeserialized(C: Context, ID,
4043 HasTypeConstraint);
4044 break;
4045 }
4046 case DECL_NON_TYPE_TEMPLATE_PARM: {
4047 bool HasTypeConstraint = Record.readInt();
4048 D = NonTypeTemplateParmDecl::CreateDeserialized(C&: Context, ID,
4049 HasTypeConstraint);
4050 break;
4051 }
4052 case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK: {
4053 bool HasTypeConstraint = Record.readInt();
4054 D = NonTypeTemplateParmDecl::CreateDeserialized(
4055 C&: Context, ID, NumExpandedTypes: Record.readInt(), HasTypeConstraint);
4056 break;
4057 }
4058 case DECL_TEMPLATE_TEMPLATE_PARM:
4059 D = TemplateTemplateParmDecl::CreateDeserialized(C&: Context, ID);
4060 break;
4061 case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
4062 D = TemplateTemplateParmDecl::CreateDeserialized(C&: Context, ID,
4063 NumExpansions: Record.readInt());
4064 break;
4065 case DECL_TYPE_ALIAS_TEMPLATE:
4066 D = TypeAliasTemplateDecl::CreateDeserialized(C&: Context, ID);
4067 break;
4068 case DECL_CONCEPT:
4069 D = ConceptDecl::CreateDeserialized(C&: Context, ID);
4070 break;
4071 case DECL_REQUIRES_EXPR_BODY:
4072 D = RequiresExprBodyDecl::CreateDeserialized(C&: Context, ID);
4073 break;
4074 case DECL_STATIC_ASSERT:
4075 D = StaticAssertDecl::CreateDeserialized(C&: Context, ID);
4076 break;
4077 case DECL_OBJC_METHOD:
4078 D = ObjCMethodDecl::CreateDeserialized(C&: Context, ID);
4079 break;
4080 case DECL_OBJC_INTERFACE:
4081 D = ObjCInterfaceDecl::CreateDeserialized(C: Context, ID);
4082 break;
4083 case DECL_OBJC_IVAR:
4084 D = ObjCIvarDecl::CreateDeserialized(C&: Context, ID);
4085 break;
4086 case DECL_OBJC_PROTOCOL:
4087 D = ObjCProtocolDecl::CreateDeserialized(C&: Context, ID);
4088 break;
4089 case DECL_OBJC_AT_DEFS_FIELD:
4090 D = ObjCAtDefsFieldDecl::CreateDeserialized(C&: Context, ID);
4091 break;
4092 case DECL_OBJC_CATEGORY:
4093 D = ObjCCategoryDecl::CreateDeserialized(C&: Context, ID);
4094 break;
4095 case DECL_OBJC_CATEGORY_IMPL:
4096 D = ObjCCategoryImplDecl::CreateDeserialized(C&: Context, ID);
4097 break;
4098 case DECL_OBJC_IMPLEMENTATION:
4099 D = ObjCImplementationDecl::CreateDeserialized(C&: Context, ID);
4100 break;
4101 case DECL_OBJC_COMPATIBLE_ALIAS:
4102 D = ObjCCompatibleAliasDecl::CreateDeserialized(C&: Context, ID);
4103 break;
4104 case DECL_OBJC_PROPERTY:
4105 D = ObjCPropertyDecl::CreateDeserialized(C&: Context, ID);
4106 break;
4107 case DECL_OBJC_PROPERTY_IMPL:
4108 D = ObjCPropertyImplDecl::CreateDeserialized(C&: Context, ID);
4109 break;
4110 case DECL_FIELD:
4111 D = FieldDecl::CreateDeserialized(C&: Context, ID);
4112 break;
4113 case DECL_INDIRECTFIELD:
4114 D = IndirectFieldDecl::CreateDeserialized(C&: Context, ID);
4115 break;
4116 case DECL_VAR:
4117 D = VarDecl::CreateDeserialized(C&: Context, ID);
4118 break;
4119 case DECL_IMPLICIT_PARAM:
4120 D = ImplicitParamDecl::CreateDeserialized(C&: Context, ID);
4121 break;
4122 case DECL_PARM_VAR:
4123 D = ParmVarDecl::CreateDeserialized(C&: Context, ID);
4124 break;
4125 case DECL_DECOMPOSITION:
4126 D = DecompositionDecl::CreateDeserialized(C&: Context, ID, NumBindings: Record.readInt());
4127 break;
4128 case DECL_BINDING:
4129 D = BindingDecl::CreateDeserialized(C&: Context, ID);
4130 break;
4131 case DECL_FILE_SCOPE_ASM:
4132 D = FileScopeAsmDecl::CreateDeserialized(C&: Context, ID);
4133 break;
4134 case DECL_TOP_LEVEL_STMT_DECL:
4135 D = TopLevelStmtDecl::CreateDeserialized(C&: Context, ID);
4136 break;
4137 case DECL_BLOCK:
4138 D = BlockDecl::CreateDeserialized(C&: Context, ID);
4139 break;
4140 case DECL_MS_PROPERTY:
4141 D = MSPropertyDecl::CreateDeserialized(C&: Context, ID);
4142 break;
4143 case DECL_MS_GUID:
4144 D = MSGuidDecl::CreateDeserialized(C&: Context, ID);
4145 break;
4146 case DECL_UNNAMED_GLOBAL_CONSTANT:
4147 D = UnnamedGlobalConstantDecl::CreateDeserialized(C&: Context, ID);
4148 break;
4149 case DECL_TEMPLATE_PARAM_OBJECT:
4150 D = TemplateParamObjectDecl::CreateDeserialized(C&: Context, ID);
4151 break;
4152 case DECL_OUTLINEDFUNCTION:
4153 D = OutlinedFunctionDecl::CreateDeserialized(C&: Context, ID, NumParams: Record.readInt());
4154 break;
4155 case DECL_CAPTURED:
4156 D = CapturedDecl::CreateDeserialized(C&: Context, ID, NumParams: Record.readInt());
4157 break;
4158 case DECL_CXX_BASE_SPECIFIERS:
4159 Error(Msg: "attempt to read a C++ base-specifier record as a declaration");
4160 return nullptr;
4161 case DECL_CXX_CTOR_INITIALIZERS:
4162 Error(Msg: "attempt to read a C++ ctor initializer record as a declaration");
4163 return nullptr;
4164 case DECL_IMPORT:
4165 // Note: last entry of the ImportDecl record is the number of stored source
4166 // locations.
4167 D = ImportDecl::CreateDeserialized(C&: Context, ID, NumLocations: Record.back());
4168 break;
4169 case DECL_OMP_THREADPRIVATE: {
4170 Record.skipInts(N: 1);
4171 unsigned NumChildren = Record.readInt();
4172 Record.skipInts(N: 1);
4173 D = OMPThreadPrivateDecl::CreateDeserialized(C&: Context, ID, N: NumChildren);
4174 break;
4175 }
4176 case DECL_OMP_ALLOCATE: {
4177 unsigned NumClauses = Record.readInt();
4178 unsigned NumVars = Record.readInt();
4179 Record.skipInts(N: 1);
4180 D = OMPAllocateDecl::CreateDeserialized(C&: Context, ID, NVars: NumVars, NClauses: NumClauses);
4181 break;
4182 }
4183 case DECL_OMP_REQUIRES: {
4184 unsigned NumClauses = Record.readInt();
4185 Record.skipInts(N: 2);
4186 D = OMPRequiresDecl::CreateDeserialized(C&: Context, ID, N: NumClauses);
4187 break;
4188 }
4189 case DECL_OMP_DECLARE_REDUCTION:
4190 D = OMPDeclareReductionDecl::CreateDeserialized(C&: Context, ID);
4191 break;
4192 case DECL_OMP_DECLARE_MAPPER: {
4193 unsigned NumClauses = Record.readInt();
4194 Record.skipInts(N: 2);
4195 D = OMPDeclareMapperDecl::CreateDeserialized(C&: Context, ID, N: NumClauses);
4196 break;
4197 }
4198 case DECL_OMP_CAPTUREDEXPR:
4199 D = OMPCapturedExprDecl::CreateDeserialized(C&: Context, ID);
4200 break;
4201 case DECL_PRAGMA_COMMENT:
4202 D = PragmaCommentDecl::CreateDeserialized(C&: Context, ID, ArgSize: Record.readInt());
4203 break;
4204 case DECL_PRAGMA_DETECT_MISMATCH:
4205 D = PragmaDetectMismatchDecl::CreateDeserialized(C&: Context, ID,
4206 NameValueSize: Record.readInt());
4207 break;
4208 case DECL_EMPTY:
4209 D = EmptyDecl::CreateDeserialized(C&: Context, ID);
4210 break;
4211 case DECL_LIFETIME_EXTENDED_TEMPORARY:
4212 D = LifetimeExtendedTemporaryDecl::CreateDeserialized(C&: Context, ID);
4213 break;
4214 case DECL_OBJC_TYPE_PARAM:
4215 D = ObjCTypeParamDecl::CreateDeserialized(ctx&: Context, ID);
4216 break;
4217 case DECL_HLSL_BUFFER:
4218 D = HLSLBufferDecl::CreateDeserialized(C&: Context, ID);
4219 break;
4220 case DECL_IMPLICIT_CONCEPT_SPECIALIZATION:
4221 D = ImplicitConceptSpecializationDecl::CreateDeserialized(C: Context, ID,
4222 NumTemplateArgs: Record.readInt());
4223 break;
4224 case DECL_OPENACC_DECLARE:
4225 D = OpenACCDeclareDecl::CreateDeserialized(Ctx&: Context, ID, NumClauses: Record.readInt());
4226 break;
4227 case DECL_OPENACC_ROUTINE:
4228 D = OpenACCRoutineDecl::CreateDeserialized(Ctx&: Context, ID, NumClauses: Record.readInt());
4229 break;
4230 }
4231
4232 assert(D && "Unknown declaration reading AST file");
4233 LoadedDecl(Index: translateGlobalDeclIDToIndex(ID), D);
4234 // Set the DeclContext before doing any deserialization, to make sure internal
4235 // calls to Decl::getASTContext() by Decl's methods will find the
4236 // TranslationUnitDecl without crashing.
4237 D->setDeclContext(Context.getTranslationUnitDecl());
4238
4239 // Reading some declarations can result in deep recursion.
4240 runWithSufficientStackSpace(Loc: DeclLoc, Fn: [&] { Reader.Visit(D); });
4241
4242 // If this declaration is also a declaration context, get the
4243 // offsets for its tables of lexical and visible declarations.
4244 if (auto *DC = dyn_cast<DeclContext>(Val: D)) {
4245 LookupBlockOffsets Offsets;
4246
4247 Reader.VisitDeclContext(DC, Offsets);
4248
4249 // Get the lexical and visible block for the delayed namespace.
4250 // It is sufficient to judge if ID is in DelayedNamespaceOffsetMap.
4251 // But it may be more efficient to filter the other cases.
4252 if (!Offsets && isa<NamespaceDecl>(Val: D))
4253 if (auto Iter = DelayedNamespaceOffsetMap.find(Val: ID);
4254 Iter != DelayedNamespaceOffsetMap.end())
4255 Offsets = Iter->second;
4256
4257 if (Offsets.VisibleOffset &&
4258 ReadVisibleDeclContextStorage(
4259 M&: *Loc.F, Cursor&: DeclsCursor, Offset: Offsets.VisibleOffset, ID,
4260 VisibleKind: VisibleDeclContextStorageKind::GenerallyVisible))
4261 return nullptr;
4262 if (Offsets.ModuleLocalOffset &&
4263 ReadVisibleDeclContextStorage(
4264 M&: *Loc.F, Cursor&: DeclsCursor, Offset: Offsets.ModuleLocalOffset, ID,
4265 VisibleKind: VisibleDeclContextStorageKind::ModuleLocalVisible))
4266 return nullptr;
4267 if (Offsets.TULocalOffset &&
4268 ReadVisibleDeclContextStorage(
4269 M&: *Loc.F, Cursor&: DeclsCursor, Offset: Offsets.TULocalOffset, ID,
4270 VisibleKind: VisibleDeclContextStorageKind::TULocalVisible))
4271 return nullptr;
4272
4273 if (Offsets.LexicalOffset &&
4274 ReadLexicalDeclContextStorage(M&: *Loc.F, Cursor&: DeclsCursor,
4275 Offset: Offsets.LexicalOffset, DC))
4276 return nullptr;
4277 }
4278 assert(Record.getIdx() == Record.size());
4279
4280 // Load any relevant update records.
4281 PendingUpdateRecords.push_back(
4282 Elt: PendingUpdateRecord(ID, D, /*JustLoaded=*/true));
4283
4284 // Load the categories after recursive loading is finished.
4285 if (auto *Class = dyn_cast<ObjCInterfaceDecl>(Val: D))
4286 // If we already have a definition when deserializing the ObjCInterfaceDecl,
4287 // we put the Decl in PendingDefinitions so we can pull the categories here.
4288 if (Class->isThisDeclarationADefinition() ||
4289 PendingDefinitions.count(Ptr: Class))
4290 loadObjCCategories(ID, D: Class);
4291
4292 // If we have deserialized a declaration that has a definition the
4293 // AST consumer might need to know about, queue it.
4294 // We don't pass it to the consumer immediately because we may be in recursive
4295 // loading, and some declarations may still be initializing.
4296 PotentiallyInterestingDecls.push_back(x: D);
4297
4298 return D;
4299}
4300
4301void ASTReader::PassInterestingDeclsToConsumer() {
4302 assert(Consumer);
4303
4304 if (!CanPassDeclsToConsumer)
4305 return;
4306
4307 // Guard variable to avoid recursively redoing the process of passing
4308 // decls to consumer.
4309 SaveAndRestore GuardPassingDeclsToConsumer(CanPassDeclsToConsumer,
4310 /*NewValue=*/false);
4311
4312 // Ensure that we've loaded all potentially-interesting declarations
4313 // that need to be eagerly loaded.
4314 for (auto ID : EagerlyDeserializedDecls)
4315 GetDecl(ID);
4316 EagerlyDeserializedDecls.clear();
4317
4318 auto ConsumingPotentialInterestingDecls = [this]() {
4319 while (!PotentiallyInterestingDecls.empty()) {
4320 Decl *D = PotentiallyInterestingDecls.front();
4321 PotentiallyInterestingDecls.pop_front();
4322 if (isConsumerInterestedIn(D))
4323 PassInterestingDeclToConsumer(D);
4324 }
4325 };
4326 std::deque<Decl *> MaybeInterestingDecls =
4327 std::move(PotentiallyInterestingDecls);
4328 PotentiallyInterestingDecls.clear();
4329 assert(PotentiallyInterestingDecls.empty());
4330 while (!MaybeInterestingDecls.empty()) {
4331 Decl *D = MaybeInterestingDecls.front();
4332 MaybeInterestingDecls.pop_front();
4333 // Since we load the variable's initializers lazily, it'd be problematic
4334 // if the initializers dependent on each other. So here we try to load the
4335 // initializers of static variables to make sure they are passed to code
4336 // generator by order. If we read anything interesting, we would consume
4337 // that before emitting the current declaration.
4338 if (auto *VD = dyn_cast<VarDecl>(Val: D);
4339 VD && VD->isFileVarDecl() && !VD->isExternallyVisible())
4340 VD->getInit();
4341 ConsumingPotentialInterestingDecls();
4342 if (isConsumerInterestedIn(D))
4343 PassInterestingDeclToConsumer(D);
4344 }
4345
4346 // If we add any new potential interesting decl in the last call, consume it.
4347 ConsumingPotentialInterestingDecls();
4348
4349 for (GlobalDeclID ID : VTablesToEmit) {
4350 auto *RD = cast<CXXRecordDecl>(Val: GetDecl(ID));
4351 assert(!RD->shouldEmitInExternalSource());
4352 PassVTableToConsumer(RD);
4353 }
4354 VTablesToEmit.clear();
4355}
4356
4357void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {
4358 // The declaration may have been modified by files later in the chain.
4359 // If this is the case, read the record containing the updates from each file
4360 // and pass it to ASTDeclReader to make the modifications.
4361 GlobalDeclID ID = Record.ID;
4362 Decl *D = Record.D;
4363 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
4364 DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(Val: ID);
4365
4366 if (UpdI != DeclUpdateOffsets.end()) {
4367 auto UpdateOffsets = std::move(UpdI->second);
4368 DeclUpdateOffsets.erase(I: UpdI);
4369
4370 // Check if this decl was interesting to the consumer. If we just loaded
4371 // the declaration, then we know it was interesting and we skip the call
4372 // to isConsumerInterestedIn because it is unsafe to call in the
4373 // current ASTReader state.
4374 bool WasInteresting = Record.JustLoaded || isConsumerInterestedIn(D);
4375 for (auto &FileAndOffset : UpdateOffsets) {
4376 ModuleFile *F = FileAndOffset.first;
4377 uint64_t Offset = FileAndOffset.second;
4378 llvm::BitstreamCursor &Cursor = F->DeclsCursor;
4379 SavedStreamPosition SavedPosition(Cursor);
4380 if (llvm::Error JumpFailed = Cursor.JumpToBit(BitNo: Offset))
4381 // FIXME don't do a fatal error.
4382 llvm::report_fatal_error(
4383 reason: Twine("ASTReader::loadDeclUpdateRecords failed jumping: ") +
4384 toString(E: std::move(JumpFailed)));
4385 Expected<unsigned> MaybeCode = Cursor.ReadCode();
4386 if (!MaybeCode)
4387 llvm::report_fatal_error(
4388 reason: Twine("ASTReader::loadDeclUpdateRecords failed reading code: ") +
4389 toString(E: MaybeCode.takeError()));
4390 unsigned Code = MaybeCode.get();
4391 ASTRecordReader Record(*this, *F);
4392 if (Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, AbbrevID: Code))
4393 assert(MaybeRecCode.get() == DECL_UPDATES &&
4394 "Expected DECL_UPDATES record!");
4395 else
4396 llvm::report_fatal_error(
4397 reason: Twine("ASTReader::loadDeclUpdateRecords failed reading rec code: ") +
4398 toString(E: MaybeCode.takeError()));
4399
4400 ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,
4401 SourceLocation());
4402 Reader.UpdateDecl(D);
4403
4404 // We might have made this declaration interesting. If so, remember that
4405 // we need to hand it off to the consumer.
4406 if (!WasInteresting && isConsumerInterestedIn(D)) {
4407 PotentiallyInterestingDecls.push_back(x: D);
4408 WasInteresting = true;
4409 }
4410 }
4411 }
4412
4413 // Load the pending visible updates for this decl context, if it has any.
4414 if (auto I = PendingVisibleUpdates.find(Val: ID);
4415 I != PendingVisibleUpdates.end()) {
4416 auto VisibleUpdates = std::move(I->second);
4417 PendingVisibleUpdates.erase(I);
4418
4419 auto *DC = cast<DeclContext>(Val: D)->getPrimaryContext();
4420 for (const auto &Update : VisibleUpdates)
4421 Lookups[DC].Table.add(
4422 File: Update.Mod, Data: Update.Data,
4423 InfoObj: reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
4424 DC->setHasExternalVisibleStorage(true);
4425 }
4426
4427 if (auto I = PendingModuleLocalVisibleUpdates.find(Val: ID);
4428 I != PendingModuleLocalVisibleUpdates.end()) {
4429 auto ModuleLocalVisibleUpdates = std::move(I->second);
4430 PendingModuleLocalVisibleUpdates.erase(I);
4431
4432 auto *DC = cast<DeclContext>(Val: D)->getPrimaryContext();
4433 for (const auto &Update : ModuleLocalVisibleUpdates)
4434 ModuleLocalLookups[DC].Table.add(
4435 File: Update.Mod, Data: Update.Data,
4436 InfoObj: reader::ModuleLocalNameLookupTrait(*this, *Update.Mod));
4437 // NOTE: Can we optimize the case that the data being loaded
4438 // is not related to current module?
4439 DC->setHasExternalVisibleStorage(true);
4440 }
4441
4442 if (auto I = TULocalUpdates.find(Val: ID); I != TULocalUpdates.end()) {
4443 auto Updates = std::move(I->second);
4444 TULocalUpdates.erase(I);
4445
4446 auto *DC = cast<DeclContext>(Val: D)->getPrimaryContext();
4447 for (const auto &Update : Updates)
4448 TULocalLookups[DC].Table.add(
4449 File: Update.Mod, Data: Update.Data,
4450 InfoObj: reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
4451 DC->setHasExternalVisibleStorage(true);
4452 }
4453
4454 // Load any pending related decls.
4455 if (D->isCanonicalDecl()) {
4456 if (auto IT = RelatedDeclsMap.find(Val: ID); IT != RelatedDeclsMap.end()) {
4457 for (auto LID : IT->second)
4458 GetDecl(ID: LID);
4459 RelatedDeclsMap.erase(I: IT);
4460 }
4461 }
4462
4463 // Load the pending specializations update for this decl, if it has any.
4464 if (auto I = PendingSpecializationsUpdates.find(Val: ID);
4465 I != PendingSpecializationsUpdates.end()) {
4466 auto SpecializationUpdates = std::move(I->second);
4467 PendingSpecializationsUpdates.erase(I);
4468
4469 for (const auto &Update : SpecializationUpdates)
4470 AddSpecializations(D, Data: Update.Data, M&: *Update.Mod, /*IsPartial=*/false);
4471 }
4472
4473 // Load the pending specializations update for this decl, if it has any.
4474 if (auto I = PendingPartialSpecializationsUpdates.find(Val: ID);
4475 I != PendingPartialSpecializationsUpdates.end()) {
4476 auto SpecializationUpdates = std::move(I->second);
4477 PendingPartialSpecializationsUpdates.erase(I);
4478
4479 for (const auto &Update : SpecializationUpdates)
4480 AddSpecializations(D, Data: Update.Data, M&: *Update.Mod, /*IsPartial=*/true);
4481 }
4482}
4483
4484void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {
4485 // Attach FirstLocal to the end of the decl chain.
4486 Decl *CanonDecl = FirstLocal->getCanonicalDecl();
4487 if (FirstLocal != CanonDecl) {
4488 Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(D: CanonDecl);
4489 ASTDeclReader::attachPreviousDecl(
4490 Reader&: *this, D: FirstLocal, Previous: PrevMostRecent ? PrevMostRecent : CanonDecl,
4491 Canon: CanonDecl);
4492 }
4493
4494 if (!LocalOffset) {
4495 ASTDeclReader::attachLatestDecl(D: CanonDecl, Latest: FirstLocal);
4496 return;
4497 }
4498
4499 // Load the list of other redeclarations from this module file.
4500 ModuleFile *M = getOwningModuleFile(D: FirstLocal);
4501 assert(M && "imported decl from no module file");
4502
4503 llvm::BitstreamCursor &Cursor = M->DeclsCursor;
4504 SavedStreamPosition SavedPosition(Cursor);
4505 if (llvm::Error JumpFailed = Cursor.JumpToBit(BitNo: LocalOffset))
4506 llvm::report_fatal_error(
4507 reason: Twine("ASTReader::loadPendingDeclChain failed jumping: ") +
4508 toString(E: std::move(JumpFailed)));
4509
4510 RecordData Record;
4511 Expected<unsigned> MaybeCode = Cursor.ReadCode();
4512 if (!MaybeCode)
4513 llvm::report_fatal_error(
4514 reason: Twine("ASTReader::loadPendingDeclChain failed reading code: ") +
4515 toString(E: MaybeCode.takeError()));
4516 unsigned Code = MaybeCode.get();
4517 if (Expected<unsigned> MaybeRecCode = Cursor.readRecord(AbbrevID: Code, Vals&: Record))
4518 assert(MaybeRecCode.get() == LOCAL_REDECLARATIONS &&
4519 "expected LOCAL_REDECLARATIONS record!");
4520 else
4521 llvm::report_fatal_error(
4522 reason: Twine("ASTReader::loadPendingDeclChain failed reading rec code: ") +
4523 toString(E: MaybeCode.takeError()));
4524
4525 // FIXME: We have several different dispatches on decl kind here; maybe
4526 // we should instead generate one loop per kind and dispatch up-front?
4527 Decl *MostRecent = FirstLocal;
4528 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
4529 unsigned Idx = N - I - 1;
4530 auto *D = ReadDecl(F&: *M, R: Record, I&: Idx);
4531 ASTDeclReader::attachPreviousDecl(Reader&: *this, D, Previous: MostRecent, Canon: CanonDecl);
4532 MostRecent = D;
4533 }
4534 ASTDeclReader::attachLatestDecl(D: CanonDecl, Latest: MostRecent);
4535}
4536
4537namespace {
4538
4539 /// Given an ObjC interface, goes through the modules and links to the
4540 /// interface all the categories for it.
4541 class ObjCCategoriesVisitor {
4542 ASTReader &Reader;
4543 ObjCInterfaceDecl *Interface;
4544 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
4545 ObjCCategoryDecl *Tail = nullptr;
4546 llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
4547 GlobalDeclID InterfaceID;
4548 unsigned PreviousGeneration;
4549
4550 void add(ObjCCategoryDecl *Cat) {
4551 // Only process each category once.
4552 if (!Deserialized.erase(Ptr: Cat))
4553 return;
4554
4555 // Check for duplicate categories.
4556 if (Cat->getDeclName()) {
4557 ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
4558 if (Existing && Reader.getOwningModuleFile(D: Existing) !=
4559 Reader.getOwningModuleFile(D: Cat)) {
4560 StructuralEquivalenceContext::NonEquivalentDeclSet NonEquivalentDecls;
4561 StructuralEquivalenceContext Ctx(
4562 Reader.getContext().getLangOpts(), Cat->getASTContext(),
4563 Existing->getASTContext(), NonEquivalentDecls,
4564 StructuralEquivalenceKind::Default,
4565 /*StrictTypeSpelling=*/false,
4566 /*Complain=*/false,
4567 /*ErrorOnTagTypeMismatch=*/true);
4568 if (!Ctx.IsEquivalent(D1: Cat, D2: Existing)) {
4569 // Warn only if the categories with the same name are different.
4570 Reader.Diag(Loc: Cat->getLocation(), DiagID: diag::warn_dup_category_def)
4571 << Interface->getDeclName() << Cat->getDeclName();
4572 Reader.Diag(Loc: Existing->getLocation(),
4573 DiagID: diag::note_previous_definition);
4574 }
4575 } else if (!Existing) {
4576 // Record this category.
4577 Existing = Cat;
4578 }
4579 }
4580
4581 // Add this category to the end of the chain.
4582 if (Tail)
4583 ASTDeclReader::setNextObjCCategory(Cat: Tail, Next: Cat);
4584 else
4585 Interface->setCategoryListRaw(Cat);
4586 Tail = Cat;
4587 }
4588
4589 public:
4590 ObjCCategoriesVisitor(
4591 ASTReader &Reader, ObjCInterfaceDecl *Interface,
4592 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
4593 GlobalDeclID InterfaceID, unsigned PreviousGeneration)
4594 : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
4595 InterfaceID(InterfaceID), PreviousGeneration(PreviousGeneration) {
4596 // Populate the name -> category map with the set of known categories.
4597 for (auto *Cat : Interface->known_categories()) {
4598 if (Cat->getDeclName())
4599 NameCategoryMap[Cat->getDeclName()] = Cat;
4600
4601 // Keep track of the tail of the category list.
4602 Tail = Cat;
4603 }
4604 }
4605
4606 bool operator()(ModuleFile &M) {
4607 // If we've loaded all of the category information we care about from
4608 // this module file, we're done.
4609 if (M.Generation <= PreviousGeneration)
4610 return true;
4611
4612 // Map global ID of the definition down to the local ID used in this
4613 // module file. If there is no such mapping, we'll find nothing here
4614 // (or in any module it imports).
4615 LocalDeclID LocalID =
4616 Reader.mapGlobalIDToModuleFileGlobalID(M, GlobalID: InterfaceID);
4617 if (LocalID.isInvalid())
4618 return true;
4619
4620 // Perform a binary search to find the local redeclarations for this
4621 // declaration (if any).
4622 const ObjCCategoriesInfo Compare = {LocalID, 0};
4623 const ObjCCategoriesInfo *Result = std::lower_bound(
4624 first: M.ObjCCategoriesMap,
4625 last: M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap, val: Compare);
4626 if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
4627 LocalID != Result->getDefinitionID()) {
4628 // We didn't find anything. If the class definition is in this module
4629 // file, then the module files it depends on cannot have any categories,
4630 // so suppress further lookup.
4631 return Reader.isDeclIDFromModule(ID: InterfaceID, M);
4632 }
4633
4634 // We found something. Dig out all of the categories.
4635 unsigned Offset = Result->Offset;
4636 unsigned N = M.ObjCCategories[Offset];
4637 M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
4638 for (unsigned I = 0; I != N; ++I)
4639 add(Cat: Reader.ReadDeclAs<ObjCCategoryDecl>(F&: M, R: M.ObjCCategories, I&: Offset));
4640 return true;
4641 }
4642 };
4643
4644} // namespace
4645
4646void ASTReader::loadObjCCategories(GlobalDeclID ID, ObjCInterfaceDecl *D,
4647 unsigned PreviousGeneration) {
4648 ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
4649 PreviousGeneration);
4650 ModuleMgr.visit(Visitor);
4651}
4652
4653template<typename DeclT, typename Fn>
4654static void forAllLaterRedecls(DeclT *D, Fn F) {
4655 F(D);
4656
4657 // Check whether we've already merged D into its redeclaration chain.
4658 // MostRecent may or may not be nullptr if D has not been merged. If
4659 // not, walk the merged redecl chain and see if it's there.
4660 auto *MostRecent = D->getMostRecentDecl();
4661 bool Found = false;
4662 for (auto *Redecl = MostRecent; Redecl && !Found;
4663 Redecl = Redecl->getPreviousDecl())
4664 Found = (Redecl == D);
4665
4666 // If this declaration is merged, apply the functor to all later decls.
4667 if (Found) {
4668 for (auto *Redecl = MostRecent; Redecl != D;
4669 Redecl = Redecl->getPreviousDecl())
4670 F(Redecl);
4671 }
4672}
4673
4674void ASTDeclReader::UpdateDecl(Decl *D) {
4675 while (Record.getIdx() < Record.size()) {
4676 switch ((DeclUpdateKind)Record.readInt()) {
4677 case DeclUpdateKind::CXXAddedImplicitMember: {
4678 auto *RD = cast<CXXRecordDecl>(Val: D);
4679 Decl *MD = Record.readDecl();
4680 assert(MD && "couldn't read decl from update record");
4681 Reader.PendingAddedClassMembers.push_back(Elt: {RD, MD});
4682 break;
4683 }
4684
4685 case DeclUpdateKind::CXXAddedAnonymousNamespace: {
4686 auto *Anon = readDeclAs<NamespaceDecl>();
4687
4688 // Each module has its own anonymous namespace, which is disjoint from
4689 // any other module's anonymous namespaces, so don't attach the anonymous
4690 // namespace at all.
4691 if (!Record.isModule()) {
4692 if (auto *TU = dyn_cast<TranslationUnitDecl>(Val: D))
4693 TU->setAnonymousNamespace(Anon);
4694 else
4695 cast<NamespaceDecl>(Val: D)->setAnonymousNamespace(Anon);
4696 }
4697 break;
4698 }
4699
4700 case DeclUpdateKind::CXXAddedVarDefinition: {
4701 auto *VD = cast<VarDecl>(Val: D);
4702 VD->NonParmVarDeclBits.IsInline = Record.readInt();
4703 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
4704 ReadVarDeclInit(VD);
4705 break;
4706 }
4707
4708 case DeclUpdateKind::CXXPointOfInstantiation: {
4709 SourceLocation POI = Record.readSourceLocation();
4710 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Val: D)) {
4711 VTSD->setPointOfInstantiation(POI);
4712 } else if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
4713 MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo();
4714 assert(MSInfo && "No member specialization information");
4715 MSInfo->setPointOfInstantiation(POI);
4716 } else {
4717 auto *FD = cast<FunctionDecl>(Val: D);
4718 if (auto *FTSInfo = dyn_cast<FunctionTemplateSpecializationInfo *>(
4719 Val&: FD->TemplateOrSpecialization))
4720 FTSInfo->setPointOfInstantiation(POI);
4721 else
4722 cast<MemberSpecializationInfo *>(Val&: FD->TemplateOrSpecialization)
4723 ->setPointOfInstantiation(POI);
4724 }
4725 break;
4726 }
4727
4728 case DeclUpdateKind::CXXInstantiatedDefaultArgument: {
4729 auto *Param = cast<ParmVarDecl>(Val: D);
4730
4731 // We have to read the default argument regardless of whether we use it
4732 // so that hypothetical further update records aren't messed up.
4733 // TODO: Add a function to skip over the next expr record.
4734 auto *DefaultArg = Record.readExpr();
4735
4736 // Only apply the update if the parameter still has an uninstantiated
4737 // default argument.
4738 if (Param->hasUninstantiatedDefaultArg())
4739 Param->setDefaultArg(DefaultArg);
4740 break;
4741 }
4742
4743 case DeclUpdateKind::CXXInstantiatedDefaultMemberInitializer: {
4744 auto *FD = cast<FieldDecl>(Val: D);
4745 auto *DefaultInit = Record.readExpr();
4746
4747 // Only apply the update if the field still has an uninstantiated
4748 // default member initializer.
4749 if (FD->hasInClassInitializer() && !FD->hasNonNullInClassInitializer()) {
4750 if (DefaultInit)
4751 FD->setInClassInitializer(DefaultInit);
4752 else
4753 // Instantiation failed. We can get here if we serialized an AST for
4754 // an invalid program.
4755 FD->removeInClassInitializer();
4756 }
4757 break;
4758 }
4759
4760 case DeclUpdateKind::CXXAddedFunctionDefinition: {
4761 auto *FD = cast<FunctionDecl>(Val: D);
4762 if (Reader.PendingBodies[FD]) {
4763 // FIXME: Maybe check for ODR violations.
4764 // It's safe to stop now because this update record is always last.
4765 return;
4766 }
4767
4768 if (Record.readInt()) {
4769 // Maintain AST consistency: any later redeclarations of this function
4770 // are inline if this one is. (We might have merged another declaration
4771 // into this one.)
4772 forAllLaterRedecls(D: FD, F: [](FunctionDecl *FD) {
4773 FD->setImplicitlyInline();
4774 });
4775 }
4776 FD->setInnerLocStart(readSourceLocation());
4777 ReadFunctionDefinition(FD);
4778 assert(Record.getIdx() == Record.size() && "lazy body must be last");
4779 break;
4780 }
4781
4782 case DeclUpdateKind::CXXInstantiatedClassDefinition: {
4783 auto *RD = cast<CXXRecordDecl>(Val: D);
4784 auto *OldDD = RD->getCanonicalDecl()->DefinitionData;
4785 bool HadRealDefinition =
4786 OldDD && (OldDD->Definition != RD ||
4787 !Reader.PendingFakeDefinitionData.count(Val: OldDD));
4788 RD->setParamDestroyedInCallee(Record.readInt());
4789 RD->setArgPassingRestrictions(
4790 static_cast<RecordArgPassingKind>(Record.readInt()));
4791 ReadCXXRecordDefinition(D: RD, /*Update*/true);
4792
4793 // Visible update is handled separately.
4794 uint64_t LexicalOffset = ReadLocalOffset();
4795 if (!HadRealDefinition && LexicalOffset) {
4796 Record.readLexicalDeclContextStorage(Offset: LexicalOffset, DC: RD);
4797 Reader.PendingFakeDefinitionData.erase(Val: OldDD);
4798 }
4799
4800 auto TSK = (TemplateSpecializationKind)Record.readInt();
4801 SourceLocation POI = readSourceLocation();
4802 if (MemberSpecializationInfo *MSInfo =
4803 RD->getMemberSpecializationInfo()) {
4804 MSInfo->setTemplateSpecializationKind(TSK);
4805 MSInfo->setPointOfInstantiation(POI);
4806 } else {
4807 auto *Spec = cast<ClassTemplateSpecializationDecl>(Val: RD);
4808 Spec->setTemplateSpecializationKind(TSK);
4809 Spec->setPointOfInstantiation(POI);
4810
4811 if (Record.readInt()) {
4812 auto *PartialSpec =
4813 readDeclAs<ClassTemplatePartialSpecializationDecl>();
4814 SmallVector<TemplateArgument, 8> TemplArgs;
4815 Record.readTemplateArgumentList(TemplArgs);
4816 auto *TemplArgList = TemplateArgumentList::CreateCopy(
4817 Context&: Reader.getContext(), Args: TemplArgs);
4818
4819 // FIXME: If we already have a partial specialization set,
4820 // check that it matches.
4821 if (!isa<ClassTemplatePartialSpecializationDecl *>(
4822 Val: Spec->getSpecializedTemplateOrPartial()))
4823 Spec->setInstantiationOf(PartialSpec, TemplateArgs: TemplArgList);
4824 }
4825 }
4826
4827 RD->setTagKind(static_cast<TagTypeKind>(Record.readInt()));
4828 RD->setLocation(readSourceLocation());
4829 RD->setLocStart(readSourceLocation());
4830 RD->setBraceRange(readSourceRange());
4831
4832 if (Record.readInt()) {
4833 AttrVec Attrs;
4834 Record.readAttributes(Attrs);
4835 // If the declaration already has attributes, we assume that some other
4836 // AST file already loaded them.
4837 if (!D->hasAttrs())
4838 D->setAttrsImpl(Attrs, Ctx&: Reader.getContext());
4839 }
4840 break;
4841 }
4842
4843 case DeclUpdateKind::CXXResolvedDtorDelete: {
4844 // Set the 'operator delete' directly to avoid emitting another update
4845 // record.
4846 auto *Del = readDeclAs<FunctionDecl>();
4847 auto *First = cast<CXXDestructorDecl>(Val: D->getCanonicalDecl());
4848 auto *ThisArg = Record.readExpr();
4849 // FIXME: Check consistency if we have an old and new operator delete.
4850 if (!First->OperatorDelete) {
4851 First->OperatorDelete = Del;
4852 First->OperatorDeleteThisArg = ThisArg;
4853 }
4854 break;
4855 }
4856
4857 case DeclUpdateKind::CXXResolvedExceptionSpec: {
4858 SmallVector<QualType, 8> ExceptionStorage;
4859 auto ESI = Record.readExceptionSpecInfo(buffer&: ExceptionStorage);
4860
4861 // Update this declaration's exception specification, if needed.
4862 auto *FD = cast<FunctionDecl>(Val: D);
4863 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
4864 // FIXME: If the exception specification is already present, check that it
4865 // matches.
4866 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
4867 FD->setType(Reader.getContext().getFunctionType(
4868 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
4869 EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI)));
4870
4871 // When we get to the end of deserializing, see if there are other decls
4872 // that we need to propagate this exception specification onto.
4873 Reader.PendingExceptionSpecUpdates.insert(
4874 KV: std::make_pair(x: FD->getCanonicalDecl(), y&: FD));
4875 }
4876 break;
4877 }
4878
4879 case DeclUpdateKind::CXXDeducedReturnType: {
4880 auto *FD = cast<FunctionDecl>(Val: D);
4881 QualType DeducedResultType = Record.readType();
4882 Reader.PendingDeducedTypeUpdates.insert(
4883 KV: {FD->getCanonicalDecl(), DeducedResultType});
4884 break;
4885 }
4886
4887 case DeclUpdateKind::DeclMarkedUsed:
4888 // Maintain AST consistency: any later redeclarations are used too.
4889 D->markUsed(C&: Reader.getContext());
4890 break;
4891
4892 case DeclUpdateKind::ManglingNumber:
4893 Reader.getContext().setManglingNumber(ND: cast<NamedDecl>(Val: D),
4894 Number: Record.readInt());
4895 break;
4896
4897 case DeclUpdateKind::StaticLocalNumber:
4898 Reader.getContext().setStaticLocalNumber(VD: cast<VarDecl>(Val: D),
4899 Number: Record.readInt());
4900 break;
4901
4902 case DeclUpdateKind::DeclMarkedOpenMPThreadPrivate:
4903 D->addAttr(A: OMPThreadPrivateDeclAttr::CreateImplicit(Ctx&: Reader.getContext(),
4904 Range: readSourceRange()));
4905 break;
4906
4907 case DeclUpdateKind::DeclMarkedOpenMPAllocate: {
4908 auto AllocatorKind =
4909 static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(Record.readInt());
4910 Expr *Allocator = Record.readExpr();
4911 Expr *Alignment = Record.readExpr();
4912 SourceRange SR = readSourceRange();
4913 D->addAttr(A: OMPAllocateDeclAttr::CreateImplicit(
4914 Ctx&: Reader.getContext(), AllocatorType: AllocatorKind, Allocator, Alignment, Range: SR));
4915 break;
4916 }
4917
4918 case DeclUpdateKind::DeclExported: {
4919 unsigned SubmoduleID = readSubmoduleID();
4920 auto *Exported = cast<NamedDecl>(Val: D);
4921 Module *Owner = SubmoduleID ? Reader.getSubmodule(GlobalID: SubmoduleID) : nullptr;
4922 Reader.getContext().mergeDefinitionIntoModule(ND: Exported, M: Owner);
4923 Reader.PendingMergedDefinitionsToDeduplicate.insert(X: Exported);
4924 break;
4925 }
4926
4927 case DeclUpdateKind::DeclMarkedOpenMPDeclareTarget: {
4928 auto MapType = Record.readEnum<OMPDeclareTargetDeclAttr::MapTypeTy>();
4929 auto DevType = Record.readEnum<OMPDeclareTargetDeclAttr::DevTypeTy>();
4930 Expr *IndirectE = Record.readExpr();
4931 bool Indirect = Record.readBool();
4932 unsigned Level = Record.readInt();
4933 D->addAttr(A: OMPDeclareTargetDeclAttr::CreateImplicit(
4934 Ctx&: Reader.getContext(), MapType, DevType, IndirectExpr: IndirectE, Indirect, Level,
4935 Range: readSourceRange()));
4936 break;
4937 }
4938
4939 case DeclUpdateKind::AddedAttrToRecord:
4940 AttrVec Attrs;
4941 Record.readAttributes(Attrs);
4942 assert(Attrs.size() == 1);
4943 D->addAttr(A: Attrs[0]);
4944 break;
4945 }
4946 }
4947}
4948

source code of clang/lib/Serialization/ASTReaderDecl.cpp