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