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 }
1638
1639 // If this variable has a deduced type, defer reading that type until we are
1640 // done deserializing this variable, because the type might refer back to the
1641 // variable.
1642 if (HasDeducedType)
1643 Reader.PendingDeducedVarTypes.push_back(Elt: {VD, DeferredTypeID});
1644 else
1645 VD->setType(Reader.GetType(ID: DeferredTypeID));
1646 DeferredTypeID = 0;
1647
1648 VD->setCachedLinkage(VarLinkage);
1649
1650 // Reconstruct the one piece of the IdentifierNamespace that we need.
1651 if (VD->getStorageClass() == SC_Extern && VarLinkage != Linkage::None &&
1652 VD->getLexicalDeclContext()->isFunctionOrMethod())
1653 VD->setLocalExternDecl();
1654
1655 if (DefGeneratedInModule) {
1656 Reader.DefinitionSource[VD] =
1657 Loc.F->Kind == ModuleKind::MK_MainFile ||
1658 Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;
1659 }
1660
1661 if (VD->hasAttr<BlocksAttr>()) {
1662 Expr *CopyExpr = Record.readExpr();
1663 if (CopyExpr)
1664 Reader.getContext().setBlockVarCopyInit(VD, CopyExpr, CanThrow: Record.readInt());
1665 }
1666
1667 enum VarKind {
1668 VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
1669 };
1670 switch ((VarKind)Record.readInt()) {
1671 case VarNotTemplate:
1672 // Only true variables (not parameters or implicit parameters) can be
1673 // merged; the other kinds are not really redeclarable at all.
1674 if (!isa<ParmVarDecl>(Val: VD) && !isa<ImplicitParamDecl>(Val: VD) &&
1675 !isa<VarTemplateSpecializationDecl>(Val: VD))
1676 mergeRedeclarable(DBase: VD, Redecl);
1677 break;
1678 case VarTemplate:
1679 // Merged when we merge the template.
1680 VD->setDescribedVarTemplate(readDeclAs<VarTemplateDecl>());
1681 break;
1682 case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
1683 auto *Tmpl = readDeclAs<VarDecl>();
1684 auto TSK = (TemplateSpecializationKind)Record.readInt();
1685 SourceLocation POI = readSourceLocation();
1686 Reader.getContext().setInstantiatedFromStaticDataMember(Inst: VD, Tmpl, TSK,PointOfInstantiation: POI);
1687 mergeRedeclarable(DBase: VD, Redecl);
1688 break;
1689 }
1690 }
1691
1692 return Redecl;
1693}
1694
1695void ASTDeclReader::ReadVarDeclInit(VarDecl *VD) {
1696 if (uint64_t Val = Record.readInt()) {
1697 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
1698 Eval->HasConstantInitialization = (Val & 2) != 0;
1699 Eval->HasConstantDestruction = (Val & 4) != 0;
1700 Eval->WasEvaluated = (Val & 8) != 0;
1701 Eval->HasSideEffects = (Val & 16) != 0;
1702 Eval->CheckedForSideEffects = true;
1703 if (Eval->WasEvaluated) {
1704 Eval->Evaluated = Record.readAPValue();
1705 if (Eval->Evaluated.needsCleanup())
1706 Reader.getContext().addDestruction(Ptr: &Eval->Evaluated);
1707 }
1708
1709 // Store the offset of the initializer. Don't deserialize it yet: it might
1710 // not be needed, and might refer back to the variable, for example if it
1711 // contains a lambda.
1712 Eval->Value = GetCurrentCursorOffset();
1713 }
1714}
1715
1716void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1717 VisitVarDecl(VD: PD);
1718}
1719
1720void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1721 VisitVarDecl(VD: PD);
1722
1723 unsigned scopeIndex = Record.readInt();
1724 BitsUnpacker ParmVarDeclBits(Record.readInt());
1725 unsigned isObjCMethodParam = ParmVarDeclBits.getNextBit();
1726 unsigned scopeDepth = ParmVarDeclBits.getNextBits(/*Width=*/7);
1727 unsigned declQualifier = ParmVarDeclBits.getNextBits(/*Width=*/7);
1728 if (isObjCMethodParam) {
1729 assert(scopeDepth == 0);
1730 PD->setObjCMethodScopeInfo(scopeIndex);
1731 PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1732 } else {
1733 PD->setScopeInfo(scopeDepth, parameterIndex: scopeIndex);
1734 }
1735 PD->ParmVarDeclBits.IsKNRPromoted = ParmVarDeclBits.getNextBit();
1736
1737 PD->ParmVarDeclBits.HasInheritedDefaultArg = ParmVarDeclBits.getNextBit();
1738 if (ParmVarDeclBits.getNextBit()) // hasUninstantiatedDefaultArg.
1739 PD->setUninstantiatedDefaultArg(Record.readExpr());
1740
1741 if (ParmVarDeclBits.getNextBit()) // Valid explicit object parameter
1742 PD->ExplicitObjectParameterIntroducerLoc = Record.readSourceLocation();
1743
1744 // FIXME: If this is a redeclaration of a function from another module, handle
1745 // inheritance of default arguments.
1746}
1747
1748void ASTDeclReader::VisitDecompositionDecl(DecompositionDecl *DD) {
1749 VisitVarDecl(VD: DD);
1750 auto **BDs = DD->getTrailingObjects();
1751 for (unsigned I = 0; I != DD->NumBindings; ++I) {
1752 BDs[I] = readDeclAs<BindingDecl>();
1753 BDs[I]->setDecomposedDecl(DD);
1754 }
1755}
1756
1757void ASTDeclReader::VisitBindingDecl(BindingDecl *BD) {
1758 VisitValueDecl(VD: BD);
1759 BD->Binding = Record.readExpr();
1760}
1761
1762void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1763 VisitDecl(D: AD);
1764 AD->setAsmString(cast<StringLiteral>(Val: Record.readExpr()));
1765 AD->setRParenLoc(readSourceLocation());
1766}
1767
1768void ASTDeclReader::VisitTopLevelStmtDecl(TopLevelStmtDecl *D) {
1769 VisitDecl(D);
1770 D->Statement = Record.readStmt();
1771}
1772
1773void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1774 VisitDecl(D: BD);
1775 BD->setBody(cast_or_null<CompoundStmt>(Val: Record.readStmt()));
1776 BD->setSignatureAsWritten(readTypeSourceInfo());
1777 unsigned NumParams = Record.readInt();
1778 SmallVector<ParmVarDecl *, 16> Params;
1779 Params.reserve(N: NumParams);
1780 for (unsigned I = 0; I != NumParams; ++I)
1781 Params.push_back(Elt: readDeclAs<ParmVarDecl>());
1782 BD->setParams(Params);
1783
1784 BD->setIsVariadic(Record.readInt());
1785 BD->setBlockMissingReturnType(Record.readInt());
1786 BD->setIsConversionFromLambda(Record.readInt());
1787 BD->setDoesNotEscape(Record.readInt());
1788 BD->setCanAvoidCopyToHeap(Record.readInt());
1789
1790 bool capturesCXXThis = Record.readInt();
1791 unsigned numCaptures = Record.readInt();
1792 SmallVector<BlockDecl::Capture, 16> captures;
1793 captures.reserve(N: numCaptures);
1794 for (unsigned i = 0; i != numCaptures; ++i) {
1795 auto *decl = readDeclAs<VarDecl>();
1796 unsigned flags = Record.readInt();
1797 bool byRef = (flags & 1);
1798 bool nested = (flags & 2);
1799 Expr *copyExpr = ((flags & 4) ? Record.readExpr() : nullptr);
1800
1801 captures.push_back(Elt: BlockDecl::Capture(decl, byRef, nested, copyExpr));
1802 }
1803 BD->setCaptures(Context&: Reader.getContext(), Captures: captures, CapturesCXXThis: capturesCXXThis);
1804}
1805
1806void ASTDeclReader::VisitOutlinedFunctionDecl(OutlinedFunctionDecl *D) {
1807 // NumParams is deserialized by OutlinedFunctionDecl::CreateDeserialized().
1808 VisitDecl(D);
1809 for (unsigned I = 0; I < D->NumParams; ++I)
1810 D->setParam(i: I, P: readDeclAs<ImplicitParamDecl>());
1811 D->setNothrow(Record.readInt() != 0);
1812 D->setBody(cast_or_null<Stmt>(Val: Record.readStmt()));
1813}
1814
1815void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1816 VisitDecl(D: CD);
1817 unsigned ContextParamPos = Record.readInt();
1818 CD->setNothrow(Record.readInt() != 0);
1819 // Body is set by VisitCapturedStmt.
1820 for (unsigned I = 0; I < CD->NumParams; ++I) {
1821 if (I != ContextParamPos)
1822 CD->setParam(i: I, P: readDeclAs<ImplicitParamDecl>());
1823 else
1824 CD->setContextParam(i: I, P: readDeclAs<ImplicitParamDecl>());
1825 }
1826}
1827
1828void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1829 VisitDecl(D);
1830 D->setLanguage(static_cast<LinkageSpecLanguageIDs>(Record.readInt()));
1831 D->setExternLoc(readSourceLocation());
1832 D->setRBraceLoc(readSourceLocation());
1833}
1834
1835void ASTDeclReader::VisitExportDecl(ExportDecl *D) {
1836 VisitDecl(D);
1837 D->RBraceLoc = readSourceLocation();
1838}
1839
1840void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1841 VisitNamedDecl(ND: D);
1842 D->setLocStart(readSourceLocation());
1843}
1844
1845void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1846 RedeclarableResult Redecl = VisitRedeclarable(D);
1847 VisitNamedDecl(ND: D);
1848
1849 BitsUnpacker NamespaceDeclBits(Record.readInt());
1850 D->setInline(NamespaceDeclBits.getNextBit());
1851 D->setNested(NamespaceDeclBits.getNextBit());
1852 D->LocStart = readSourceLocation();
1853 D->RBraceLoc = readSourceLocation();
1854
1855 // Defer loading the anonymous namespace until we've finished merging
1856 // this namespace; loading it might load a later declaration of the
1857 // same namespace, and we have an invariant that older declarations
1858 // get merged before newer ones try to merge.
1859 GlobalDeclID AnonNamespace;
1860 if (Redecl.getFirstID() == ThisDeclID)
1861 AnonNamespace = readDeclID();
1862
1863 mergeRedeclarable(DBase: D, Redecl);
1864
1865 if (AnonNamespace.isValid()) {
1866 // Each module has its own anonymous namespace, which is disjoint from
1867 // any other module's anonymous namespaces, so don't attach the anonymous
1868 // namespace at all.
1869 auto *Anon = cast<NamespaceDecl>(Val: Reader.GetDecl(ID: AnonNamespace));
1870 if (!Record.isModule())
1871 D->setAnonymousNamespace(Anon);
1872 }
1873}
1874
1875void ASTDeclReader::VisitHLSLBufferDecl(HLSLBufferDecl *D) {
1876 VisitNamedDecl(ND: D);
1877 LookupBlockOffsets Offsets;
1878 VisitDeclContext(DC: D, Offsets);
1879 D->IsCBuffer = Record.readBool();
1880 D->KwLoc = readSourceLocation();
1881 D->LBraceLoc = readSourceLocation();
1882 D->RBraceLoc = readSourceLocation();
1883}
1884
1885void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1886 RedeclarableResult Redecl = VisitRedeclarable(D);
1887 VisitNamedDecl(ND: D);
1888 D->NamespaceLoc = readSourceLocation();
1889 D->IdentLoc = readSourceLocation();
1890 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1891 D->Namespace = readDeclAs<NamedDecl>();
1892 mergeRedeclarable(DBase: D, Redecl);
1893}
1894
1895void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1896 VisitNamedDecl(ND: D);
1897 D->setUsingLoc(readSourceLocation());
1898 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1899 D->DNLoc = Record.readDeclarationNameLoc(Name: D->getDeclName());
1900 D->FirstUsingShadow.setPointer(readDeclAs<UsingShadowDecl>());
1901 D->setTypename(Record.readInt());
1902 if (auto *Pattern = readDeclAs<NamedDecl>())
1903 Reader.getContext().setInstantiatedFromUsingDecl(Inst: D, Pattern);
1904 mergeMergeable(D);
1905}
1906
1907void ASTDeclReader::VisitUsingEnumDecl(UsingEnumDecl *D) {
1908 VisitNamedDecl(ND: D);
1909 D->setUsingLoc(readSourceLocation());
1910 D->setEnumLoc(readSourceLocation());
1911 D->setEnumType(Record.readTypeSourceInfo());
1912 D->FirstUsingShadow.setPointer(readDeclAs<UsingShadowDecl>());
1913 if (auto *Pattern = readDeclAs<UsingEnumDecl>())
1914 Reader.getContext().setInstantiatedFromUsingEnumDecl(Inst: D, Pattern);
1915 mergeMergeable(D);
1916}
1917
1918void ASTDeclReader::VisitUsingPackDecl(UsingPackDecl *D) {
1919 VisitNamedDecl(ND: D);
1920 D->InstantiatedFrom = readDeclAs<NamedDecl>();
1921 auto **Expansions = D->getTrailingObjects();
1922 for (unsigned I = 0; I != D->NumExpansions; ++I)
1923 Expansions[I] = readDeclAs<NamedDecl>();
1924 mergeMergeable(D);
1925}
1926
1927void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1928 RedeclarableResult Redecl = VisitRedeclarable(D);
1929 VisitNamedDecl(ND: D);
1930 D->Underlying = readDeclAs<NamedDecl>();
1931 D->IdentifierNamespace = Record.readInt();
1932 D->UsingOrNextShadow = readDeclAs<NamedDecl>();
1933 auto *Pattern = readDeclAs<UsingShadowDecl>();
1934 if (Pattern)
1935 Reader.getContext().setInstantiatedFromUsingShadowDecl(Inst: D, Pattern);
1936 mergeRedeclarable(DBase: D, Redecl);
1937}
1938
1939void ASTDeclReader::VisitConstructorUsingShadowDecl(
1940 ConstructorUsingShadowDecl *D) {
1941 VisitUsingShadowDecl(D);
1942 D->NominatedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1943 D->ConstructedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1944 D->IsVirtual = Record.readInt();
1945}
1946
1947void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1948 VisitNamedDecl(ND: D);
1949 D->UsingLoc = readSourceLocation();
1950 D->NamespaceLoc = readSourceLocation();
1951 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1952 D->NominatedNamespace = readDeclAs<NamedDecl>();
1953 D->CommonAncestor = readDeclAs<DeclContext>();
1954}
1955
1956void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1957 VisitValueDecl(VD: D);
1958 D->setUsingLoc(readSourceLocation());
1959 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1960 D->DNLoc = Record.readDeclarationNameLoc(Name: D->getDeclName());
1961 D->EllipsisLoc = readSourceLocation();
1962 mergeMergeable(D);
1963}
1964
1965void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1966 UnresolvedUsingTypenameDecl *D) {
1967 VisitTypeDecl(TD: D);
1968 D->TypenameLocation = readSourceLocation();
1969 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1970 D->EllipsisLoc = readSourceLocation();
1971 mergeMergeable(D);
1972}
1973
1974void ASTDeclReader::VisitUnresolvedUsingIfExistsDecl(
1975 UnresolvedUsingIfExistsDecl *D) {
1976 VisitNamedDecl(ND: D);
1977}
1978
1979void ASTDeclReader::ReadCXXDefinitionData(
1980 struct CXXRecordDecl::DefinitionData &Data, const CXXRecordDecl *D,
1981 Decl *LambdaContext, unsigned IndexInLambdaContext) {
1982
1983 BitsUnpacker CXXRecordDeclBits = Record.readInt();
1984
1985#define FIELD(Name, Width, Merge) \
1986 if (!CXXRecordDeclBits.canGetNextNBits(Width)) \
1987 CXXRecordDeclBits.updateValue(Record.readInt()); \
1988 Data.Name = CXXRecordDeclBits.getNextBits(Width);
1989
1990#include "clang/AST/CXXRecordDeclDefinitionBits.def"
1991#undef FIELD
1992
1993 // Note: the caller has deserialized the IsLambda bit already.
1994 Data.ODRHash = Record.readInt();
1995 Data.HasODRHash = true;
1996
1997 if (Record.readInt()) {
1998 Reader.DefinitionSource[D] =
1999 Loc.F->Kind == ModuleKind::MK_MainFile ||
2000 Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;
2001 }
2002
2003 Record.readUnresolvedSet(Set&: Data.Conversions);
2004 Data.ComputedVisibleConversions = Record.readInt();
2005 if (Data.ComputedVisibleConversions)
2006 Record.readUnresolvedSet(Set&: Data.VisibleConversions);
2007 assert(Data.Definition && "Data.Definition should be already set!");
2008
2009 if (!Data.IsLambda) {
2010 assert(!LambdaContext && !IndexInLambdaContext &&
2011 "given lambda context for non-lambda");
2012
2013 Data.NumBases = Record.readInt();
2014 if (Data.NumBases)
2015 Data.Bases = ReadGlobalOffset();
2016
2017 Data.NumVBases = Record.readInt();
2018 if (Data.NumVBases)
2019 Data.VBases = ReadGlobalOffset();
2020
2021 Data.FirstFriend = readDeclID().getRawValue();
2022 } else {
2023 using Capture = LambdaCapture;
2024
2025 auto &Lambda = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
2026
2027 BitsUnpacker LambdaBits(Record.readInt());
2028 Lambda.DependencyKind = LambdaBits.getNextBits(/*Width=*/2);
2029 Lambda.IsGenericLambda = LambdaBits.getNextBit();
2030 Lambda.CaptureDefault = LambdaBits.getNextBits(/*Width=*/2);
2031 Lambda.NumCaptures = LambdaBits.getNextBits(/*Width=*/15);
2032 Lambda.HasKnownInternalLinkage = LambdaBits.getNextBit();
2033
2034 Lambda.NumExplicitCaptures = Record.readInt();
2035 Lambda.ManglingNumber = Record.readInt();
2036 if (unsigned DeviceManglingNumber = Record.readInt())
2037 Reader.getContext().DeviceLambdaManglingNumbers[D] = DeviceManglingNumber;
2038 Lambda.IndexInContext = IndexInLambdaContext;
2039 Lambda.ContextDecl = LambdaContext;
2040 Capture *ToCapture = nullptr;
2041 if (Lambda.NumCaptures) {
2042 ToCapture = (Capture *)Reader.getContext().Allocate(Size: sizeof(Capture) *
2043 Lambda.NumCaptures);
2044 Lambda.AddCaptureList(Ctx&: Reader.getContext(), CaptureList: ToCapture);
2045 }
2046 Lambda.MethodTyInfo = readTypeSourceInfo();
2047 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
2048 SourceLocation Loc = readSourceLocation();
2049 BitsUnpacker CaptureBits(Record.readInt());
2050 bool IsImplicit = CaptureBits.getNextBit();
2051 auto Kind =
2052 static_cast<LambdaCaptureKind>(CaptureBits.getNextBits(/*Width=*/3));
2053 switch (Kind) {
2054 case LCK_StarThis:
2055 case LCK_This:
2056 case LCK_VLAType:
2057 new (ToCapture)
2058 Capture(Loc, IsImplicit, Kind, nullptr, SourceLocation());
2059 ToCapture++;
2060 break;
2061 case LCK_ByCopy:
2062 case LCK_ByRef:
2063 auto *Var = readDeclAs<ValueDecl>();
2064 SourceLocation EllipsisLoc = readSourceLocation();
2065 new (ToCapture) Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
2066 ToCapture++;
2067 break;
2068 }
2069 }
2070 }
2071}
2072
2073void ASTDeclMerger::MergeDefinitionData(
2074 CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {
2075 assert(D->DefinitionData &&
2076 "merging class definition into non-definition");
2077 auto &DD = *D->DefinitionData;
2078
2079 if (DD.Definition != MergeDD.Definition) {
2080 // Track that we merged the definitions.
2081 Reader.MergedDeclContexts.insert(KV: std::make_pair(x&: MergeDD.Definition,
2082 y&: DD.Definition));
2083 Reader.PendingDefinitions.erase(Ptr: MergeDD.Definition);
2084 MergeDD.Definition->demoteThisDefinitionToDeclaration();
2085 Reader.mergeDefinitionVisibility(Def: DD.Definition, MergedDef: MergeDD.Definition);
2086 assert(!Reader.Lookups.contains(MergeDD.Definition) &&
2087 "already loaded pending lookups for merged definition");
2088 }
2089
2090 auto PFDI = Reader.PendingFakeDefinitionData.find(Val: &DD);
2091 if (PFDI != Reader.PendingFakeDefinitionData.end() &&
2092 PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) {
2093 // We faked up this definition data because we found a class for which we'd
2094 // not yet loaded the definition. Replace it with the real thing now.
2095 assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?");
2096 PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded;
2097
2098 // Don't change which declaration is the definition; that is required
2099 // to be invariant once we select it.
2100 auto *Def = DD.Definition;
2101 DD = std::move(MergeDD);
2102 DD.Definition = Def;
2103 return;
2104 }
2105
2106 bool DetectedOdrViolation = false;
2107
2108 #define FIELD(Name, Width, Merge) Merge(Name)
2109 #define MERGE_OR(Field) DD.Field |= MergeDD.Field;
2110 #define NO_MERGE(Field) \
2111 DetectedOdrViolation |= DD.Field != MergeDD.Field; \
2112 MERGE_OR(Field)
2113 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
2114 NO_MERGE(IsLambda)
2115 #undef NO_MERGE
2116 #undef MERGE_OR
2117
2118 if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
2119 DetectedOdrViolation = true;
2120 // FIXME: Issue a diagnostic if the base classes don't match when we come
2121 // to lazily load them.
2122
2123 // FIXME: Issue a diagnostic if the list of conversion functions doesn't
2124 // match when we come to lazily load them.
2125 if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
2126 DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
2127 DD.ComputedVisibleConversions = true;
2128 }
2129
2130 // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
2131 // lazily load it.
2132
2133 if (DD.IsLambda) {
2134 auto &Lambda1 = static_cast<CXXRecordDecl::LambdaDefinitionData &>(DD);
2135 auto &Lambda2 = static_cast<CXXRecordDecl::LambdaDefinitionData &>(MergeDD);
2136 DetectedOdrViolation |= Lambda1.DependencyKind != Lambda2.DependencyKind;
2137 DetectedOdrViolation |= Lambda1.IsGenericLambda != Lambda2.IsGenericLambda;
2138 DetectedOdrViolation |= Lambda1.CaptureDefault != Lambda2.CaptureDefault;
2139 DetectedOdrViolation |= Lambda1.NumCaptures != Lambda2.NumCaptures;
2140 DetectedOdrViolation |=
2141 Lambda1.NumExplicitCaptures != Lambda2.NumExplicitCaptures;
2142 DetectedOdrViolation |=
2143 Lambda1.HasKnownInternalLinkage != Lambda2.HasKnownInternalLinkage;
2144 DetectedOdrViolation |= Lambda1.ManglingNumber != Lambda2.ManglingNumber;
2145
2146 if (Lambda1.NumCaptures && Lambda1.NumCaptures == Lambda2.NumCaptures) {
2147 for (unsigned I = 0, N = Lambda1.NumCaptures; I != N; ++I) {
2148 LambdaCapture &Cap1 = Lambda1.Captures.front()[I];
2149 LambdaCapture &Cap2 = Lambda2.Captures.front()[I];
2150 DetectedOdrViolation |= Cap1.getCaptureKind() != Cap2.getCaptureKind();
2151 }
2152 Lambda1.AddCaptureList(Ctx&: Reader.getContext(), CaptureList: Lambda2.Captures.front());
2153 }
2154 }
2155
2156 // We don't want to check ODR for decls in the global module fragment.
2157 if (shouldSkipCheckingODR(D: MergeDD.Definition) || shouldSkipCheckingODR(D))
2158 return;
2159
2160 if (D->getODRHash() != MergeDD.ODRHash) {
2161 DetectedOdrViolation = true;
2162 }
2163
2164 if (DetectedOdrViolation)
2165 Reader.PendingOdrMergeFailures[DD.Definition].push_back(
2166 Elt: {MergeDD.Definition, &MergeDD});
2167}
2168
2169void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update,
2170 Decl *LambdaContext,
2171 unsigned IndexInLambdaContext) {
2172 struct CXXRecordDecl::DefinitionData *DD;
2173 ASTContext &C = Reader.getContext();
2174
2175 // Determine whether this is a lambda closure type, so that we can
2176 // allocate the appropriate DefinitionData structure.
2177 bool IsLambda = Record.readInt();
2178 assert(!(IsLambda && Update) &&
2179 "lambda definition should not be added by update record");
2180 if (IsLambda)
2181 DD = new (C) CXXRecordDecl::LambdaDefinitionData(
2182 D, nullptr, CXXRecordDecl::LDK_Unknown, false, LCD_None);
2183 else
2184 DD = new (C) struct CXXRecordDecl::DefinitionData(D);
2185
2186 CXXRecordDecl *Canon = D->getCanonicalDecl();
2187 // Set decl definition data before reading it, so that during deserialization
2188 // when we read CXXRecordDecl, it already has definition data and we don't
2189 // set fake one.
2190 if (!Canon->DefinitionData)
2191 Canon->DefinitionData = DD;
2192 D->DefinitionData = Canon->DefinitionData;
2193 ReadCXXDefinitionData(Data&: *DD, D, LambdaContext, IndexInLambdaContext);
2194
2195 // Mark this declaration as being a definition.
2196 D->setCompleteDefinition(true);
2197
2198 // We might already have a different definition for this record. This can
2199 // happen either because we're reading an update record, or because we've
2200 // already done some merging. Either way, just merge into it.
2201 if (Canon->DefinitionData != DD) {
2202 MergeImpl.MergeDefinitionData(D: Canon, MergeDD: std::move(*DD));
2203 return;
2204 }
2205
2206 // If this is not the first declaration or is an update record, we can have
2207 // other redeclarations already. Make a note that we need to propagate the
2208 // DefinitionData pointer onto them.
2209 if (Update || Canon != D)
2210 Reader.PendingDefinitions.insert(Ptr: D);
2211}
2212
2213RedeclarableResult ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
2214 RedeclarableResult Redecl = VisitRecordDeclImpl(RD: D);
2215
2216 ASTContext &C = Reader.getContext();
2217
2218 enum CXXRecKind {
2219 CXXRecNotTemplate = 0,
2220 CXXRecTemplate,
2221 CXXRecMemberSpecialization,
2222 CXXLambda
2223 };
2224
2225 Decl *LambdaContext = nullptr;
2226 unsigned IndexInLambdaContext = 0;
2227
2228 switch ((CXXRecKind)Record.readInt()) {
2229 case CXXRecNotTemplate:
2230 // Merged when we merge the folding set entry in the primary template.
2231 if (!isa<ClassTemplateSpecializationDecl>(Val: D))
2232 mergeRedeclarable(DBase: D, Redecl);
2233 break;
2234 case CXXRecTemplate: {
2235 // Merged when we merge the template.
2236 auto *Template = readDeclAs<ClassTemplateDecl>();
2237 D->TemplateOrInstantiation = Template;
2238 if (!Template->getTemplatedDecl()) {
2239 // We've not actually loaded the ClassTemplateDecl yet, because we're
2240 // currently being loaded as its pattern. Rely on it to set up our
2241 // TypeForDecl (see VisitClassTemplateDecl).
2242 //
2243 // Beware: we do not yet know our canonical declaration, and may still
2244 // get merged once the surrounding class template has got off the ground.
2245 DeferredTypeID = 0;
2246 }
2247 break;
2248 }
2249 case CXXRecMemberSpecialization: {
2250 auto *RD = readDeclAs<CXXRecordDecl>();
2251 auto TSK = (TemplateSpecializationKind)Record.readInt();
2252 SourceLocation POI = readSourceLocation();
2253 MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
2254 MSI->setPointOfInstantiation(POI);
2255 D->TemplateOrInstantiation = MSI;
2256 mergeRedeclarable(DBase: D, Redecl);
2257 break;
2258 }
2259 case CXXLambda: {
2260 LambdaContext = readDecl();
2261 if (LambdaContext)
2262 IndexInLambdaContext = Record.readInt();
2263 if (LambdaContext)
2264 MergeImpl.mergeLambda(D, Redecl, Context&: *LambdaContext, Number: IndexInLambdaContext);
2265 else
2266 // If we don't have a mangling context, treat this like any other
2267 // declaration.
2268 mergeRedeclarable(DBase: D, Redecl);
2269 break;
2270 }
2271 }
2272
2273 bool WasDefinition = Record.readInt();
2274 if (WasDefinition)
2275 ReadCXXRecordDefinition(D, /*Update=*/false, LambdaContext,
2276 IndexInLambdaContext);
2277 else
2278 // Propagate DefinitionData pointer from the canonical declaration.
2279 D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
2280
2281 // Lazily load the key function to avoid deserializing every method so we can
2282 // compute it.
2283 if (WasDefinition) {
2284 GlobalDeclID KeyFn = readDeclID();
2285 if (KeyFn.isValid() && D->isCompleteDefinition())
2286 // FIXME: This is wrong for the ARM ABI, where some other module may have
2287 // made this function no longer be a key function. We need an update
2288 // record or similar for that case.
2289 C.KeyFunctions[D] = KeyFn.getRawValue();
2290 }
2291
2292 return Redecl;
2293}
2294
2295void ASTDeclReader::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
2296 D->setExplicitSpecifier(Record.readExplicitSpec());
2297 D->Ctor = readDeclAs<CXXConstructorDecl>();
2298 VisitFunctionDecl(FD: D);
2299 D->setDeductionCandidateKind(
2300 static_cast<DeductionCandidate>(Record.readInt()));
2301 D->setSourceDeductionGuide(readDeclAs<CXXDeductionGuideDecl>());
2302 D->setSourceDeductionGuideKind(
2303 static_cast<CXXDeductionGuideDecl::SourceDeductionGuideKind>(
2304 Record.readInt()));
2305}
2306
2307void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
2308 VisitFunctionDecl(FD: D);
2309
2310 unsigned NumOverridenMethods = Record.readInt();
2311 if (D->isCanonicalDecl()) {
2312 while (NumOverridenMethods--) {
2313 // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
2314 // MD may be initializing.
2315 if (auto *MD = readDeclAs<CXXMethodDecl>())
2316 Reader.getContext().addOverriddenMethod(Method: D, Overridden: MD->getCanonicalDecl());
2317 }
2318 } else {
2319 // We don't care about which declarations this used to override; we get
2320 // the relevant information from the canonical declaration.
2321 Record.skipInts(N: NumOverridenMethods);
2322 }
2323}
2324
2325void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2326 // We need the inherited constructor information to merge the declaration,
2327 // so we have to read it before we call VisitCXXMethodDecl.
2328 D->setExplicitSpecifier(Record.readExplicitSpec());
2329 if (D->isInheritingConstructor()) {
2330 auto *Shadow = readDeclAs<ConstructorUsingShadowDecl>();
2331 auto *Ctor = readDeclAs<CXXConstructorDecl>();
2332 *D->getTrailingObjects<InheritedConstructor>() =
2333 InheritedConstructor(Shadow, Ctor);
2334 }
2335
2336 VisitCXXMethodDecl(D);
2337}
2338
2339void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2340 VisitCXXMethodDecl(D);
2341
2342 if (auto *OperatorDelete = readDeclAs<FunctionDecl>()) {
2343 CXXDestructorDecl *Canon = D->getCanonicalDecl();
2344 auto *ThisArg = Record.readExpr();
2345 // FIXME: Check consistency if we have an old and new operator delete.
2346 if (!Canon->OperatorDelete) {
2347 Canon->OperatorDelete = OperatorDelete;
2348 Canon->OperatorDeleteThisArg = ThisArg;
2349 }
2350 }
2351}
2352
2353void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
2354 D->setExplicitSpecifier(Record.readExplicitSpec());
2355 VisitCXXMethodDecl(D);
2356}
2357
2358void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
2359 VisitDecl(D);
2360 D->ImportedModule = readModule();
2361 D->setImportComplete(Record.readInt());
2362 auto *StoredLocs = D->getTrailingObjects();
2363 for (unsigned I = 0, N = Record.back(); I != N; ++I)
2364 StoredLocs[I] = readSourceLocation();
2365 Record.skipInts(N: 1); // The number of stored source locations.
2366}
2367
2368void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
2369 VisitDecl(D);
2370 D->setColonLoc(readSourceLocation());
2371}
2372
2373void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
2374 VisitDecl(D);
2375 if (Record.readInt()) // hasFriendDecl
2376 D->Friend = readDeclAs<NamedDecl>();
2377 else
2378 D->Friend = readTypeSourceInfo();
2379 for (unsigned i = 0; i != D->NumTPLists; ++i)
2380 D->getTrailingObjects()[i] = Record.readTemplateParameterList();
2381 D->NextFriend = readDeclID().getRawValue();
2382 D->UnsupportedFriend = (Record.readInt() != 0);
2383 D->FriendLoc = readSourceLocation();
2384 D->EllipsisLoc = readSourceLocation();
2385}
2386
2387void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2388 VisitDecl(D);
2389 unsigned NumParams = Record.readInt();
2390 D->NumParams = NumParams;
2391 D->Params = new (Reader.getContext()) TemplateParameterList *[NumParams];
2392 for (unsigned i = 0; i != NumParams; ++i)
2393 D->Params[i] = Record.readTemplateParameterList();
2394 if (Record.readInt()) // HasFriendDecl
2395 D->Friend = readDeclAs<NamedDecl>();
2396 else
2397 D->Friend = readTypeSourceInfo();
2398 D->FriendLoc = readSourceLocation();
2399}
2400
2401void ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
2402 VisitNamedDecl(ND: D);
2403
2404 assert(!D->TemplateParams && "TemplateParams already set!");
2405 D->TemplateParams = Record.readTemplateParameterList();
2406 D->init(NewTemplatedDecl: readDeclAs<NamedDecl>());
2407}
2408
2409void ASTDeclReader::VisitConceptDecl(ConceptDecl *D) {
2410 VisitTemplateDecl(D);
2411 D->ConstraintExpr = Record.readExpr();
2412 mergeMergeable(D);
2413}
2414
2415void ASTDeclReader::VisitImplicitConceptSpecializationDecl(
2416 ImplicitConceptSpecializationDecl *D) {
2417 // The size of the template list was read during creation of the Decl, so we
2418 // don't have to re-read it here.
2419 VisitDecl(D);
2420 llvm::SmallVector<TemplateArgument, 4> Args;
2421 for (unsigned I = 0; I < D->NumTemplateArgs; ++I)
2422 Args.push_back(Elt: Record.readTemplateArgument(/*Canonicalize=*/true));
2423 D->setTemplateArguments(Args);
2424}
2425
2426void ASTDeclReader::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
2427}
2428
2429void ASTDeclReader::ReadSpecializations(ModuleFile &M, Decl *D,
2430 llvm::BitstreamCursor &DeclsCursor,
2431 bool IsPartial) {
2432 uint64_t Offset = ReadLocalOffset();
2433 bool Failed =
2434 Reader.ReadSpecializations(M, Cursor&: DeclsCursor, Offset, D, IsPartial);
2435 (void)Failed;
2436 assert(!Failed);
2437}
2438
2439RedeclarableResult
2440ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
2441 RedeclarableResult Redecl = VisitRedeclarable(D);
2442
2443 // Make sure we've allocated the Common pointer first. We do this before
2444 // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
2445 RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
2446 if (!CanonD->Common) {
2447 CanonD->Common = CanonD->newCommon(C&: Reader.getContext());
2448 Reader.PendingDefinitions.insert(Ptr: CanonD);
2449 }
2450 D->Common = CanonD->Common;
2451
2452 // If this is the first declaration of the template, fill in the information
2453 // for the 'common' pointer.
2454 if (ThisDeclID == Redecl.getFirstID()) {
2455 if (auto *RTD = readDeclAs<RedeclarableTemplateDecl>()) {
2456 assert(RTD->getKind() == D->getKind() &&
2457 "InstantiatedFromMemberTemplate kind mismatch");
2458 D->setInstantiatedFromMemberTemplate(RTD);
2459 if (Record.readInt())
2460 D->setMemberSpecialization();
2461 }
2462 }
2463
2464 VisitTemplateDecl(D);
2465 D->IdentifierNamespace = Record.readInt();
2466
2467 return Redecl;
2468}
2469
2470void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
2471 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2472 mergeRedeclarableTemplate(D, Redecl);
2473
2474 if (ThisDeclID == Redecl.getFirstID()) {
2475 // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
2476 // the specializations.
2477 ReadSpecializations(M&: *Loc.F, D, DeclsCursor&: Loc.F->DeclsCursor, /*IsPartial=*/false);
2478 ReadSpecializations(M&: *Loc.F, D, DeclsCursor&: Loc.F->DeclsCursor, /*IsPartial=*/true);
2479 }
2480
2481 if (D->getTemplatedDecl()->TemplateOrInstantiation) {
2482 // We were loaded before our templated declaration was. We've not set up
2483 // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
2484 // it now.
2485 Reader.getContext().getInjectedClassNameType(
2486 Decl: D->getTemplatedDecl(), TST: D->getInjectedClassNameSpecialization());
2487 }
2488}
2489
2490void ASTDeclReader::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
2491 llvm_unreachable("BuiltinTemplates are not serialized");
2492}
2493
2494/// TODO: Unify with ClassTemplateDecl version?
2495/// May require unifying ClassTemplateDecl and
2496/// VarTemplateDecl beyond TemplateDecl...
2497void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
2498 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2499 mergeRedeclarableTemplate(D, Redecl);
2500
2501 if (ThisDeclID == Redecl.getFirstID()) {
2502 // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
2503 // the specializations.
2504 ReadSpecializations(M&: *Loc.F, D, DeclsCursor&: Loc.F->DeclsCursor, /*IsPartial=*/false);
2505 ReadSpecializations(M&: *Loc.F, D, DeclsCursor&: Loc.F->DeclsCursor, /*IsPartial=*/true);
2506 }
2507}
2508
2509RedeclarableResult ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
2510 ClassTemplateSpecializationDecl *D) {
2511 RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
2512
2513 ASTContext &C = Reader.getContext();
2514 if (Decl *InstD = readDecl()) {
2515 if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: InstD)) {
2516 D->SpecializedTemplate = CTD;
2517 } else {
2518 SmallVector<TemplateArgument, 8> TemplArgs;
2519 Record.readTemplateArgumentList(TemplArgs);
2520 TemplateArgumentList *ArgList
2521 = TemplateArgumentList::CreateCopy(Context&: C, Args: TemplArgs);
2522 auto *PS =
2523 new (C) ClassTemplateSpecializationDecl::
2524 SpecializedPartialSpecialization();
2525 PS->PartialSpecialization
2526 = cast<ClassTemplatePartialSpecializationDecl>(Val: InstD);
2527 PS->TemplateArgs = ArgList;
2528 D->SpecializedTemplate = PS;
2529 }
2530 }
2531
2532 SmallVector<TemplateArgument, 8> TemplArgs;
2533 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2534 D->TemplateArgs = TemplateArgumentList::CreateCopy(Context&: C, Args: TemplArgs);
2535 D->PointOfInstantiation = readSourceLocation();
2536 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2537 D->StrictPackMatch = Record.readBool();
2538
2539 bool writtenAsCanonicalDecl = Record.readInt();
2540 if (writtenAsCanonicalDecl) {
2541 auto *CanonPattern = readDeclAs<ClassTemplateDecl>();
2542 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2543 // Set this as, or find, the canonical declaration for this specialization
2544 ClassTemplateSpecializationDecl *CanonSpec;
2545 if (auto *Partial = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: D)) {
2546 CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
2547 .GetOrInsertNode(N: Partial);
2548 } else {
2549 CanonSpec =
2550 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(N: D);
2551 }
2552 // If there was already a canonical specialization, merge into it.
2553 if (CanonSpec != D) {
2554 MergeImpl.mergeRedeclarable<TagDecl>(D, Existing: CanonSpec, Redecl);
2555
2556 // This declaration might be a definition. Merge with any existing
2557 // definition.
2558 if (auto *DDD = D->DefinitionData) {
2559 if (CanonSpec->DefinitionData)
2560 MergeImpl.MergeDefinitionData(D: CanonSpec, MergeDD: std::move(*DDD));
2561 else
2562 CanonSpec->DefinitionData = D->DefinitionData;
2563 }
2564 D->DefinitionData = CanonSpec->DefinitionData;
2565 }
2566 }
2567 }
2568
2569 // extern/template keyword locations for explicit instantiations
2570 if (Record.readBool()) {
2571 auto *ExplicitInfo = new (C) ExplicitInstantiationInfo;
2572 ExplicitInfo->ExternKeywordLoc = readSourceLocation();
2573 ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2574 D->ExplicitInfo = ExplicitInfo;
2575 }
2576
2577 if (Record.readBool())
2578 D->setTemplateArgsAsWritten(Record.readASTTemplateArgumentListInfo());
2579
2580 return Redecl;
2581}
2582
2583void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
2584 ClassTemplatePartialSpecializationDecl *D) {
2585 // We need to read the template params first because redeclarable is going to
2586 // need them for profiling
2587 TemplateParameterList *Params = Record.readTemplateParameterList();
2588 D->TemplateParams = Params;
2589
2590 RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
2591
2592 // These are read/set from/to the first declaration.
2593 if (ThisDeclID == Redecl.getFirstID()) {
2594 D->InstantiatedFromMember.setPointer(
2595 readDeclAs<ClassTemplatePartialSpecializationDecl>());
2596 D->InstantiatedFromMember.setInt(Record.readInt());
2597 }
2598}
2599
2600void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2601 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2602
2603 if (ThisDeclID == Redecl.getFirstID()) {
2604 // This FunctionTemplateDecl owns a CommonPtr; read it.
2605 ReadSpecializations(M&: *Loc.F, D, DeclsCursor&: Loc.F->DeclsCursor, /*IsPartial=*/false);
2606 }
2607}
2608
2609/// TODO: Unify with ClassTemplateSpecializationDecl version?
2610/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2611/// VarTemplate(Partial)SpecializationDecl with a new data
2612/// structure Template(Partial)SpecializationDecl, and
2613/// using Template(Partial)SpecializationDecl as input type.
2614RedeclarableResult ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
2615 VarTemplateSpecializationDecl *D) {
2616 ASTContext &C = Reader.getContext();
2617 if (Decl *InstD = readDecl()) {
2618 if (auto *VTD = dyn_cast<VarTemplateDecl>(Val: InstD)) {
2619 D->SpecializedTemplate = VTD;
2620 } else {
2621 SmallVector<TemplateArgument, 8> TemplArgs;
2622 Record.readTemplateArgumentList(TemplArgs);
2623 TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
2624 Context&: C, Args: TemplArgs);
2625 auto *PS =
2626 new (C)
2627 VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
2628 PS->PartialSpecialization =
2629 cast<VarTemplatePartialSpecializationDecl>(Val: InstD);
2630 PS->TemplateArgs = ArgList;
2631 D->SpecializedTemplate = PS;
2632 }
2633 }
2634
2635 // extern/template keyword locations for explicit instantiations
2636 if (Record.readBool()) {
2637 auto *ExplicitInfo = new (C) ExplicitInstantiationInfo;
2638 ExplicitInfo->ExternKeywordLoc = readSourceLocation();
2639 ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2640 D->ExplicitInfo = ExplicitInfo;
2641 }
2642
2643 if (Record.readBool())
2644 D->setTemplateArgsAsWritten(Record.readASTTemplateArgumentListInfo());
2645
2646 SmallVector<TemplateArgument, 8> TemplArgs;
2647 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2648 D->TemplateArgs = TemplateArgumentList::CreateCopy(Context&: C, Args: TemplArgs);
2649 D->PointOfInstantiation = readSourceLocation();
2650 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2651 D->IsCompleteDefinition = Record.readInt();
2652
2653 RedeclarableResult Redecl = VisitVarDeclImpl(VD: D);
2654
2655 bool writtenAsCanonicalDecl = Record.readInt();
2656 if (writtenAsCanonicalDecl) {
2657 auto *CanonPattern = readDeclAs<VarTemplateDecl>();
2658 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2659 VarTemplateSpecializationDecl *CanonSpec;
2660 if (auto *Partial = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: D)) {
2661 CanonSpec = CanonPattern->getCommonPtr()
2662 ->PartialSpecializations.GetOrInsertNode(N: Partial);
2663 } else {
2664 CanonSpec =
2665 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(N: D);
2666 }
2667 // If we already have a matching specialization, merge it.
2668 if (CanonSpec != D)
2669 MergeImpl.mergeRedeclarable<VarDecl>(D, Existing: CanonSpec, Redecl);
2670 }
2671 }
2672
2673 return Redecl;
2674}
2675
2676/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2677/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2678/// VarTemplate(Partial)SpecializationDecl with a new data
2679/// structure Template(Partial)SpecializationDecl, and
2680/// using Template(Partial)SpecializationDecl as input type.
2681void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
2682 VarTemplatePartialSpecializationDecl *D) {
2683 TemplateParameterList *Params = Record.readTemplateParameterList();
2684 D->TemplateParams = Params;
2685
2686 RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
2687
2688 // These are read/set from/to the first declaration.
2689 if (ThisDeclID == Redecl.getFirstID()) {
2690 D->InstantiatedFromMember.setPointer(
2691 readDeclAs<VarTemplatePartialSpecializationDecl>());
2692 D->InstantiatedFromMember.setInt(Record.readInt());
2693 }
2694}
2695
2696void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
2697 VisitTypeDecl(TD: D);
2698
2699 D->setDeclaredWithTypename(Record.readInt());
2700
2701 bool TypeConstraintInitialized = D->hasTypeConstraint() && Record.readBool();
2702 if (TypeConstraintInitialized) {
2703 ConceptReference *CR = nullptr;
2704 if (Record.readBool())
2705 CR = Record.readConceptReference();
2706 Expr *ImmediatelyDeclaredConstraint = Record.readExpr();
2707 UnsignedOrNone ArgPackSubstIndex = Record.readUnsignedOrNone();
2708
2709 D->setTypeConstraint(CR, ImmediatelyDeclaredConstraint, ArgPackSubstIndex);
2710 D->NumExpanded = Record.readUnsignedOrNone();
2711 }
2712
2713 if (Record.readInt())
2714 D->setDefaultArgument(C: Reader.getContext(),
2715 DefArg: Record.readTemplateArgumentLoc());
2716}
2717
2718void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
2719 VisitDeclaratorDecl(DD: D);
2720 // TemplateParmPosition.
2721 D->setDepth(Record.readInt());
2722 D->setPosition(Record.readInt());
2723 if (D->hasPlaceholderTypeConstraint())
2724 D->setPlaceholderTypeConstraint(Record.readExpr());
2725 if (D->isExpandedParameterPack()) {
2726 auto TypesAndInfos =
2727 D->getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
2728 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2729 new (&TypesAndInfos[I].first) QualType(Record.readType());
2730 TypesAndInfos[I].second = readTypeSourceInfo();
2731 }
2732 } else {
2733 // Rest of NonTypeTemplateParmDecl.
2734 D->ParameterPack = Record.readInt();
2735 if (Record.readInt())
2736 D->setDefaultArgument(C: Reader.getContext(),
2737 DefArg: Record.readTemplateArgumentLoc());
2738 }
2739}
2740
2741void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
2742 VisitTemplateDecl(D);
2743 D->setDeclaredWithTypename(Record.readBool());
2744 // TemplateParmPosition.
2745 D->setDepth(Record.readInt());
2746 D->setPosition(Record.readInt());
2747 if (D->isExpandedParameterPack()) {
2748 auto **Data = D->getTrailingObjects();
2749 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2750 I != N; ++I)
2751 Data[I] = Record.readTemplateParameterList();
2752 } else {
2753 // Rest of TemplateTemplateParmDecl.
2754 D->ParameterPack = Record.readInt();
2755 if (Record.readInt())
2756 D->setDefaultArgument(C: Reader.getContext(),
2757 DefArg: Record.readTemplateArgumentLoc());
2758 }
2759}
2760
2761void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2762 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2763 mergeRedeclarableTemplate(D, Redecl);
2764}
2765
2766void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
2767 VisitDecl(D);
2768 D->AssertExprAndFailed.setPointer(Record.readExpr());
2769 D->AssertExprAndFailed.setInt(Record.readInt());
2770 D->Message = cast_or_null<StringLiteral>(Val: Record.readExpr());
2771 D->RParenLoc = readSourceLocation();
2772}
2773
2774void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
2775 VisitDecl(D);
2776}
2777
2778void ASTDeclReader::VisitLifetimeExtendedTemporaryDecl(
2779 LifetimeExtendedTemporaryDecl *D) {
2780 VisitDecl(D);
2781 D->ExtendingDecl = readDeclAs<ValueDecl>();
2782 D->ExprWithTemporary = Record.readStmt();
2783 if (Record.readInt()) {
2784 D->Value = new (D->getASTContext()) APValue(Record.readAPValue());
2785 D->getASTContext().addDestruction(Ptr: D->Value);
2786 }
2787 D->ManglingNumber = Record.readInt();
2788 mergeMergeable(D);
2789}
2790
2791void ASTDeclReader::VisitDeclContext(DeclContext *DC,
2792 LookupBlockOffsets &Offsets) {
2793 Offsets.LexicalOffset = ReadLocalOffset();
2794 Offsets.VisibleOffset = ReadLocalOffset();
2795 Offsets.ModuleLocalOffset = ReadLocalOffset();
2796 Offsets.TULocalOffset = ReadLocalOffset();
2797}
2798
2799template <typename T>
2800RedeclarableResult ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
2801 GlobalDeclID FirstDeclID = readDeclID();
2802 Decl *MergeWith = nullptr;
2803
2804 bool IsKeyDecl = ThisDeclID == FirstDeclID;
2805 bool IsFirstLocalDecl = false;
2806
2807 uint64_t RedeclOffset = 0;
2808
2809 // invalid FirstDeclID indicates that this declaration was the only
2810 // declaration of its entity, and is used for space optimization.
2811 if (FirstDeclID.isInvalid()) {
2812 FirstDeclID = ThisDeclID;
2813 IsKeyDecl = true;
2814 IsFirstLocalDecl = true;
2815 } else if (unsigned N = Record.readInt()) {
2816 // This declaration was the first local declaration, but may have imported
2817 // other declarations.
2818 IsKeyDecl = N == 1;
2819 IsFirstLocalDecl = true;
2820
2821 // We have some declarations that must be before us in our redeclaration
2822 // chain. Read them now, and remember that we ought to merge with one of
2823 // them.
2824 // FIXME: Provide a known merge target to the second and subsequent such
2825 // declaration.
2826 for (unsigned I = 0; I != N - 1; ++I)
2827 MergeWith = readDecl();
2828
2829 RedeclOffset = ReadLocalOffset();
2830 } else {
2831 // This declaration was not the first local declaration. Read the first
2832 // local declaration now, to trigger the import of other redeclarations.
2833 (void)readDecl();
2834 }
2835
2836 auto *FirstDecl = cast_or_null<T>(Reader.GetDecl(ID: FirstDeclID));
2837 if (FirstDecl != D) {
2838 // We delay loading of the redeclaration chain to avoid deeply nested calls.
2839 // We temporarily set the first (canonical) declaration as the previous one
2840 // which is the one that matters and mark the real previous DeclID to be
2841 // loaded & attached later on.
2842 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
2843 D->First = FirstDecl->getCanonicalDecl();
2844 }
2845
2846 auto *DAsT = static_cast<T *>(D);
2847
2848 // Note that we need to load local redeclarations of this decl and build a
2849 // decl chain for them. This must happen *after* we perform the preloading
2850 // above; this ensures that the redeclaration chain is built in the correct
2851 // order.
2852 if (IsFirstLocalDecl)
2853 Reader.PendingDeclChains.push_back(Elt: std::make_pair(DAsT, RedeclOffset));
2854
2855 return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
2856}
2857
2858/// Attempts to merge the given declaration (D) with another declaration
2859/// of the same entity.
2860template <typename T>
2861void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
2862 RedeclarableResult &Redecl) {
2863 // If modules are not available, there is no reason to perform this merge.
2864 if (!Reader.getContext().getLangOpts().Modules)
2865 return;
2866
2867 // If we're not the canonical declaration, we don't need to merge.
2868 if (!DBase->isFirstDecl())
2869 return;
2870
2871 auto *D = static_cast<T *>(DBase);
2872
2873 if (auto *Existing = Redecl.getKnownMergeTarget())
2874 // We already know of an existing declaration we should merge with.
2875 MergeImpl.mergeRedeclarable(D, cast<T>(Existing), Redecl);
2876 else if (FindExistingResult ExistingRes = findExisting(D))
2877 if (T *Existing = ExistingRes)
2878 MergeImpl.mergeRedeclarable(D, Existing, Redecl);
2879}
2880
2881/// Attempt to merge D with a previous declaration of the same lambda, which is
2882/// found by its index within its context declaration, if it has one.
2883///
2884/// We can't look up lambdas in their enclosing lexical or semantic context in
2885/// general, because for lambdas in variables, both of those might be a
2886/// namespace or the translation unit.
2887void ASTDeclMerger::mergeLambda(CXXRecordDecl *D, RedeclarableResult &Redecl,
2888 Decl &Context, unsigned IndexInContext) {
2889 // If modules are not available, there is no reason to perform this merge.
2890 if (!Reader.getContext().getLangOpts().Modules)
2891 return;
2892
2893 // If we're not the canonical declaration, we don't need to merge.
2894 if (!D->isFirstDecl())
2895 return;
2896
2897 if (auto *Existing = Redecl.getKnownMergeTarget())
2898 // We already know of an existing declaration we should merge with.
2899 mergeRedeclarable(D, Existing: cast<TagDecl>(Val: Existing), Redecl);
2900
2901 // Look up this lambda to see if we've seen it before. If so, merge with the
2902 // one we already loaded.
2903 NamedDecl *&Slot = Reader.LambdaDeclarationsForMerging[{
2904 Context.getCanonicalDecl(), IndexInContext}];
2905 if (Slot)
2906 mergeRedeclarable(D, Existing: cast<TagDecl>(Val: Slot), Redecl);
2907 else
2908 Slot = D;
2909}
2910
2911void ASTDeclReader::mergeRedeclarableTemplate(RedeclarableTemplateDecl *D,
2912 RedeclarableResult &Redecl) {
2913 mergeRedeclarable(DBase: D, Redecl);
2914 // If we merged the template with a prior declaration chain, merge the
2915 // common pointer.
2916 // FIXME: Actually merge here, don't just overwrite.
2917 D->Common = D->getCanonicalDecl()->Common;
2918}
2919
2920/// "Cast" to type T, asserting if we don't have an implicit conversion.
2921/// We use this to put code in a template that will only be valid for certain
2922/// instantiations.
2923template<typename T> static T assert_cast(T t) { return t; }
2924template<typename T> static T assert_cast(...) {
2925 llvm_unreachable("bad assert_cast");
2926}
2927
2928/// Merge together the pattern declarations from two template
2929/// declarations.
2930void ASTDeclMerger::mergeTemplatePattern(RedeclarableTemplateDecl *D,
2931 RedeclarableTemplateDecl *Existing,
2932 bool IsKeyDecl) {
2933 auto *DPattern = D->getTemplatedDecl();
2934 auto *ExistingPattern = Existing->getTemplatedDecl();
2935 RedeclarableResult Result(
2936 /*MergeWith*/ ExistingPattern,
2937 DPattern->getCanonicalDecl()->getGlobalID(), IsKeyDecl);
2938
2939 if (auto *DClass = dyn_cast<CXXRecordDecl>(Val: DPattern)) {
2940 // Merge with any existing definition.
2941 // FIXME: This is duplicated in several places. Refactor.
2942 auto *ExistingClass =
2943 cast<CXXRecordDecl>(Val: ExistingPattern)->getCanonicalDecl();
2944 if (auto *DDD = DClass->DefinitionData) {
2945 if (ExistingClass->DefinitionData) {
2946 MergeDefinitionData(D: ExistingClass, MergeDD: std::move(*DDD));
2947 } else {
2948 ExistingClass->DefinitionData = DClass->DefinitionData;
2949 // We may have skipped this before because we thought that DClass
2950 // was the canonical declaration.
2951 Reader.PendingDefinitions.insert(Ptr: DClass);
2952 }
2953 }
2954 DClass->DefinitionData = ExistingClass->DefinitionData;
2955
2956 return mergeRedeclarable(D: DClass, Existing: cast<TagDecl>(Val: ExistingPattern),
2957 Redecl&: Result);
2958 }
2959 if (auto *DFunction = dyn_cast<FunctionDecl>(Val: DPattern))
2960 return mergeRedeclarable(D: DFunction, Existing: cast<FunctionDecl>(Val: ExistingPattern),
2961 Redecl&: Result);
2962 if (auto *DVar = dyn_cast<VarDecl>(Val: DPattern))
2963 return mergeRedeclarable(D: DVar, Existing: cast<VarDecl>(Val: ExistingPattern), Redecl&: Result);
2964 if (auto *DAlias = dyn_cast<TypeAliasDecl>(Val: DPattern))
2965 return mergeRedeclarable(D: DAlias, Existing: cast<TypedefNameDecl>(Val: ExistingPattern),
2966 Redecl&: Result);
2967 llvm_unreachable("merged an unknown kind of redeclarable template");
2968}
2969
2970/// Attempts to merge the given declaration (D) with another declaration
2971/// of the same entity.
2972template <typename T>
2973void ASTDeclMerger::mergeRedeclarableImpl(Redeclarable<T> *DBase, T *Existing,
2974 GlobalDeclID KeyDeclID) {
2975 auto *D = static_cast<T *>(DBase);
2976 T *ExistingCanon = Existing->getCanonicalDecl();
2977 T *DCanon = D->getCanonicalDecl();
2978 if (ExistingCanon != DCanon) {
2979 // Have our redeclaration link point back at the canonical declaration
2980 // of the existing declaration, so that this declaration has the
2981 // appropriate canonical declaration.
2982 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
2983 D->First = ExistingCanon;
2984 ExistingCanon->Used |= D->Used;
2985 D->Used = false;
2986
2987 bool IsKeyDecl = KeyDeclID.isValid();
2988
2989 // When we merge a template, merge its pattern.
2990 if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
2991 mergeTemplatePattern(
2992 D: DTemplate, Existing: assert_cast<RedeclarableTemplateDecl *>(ExistingCanon),
2993 IsKeyDecl);
2994
2995 // If this declaration is a key declaration, make a note of that.
2996 if (IsKeyDecl)
2997 Reader.KeyDecls[ExistingCanon].push_back(KeyDeclID);
2998 }
2999}
3000
3001/// ODR-like semantics for C/ObjC allow us to merge tag types and a structural
3002/// check in Sema guarantees the types can be merged (see C11 6.2.7/1 or C89
3003/// 6.1.2.6/1). Although most merging is done in Sema, we need to guarantee
3004/// that some types are mergeable during deserialization, otherwise name
3005/// lookup fails. This is the case for EnumConstantDecl.
3006static bool allowODRLikeMergeInC(NamedDecl *ND) {
3007 if (!ND)
3008 return false;
3009 // TODO: implement merge for other necessary decls.
3010 if (isa<EnumConstantDecl, FieldDecl, IndirectFieldDecl>(Val: ND))
3011 return true;
3012 return false;
3013}
3014
3015/// Attempts to merge LifetimeExtendedTemporaryDecl with
3016/// identical class definitions from two different modules.
3017void ASTDeclReader::mergeMergeable(LifetimeExtendedTemporaryDecl *D) {
3018 // If modules are not available, there is no reason to perform this merge.
3019 if (!Reader.getContext().getLangOpts().Modules)
3020 return;
3021
3022 LifetimeExtendedTemporaryDecl *LETDecl = D;
3023
3024 LifetimeExtendedTemporaryDecl *&LookupResult =
3025 Reader.LETemporaryForMerging[std::make_pair(
3026 x: LETDecl->getExtendingDecl(), y: LETDecl->getManglingNumber())];
3027 if (LookupResult)
3028 Reader.getContext().setPrimaryMergedDecl(D: LETDecl,
3029 Primary: LookupResult->getCanonicalDecl());
3030 else
3031 LookupResult = LETDecl;
3032}
3033
3034/// Attempts to merge the given declaration (D) with another declaration
3035/// of the same entity, for the case where the entity is not actually
3036/// redeclarable. This happens, for instance, when merging the fields of
3037/// identical class definitions from two different modules.
3038template<typename T>
3039void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
3040 // If modules are not available, there is no reason to perform this merge.
3041 if (!Reader.getContext().getLangOpts().Modules)
3042 return;
3043
3044 // ODR-based merging is performed in C++ and in some cases (tag types) in C.
3045 // Note that C identically-named things in different translation units are
3046 // not redeclarations, but may still have compatible types, where ODR-like
3047 // semantics may apply.
3048 if (!Reader.getContext().getLangOpts().CPlusPlus &&
3049 !allowODRLikeMergeInC(dyn_cast<NamedDecl>(static_cast<T*>(D))))
3050 return;
3051
3052 if (FindExistingResult ExistingRes = findExisting(D: static_cast<T*>(D)))
3053 if (T *Existing = ExistingRes)
3054 Reader.getContext().setPrimaryMergedDecl(D: static_cast<T *>(D),
3055 Primary: Existing->getCanonicalDecl());
3056}
3057
3058void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
3059 Record.readOMPChildren(Data: D->Data);
3060 VisitDecl(D);
3061}
3062
3063void ASTDeclReader::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3064 Record.readOMPChildren(Data: D->Data);
3065 VisitDecl(D);
3066}
3067
3068void ASTDeclReader::VisitOMPRequiresDecl(OMPRequiresDecl * D) {
3069 Record.readOMPChildren(Data: D->Data);
3070 VisitDecl(D);
3071}
3072
3073void ASTDeclReader::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
3074 VisitValueDecl(VD: D);
3075 D->setLocation(readSourceLocation());
3076 Expr *In = Record.readExpr();
3077 Expr *Out = Record.readExpr();
3078 D->setCombinerData(InE: In, OutE: Out);
3079 Expr *Combiner = Record.readExpr();
3080 D->setCombiner(Combiner);
3081 Expr *Orig = Record.readExpr();
3082 Expr *Priv = Record.readExpr();
3083 D->setInitializerData(OrigE: Orig, PrivE: Priv);
3084 Expr *Init = Record.readExpr();
3085 auto IK = static_cast<OMPDeclareReductionInitKind>(Record.readInt());
3086 D->setInitializer(E: Init, IK);
3087 D->PrevDeclInScope = readDeclID().getRawValue();
3088}
3089
3090void ASTDeclReader::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3091 Record.readOMPChildren(Data: D->Data);
3092 VisitValueDecl(VD: D);
3093 D->VarName = Record.readDeclarationName();
3094 D->PrevDeclInScope = readDeclID().getRawValue();
3095}
3096
3097void ASTDeclReader::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
3098 VisitVarDecl(VD: D);
3099}
3100
3101void ASTDeclReader::VisitOpenACCDeclareDecl(OpenACCDeclareDecl *D) {
3102 VisitDecl(D);
3103 D->DirKind = Record.readEnum<OpenACCDirectiveKind>();
3104 D->DirectiveLoc = Record.readSourceLocation();
3105 D->EndLoc = Record.readSourceLocation();
3106 Record.readOpenACCClauseList(Clauses: D->Clauses);
3107}
3108void ASTDeclReader::VisitOpenACCRoutineDecl(OpenACCRoutineDecl *D) {
3109 VisitDecl(D);
3110 D->DirKind = Record.readEnum<OpenACCDirectiveKind>();
3111 D->DirectiveLoc = Record.readSourceLocation();
3112 D->EndLoc = Record.readSourceLocation();
3113 D->ParensLoc = Record.readSourceRange();
3114 D->FuncRef = Record.readExpr();
3115 Record.readOpenACCClauseList(Clauses: D->Clauses);
3116}
3117
3118//===----------------------------------------------------------------------===//
3119// Attribute Reading
3120//===----------------------------------------------------------------------===//
3121
3122namespace {
3123class AttrReader {
3124 ASTRecordReader &Reader;
3125
3126public:
3127 AttrReader(ASTRecordReader &Reader) : Reader(Reader) {}
3128
3129 uint64_t readInt() {
3130 return Reader.readInt();
3131 }
3132
3133 bool readBool() { return Reader.readBool(); }
3134
3135 SourceRange readSourceRange() {
3136 return Reader.readSourceRange();
3137 }
3138
3139 SourceLocation readSourceLocation() {
3140 return Reader.readSourceLocation();
3141 }
3142
3143 Expr *readExpr() { return Reader.readExpr(); }
3144
3145 Attr *readAttr() { return Reader.readAttr(); }
3146
3147 std::string readString() {
3148 return Reader.readString();
3149 }
3150
3151 TypeSourceInfo *readTypeSourceInfo() {
3152 return Reader.readTypeSourceInfo();
3153 }
3154
3155 IdentifierInfo *readIdentifier() {
3156 return Reader.readIdentifier();
3157 }
3158
3159 VersionTuple readVersionTuple() {
3160 return Reader.readVersionTuple();
3161 }
3162
3163 OMPTraitInfo *readOMPTraitInfo() { return Reader.readOMPTraitInfo(); }
3164
3165 template <typename T> T *readDeclAs() { return Reader.readDeclAs<T>(); }
3166};
3167}
3168
3169Attr *ASTRecordReader::readAttr() {
3170 AttrReader Record(*this);
3171 auto V = Record.readInt();
3172 if (!V)
3173 return nullptr;
3174
3175 Attr *New = nullptr;
3176 // Kind is stored as a 1-based integer because 0 is used to indicate a null
3177 // Attr pointer.
3178 auto Kind = static_cast<attr::Kind>(V - 1);
3179 ASTContext &Context = getContext();
3180
3181 IdentifierInfo *AttrName = Record.readIdentifier();
3182 IdentifierInfo *ScopeName = Record.readIdentifier();
3183 SourceRange AttrRange = Record.readSourceRange();
3184 SourceLocation ScopeLoc = Record.readSourceLocation();
3185 unsigned ParsedKind = Record.readInt();
3186 unsigned Syntax = Record.readInt();
3187 unsigned SpellingIndex = Record.readInt();
3188 bool IsAlignas = (ParsedKind == AttributeCommonInfo::AT_Aligned &&
3189 Syntax == AttributeCommonInfo::AS_Keyword &&
3190 SpellingIndex == AlignedAttr::Keyword_alignas);
3191 bool IsRegularKeywordAttribute = Record.readBool();
3192
3193 AttributeCommonInfo Info(AttrName, AttributeScopeInfo(ScopeName, ScopeLoc),
3194 AttrRange, AttributeCommonInfo::Kind(ParsedKind),
3195 {AttributeCommonInfo::Syntax(Syntax), SpellingIndex,
3196 IsAlignas, IsRegularKeywordAttribute});
3197
3198#include "clang/Serialization/AttrPCHRead.inc"
3199
3200 assert(New && "Unable to decode attribute?");
3201 return New;
3202}
3203
3204/// Reads attributes from the current stream position.
3205void ASTRecordReader::readAttributes(AttrVec &Attrs) {
3206 for (unsigned I = 0, E = readInt(); I != E; ++I)
3207 if (auto *A = readAttr())
3208 Attrs.push_back(Elt: A);
3209}
3210
3211//===----------------------------------------------------------------------===//
3212// ASTReader Implementation
3213//===----------------------------------------------------------------------===//
3214
3215/// Note that we have loaded the declaration with the given
3216/// Index.
3217///
3218/// This routine notes that this declaration has already been loaded,
3219/// so that future GetDecl calls will return this declaration rather
3220/// than trying to load a new declaration.
3221inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
3222 assert(!DeclsLoaded[Index] && "Decl loaded twice?");
3223 DeclsLoaded[Index] = D;
3224}
3225
3226/// Determine whether the consumer will be interested in seeing
3227/// this declaration (via HandleTopLevelDecl).
3228///
3229/// This routine should return true for anything that might affect
3230/// code generation, e.g., inline function definitions, Objective-C
3231/// declarations with metadata, etc.
3232bool ASTReader::isConsumerInterestedIn(Decl *D) {
3233 // An ObjCMethodDecl is never considered as "interesting" because its
3234 // implementation container always is.
3235
3236 // An ImportDecl or VarDecl imported from a module map module will get
3237 // emitted when we import the relevant module.
3238 if (isPartOfPerModuleInitializer(D)) {
3239 auto *M = D->getImportedOwningModule();
3240 if (M && M->Kind == Module::ModuleMapModule &&
3241 getContext().DeclMustBeEmitted(D))
3242 return false;
3243 }
3244
3245 if (isa<FileScopeAsmDecl, TopLevelStmtDecl, ObjCProtocolDecl, ObjCImplDecl,
3246 ImportDecl, PragmaCommentDecl, PragmaDetectMismatchDecl>(Val: D))
3247 return true;
3248 if (isa<OMPThreadPrivateDecl, OMPDeclareReductionDecl, OMPDeclareMapperDecl,
3249 OMPAllocateDecl, OMPRequiresDecl>(Val: D))
3250 return !D->getDeclContext()->isFunctionOrMethod();
3251 if (const auto *Var = dyn_cast<VarDecl>(Val: D))
3252 return Var->isFileVarDecl() &&
3253 (Var->isThisDeclarationADefinition() == VarDecl::Definition ||
3254 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD: Var));
3255 if (const auto *Func = dyn_cast<FunctionDecl>(Val: D))
3256 return Func->doesThisDeclarationHaveABody() || PendingBodies.count(Key: D);
3257
3258 if (auto *ES = D->getASTContext().getExternalSource())
3259 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
3260 return true;
3261
3262 return false;
3263}
3264
3265/// Get the correct cursor and offset for loading a declaration.
3266ASTReader::RecordLocation ASTReader::DeclCursorForID(GlobalDeclID ID,
3267 SourceLocation &Loc) {
3268 ModuleFile *M = getOwningModuleFile(ID);
3269 assert(M);
3270 unsigned LocalDeclIndex = ID.getLocalDeclIndex();
3271 const DeclOffset &DOffs = M->DeclOffsets[LocalDeclIndex];
3272 Loc = ReadSourceLocation(MF&: *M, Raw: DOffs.getRawLoc());
3273 return RecordLocation(M, DOffs.getBitOffset(DeclTypesBlockStartOffset: M->DeclsBlockStartOffset));
3274}
3275
3276ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
3277 auto I = GlobalBitOffsetsMap.find(K: GlobalOffset);
3278
3279 assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
3280 return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
3281}
3282
3283uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint64_t LocalOffset) {
3284 return LocalOffset + M.GlobalBitOffset;
3285}
3286
3287CXXRecordDecl *
3288ASTDeclReader::getOrFakePrimaryClassDefinition(ASTReader &Reader,
3289 CXXRecordDecl *RD) {
3290 // Try to dig out the definition.
3291 auto *DD = RD->DefinitionData;
3292 if (!DD)
3293 DD = RD->getCanonicalDecl()->DefinitionData;
3294
3295 // If there's no definition yet, then DC's definition is added by an update
3296 // record, but we've not yet loaded that update record. In this case, we
3297 // commit to DC being the canonical definition now, and will fix this when
3298 // we load the update record.
3299 if (!DD) {
3300 DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);
3301 RD->setCompleteDefinition(true);
3302 RD->DefinitionData = DD;
3303 RD->getCanonicalDecl()->DefinitionData = DD;
3304
3305 // Track that we did this horrible thing so that we can fix it later.
3306 Reader.PendingFakeDefinitionData.insert(
3307 KV: std::make_pair(x&: DD, y: ASTReader::PendingFakeDefinitionKind::Fake));
3308 }
3309
3310 return DD->Definition;
3311}
3312
3313/// Find the context in which we should search for previous declarations when
3314/// looking for declarations to merge.
3315DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
3316 DeclContext *DC) {
3317 if (auto *ND = dyn_cast<NamespaceDecl>(Val: DC))
3318 return ND->getFirstDecl();
3319
3320 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
3321 return getOrFakePrimaryClassDefinition(Reader, RD);
3322
3323 if (auto *RD = dyn_cast<RecordDecl>(Val: DC))
3324 return RD->getDefinition();
3325
3326 if (auto *ED = dyn_cast<EnumDecl>(Val: DC))
3327 return ED->getDefinition();
3328
3329 if (auto *OID = dyn_cast<ObjCInterfaceDecl>(Val: DC))
3330 return OID->getDefinition();
3331
3332 // We can see the TU here only if we have no Sema object. It is possible
3333 // we're in clang-repl so we still need to get the primary context.
3334 if (auto *TU = dyn_cast<TranslationUnitDecl>(Val: DC))
3335 return TU->getPrimaryContext();
3336
3337 return nullptr;
3338}
3339
3340ASTDeclReader::FindExistingResult::~FindExistingResult() {
3341 // Record that we had a typedef name for linkage whether or not we merge
3342 // with that declaration.
3343 if (TypedefNameForLinkage) {
3344 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3345 Reader.ImportedTypedefNamesForLinkage.insert(
3346 KV: std::make_pair(x: std::make_pair(x&: DC, y&: TypedefNameForLinkage), y&: New));
3347 return;
3348 }
3349
3350 if (!AddResult || Existing)
3351 return;
3352
3353 DeclarationName Name = New->getDeclName();
3354 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3355 if (needsAnonymousDeclarationNumber(D: New)) {
3356 setAnonymousDeclForMerging(Reader, DC: New->getLexicalDeclContext(),
3357 Index: AnonymousDeclNumber, D: New);
3358 } else if (DC->isTranslationUnit() &&
3359 !Reader.getContext().getLangOpts().CPlusPlus) {
3360 if (Reader.getIdResolver().tryAddTopLevelDecl(D: New, Name))
3361 Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
3362 .push_back(Elt: New);
3363 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3364 // Add the declaration to its redeclaration context so later merging
3365 // lookups will find it.
3366 MergeDC->makeDeclVisibleInContextImpl(D: New, /*Internal*/true);
3367 }
3368}
3369
3370/// Find the declaration that should be merged into, given the declaration found
3371/// by name lookup. If we're merging an anonymous declaration within a typedef,
3372/// we need a matching typedef, and we merge with the type inside it.
3373static NamedDecl *getDeclForMerging(NamedDecl *Found,
3374 bool IsTypedefNameForLinkage) {
3375 if (!IsTypedefNameForLinkage)
3376 return Found;
3377
3378 // If we found a typedef declaration that gives a name to some other
3379 // declaration, then we want that inner declaration. Declarations from
3380 // AST files are handled via ImportedTypedefNamesForLinkage.
3381 if (Found->isFromASTFile())
3382 return nullptr;
3383
3384 if (auto *TND = dyn_cast<TypedefNameDecl>(Val: Found))
3385 return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
3386
3387 return nullptr;
3388}
3389
3390/// Find the declaration to use to populate the anonymous declaration table
3391/// for the given lexical DeclContext. We only care about finding local
3392/// definitions of the context; we'll merge imported ones as we go.
3393DeclContext *
3394ASTDeclReader::getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC) {
3395 // For classes, we track the definition as we merge.
3396 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: LexicalDC)) {
3397 auto *DD = RD->getCanonicalDecl()->DefinitionData;
3398 return DD ? DD->Definition : nullptr;
3399 } else if (auto *OID = dyn_cast<ObjCInterfaceDecl>(Val: LexicalDC)) {
3400 return OID->getCanonicalDecl()->getDefinition();
3401 }
3402
3403 // For anything else, walk its merged redeclarations looking for a definition.
3404 // Note that we can't just call getDefinition here because the redeclaration
3405 // chain isn't wired up.
3406 for (auto *D : merged_redecls(D: cast<Decl>(Val: LexicalDC))) {
3407 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
3408 if (FD->isThisDeclarationADefinition())
3409 return FD;
3410 if (auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
3411 if (MD->isThisDeclarationADefinition())
3412 return MD;
3413 if (auto *RD = dyn_cast<RecordDecl>(Val: D))
3414 if (RD->isThisDeclarationADefinition())
3415 return RD;
3416 }
3417
3418 // No merged definition yet.
3419 return nullptr;
3420}
3421
3422NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
3423 DeclContext *DC,
3424 unsigned Index) {
3425 // If the lexical context has been merged, look into the now-canonical
3426 // definition.
3427 auto *CanonDC = cast<Decl>(Val: DC)->getCanonicalDecl();
3428
3429 // If we've seen this before, return the canonical declaration.
3430 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3431 if (Index < Previous.size() && Previous[Index])
3432 return Previous[Index];
3433
3434 // If this is the first time, but we have parsed a declaration of the context,
3435 // build the anonymous declaration list from the parsed declaration.
3436 auto *PrimaryDC = getPrimaryDCForAnonymousDecl(LexicalDC: DC);
3437 if (PrimaryDC && !cast<Decl>(Val: PrimaryDC)->isFromASTFile()) {
3438 numberAnonymousDeclsWithin(DC: PrimaryDC, Visit: [&](NamedDecl *ND, unsigned Number) {
3439 if (Previous.size() == Number)
3440 Previous.push_back(Elt: cast<NamedDecl>(Val: ND->getCanonicalDecl()));
3441 else
3442 Previous[Number] = cast<NamedDecl>(Val: ND->getCanonicalDecl());
3443 });
3444 }
3445
3446 return Index < Previous.size() ? Previous[Index] : nullptr;
3447}
3448
3449void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
3450 DeclContext *DC, unsigned Index,
3451 NamedDecl *D) {
3452 auto *CanonDC = cast<Decl>(Val: DC)->getCanonicalDecl();
3453
3454 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3455 if (Index >= Previous.size())
3456 Previous.resize(N: Index + 1);
3457 if (!Previous[Index])
3458 Previous[Index] = D;
3459}
3460
3461ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
3462 DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
3463 : D->getDeclName();
3464
3465 if (!Name && !needsAnonymousDeclarationNumber(D)) {
3466 // Don't bother trying to find unnamed declarations that are in
3467 // unmergeable contexts.
3468 FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
3469 AnonymousDeclNumber, TypedefNameForLinkage);
3470 Result.suppress();
3471 return Result;
3472 }
3473
3474 ASTContext &C = Reader.getContext();
3475 DeclContext *DC = D->getDeclContext()->getRedeclContext();
3476 if (TypedefNameForLinkage) {
3477 auto It = Reader.ImportedTypedefNamesForLinkage.find(
3478 Val: std::make_pair(x&: DC, y&: TypedefNameForLinkage));
3479 if (It != Reader.ImportedTypedefNamesForLinkage.end())
3480 if (C.isSameEntity(X: It->second, Y: D))
3481 return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
3482 TypedefNameForLinkage);
3483 // Go on to check in other places in case an existing typedef name
3484 // was not imported.
3485 }
3486
3487 if (needsAnonymousDeclarationNumber(D)) {
3488 // This is an anonymous declaration that we may need to merge. Look it up
3489 // in its context by number.
3490 if (auto *Existing = getAnonymousDeclForMerging(
3491 Reader, DC: D->getLexicalDeclContext(), Index: AnonymousDeclNumber))
3492 if (C.isSameEntity(X: Existing, Y: D))
3493 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3494 TypedefNameForLinkage);
3495 } else if (DC->isTranslationUnit() &&
3496 !Reader.getContext().getLangOpts().CPlusPlus) {
3497 IdentifierResolver &IdResolver = Reader.getIdResolver();
3498
3499 // Temporarily consider the identifier to be up-to-date. We don't want to
3500 // cause additional lookups here.
3501 class UpToDateIdentifierRAII {
3502 IdentifierInfo *II;
3503 bool WasOutToDate = false;
3504
3505 public:
3506 explicit UpToDateIdentifierRAII(IdentifierInfo *II) : II(II) {
3507 if (II) {
3508 WasOutToDate = II->isOutOfDate();
3509 if (WasOutToDate)
3510 II->setOutOfDate(false);
3511 }
3512 }
3513
3514 ~UpToDateIdentifierRAII() {
3515 if (WasOutToDate)
3516 II->setOutOfDate(true);
3517 }
3518 } UpToDate(Name.getAsIdentifierInfo());
3519
3520 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
3521 IEnd = IdResolver.end();
3522 I != IEnd; ++I) {
3523 if (NamedDecl *Existing = getDeclForMerging(Found: *I, IsTypedefNameForLinkage: TypedefNameForLinkage))
3524 if (C.isSameEntity(X: Existing, Y: D))
3525 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3526 TypedefNameForLinkage);
3527 }
3528 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3529 DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
3530 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
3531 if (NamedDecl *Existing = getDeclForMerging(Found: *I, IsTypedefNameForLinkage: TypedefNameForLinkage))
3532 if (C.isSameEntity(X: Existing, Y: D))
3533 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3534 TypedefNameForLinkage);
3535 }
3536 } else {
3537 // Not in a mergeable context.
3538 return FindExistingResult(Reader);
3539 }
3540
3541 // If this declaration is from a merged context, make a note that we need to
3542 // check that the canonical definition of that context contains the decl.
3543 //
3544 // Note that we don't perform ODR checks for decls from the global module
3545 // fragment.
3546 //
3547 // FIXME: We should do something similar if we merge two definitions of the
3548 // same template specialization into the same CXXRecordDecl.
3549 auto MergedDCIt = Reader.MergedDeclContexts.find(Val: D->getLexicalDeclContext());
3550 if (MergedDCIt != Reader.MergedDeclContexts.end() &&
3551 !shouldSkipCheckingODR(D) && MergedDCIt->second == D->getDeclContext() &&
3552 !shouldSkipCheckingODR(D: cast<Decl>(Val: D->getDeclContext())))
3553 Reader.PendingOdrMergeChecks.push_back(Elt: D);
3554
3555 return FindExistingResult(Reader, D, /*Existing=*/nullptr,
3556 AnonymousDeclNumber, TypedefNameForLinkage);
3557}
3558
3559template<typename DeclT>
3560Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
3561 return D->RedeclLink.getLatestNotUpdated();
3562}
3563
3564Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
3565 llvm_unreachable("getMostRecentDecl on non-redeclarable declaration");
3566}
3567
3568Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
3569 assert(D);
3570
3571 switch (D->getKind()) {
3572#define ABSTRACT_DECL(TYPE)
3573#define DECL(TYPE, BASE) \
3574 case Decl::TYPE: \
3575 return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
3576#include "clang/AST/DeclNodes.inc"
3577 }
3578 llvm_unreachable("unknown decl kind");
3579}
3580
3581Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
3582 return ASTDeclReader::getMostRecentDecl(D: D->getCanonicalDecl());
3583}
3584
3585namespace {
3586void mergeInheritableAttributes(ASTReader &Reader, Decl *D, Decl *Previous) {
3587 InheritableAttr *NewAttr = nullptr;
3588 ASTContext &Context = Reader.getContext();
3589 const auto *IA = Previous->getAttr<MSInheritanceAttr>();
3590
3591 if (IA && !D->hasAttr<MSInheritanceAttr>()) {
3592 NewAttr = cast<InheritableAttr>(Val: IA->clone(C&: Context));
3593 NewAttr->setInherited(true);
3594 D->addAttr(A: NewAttr);
3595 }
3596
3597 const auto *AA = Previous->getAttr<AvailabilityAttr>();
3598 if (AA && !D->hasAttr<AvailabilityAttr>()) {
3599 NewAttr = AA->clone(C&: Context);
3600 NewAttr->setInherited(true);
3601 D->addAttr(A: NewAttr);
3602 }
3603}
3604} // namespace
3605
3606template<typename DeclT>
3607void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3608 Redeclarable<DeclT> *D,
3609 Decl *Previous, Decl *Canon) {
3610 D->RedeclLink.setPrevious(cast<DeclT>(Previous));
3611 D->First = cast<DeclT>(Previous)->First;
3612}
3613
3614namespace clang {
3615
3616template<>
3617void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3618 Redeclarable<VarDecl> *D,
3619 Decl *Previous, Decl *Canon) {
3620 auto *VD = static_cast<VarDecl *>(D);
3621 auto *PrevVD = cast<VarDecl>(Val: Previous);
3622 D->RedeclLink.setPrevious(PrevVD);
3623 D->First = PrevVD->First;
3624
3625 // We should keep at most one definition on the chain.
3626 // FIXME: Cache the definition once we've found it. Building a chain with
3627 // N definitions currently takes O(N^2) time here.
3628 if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {
3629 for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {
3630 if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {
3631 Reader.mergeDefinitionVisibility(Def: CurD, MergedDef: VD);
3632 VD->demoteThisDefinitionToDeclaration();
3633 break;
3634 }
3635 }
3636 }
3637}
3638
3639static bool isUndeducedReturnType(QualType T) {
3640 auto *DT = T->getContainedDeducedType();
3641 return DT && !DT->isDeduced();
3642}
3643
3644template<>
3645void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3646 Redeclarable<FunctionDecl> *D,
3647 Decl *Previous, Decl *Canon) {
3648 auto *FD = static_cast<FunctionDecl *>(D);
3649 auto *PrevFD = cast<FunctionDecl>(Val: Previous);
3650
3651 FD->RedeclLink.setPrevious(PrevFD);
3652 FD->First = PrevFD->First;
3653
3654 // If the previous declaration is an inline function declaration, then this
3655 // declaration is too.
3656 if (PrevFD->isInlined() != FD->isInlined()) {
3657 // FIXME: [dcl.fct.spec]p4:
3658 // If a function with external linkage is declared inline in one
3659 // translation unit, it shall be declared inline in all translation
3660 // units in which it appears.
3661 //
3662 // Be careful of this case:
3663 //
3664 // module A:
3665 // template<typename T> struct X { void f(); };
3666 // template<typename T> inline void X<T>::f() {}
3667 //
3668 // module B instantiates the declaration of X<int>::f
3669 // module C instantiates the definition of X<int>::f
3670 //
3671 // If module B and C are merged, we do not have a violation of this rule.
3672 FD->setImplicitlyInline(true);
3673 }
3674
3675 auto *FPT = FD->getType()->getAs<FunctionProtoType>();
3676 auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
3677 if (FPT && PrevFPT) {
3678 // If we need to propagate an exception specification along the redecl
3679 // chain, make a note of that so that we can do so later.
3680 bool IsUnresolved = isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType());
3681 bool WasUnresolved =
3682 isUnresolvedExceptionSpec(ESpecType: PrevFPT->getExceptionSpecType());
3683 if (IsUnresolved != WasUnresolved)
3684 Reader.PendingExceptionSpecUpdates.insert(
3685 KV: {Canon, IsUnresolved ? PrevFD : FD});
3686
3687 // If we need to propagate a deduced return type along the redecl chain,
3688 // make a note of that so that we can do it later.
3689 bool IsUndeduced = isUndeducedReturnType(T: FPT->getReturnType());
3690 bool WasUndeduced = isUndeducedReturnType(T: PrevFPT->getReturnType());
3691 if (IsUndeduced != WasUndeduced)
3692 Reader.PendingDeducedTypeUpdates.insert(
3693 KV: {cast<FunctionDecl>(Val: Canon),
3694 (IsUndeduced ? PrevFPT : FPT)->getReturnType()});
3695 }
3696}
3697
3698} // namespace clang
3699
3700void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
3701 llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
3702}
3703
3704/// Inherit the default template argument from \p From to \p To. Returns
3705/// \c false if there is no default template for \p From.
3706template <typename ParmDecl>
3707static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,
3708 Decl *ToD) {
3709 auto *To = cast<ParmDecl>(ToD);
3710 if (!From->hasDefaultArgument())
3711 return false;
3712 To->setInheritedDefaultArgument(Context, From);
3713 return true;
3714}
3715
3716static void inheritDefaultTemplateArguments(ASTContext &Context,
3717 TemplateDecl *From,
3718 TemplateDecl *To) {
3719 auto *FromTP = From->getTemplateParameters();
3720 auto *ToTP = To->getTemplateParameters();
3721 assert(FromTP->size() == ToTP->size() && "merged mismatched templates?");
3722
3723 for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {
3724 NamedDecl *FromParam = FromTP->getParam(Idx: I);
3725 NamedDecl *ToParam = ToTP->getParam(Idx: I);
3726
3727 if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(Val: FromParam))
3728 inheritDefaultTemplateArgument(Context, From: FTTP, ToD: ToParam);
3729 else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: FromParam))
3730 inheritDefaultTemplateArgument(Context, From: FNTTP, ToD: ToParam);
3731 else
3732 inheritDefaultTemplateArgument(
3733 Context, From: cast<TemplateTemplateParmDecl>(Val: FromParam), ToD: ToParam);
3734 }
3735}
3736
3737// [basic.link]/p10:
3738// If two declarations of an entity are attached to different modules,
3739// the program is ill-formed;
3740void ASTDeclReader::checkMultipleDefinitionInNamedModules(ASTReader &Reader,
3741 Decl *D,
3742 Decl *Previous) {
3743 // If it is previous implcitly introduced, it is not meaningful to
3744 // diagnose it.
3745 if (Previous->isImplicit())
3746 return;
3747
3748 // FIXME: Get rid of the enumeration of decl types once we have an appropriate
3749 // abstract for decls of an entity. e.g., the namespace decl and using decl
3750 // doesn't introduce an entity.
3751 if (!isa<VarDecl, FunctionDecl, TagDecl, RedeclarableTemplateDecl>(Val: Previous))
3752 return;
3753
3754 // Skip implicit instantiations since it may give false positive diagnostic
3755 // messages.
3756 // FIXME: Maybe this shows the implicit instantiations may have incorrect
3757 // module owner ships. But given we've finished the compilation of a module,
3758 // how can we add new entities to that module?
3759 if (isa<VarTemplateSpecializationDecl>(Val: Previous))
3760 return;
3761 if (isa<ClassTemplateSpecializationDecl>(Val: Previous))
3762 return;
3763 if (auto *Func = dyn_cast<FunctionDecl>(Val: Previous);
3764 Func && Func->getTemplateSpecializationInfo())
3765 return;
3766
3767 // The module ownership of in-class friend declaration is not straightforward.
3768 // Avoid diagnosing such cases.
3769 if (D->getFriendObjectKind() || Previous->getFriendObjectKind())
3770 return;
3771
3772 // Skip diagnosing in-class declarations.
3773 if (!Previous->getLexicalDeclContext()
3774 ->getNonTransparentContext()
3775 ->isFileContext() ||
3776 !D->getLexicalDeclContext()->getNonTransparentContext()->isFileContext())
3777 return;
3778
3779 Module *M = Previous->getOwningModule();
3780 if (!M)
3781 return;
3782
3783 // We only forbids merging decls within named modules.
3784 if (!M->isNamedModule()) {
3785 // Try to warn the case that we merged decls from global module.
3786 if (!M->isGlobalModule())
3787 return;
3788
3789 if (D->getOwningModule() &&
3790 M->getTopLevelModule() == D->getOwningModule()->getTopLevelModule())
3791 return;
3792
3793 Reader.PendingWarningForDuplicatedDefsInModuleUnits.push_back(
3794 Elt: {D, Previous});
3795 return;
3796 }
3797
3798 // It is fine if they are in the same module.
3799 if (Reader.getContext().isInSameModule(M1: M, M2: D->getOwningModule()))
3800 return;
3801
3802 Reader.Diag(Loc: Previous->getLocation(),
3803 DiagID: diag::err_multiple_decl_in_different_modules)
3804 << cast<NamedDecl>(Val: Previous) << M->Name;
3805 Reader.Diag(Loc: D->getLocation(), DiagID: diag::note_also_found);
3806}
3807
3808void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
3809 Decl *Previous, Decl *Canon) {
3810 assert(D && Previous);
3811
3812 switch (D->getKind()) {
3813#define ABSTRACT_DECL(TYPE)
3814#define DECL(TYPE, BASE) \
3815 case Decl::TYPE: \
3816 attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
3817 break;
3818#include "clang/AST/DeclNodes.inc"
3819 }
3820
3821 checkMultipleDefinitionInNamedModules(Reader, D, Previous);
3822
3823 // If the declaration was visible in one module, a redeclaration of it in
3824 // another module remains visible even if it wouldn't be visible by itself.
3825 //
3826 // FIXME: In this case, the declaration should only be visible if a module
3827 // that makes it visible has been imported.
3828 D->IdentifierNamespace |=
3829 Previous->IdentifierNamespace &
3830 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3831
3832 // If the declaration declares a template, it may inherit default arguments
3833 // from the previous declaration.
3834 if (auto *TD = dyn_cast<TemplateDecl>(Val: D))
3835 inheritDefaultTemplateArguments(Context&: Reader.getContext(),
3836 From: cast<TemplateDecl>(Val: Previous), To: TD);
3837
3838 // If any of the declaration in the chain contains an Inheritable attribute,
3839 // it needs to be added to all the declarations in the redeclarable chain.
3840 // FIXME: Only the logic of merging MSInheritableAttr is present, it should
3841 // be extended for all inheritable attributes.
3842 mergeInheritableAttributes(Reader, D, Previous);
3843}
3844
3845template<typename DeclT>
3846void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
3847 D->RedeclLink.setLatest(cast<DeclT>(Latest));
3848}
3849
3850void ASTDeclReader::attachLatestDeclImpl(...) {
3851 llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
3852}
3853
3854void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
3855 assert(D && Latest);
3856
3857 switch (D->getKind()) {
3858#define ABSTRACT_DECL(TYPE)
3859#define DECL(TYPE, BASE) \
3860 case Decl::TYPE: \
3861 attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
3862 break;
3863#include "clang/AST/DeclNodes.inc"
3864 }
3865}
3866
3867template<typename DeclT>
3868void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
3869 D->RedeclLink.markIncomplete();
3870}
3871
3872void ASTDeclReader::markIncompleteDeclChainImpl(...) {
3873 llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
3874}
3875
3876void ASTReader::markIncompleteDeclChain(Decl *D) {
3877 switch (D->getKind()) {
3878#define ABSTRACT_DECL(TYPE)
3879#define DECL(TYPE, BASE) \
3880 case Decl::TYPE: \
3881 ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
3882 break;
3883#include "clang/AST/DeclNodes.inc"
3884 }
3885}
3886
3887/// Read the declaration at the given offset from the AST file.
3888Decl *ASTReader::ReadDeclRecord(GlobalDeclID ID) {
3889 SourceLocation DeclLoc;
3890 RecordLocation Loc = DeclCursorForID(ID, Loc&: DeclLoc);
3891 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3892 // Keep track of where we are in the stream, then jump back there
3893 // after reading this declaration.
3894 SavedStreamPosition SavedPosition(DeclsCursor);
3895
3896 ReadingKindTracker ReadingKind(Read_Decl, *this);
3897
3898 // Note that we are loading a declaration record.
3899 Deserializing ADecl(this);
3900
3901 auto Fail = [](const char *what, llvm::Error &&Err) {
3902 llvm::report_fatal_error(reason: Twine("ASTReader::readDeclRecord failed ") + what +
3903 ": " + toString(E: std::move(Err)));
3904 };
3905
3906 if (llvm::Error JumpFailed = DeclsCursor.JumpToBit(BitNo: Loc.Offset))
3907 Fail("jumping", std::move(JumpFailed));
3908 ASTRecordReader Record(*this, *Loc.F);
3909 ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);
3910 Expected<unsigned> MaybeCode = DeclsCursor.ReadCode();
3911 if (!MaybeCode)
3912 Fail("reading code", MaybeCode.takeError());
3913 unsigned Code = MaybeCode.get();
3914
3915 ASTContext &Context = getContext();
3916 Decl *D = nullptr;
3917 Expected<unsigned> MaybeDeclCode = Record.readRecord(Cursor&: DeclsCursor, AbbrevID: Code);
3918 if (!MaybeDeclCode)
3919 llvm::report_fatal_error(
3920 reason: Twine("ASTReader::readDeclRecord failed reading decl code: ") +
3921 toString(E: MaybeDeclCode.takeError()));
3922
3923 switch ((DeclCode)MaybeDeclCode.get()) {
3924 case DECL_CONTEXT_LEXICAL:
3925 case DECL_CONTEXT_VISIBLE:
3926 case DECL_CONTEXT_MODULE_LOCAL_VISIBLE:
3927 case DECL_CONTEXT_TU_LOCAL_VISIBLE:
3928 case DECL_SPECIALIZATIONS:
3929 case DECL_PARTIAL_SPECIALIZATIONS:
3930 llvm_unreachable("Record cannot be de-serialized with readDeclRecord");
3931 case DECL_TYPEDEF:
3932 D = TypedefDecl::CreateDeserialized(C&: Context, ID);
3933 break;
3934 case DECL_TYPEALIAS:
3935 D = TypeAliasDecl::CreateDeserialized(C&: Context, ID);
3936 break;
3937 case DECL_ENUM:
3938 D = EnumDecl::CreateDeserialized(C&: Context, ID);
3939 break;
3940 case DECL_RECORD:
3941 D = RecordDecl::CreateDeserialized(C: Context, ID);
3942 break;
3943 case DECL_ENUM_CONSTANT:
3944 D = EnumConstantDecl::CreateDeserialized(C&: Context, ID);
3945 break;
3946 case DECL_FUNCTION:
3947 D = FunctionDecl::CreateDeserialized(C&: Context, ID);
3948 break;
3949 case DECL_LINKAGE_SPEC:
3950 D = LinkageSpecDecl::CreateDeserialized(C&: Context, ID);
3951 break;
3952 case DECL_EXPORT:
3953 D = ExportDecl::CreateDeserialized(C&: Context, ID);
3954 break;
3955 case DECL_LABEL:
3956 D = LabelDecl::CreateDeserialized(C&: Context, ID);
3957 break;
3958 case DECL_NAMESPACE:
3959 D = NamespaceDecl::CreateDeserialized(C&: Context, ID);
3960 break;
3961 case DECL_NAMESPACE_ALIAS:
3962 D = NamespaceAliasDecl::CreateDeserialized(C&: Context, ID);
3963 break;
3964 case DECL_USING:
3965 D = UsingDecl::CreateDeserialized(C&: Context, ID);
3966 break;
3967 case DECL_USING_PACK:
3968 D = UsingPackDecl::CreateDeserialized(C&: Context, ID, NumExpansions: Record.readInt());
3969 break;
3970 case DECL_USING_SHADOW:
3971 D = UsingShadowDecl::CreateDeserialized(C&: Context, ID);
3972 break;
3973 case DECL_USING_ENUM:
3974 D = UsingEnumDecl::CreateDeserialized(C&: Context, ID);
3975 break;
3976 case DECL_CONSTRUCTOR_USING_SHADOW:
3977 D = ConstructorUsingShadowDecl::CreateDeserialized(C&: Context, ID);
3978 break;
3979 case DECL_USING_DIRECTIVE:
3980 D = UsingDirectiveDecl::CreateDeserialized(C&: Context, ID);
3981 break;
3982 case DECL_UNRESOLVED_USING_VALUE:
3983 D = UnresolvedUsingValueDecl::CreateDeserialized(C&: Context, ID);
3984 break;
3985 case DECL_UNRESOLVED_USING_TYPENAME:
3986 D = UnresolvedUsingTypenameDecl::CreateDeserialized(C&: Context, ID);
3987 break;
3988 case DECL_UNRESOLVED_USING_IF_EXISTS:
3989 D = UnresolvedUsingIfExistsDecl::CreateDeserialized(Ctx&: Context, ID);
3990 break;
3991 case DECL_CXX_RECORD:
3992 D = CXXRecordDecl::CreateDeserialized(C: Context, ID);
3993 break;
3994 case DECL_CXX_DEDUCTION_GUIDE:
3995 D = CXXDeductionGuideDecl::CreateDeserialized(C&: Context, ID);
3996 break;
3997 case DECL_CXX_METHOD:
3998 D = CXXMethodDecl::CreateDeserialized(C&: Context, ID);
3999 break;
4000 case DECL_CXX_CONSTRUCTOR:
4001 D = CXXConstructorDecl::CreateDeserialized(C&: Context, ID, AllocKind: Record.readInt());
4002 break;
4003 case DECL_CXX_DESTRUCTOR:
4004 D = CXXDestructorDecl::CreateDeserialized(C&: Context, ID);
4005 break;
4006 case DECL_CXX_CONVERSION:
4007 D = CXXConversionDecl::CreateDeserialized(C&: Context, ID);
4008 break;
4009 case DECL_ACCESS_SPEC:
4010 D = AccessSpecDecl::CreateDeserialized(C&: Context, ID);
4011 break;
4012 case DECL_FRIEND:
4013 D = FriendDecl::CreateDeserialized(C&: Context, ID, FriendTypeNumTPLists: Record.readInt());
4014 break;
4015 case DECL_FRIEND_TEMPLATE:
4016 D = FriendTemplateDecl::CreateDeserialized(C&: Context, ID);
4017 break;
4018 case DECL_CLASS_TEMPLATE:
4019 D = ClassTemplateDecl::CreateDeserialized(C&: Context, ID);
4020 break;
4021 case DECL_CLASS_TEMPLATE_SPECIALIZATION:
4022 D = ClassTemplateSpecializationDecl::CreateDeserialized(C&: Context, ID);
4023 break;
4024 case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
4025 D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(C&: Context, ID);
4026 break;
4027 case DECL_VAR_TEMPLATE:
4028 D = VarTemplateDecl::CreateDeserialized(C&: Context, ID);
4029 break;
4030 case DECL_VAR_TEMPLATE_SPECIALIZATION:
4031 D = VarTemplateSpecializationDecl::CreateDeserialized(C&: Context, ID);
4032 break;
4033 case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
4034 D = VarTemplatePartialSpecializationDecl::CreateDeserialized(C&: Context, ID);
4035 break;
4036 case DECL_FUNCTION_TEMPLATE:
4037 D = FunctionTemplateDecl::CreateDeserialized(C&: Context, ID);
4038 break;
4039 case DECL_TEMPLATE_TYPE_PARM: {
4040 bool HasTypeConstraint = Record.readInt();
4041 D = TemplateTypeParmDecl::CreateDeserialized(C: Context, ID,
4042 HasTypeConstraint);
4043 break;
4044 }
4045 case DECL_NON_TYPE_TEMPLATE_PARM: {
4046 bool HasTypeConstraint = Record.readInt();
4047 D = NonTypeTemplateParmDecl::CreateDeserialized(C&: Context, ID,
4048 HasTypeConstraint);
4049 break;
4050 }
4051 case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK: {
4052 bool HasTypeConstraint = Record.readInt();
4053 D = NonTypeTemplateParmDecl::CreateDeserialized(
4054 C&: Context, ID, NumExpandedTypes: Record.readInt(), HasTypeConstraint);
4055 break;
4056 }
4057 case DECL_TEMPLATE_TEMPLATE_PARM:
4058 D = TemplateTemplateParmDecl::CreateDeserialized(C&: Context, ID);
4059 break;
4060 case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
4061 D = TemplateTemplateParmDecl::CreateDeserialized(C&: Context, ID,
4062 NumExpansions: Record.readInt());
4063 break;
4064 case DECL_TYPE_ALIAS_TEMPLATE:
4065 D = TypeAliasTemplateDecl::CreateDeserialized(C&: Context, ID);
4066 break;
4067 case DECL_CONCEPT:
4068 D = ConceptDecl::CreateDeserialized(C&: Context, ID);
4069 break;
4070 case DECL_REQUIRES_EXPR_BODY:
4071 D = RequiresExprBodyDecl::CreateDeserialized(C&: Context, ID);
4072 break;
4073 case DECL_STATIC_ASSERT:
4074 D = StaticAssertDecl::CreateDeserialized(C&: Context, ID);
4075 break;
4076 case DECL_OBJC_METHOD:
4077 D = ObjCMethodDecl::CreateDeserialized(C&: Context, ID);
4078 break;
4079 case DECL_OBJC_INTERFACE:
4080 D = ObjCInterfaceDecl::CreateDeserialized(C: Context, ID);
4081 break;
4082 case DECL_OBJC_IVAR:
4083 D = ObjCIvarDecl::CreateDeserialized(C&: Context, ID);
4084 break;
4085 case DECL_OBJC_PROTOCOL:
4086 D = ObjCProtocolDecl::CreateDeserialized(C&: Context, ID);
4087 break;
4088 case DECL_OBJC_AT_DEFS_FIELD:
4089 D = ObjCAtDefsFieldDecl::CreateDeserialized(C&: Context, ID);
4090 break;
4091 case DECL_OBJC_CATEGORY:
4092 D = ObjCCategoryDecl::CreateDeserialized(C&: Context, ID);
4093 break;
4094 case DECL_OBJC_CATEGORY_IMPL:
4095 D = ObjCCategoryImplDecl::CreateDeserialized(C&: Context, ID);
4096 break;
4097 case DECL_OBJC_IMPLEMENTATION:
4098 D = ObjCImplementationDecl::CreateDeserialized(C&: Context, ID);
4099 break;
4100 case DECL_OBJC_COMPATIBLE_ALIAS:
4101 D = ObjCCompatibleAliasDecl::CreateDeserialized(C&: Context, ID);
4102 break;
4103 case DECL_OBJC_PROPERTY:
4104 D = ObjCPropertyDecl::CreateDeserialized(C&: Context, ID);
4105 break;
4106 case DECL_OBJC_PROPERTY_IMPL:
4107 D = ObjCPropertyImplDecl::CreateDeserialized(C&: Context, ID);
4108 break;
4109 case DECL_FIELD:
4110 D = FieldDecl::CreateDeserialized(C&: Context, ID);
4111 break;
4112 case DECL_INDIRECTFIELD:
4113 D = IndirectFieldDecl::CreateDeserialized(C&: Context, ID);
4114 break;
4115 case DECL_VAR:
4116 D = VarDecl::CreateDeserialized(C&: Context, ID);
4117 break;
4118 case DECL_IMPLICIT_PARAM:
4119 D = ImplicitParamDecl::CreateDeserialized(C&: Context, ID);
4120 break;
4121 case DECL_PARM_VAR:
4122 D = ParmVarDecl::CreateDeserialized(C&: Context, ID);
4123 break;
4124 case DECL_DECOMPOSITION:
4125 D = DecompositionDecl::CreateDeserialized(C&: Context, ID, NumBindings: Record.readInt());
4126 break;
4127 case DECL_BINDING:
4128 D = BindingDecl::CreateDeserialized(C&: Context, ID);
4129 break;
4130 case DECL_FILE_SCOPE_ASM:
4131 D = FileScopeAsmDecl::CreateDeserialized(C&: Context, ID);
4132 break;
4133 case DECL_TOP_LEVEL_STMT_DECL:
4134 D = TopLevelStmtDecl::CreateDeserialized(C&: Context, ID);
4135 break;
4136 case DECL_BLOCK:
4137 D = BlockDecl::CreateDeserialized(C&: Context, ID);
4138 break;
4139 case DECL_MS_PROPERTY:
4140 D = MSPropertyDecl::CreateDeserialized(C&: Context, ID);
4141 break;
4142 case DECL_MS_GUID:
4143 D = MSGuidDecl::CreateDeserialized(C&: Context, ID);
4144 break;
4145 case DECL_UNNAMED_GLOBAL_CONSTANT:
4146 D = UnnamedGlobalConstantDecl::CreateDeserialized(C&: Context, ID);
4147 break;
4148 case DECL_TEMPLATE_PARAM_OBJECT:
4149 D = TemplateParamObjectDecl::CreateDeserialized(C&: Context, ID);
4150 break;
4151 case DECL_OUTLINEDFUNCTION:
4152 D = OutlinedFunctionDecl::CreateDeserialized(C&: Context, ID, NumParams: Record.readInt());
4153 break;
4154 case DECL_CAPTURED:
4155 D = CapturedDecl::CreateDeserialized(C&: Context, ID, NumParams: Record.readInt());
4156 break;
4157 case DECL_CXX_BASE_SPECIFIERS:
4158 Error(Msg: "attempt to read a C++ base-specifier record as a declaration");
4159 return nullptr;
4160 case DECL_CXX_CTOR_INITIALIZERS:
4161 Error(Msg: "attempt to read a C++ ctor initializer record as a declaration");
4162 return nullptr;
4163 case DECL_IMPORT:
4164 // Note: last entry of the ImportDecl record is the number of stored source
4165 // locations.
4166 D = ImportDecl::CreateDeserialized(C&: Context, ID, NumLocations: Record.back());
4167 break;
4168 case DECL_OMP_THREADPRIVATE: {
4169 Record.skipInts(N: 1);
4170 unsigned NumChildren = Record.readInt();
4171 Record.skipInts(N: 1);
4172 D = OMPThreadPrivateDecl::CreateDeserialized(C&: Context, ID, N: NumChildren);
4173 break;
4174 }
4175 case DECL_OMP_ALLOCATE: {
4176 unsigned NumClauses = Record.readInt();
4177 unsigned NumVars = Record.readInt();
4178 Record.skipInts(N: 1);
4179 D = OMPAllocateDecl::CreateDeserialized(C&: Context, ID, NVars: NumVars, NClauses: NumClauses);
4180 break;
4181 }
4182 case DECL_OMP_REQUIRES: {
4183 unsigned NumClauses = Record.readInt();
4184 Record.skipInts(N: 2);
4185 D = OMPRequiresDecl::CreateDeserialized(C&: Context, ID, N: NumClauses);
4186 break;
4187 }
4188 case DECL_OMP_DECLARE_REDUCTION:
4189 D = OMPDeclareReductionDecl::CreateDeserialized(C&: Context, ID);
4190 break;
4191 case DECL_OMP_DECLARE_MAPPER: {
4192 unsigned NumClauses = Record.readInt();
4193 Record.skipInts(N: 2);
4194 D = OMPDeclareMapperDecl::CreateDeserialized(C&: Context, ID, N: NumClauses);
4195 break;
4196 }
4197 case DECL_OMP_CAPTUREDEXPR:
4198 D = OMPCapturedExprDecl::CreateDeserialized(C&: Context, ID);
4199 break;
4200 case DECL_PRAGMA_COMMENT:
4201 D = PragmaCommentDecl::CreateDeserialized(C&: Context, ID, ArgSize: Record.readInt());
4202 break;
4203 case DECL_PRAGMA_DETECT_MISMATCH:
4204 D = PragmaDetectMismatchDecl::CreateDeserialized(C&: Context, ID,
4205 NameValueSize: Record.readInt());
4206 break;
4207 case DECL_EMPTY:
4208 D = EmptyDecl::CreateDeserialized(C&: Context, ID);
4209 break;
4210 case DECL_LIFETIME_EXTENDED_TEMPORARY:
4211 D = LifetimeExtendedTemporaryDecl::CreateDeserialized(C&: Context, ID);
4212 break;
4213 case DECL_OBJC_TYPE_PARAM:
4214 D = ObjCTypeParamDecl::CreateDeserialized(ctx&: Context, ID);
4215 break;
4216 case DECL_HLSL_BUFFER:
4217 D = HLSLBufferDecl::CreateDeserialized(C&: Context, ID);
4218 break;
4219 case DECL_IMPLICIT_CONCEPT_SPECIALIZATION:
4220 D = ImplicitConceptSpecializationDecl::CreateDeserialized(C: Context, ID,
4221 NumTemplateArgs: Record.readInt());
4222 break;
4223 case DECL_OPENACC_DECLARE:
4224 D = OpenACCDeclareDecl::CreateDeserialized(Ctx&: Context, ID, NumClauses: Record.readInt());
4225 break;
4226 case DECL_OPENACC_ROUTINE:
4227 D = OpenACCRoutineDecl::CreateDeserialized(Ctx&: Context, ID, NumClauses: Record.readInt());
4228 break;
4229 }
4230
4231 assert(D && "Unknown declaration reading AST file");
4232 LoadedDecl(Index: translateGlobalDeclIDToIndex(ID), D);
4233 // Set the DeclContext before doing any deserialization, to make sure internal
4234 // calls to Decl::getASTContext() by Decl's methods will find the
4235 // TranslationUnitDecl without crashing.
4236 D->setDeclContext(Context.getTranslationUnitDecl());
4237
4238 // Reading some declarations can result in deep recursion.
4239 runWithSufficientStackSpace(Loc: DeclLoc, Fn: [&] { Reader.Visit(D); });
4240
4241 // If this declaration is also a declaration context, get the
4242 // offsets for its tables of lexical and visible declarations.
4243 if (auto *DC = dyn_cast<DeclContext>(Val: D)) {
4244 LookupBlockOffsets Offsets;
4245
4246 Reader.VisitDeclContext(DC, Offsets);
4247
4248 // Get the lexical and visible block for the delayed namespace.
4249 // It is sufficient to judge if ID is in DelayedNamespaceOffsetMap.
4250 // But it may be more efficient to filter the other cases.
4251 if (!Offsets && isa<NamespaceDecl>(Val: D))
4252 if (auto Iter = DelayedNamespaceOffsetMap.find(Val: ID);
4253 Iter != DelayedNamespaceOffsetMap.end())
4254 Offsets = Iter->second;
4255
4256 if (Offsets.VisibleOffset &&
4257 ReadVisibleDeclContextStorage(
4258 M&: *Loc.F, Cursor&: DeclsCursor, Offset: Offsets.VisibleOffset, ID,
4259 VisibleKind: VisibleDeclContextStorageKind::GenerallyVisible))
4260 return nullptr;
4261 if (Offsets.ModuleLocalOffset &&
4262 ReadVisibleDeclContextStorage(
4263 M&: *Loc.F, Cursor&: DeclsCursor, Offset: Offsets.ModuleLocalOffset, ID,
4264 VisibleKind: VisibleDeclContextStorageKind::ModuleLocalVisible))
4265 return nullptr;
4266 if (Offsets.TULocalOffset &&
4267 ReadVisibleDeclContextStorage(
4268 M&: *Loc.F, Cursor&: DeclsCursor, Offset: Offsets.TULocalOffset, ID,
4269 VisibleKind: VisibleDeclContextStorageKind::TULocalVisible))
4270 return nullptr;
4271
4272 if (Offsets.LexicalOffset &&
4273 ReadLexicalDeclContextStorage(M&: *Loc.F, Cursor&: DeclsCursor,
4274 Offset: Offsets.LexicalOffset, DC))
4275 return nullptr;
4276 }
4277 assert(Record.getIdx() == Record.size());
4278
4279 // Load any relevant update records.
4280 PendingUpdateRecords.push_back(
4281 Elt: PendingUpdateRecord(ID, D, /*JustLoaded=*/true));
4282
4283 // Load the categories after recursive loading is finished.
4284 if (auto *Class = dyn_cast<ObjCInterfaceDecl>(Val: D))
4285 // If we already have a definition when deserializing the ObjCInterfaceDecl,
4286 // we put the Decl in PendingDefinitions so we can pull the categories here.
4287 if (Class->isThisDeclarationADefinition() ||
4288 PendingDefinitions.count(Ptr: Class))
4289 loadObjCCategories(ID, D: Class);
4290
4291 // If we have deserialized a declaration that has a definition the
4292 // AST consumer might need to know about, queue it.
4293 // We don't pass it to the consumer immediately because we may be in recursive
4294 // loading, and some declarations may still be initializing.
4295 PotentiallyInterestingDecls.push_back(x: D);
4296
4297 return D;
4298}
4299
4300void ASTReader::PassInterestingDeclsToConsumer() {
4301 assert(Consumer);
4302
4303 if (!CanPassDeclsToConsumer)
4304 return;
4305
4306 // Guard variable to avoid recursively redoing the process of passing
4307 // decls to consumer.
4308 SaveAndRestore GuardPassingDeclsToConsumer(CanPassDeclsToConsumer,
4309 /*NewValue=*/false);
4310
4311 // Ensure that we've loaded all potentially-interesting declarations
4312 // that need to be eagerly loaded.
4313 for (auto ID : EagerlyDeserializedDecls)
4314 GetDecl(ID);
4315 EagerlyDeserializedDecls.clear();
4316
4317 auto ConsumingPotentialInterestingDecls = [this]() {
4318 while (!PotentiallyInterestingDecls.empty()) {
4319 Decl *D = PotentiallyInterestingDecls.front();
4320 PotentiallyInterestingDecls.pop_front();
4321 if (isConsumerInterestedIn(D))
4322 PassInterestingDeclToConsumer(D);
4323 }
4324 };
4325 std::deque<Decl *> MaybeInterestingDecls =
4326 std::move(PotentiallyInterestingDecls);
4327 PotentiallyInterestingDecls.clear();
4328 assert(PotentiallyInterestingDecls.empty());
4329 while (!MaybeInterestingDecls.empty()) {
4330 Decl *D = MaybeInterestingDecls.front();
4331 MaybeInterestingDecls.pop_front();
4332 // Since we load the variable's initializers lazily, it'd be problematic
4333 // if the initializers dependent on each other. So here we try to load the
4334 // initializers of static variables to make sure they are passed to code
4335 // generator by order. If we read anything interesting, we would consume
4336 // that before emitting the current declaration.
4337 if (auto *VD = dyn_cast<VarDecl>(Val: D);
4338 VD && VD->isFileVarDecl() && !VD->isExternallyVisible())
4339 VD->getInit();
4340 ConsumingPotentialInterestingDecls();
4341 if (isConsumerInterestedIn(D))
4342 PassInterestingDeclToConsumer(D);
4343 }
4344
4345 // If we add any new potential interesting decl in the last call, consume it.
4346 ConsumingPotentialInterestingDecls();
4347
4348 for (GlobalDeclID ID : VTablesToEmit) {
4349 auto *RD = cast<CXXRecordDecl>(Val: GetDecl(ID));
4350 assert(!RD->shouldEmitInExternalSource());
4351 PassVTableToConsumer(RD);
4352 }
4353 VTablesToEmit.clear();
4354}
4355
4356void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {
4357 // The declaration may have been modified by files later in the chain.
4358 // If this is the case, read the record containing the updates from each file
4359 // and pass it to ASTDeclReader to make the modifications.
4360 GlobalDeclID ID = Record.ID;
4361 Decl *D = Record.D;
4362 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
4363 DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(Val: ID);
4364
4365 if (UpdI != DeclUpdateOffsets.end()) {
4366 auto UpdateOffsets = std::move(UpdI->second);
4367 DeclUpdateOffsets.erase(I: UpdI);
4368
4369 // Check if this decl was interesting to the consumer. If we just loaded
4370 // the declaration, then we know it was interesting and we skip the call
4371 // to isConsumerInterestedIn because it is unsafe to call in the
4372 // current ASTReader state.
4373 bool WasInteresting = Record.JustLoaded || isConsumerInterestedIn(D);
4374 for (auto &FileAndOffset : UpdateOffsets) {
4375 ModuleFile *F = FileAndOffset.first;
4376 uint64_t Offset = FileAndOffset.second;
4377 llvm::BitstreamCursor &Cursor = F->DeclsCursor;
4378 SavedStreamPosition SavedPosition(Cursor);
4379 if (llvm::Error JumpFailed = Cursor.JumpToBit(BitNo: Offset))
4380 // FIXME don't do a fatal error.
4381 llvm::report_fatal_error(
4382 reason: Twine("ASTReader::loadDeclUpdateRecords failed jumping: ") +
4383 toString(E: std::move(JumpFailed)));
4384 Expected<unsigned> MaybeCode = Cursor.ReadCode();
4385 if (!MaybeCode)
4386 llvm::report_fatal_error(
4387 reason: Twine("ASTReader::loadDeclUpdateRecords failed reading code: ") +
4388 toString(E: MaybeCode.takeError()));
4389 unsigned Code = MaybeCode.get();
4390 ASTRecordReader Record(*this, *F);
4391 if (Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, AbbrevID: Code))
4392 assert(MaybeRecCode.get() == DECL_UPDATES &&
4393 "Expected DECL_UPDATES record!");
4394 else
4395 llvm::report_fatal_error(
4396 reason: Twine("ASTReader::loadDeclUpdateRecords failed reading rec code: ") +
4397 toString(E: MaybeCode.takeError()));
4398
4399 ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,
4400 SourceLocation());
4401 Reader.UpdateDecl(D);
4402
4403 // We might have made this declaration interesting. If so, remember that
4404 // we need to hand it off to the consumer.
4405 if (!WasInteresting && isConsumerInterestedIn(D)) {
4406 PotentiallyInterestingDecls.push_back(x: D);
4407 WasInteresting = true;
4408 }
4409 }
4410 }
4411
4412 // Load the pending visible updates for this decl context, if it has any.
4413 if (auto I = PendingVisibleUpdates.find(Val: ID);
4414 I != PendingVisibleUpdates.end()) {
4415 auto VisibleUpdates = std::move(I->second);
4416 PendingVisibleUpdates.erase(I);
4417
4418 auto *DC = cast<DeclContext>(Val: D)->getPrimaryContext();
4419 for (const auto &Update : VisibleUpdates)
4420 Lookups[DC].Table.add(
4421 File: Update.Mod, Data: Update.Data,
4422 InfoObj: reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
4423 DC->setHasExternalVisibleStorage(true);
4424 }
4425
4426 if (auto I = PendingModuleLocalVisibleUpdates.find(Val: ID);
4427 I != PendingModuleLocalVisibleUpdates.end()) {
4428 auto ModuleLocalVisibleUpdates = std::move(I->second);
4429 PendingModuleLocalVisibleUpdates.erase(I);
4430
4431 auto *DC = cast<DeclContext>(Val: D)->getPrimaryContext();
4432 for (const auto &Update : ModuleLocalVisibleUpdates)
4433 ModuleLocalLookups[DC].Table.add(
4434 File: Update.Mod, Data: Update.Data,
4435 InfoObj: reader::ModuleLocalNameLookupTrait(*this, *Update.Mod));
4436 // NOTE: Can we optimize the case that the data being loaded
4437 // is not related to current module?
4438 DC->setHasExternalVisibleStorage(true);
4439 }
4440
4441 if (auto I = TULocalUpdates.find(Val: ID); I != TULocalUpdates.end()) {
4442 auto Updates = std::move(I->second);
4443 TULocalUpdates.erase(I);
4444
4445 auto *DC = cast<DeclContext>(Val: D)->getPrimaryContext();
4446 for (const auto &Update : Updates)
4447 TULocalLookups[DC].Table.add(
4448 File: Update.Mod, Data: Update.Data,
4449 InfoObj: reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
4450 DC->setHasExternalVisibleStorage(true);
4451 }
4452
4453 // Load any pending related decls.
4454 if (D->isCanonicalDecl()) {
4455 if (auto IT = RelatedDeclsMap.find(Val: ID); IT != RelatedDeclsMap.end()) {
4456 for (auto LID : IT->second)
4457 GetDecl(ID: LID);
4458 RelatedDeclsMap.erase(I: IT);
4459 }
4460 }
4461
4462 // Load the pending specializations update for this decl, if it has any.
4463 if (auto I = PendingSpecializationsUpdates.find(Val: ID);
4464 I != PendingSpecializationsUpdates.end()) {
4465 auto SpecializationUpdates = std::move(I->second);
4466 PendingSpecializationsUpdates.erase(I);
4467
4468 for (const auto &Update : SpecializationUpdates)
4469 AddSpecializations(D, Data: Update.Data, M&: *Update.Mod, /*IsPartial=*/false);
4470 }
4471
4472 // Load the pending specializations update for this decl, if it has any.
4473 if (auto I = PendingPartialSpecializationsUpdates.find(Val: ID);
4474 I != PendingPartialSpecializationsUpdates.end()) {
4475 auto SpecializationUpdates = std::move(I->second);
4476 PendingPartialSpecializationsUpdates.erase(I);
4477
4478 for (const auto &Update : SpecializationUpdates)
4479 AddSpecializations(D, Data: Update.Data, M&: *Update.Mod, /*IsPartial=*/true);
4480 }
4481}
4482
4483void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {
4484 // Attach FirstLocal to the end of the decl chain.
4485 Decl *CanonDecl = FirstLocal->getCanonicalDecl();
4486 if (FirstLocal != CanonDecl) {
4487 Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(D: CanonDecl);
4488 ASTDeclReader::attachPreviousDecl(
4489 Reader&: *this, D: FirstLocal, Previous: PrevMostRecent ? PrevMostRecent : CanonDecl,
4490 Canon: CanonDecl);
4491 }
4492
4493 if (!LocalOffset) {
4494 ASTDeclReader::attachLatestDecl(D: CanonDecl, Latest: FirstLocal);
4495 return;
4496 }
4497
4498 // Load the list of other redeclarations from this module file.
4499 ModuleFile *M = getOwningModuleFile(D: FirstLocal);
4500 assert(M && "imported decl from no module file");
4501
4502 llvm::BitstreamCursor &Cursor = M->DeclsCursor;
4503 SavedStreamPosition SavedPosition(Cursor);
4504 if (llvm::Error JumpFailed = Cursor.JumpToBit(BitNo: LocalOffset))
4505 llvm::report_fatal_error(
4506 reason: Twine("ASTReader::loadPendingDeclChain failed jumping: ") +
4507 toString(E: std::move(JumpFailed)));
4508
4509 RecordData Record;
4510 Expected<unsigned> MaybeCode = Cursor.ReadCode();
4511 if (!MaybeCode)
4512 llvm::report_fatal_error(
4513 reason: Twine("ASTReader::loadPendingDeclChain failed reading code: ") +
4514 toString(E: MaybeCode.takeError()));
4515 unsigned Code = MaybeCode.get();
4516 if (Expected<unsigned> MaybeRecCode = Cursor.readRecord(AbbrevID: Code, Vals&: Record))
4517 assert(MaybeRecCode.get() == LOCAL_REDECLARATIONS &&
4518 "expected LOCAL_REDECLARATIONS record!");
4519 else
4520 llvm::report_fatal_error(
4521 reason: Twine("ASTReader::loadPendingDeclChain failed reading rec code: ") +
4522 toString(E: MaybeCode.takeError()));
4523
4524 // FIXME: We have several different dispatches on decl kind here; maybe
4525 // we should instead generate one loop per kind and dispatch up-front?
4526 Decl *MostRecent = FirstLocal;
4527 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
4528 unsigned Idx = N - I - 1;
4529 auto *D = ReadDecl(F&: *M, R: Record, I&: Idx);
4530 ASTDeclReader::attachPreviousDecl(Reader&: *this, D, Previous: MostRecent, Canon: CanonDecl);
4531 MostRecent = D;
4532 }
4533 ASTDeclReader::attachLatestDecl(D: CanonDecl, Latest: MostRecent);
4534}
4535
4536namespace {
4537
4538 /// Given an ObjC interface, goes through the modules and links to the
4539 /// interface all the categories for it.
4540 class ObjCCategoriesVisitor {
4541 ASTReader &Reader;
4542 ObjCInterfaceDecl *Interface;
4543 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
4544 ObjCCategoryDecl *Tail = nullptr;
4545 llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
4546 GlobalDeclID InterfaceID;
4547 unsigned PreviousGeneration;
4548
4549 void add(ObjCCategoryDecl *Cat) {
4550 // Only process each category once.
4551 if (!Deserialized.erase(Ptr: Cat))
4552 return;
4553
4554 // Check for duplicate categories.
4555 if (Cat->getDeclName()) {
4556 ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
4557 if (Existing && Reader.getOwningModuleFile(D: Existing) !=
4558 Reader.getOwningModuleFile(D: Cat)) {
4559 StructuralEquivalenceContext::NonEquivalentDeclSet NonEquivalentDecls;
4560 StructuralEquivalenceContext Ctx(
4561 Reader.getContext().getLangOpts(), Cat->getASTContext(),
4562 Existing->getASTContext(), NonEquivalentDecls,
4563 StructuralEquivalenceKind::Default,
4564 /*StrictTypeSpelling=*/false,
4565 /*Complain=*/false,
4566 /*ErrorOnTagTypeMismatch=*/true);
4567 if (!Ctx.IsEquivalent(D1: Cat, D2: Existing)) {
4568 // Warn only if the categories with the same name are different.
4569 Reader.Diag(Loc: Cat->getLocation(), DiagID: diag::warn_dup_category_def)
4570 << Interface->getDeclName() << Cat->getDeclName();
4571 Reader.Diag(Loc: Existing->getLocation(),
4572 DiagID: diag::note_previous_definition);
4573 }
4574 } else if (!Existing) {
4575 // Record this category.
4576 Existing = Cat;
4577 }
4578 }
4579
4580 // Add this category to the end of the chain.
4581 if (Tail)
4582 ASTDeclReader::setNextObjCCategory(Cat: Tail, Next: Cat);
4583 else
4584 Interface->setCategoryListRaw(Cat);
4585 Tail = Cat;
4586 }
4587
4588 public:
4589 ObjCCategoriesVisitor(
4590 ASTReader &Reader, ObjCInterfaceDecl *Interface,
4591 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
4592 GlobalDeclID InterfaceID, unsigned PreviousGeneration)
4593 : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
4594 InterfaceID(InterfaceID), PreviousGeneration(PreviousGeneration) {
4595 // Populate the name -> category map with the set of known categories.
4596 for (auto *Cat : Interface->known_categories()) {
4597 if (Cat->getDeclName())
4598 NameCategoryMap[Cat->getDeclName()] = Cat;
4599
4600 // Keep track of the tail of the category list.
4601 Tail = Cat;
4602 }
4603 }
4604
4605 bool operator()(ModuleFile &M) {
4606 // If we've loaded all of the category information we care about from
4607 // this module file, we're done.
4608 if (M.Generation <= PreviousGeneration)
4609 return true;
4610
4611 // Map global ID of the definition down to the local ID used in this
4612 // module file. If there is no such mapping, we'll find nothing here
4613 // (or in any module it imports).
4614 LocalDeclID LocalID =
4615 Reader.mapGlobalIDToModuleFileGlobalID(M, GlobalID: InterfaceID);
4616 if (LocalID.isInvalid())
4617 return true;
4618
4619 // Perform a binary search to find the local redeclarations for this
4620 // declaration (if any).
4621 const ObjCCategoriesInfo Compare = {LocalID, 0};
4622 const ObjCCategoriesInfo *Result = std::lower_bound(
4623 first: M.ObjCCategoriesMap,
4624 last: M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap, val: Compare);
4625 if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
4626 LocalID != Result->getDefinitionID()) {
4627 // We didn't find anything. If the class definition is in this module
4628 // file, then the module files it depends on cannot have any categories,
4629 // so suppress further lookup.
4630 return Reader.isDeclIDFromModule(ID: InterfaceID, M);
4631 }
4632
4633 // We found something. Dig out all of the categories.
4634 unsigned Offset = Result->Offset;
4635 unsigned N = M.ObjCCategories[Offset];
4636 M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
4637 for (unsigned I = 0; I != N; ++I)
4638 add(Cat: Reader.ReadDeclAs<ObjCCategoryDecl>(F&: M, R: M.ObjCCategories, I&: Offset));
4639 return true;
4640 }
4641 };
4642
4643} // namespace
4644
4645void ASTReader::loadObjCCategories(GlobalDeclID ID, ObjCInterfaceDecl *D,
4646 unsigned PreviousGeneration) {
4647 ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
4648 PreviousGeneration);
4649 ModuleMgr.visit(Visitor);
4650}
4651
4652template<typename DeclT, typename Fn>
4653static void forAllLaterRedecls(DeclT *D, Fn F) {
4654 F(D);
4655
4656 // Check whether we've already merged D into its redeclaration chain.
4657 // MostRecent may or may not be nullptr if D has not been merged. If
4658 // not, walk the merged redecl chain and see if it's there.
4659 auto *MostRecent = D->getMostRecentDecl();
4660 bool Found = false;
4661 for (auto *Redecl = MostRecent; Redecl && !Found;
4662 Redecl = Redecl->getPreviousDecl())
4663 Found = (Redecl == D);
4664
4665 // If this declaration is merged, apply the functor to all later decls.
4666 if (Found) {
4667 for (auto *Redecl = MostRecent; Redecl != D;
4668 Redecl = Redecl->getPreviousDecl())
4669 F(Redecl);
4670 }
4671}
4672
4673void ASTDeclReader::UpdateDecl(Decl *D) {
4674 while (Record.getIdx() < Record.size()) {
4675 switch ((DeclUpdateKind)Record.readInt()) {
4676 case DeclUpdateKind::CXXAddedImplicitMember: {
4677 auto *RD = cast<CXXRecordDecl>(Val: D);
4678 Decl *MD = Record.readDecl();
4679 assert(MD && "couldn't read decl from update record");
4680 Reader.PendingAddedClassMembers.push_back(Elt: {RD, MD});
4681 break;
4682 }
4683
4684 case DeclUpdateKind::CXXAddedAnonymousNamespace: {
4685 auto *Anon = readDeclAs<NamespaceDecl>();
4686
4687 // Each module has its own anonymous namespace, which is disjoint from
4688 // any other module's anonymous namespaces, so don't attach the anonymous
4689 // namespace at all.
4690 if (!Record.isModule()) {
4691 if (auto *TU = dyn_cast<TranslationUnitDecl>(Val: D))
4692 TU->setAnonymousNamespace(Anon);
4693 else
4694 cast<NamespaceDecl>(Val: D)->setAnonymousNamespace(Anon);
4695 }
4696 break;
4697 }
4698
4699 case DeclUpdateKind::CXXAddedVarDefinition: {
4700 auto *VD = cast<VarDecl>(Val: D);
4701 VD->NonParmVarDeclBits.IsInline = Record.readInt();
4702 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
4703 ReadVarDeclInit(VD);
4704 break;
4705 }
4706
4707 case DeclUpdateKind::CXXPointOfInstantiation: {
4708 SourceLocation POI = Record.readSourceLocation();
4709 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Val: D)) {
4710 VTSD->setPointOfInstantiation(POI);
4711 } else if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
4712 MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo();
4713 assert(MSInfo && "No member specialization information");
4714 MSInfo->setPointOfInstantiation(POI);
4715 } else {
4716 auto *FD = cast<FunctionDecl>(Val: D);
4717 if (auto *FTSInfo = dyn_cast<FunctionTemplateSpecializationInfo *>(
4718 Val&: FD->TemplateOrSpecialization))
4719 FTSInfo->setPointOfInstantiation(POI);
4720 else
4721 cast<MemberSpecializationInfo *>(Val&: FD->TemplateOrSpecialization)
4722 ->setPointOfInstantiation(POI);
4723 }
4724 break;
4725 }
4726
4727 case DeclUpdateKind::CXXInstantiatedDefaultArgument: {
4728 auto *Param = cast<ParmVarDecl>(Val: D);
4729
4730 // We have to read the default argument regardless of whether we use it
4731 // so that hypothetical further update records aren't messed up.
4732 // TODO: Add a function to skip over the next expr record.
4733 auto *DefaultArg = Record.readExpr();
4734
4735 // Only apply the update if the parameter still has an uninstantiated
4736 // default argument.
4737 if (Param->hasUninstantiatedDefaultArg())
4738 Param->setDefaultArg(DefaultArg);
4739 break;
4740 }
4741
4742 case DeclUpdateKind::CXXInstantiatedDefaultMemberInitializer: {
4743 auto *FD = cast<FieldDecl>(Val: D);
4744 auto *DefaultInit = Record.readExpr();
4745
4746 // Only apply the update if the field still has an uninstantiated
4747 // default member initializer.
4748 if (FD->hasInClassInitializer() && !FD->hasNonNullInClassInitializer()) {
4749 if (DefaultInit)
4750 FD->setInClassInitializer(DefaultInit);
4751 else
4752 // Instantiation failed. We can get here if we serialized an AST for
4753 // an invalid program.
4754 FD->removeInClassInitializer();
4755 }
4756 break;
4757 }
4758
4759 case DeclUpdateKind::CXXAddedFunctionDefinition: {
4760 auto *FD = cast<FunctionDecl>(Val: D);
4761 if (Reader.PendingBodies[FD]) {
4762 // FIXME: Maybe check for ODR violations.
4763 // It's safe to stop now because this update record is always last.
4764 return;
4765 }
4766
4767 if (Record.readInt()) {
4768 // Maintain AST consistency: any later redeclarations of this function
4769 // are inline if this one is. (We might have merged another declaration
4770 // into this one.)
4771 forAllLaterRedecls(D: FD, F: [](FunctionDecl *FD) {
4772 FD->setImplicitlyInline();
4773 });
4774 }
4775 FD->setInnerLocStart(readSourceLocation());
4776 ReadFunctionDefinition(FD);
4777 assert(Record.getIdx() == Record.size() && "lazy body must be last");
4778 break;
4779 }
4780
4781 case DeclUpdateKind::CXXInstantiatedClassDefinition: {
4782 auto *RD = cast<CXXRecordDecl>(Val: D);
4783 auto *OldDD = RD->getCanonicalDecl()->DefinitionData;
4784 bool HadRealDefinition =
4785 OldDD && (OldDD->Definition != RD ||
4786 !Reader.PendingFakeDefinitionData.count(Val: OldDD));
4787 RD->setParamDestroyedInCallee(Record.readInt());
4788 RD->setArgPassingRestrictions(
4789 static_cast<RecordArgPassingKind>(Record.readInt()));
4790 ReadCXXRecordDefinition(D: RD, /*Update*/true);
4791
4792 // Visible update is handled separately.
4793 uint64_t LexicalOffset = ReadLocalOffset();
4794 if (!HadRealDefinition && LexicalOffset) {
4795 Record.readLexicalDeclContextStorage(Offset: LexicalOffset, DC: RD);
4796 Reader.PendingFakeDefinitionData.erase(Val: OldDD);
4797 }
4798
4799 auto TSK = (TemplateSpecializationKind)Record.readInt();
4800 SourceLocation POI = readSourceLocation();
4801 if (MemberSpecializationInfo *MSInfo =
4802 RD->getMemberSpecializationInfo()) {
4803 MSInfo->setTemplateSpecializationKind(TSK);
4804 MSInfo->setPointOfInstantiation(POI);
4805 } else {
4806 auto *Spec = cast<ClassTemplateSpecializationDecl>(Val: RD);
4807 Spec->setTemplateSpecializationKind(TSK);
4808 Spec->setPointOfInstantiation(POI);
4809
4810 if (Record.readInt()) {
4811 auto *PartialSpec =
4812 readDeclAs<ClassTemplatePartialSpecializationDecl>();
4813 SmallVector<TemplateArgument, 8> TemplArgs;
4814 Record.readTemplateArgumentList(TemplArgs);
4815 auto *TemplArgList = TemplateArgumentList::CreateCopy(
4816 Context&: Reader.getContext(), Args: TemplArgs);
4817
4818 // FIXME: If we already have a partial specialization set,
4819 // check that it matches.
4820 if (!isa<ClassTemplatePartialSpecializationDecl *>(
4821 Val: Spec->getSpecializedTemplateOrPartial()))
4822 Spec->setInstantiationOf(PartialSpec, TemplateArgs: TemplArgList);
4823 }
4824 }
4825
4826 RD->setTagKind(static_cast<TagTypeKind>(Record.readInt()));
4827 RD->setLocation(readSourceLocation());
4828 RD->setLocStart(readSourceLocation());
4829 RD->setBraceRange(readSourceRange());
4830
4831 if (Record.readInt()) {
4832 AttrVec Attrs;
4833 Record.readAttributes(Attrs);
4834 // If the declaration already has attributes, we assume that some other
4835 // AST file already loaded them.
4836 if (!D->hasAttrs())
4837 D->setAttrsImpl(Attrs, Ctx&: Reader.getContext());
4838 }
4839 break;
4840 }
4841
4842 case DeclUpdateKind::CXXResolvedDtorDelete: {
4843 // Set the 'operator delete' directly to avoid emitting another update
4844 // record.
4845 auto *Del = readDeclAs<FunctionDecl>();
4846 auto *First = cast<CXXDestructorDecl>(Val: D->getCanonicalDecl());
4847 auto *ThisArg = Record.readExpr();
4848 // FIXME: Check consistency if we have an old and new operator delete.
4849 if (!First->OperatorDelete) {
4850 First->OperatorDelete = Del;
4851 First->OperatorDeleteThisArg = ThisArg;
4852 }
4853 break;
4854 }
4855
4856 case DeclUpdateKind::CXXResolvedExceptionSpec: {
4857 SmallVector<QualType, 8> ExceptionStorage;
4858 auto ESI = Record.readExceptionSpecInfo(buffer&: ExceptionStorage);
4859
4860 // Update this declaration's exception specification, if needed.
4861 auto *FD = cast<FunctionDecl>(Val: D);
4862 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
4863 // FIXME: If the exception specification is already present, check that it
4864 // matches.
4865 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
4866 FD->setType(Reader.getContext().getFunctionType(
4867 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
4868 EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI)));
4869
4870 // When we get to the end of deserializing, see if there are other decls
4871 // that we need to propagate this exception specification onto.
4872 Reader.PendingExceptionSpecUpdates.insert(
4873 KV: std::make_pair(x: FD->getCanonicalDecl(), y&: FD));
4874 }
4875 break;
4876 }
4877
4878 case DeclUpdateKind::CXXDeducedReturnType: {
4879 auto *FD = cast<FunctionDecl>(Val: D);
4880 QualType DeducedResultType = Record.readType();
4881 Reader.PendingDeducedTypeUpdates.insert(
4882 KV: {FD->getCanonicalDecl(), DeducedResultType});
4883 break;
4884 }
4885
4886 case DeclUpdateKind::DeclMarkedUsed:
4887 // Maintain AST consistency: any later redeclarations are used too.
4888 D->markUsed(C&: Reader.getContext());
4889 break;
4890
4891 case DeclUpdateKind::ManglingNumber:
4892 Reader.getContext().setManglingNumber(ND: cast<NamedDecl>(Val: D),
4893 Number: Record.readInt());
4894 break;
4895
4896 case DeclUpdateKind::StaticLocalNumber:
4897 Reader.getContext().setStaticLocalNumber(VD: cast<VarDecl>(Val: D),
4898 Number: Record.readInt());
4899 break;
4900
4901 case DeclUpdateKind::DeclMarkedOpenMPThreadPrivate:
4902 D->addAttr(A: OMPThreadPrivateDeclAttr::CreateImplicit(Ctx&: Reader.getContext(),
4903 Range: readSourceRange()));
4904 break;
4905
4906 case DeclUpdateKind::DeclMarkedOpenMPAllocate: {
4907 auto AllocatorKind =
4908 static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(Record.readInt());
4909 Expr *Allocator = Record.readExpr();
4910 Expr *Alignment = Record.readExpr();
4911 SourceRange SR = readSourceRange();
4912 D->addAttr(A: OMPAllocateDeclAttr::CreateImplicit(
4913 Ctx&: Reader.getContext(), AllocatorType: AllocatorKind, Allocator, Alignment, Range: SR));
4914 break;
4915 }
4916
4917 case DeclUpdateKind::DeclExported: {
4918 unsigned SubmoduleID = readSubmoduleID();
4919 auto *Exported = cast<NamedDecl>(Val: D);
4920 Module *Owner = SubmoduleID ? Reader.getSubmodule(GlobalID: SubmoduleID) : nullptr;
4921 Reader.getContext().mergeDefinitionIntoModule(ND: Exported, M: Owner);
4922 Reader.PendingMergedDefinitionsToDeduplicate.insert(X: Exported);
4923 break;
4924 }
4925
4926 case DeclUpdateKind::DeclMarkedOpenMPDeclareTarget: {
4927 auto MapType = Record.readEnum<OMPDeclareTargetDeclAttr::MapTypeTy>();
4928 auto DevType = Record.readEnum<OMPDeclareTargetDeclAttr::DevTypeTy>();
4929 Expr *IndirectE = Record.readExpr();
4930 bool Indirect = Record.readBool();
4931 unsigned Level = Record.readInt();
4932 D->addAttr(A: OMPDeclareTargetDeclAttr::CreateImplicit(
4933 Ctx&: Reader.getContext(), MapType, DevType, IndirectExpr: IndirectE, Indirect, Level,
4934 Range: readSourceRange()));
4935 break;
4936 }
4937
4938 case DeclUpdateKind::AddedAttrToRecord:
4939 AttrVec Attrs;
4940 Record.readAttributes(Attrs);
4941 assert(Attrs.size() == 1);
4942 D->addAttr(A: Attrs[0]);
4943 break;
4944 }
4945 }
4946}
4947