[docs] Add LICENSE.txt to the root of the mono-repo
[llvm-project.git] / clang / lib / Serialization / ASTReaderDecl.cpp
blob674b524a00e38aa281427702c572f1f874b1c569
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/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/AttrIterator.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclFriend.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclOpenMP.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/DeclVisitor.h"
27 #include "clang/AST/DeclarationName.h"
28 #include "clang/AST/Expr.h"
29 #include "clang/AST/ExternalASTSource.h"
30 #include "clang/AST/LambdaCapture.h"
31 #include "clang/AST/NestedNameSpecifier.h"
32 #include "clang/AST/OpenMPClause.h"
33 #include "clang/AST/Redeclarable.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/UnresolvedSet.h"
38 #include "clang/Basic/AttrKinds.h"
39 #include "clang/Basic/DiagnosticSema.h"
40 #include "clang/Basic/ExceptionSpecificationType.h"
41 #include "clang/Basic/IdentifierTable.h"
42 #include "clang/Basic/LLVM.h"
43 #include "clang/Basic/Lambda.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/Linkage.h"
46 #include "clang/Basic/Module.h"
47 #include "clang/Basic/PragmaKinds.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/Specifiers.h"
50 #include "clang/Sema/IdentifierResolver.h"
51 #include "clang/Serialization/ASTBitCodes.h"
52 #include "clang/Serialization/ASTRecordReader.h"
53 #include "clang/Serialization/ContinuousRangeMap.h"
54 #include "clang/Serialization/ModuleFile.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/FoldingSet.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include "llvm/ADT/SmallPtrSet.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/iterator_range.h"
61 #include "llvm/Bitstream/BitstreamReader.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/SaveAndRestore.h"
65 #include <algorithm>
66 #include <cassert>
67 #include <cstdint>
68 #include <cstring>
69 #include <string>
70 #include <utility>
72 using namespace clang;
73 using namespace serialization;
75 //===----------------------------------------------------------------------===//
76 // Declaration deserialization
77 //===----------------------------------------------------------------------===//
79 namespace clang {
81 class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
82 ASTReader &Reader;
83 ASTRecordReader &Record;
84 ASTReader::RecordLocation Loc;
85 const DeclID ThisDeclID;
86 const SourceLocation ThisDeclLoc;
88 using RecordData = ASTReader::RecordData;
90 TypeID DeferredTypeID = 0;
91 unsigned AnonymousDeclNumber;
92 GlobalDeclID NamedDeclForTagDecl = 0;
93 IdentifierInfo *TypedefNameForLinkage = nullptr;
95 bool HasPendingBody = false;
97 ///A flag to carry the information for a decl from the entity is
98 /// used. We use it to delay the marking of the canonical decl as used until
99 /// the entire declaration is deserialized and merged.
100 bool IsDeclMarkedUsed = false;
102 uint64_t GetCurrentCursorOffset();
104 uint64_t ReadLocalOffset() {
105 uint64_t LocalOffset = Record.readInt();
106 assert(LocalOffset < Loc.Offset && "offset point after current record");
107 return LocalOffset ? Loc.Offset - LocalOffset : 0;
110 uint64_t ReadGlobalOffset() {
111 uint64_t Local = ReadLocalOffset();
112 return Local ? Record.getGlobalBitOffset(Local) : 0;
115 SourceLocation readSourceLocation() {
116 return Record.readSourceLocation();
119 SourceRange readSourceRange() {
120 return Record.readSourceRange();
123 TypeSourceInfo *readTypeSourceInfo() {
124 return Record.readTypeSourceInfo();
127 serialization::DeclID readDeclID() {
128 return Record.readDeclID();
131 std::string readString() {
132 return Record.readString();
135 void readDeclIDList(SmallVectorImpl<DeclID> &IDs) {
136 for (unsigned I = 0, Size = Record.readInt(); I != Size; ++I)
137 IDs.push_back(readDeclID());
140 Decl *readDecl() {
141 return Record.readDecl();
144 template<typename T>
145 T *readDeclAs() {
146 return Record.readDeclAs<T>();
149 serialization::SubmoduleID readSubmoduleID() {
150 if (Record.getIdx() == Record.size())
151 return 0;
153 return Record.getGlobalSubmoduleID(Record.readInt());
156 Module *readModule() {
157 return Record.getSubmodule(readSubmoduleID());
160 void ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update);
161 void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
162 const CXXRecordDecl *D);
163 void MergeDefinitionData(CXXRecordDecl *D,
164 struct CXXRecordDecl::DefinitionData &&NewDD);
165 void ReadObjCDefinitionData(struct ObjCInterfaceDecl::DefinitionData &Data);
166 void MergeDefinitionData(ObjCInterfaceDecl *D,
167 struct ObjCInterfaceDecl::DefinitionData &&NewDD);
168 void ReadObjCDefinitionData(struct ObjCProtocolDecl::DefinitionData &Data);
169 void MergeDefinitionData(ObjCProtocolDecl *D,
170 struct ObjCProtocolDecl::DefinitionData &&NewDD);
172 static DeclContext *getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC);
174 static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader,
175 DeclContext *DC,
176 unsigned Index);
177 static void setAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC,
178 unsigned Index, NamedDecl *D);
180 /// Results from loading a RedeclarableDecl.
181 class RedeclarableResult {
182 Decl *MergeWith;
183 GlobalDeclID FirstID;
184 bool IsKeyDecl;
186 public:
187 RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
188 : MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}
190 /// Retrieve the first ID.
191 GlobalDeclID getFirstID() const { return FirstID; }
193 /// Is this declaration a key declaration?
194 bool isKeyDecl() const { return IsKeyDecl; }
196 /// Get a known declaration that this should be merged with, if
197 /// any.
198 Decl *getKnownMergeTarget() const { return MergeWith; }
201 /// Class used to capture the result of searching for an existing
202 /// declaration of a specific kind and name, along with the ability
203 /// to update the place where this result was found (the declaration
204 /// chain hanging off an identifier or the DeclContext we searched in)
205 /// if requested.
206 class FindExistingResult {
207 ASTReader &Reader;
208 NamedDecl *New = nullptr;
209 NamedDecl *Existing = nullptr;
210 bool AddResult = false;
211 unsigned AnonymousDeclNumber = 0;
212 IdentifierInfo *TypedefNameForLinkage = nullptr;
214 public:
215 FindExistingResult(ASTReader &Reader) : Reader(Reader) {}
217 FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing,
218 unsigned AnonymousDeclNumber,
219 IdentifierInfo *TypedefNameForLinkage)
220 : Reader(Reader), New(New), Existing(Existing), AddResult(true),
221 AnonymousDeclNumber(AnonymousDeclNumber),
222 TypedefNameForLinkage(TypedefNameForLinkage) {}
224 FindExistingResult(FindExistingResult &&Other)
225 : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
226 AddResult(Other.AddResult),
227 AnonymousDeclNumber(Other.AnonymousDeclNumber),
228 TypedefNameForLinkage(Other.TypedefNameForLinkage) {
229 Other.AddResult = false;
232 FindExistingResult &operator=(FindExistingResult &&) = delete;
233 ~FindExistingResult();
235 /// Suppress the addition of this result into the known set of
236 /// names.
237 void suppress() { AddResult = false; }
239 operator NamedDecl*() const { return Existing; }
241 template<typename T>
242 operator T*() const { return dyn_cast_or_null<T>(Existing); }
245 static DeclContext *getPrimaryContextForMerging(ASTReader &Reader,
246 DeclContext *DC);
247 FindExistingResult findExisting(NamedDecl *D);
249 public:
250 ASTDeclReader(ASTReader &Reader, ASTRecordReader &Record,
251 ASTReader::RecordLocation Loc,
252 DeclID thisDeclID, SourceLocation ThisDeclLoc)
253 : Reader(Reader), Record(Record), Loc(Loc), ThisDeclID(thisDeclID),
254 ThisDeclLoc(ThisDeclLoc) {}
256 template <typename T> static
257 void AddLazySpecializations(T *D,
258 SmallVectorImpl<serialization::DeclID>& IDs) {
259 if (IDs.empty())
260 return;
262 // FIXME: We should avoid this pattern of getting the ASTContext.
263 ASTContext &C = D->getASTContext();
265 auto *&LazySpecializations = D->getCommonPtr()->LazySpecializations;
267 if (auto &Old = LazySpecializations) {
268 IDs.insert(IDs.end(), Old + 1, Old + 1 + Old[0]);
269 llvm::sort(IDs);
270 IDs.erase(std::unique(IDs.begin(), IDs.end()), IDs.end());
273 auto *Result = new (C) serialization::DeclID[1 + IDs.size()];
274 *Result = IDs.size();
275 std::copy(IDs.begin(), IDs.end(), Result + 1);
277 LazySpecializations = Result;
280 template <typename DeclT>
281 static Decl *getMostRecentDeclImpl(Redeclarable<DeclT> *D);
282 static Decl *getMostRecentDeclImpl(...);
283 static Decl *getMostRecentDecl(Decl *D);
285 static void mergeInheritableAttributes(ASTReader &Reader, Decl *D,
286 Decl *Previous);
288 template <typename DeclT>
289 static void attachPreviousDeclImpl(ASTReader &Reader,
290 Redeclarable<DeclT> *D, Decl *Previous,
291 Decl *Canon);
292 static void attachPreviousDeclImpl(ASTReader &Reader, ...);
293 static void attachPreviousDecl(ASTReader &Reader, Decl *D, Decl *Previous,
294 Decl *Canon);
296 template <typename DeclT>
297 static void attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest);
298 static void attachLatestDeclImpl(...);
299 static void attachLatestDecl(Decl *D, Decl *latest);
301 template <typename DeclT>
302 static void markIncompleteDeclChainImpl(Redeclarable<DeclT> *D);
303 static void markIncompleteDeclChainImpl(...);
305 /// Determine whether this declaration has a pending body.
306 bool hasPendingBody() const { return HasPendingBody; }
308 void ReadFunctionDefinition(FunctionDecl *FD);
309 void Visit(Decl *D);
311 void UpdateDecl(Decl *D, SmallVectorImpl<serialization::DeclID> &);
313 static void setNextObjCCategory(ObjCCategoryDecl *Cat,
314 ObjCCategoryDecl *Next) {
315 Cat->NextClassCategory = Next;
318 void VisitDecl(Decl *D);
319 void VisitPragmaCommentDecl(PragmaCommentDecl *D);
320 void VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D);
321 void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
322 void VisitNamedDecl(NamedDecl *ND);
323 void VisitLabelDecl(LabelDecl *LD);
324 void VisitNamespaceDecl(NamespaceDecl *D);
325 void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
326 void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
327 void VisitTypeDecl(TypeDecl *TD);
328 RedeclarableResult VisitTypedefNameDecl(TypedefNameDecl *TD);
329 void VisitTypedefDecl(TypedefDecl *TD);
330 void VisitTypeAliasDecl(TypeAliasDecl *TD);
331 void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
332 void VisitUnresolvedUsingIfExistsDecl(UnresolvedUsingIfExistsDecl *D);
333 RedeclarableResult VisitTagDecl(TagDecl *TD);
334 void VisitEnumDecl(EnumDecl *ED);
335 RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD);
336 void VisitRecordDecl(RecordDecl *RD);
337 RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D);
338 void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); }
339 RedeclarableResult VisitClassTemplateSpecializationDeclImpl(
340 ClassTemplateSpecializationDecl *D);
342 void VisitClassTemplateSpecializationDecl(
343 ClassTemplateSpecializationDecl *D) {
344 VisitClassTemplateSpecializationDeclImpl(D);
347 void VisitClassTemplatePartialSpecializationDecl(
348 ClassTemplatePartialSpecializationDecl *D);
349 void VisitClassScopeFunctionSpecializationDecl(
350 ClassScopeFunctionSpecializationDecl *D);
351 RedeclarableResult
352 VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D);
354 void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
355 VisitVarTemplateSpecializationDeclImpl(D);
358 void VisitVarTemplatePartialSpecializationDecl(
359 VarTemplatePartialSpecializationDecl *D);
360 void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
361 void VisitValueDecl(ValueDecl *VD);
362 void VisitEnumConstantDecl(EnumConstantDecl *ECD);
363 void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
364 void VisitDeclaratorDecl(DeclaratorDecl *DD);
365 void VisitFunctionDecl(FunctionDecl *FD);
366 void VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *GD);
367 void VisitCXXMethodDecl(CXXMethodDecl *D);
368 void VisitCXXConstructorDecl(CXXConstructorDecl *D);
369 void VisitCXXDestructorDecl(CXXDestructorDecl *D);
370 void VisitCXXConversionDecl(CXXConversionDecl *D);
371 void VisitFieldDecl(FieldDecl *FD);
372 void VisitMSPropertyDecl(MSPropertyDecl *FD);
373 void VisitMSGuidDecl(MSGuidDecl *D);
374 void VisitUnnamedGlobalConstantDecl(UnnamedGlobalConstantDecl *D);
375 void VisitTemplateParamObjectDecl(TemplateParamObjectDecl *D);
376 void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
377 RedeclarableResult VisitVarDeclImpl(VarDecl *D);
378 void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); }
379 void VisitImplicitParamDecl(ImplicitParamDecl *PD);
380 void VisitParmVarDecl(ParmVarDecl *PD);
381 void VisitDecompositionDecl(DecompositionDecl *DD);
382 void VisitBindingDecl(BindingDecl *BD);
383 void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
384 DeclID VisitTemplateDecl(TemplateDecl *D);
385 void VisitConceptDecl(ConceptDecl *D);
386 void VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D);
387 RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
388 void VisitClassTemplateDecl(ClassTemplateDecl *D);
389 void VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
390 void VisitVarTemplateDecl(VarTemplateDecl *D);
391 void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
392 void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
393 void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
394 void VisitUsingDecl(UsingDecl *D);
395 void VisitUsingEnumDecl(UsingEnumDecl *D);
396 void VisitUsingPackDecl(UsingPackDecl *D);
397 void VisitUsingShadowDecl(UsingShadowDecl *D);
398 void VisitConstructorUsingShadowDecl(ConstructorUsingShadowDecl *D);
399 void VisitLinkageSpecDecl(LinkageSpecDecl *D);
400 void VisitExportDecl(ExportDecl *D);
401 void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
402 void VisitImportDecl(ImportDecl *D);
403 void VisitAccessSpecDecl(AccessSpecDecl *D);
404 void VisitFriendDecl(FriendDecl *D);
405 void VisitFriendTemplateDecl(FriendTemplateDecl *D);
406 void VisitStaticAssertDecl(StaticAssertDecl *D);
407 void VisitBlockDecl(BlockDecl *BD);
408 void VisitCapturedDecl(CapturedDecl *CD);
409 void VisitEmptyDecl(EmptyDecl *D);
410 void VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D);
412 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
414 template<typename T>
415 RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
417 template<typename T>
418 void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl,
419 DeclID TemplatePatternID = 0);
421 template<typename T>
422 void mergeRedeclarable(Redeclarable<T> *D, T *Existing,
423 RedeclarableResult &Redecl,
424 DeclID TemplatePatternID = 0);
426 template<typename T>
427 void mergeMergeable(Mergeable<T> *D);
429 void mergeMergeable(LifetimeExtendedTemporaryDecl *D);
431 void mergeTemplatePattern(RedeclarableTemplateDecl *D,
432 RedeclarableTemplateDecl *Existing,
433 DeclID DsID, bool IsKeyDecl);
435 ObjCTypeParamList *ReadObjCTypeParamList();
437 // FIXME: Reorder according to DeclNodes.td?
438 void VisitObjCMethodDecl(ObjCMethodDecl *D);
439 void VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
440 void VisitObjCContainerDecl(ObjCContainerDecl *D);
441 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
442 void VisitObjCIvarDecl(ObjCIvarDecl *D);
443 void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
444 void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
445 void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
446 void VisitObjCImplDecl(ObjCImplDecl *D);
447 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
448 void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
449 void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
450 void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
451 void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
452 void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
453 void VisitOMPAllocateDecl(OMPAllocateDecl *D);
454 void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
455 void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D);
456 void VisitOMPRequiresDecl(OMPRequiresDecl *D);
457 void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
460 } // namespace clang
462 namespace {
464 /// Iterator over the redeclarations of a declaration that have already
465 /// been merged into the same redeclaration chain.
466 template<typename DeclT>
467 class MergedRedeclIterator {
468 DeclT *Start;
469 DeclT *Canonical = nullptr;
470 DeclT *Current = nullptr;
472 public:
473 MergedRedeclIterator() = default;
474 MergedRedeclIterator(DeclT *Start) : Start(Start), Current(Start) {}
476 DeclT *operator*() { return Current; }
478 MergedRedeclIterator &operator++() {
479 if (Current->isFirstDecl()) {
480 Canonical = Current;
481 Current = Current->getMostRecentDecl();
482 } else
483 Current = Current->getPreviousDecl();
485 // If we started in the merged portion, we'll reach our start position
486 // eventually. Otherwise, we'll never reach it, but the second declaration
487 // we reached was the canonical declaration, so stop when we see that one
488 // again.
489 if (Current == Start || Current == Canonical)
490 Current = nullptr;
491 return *this;
494 friend bool operator!=(const MergedRedeclIterator &A,
495 const MergedRedeclIterator &B) {
496 return A.Current != B.Current;
500 } // namespace
502 template <typename DeclT>
503 static llvm::iterator_range<MergedRedeclIterator<DeclT>>
504 merged_redecls(DeclT *D) {
505 return llvm::make_range(MergedRedeclIterator<DeclT>(D),
506 MergedRedeclIterator<DeclT>());
509 uint64_t ASTDeclReader::GetCurrentCursorOffset() {
510 return Loc.F->DeclsCursor.GetCurrentBitNo() + Loc.F->GlobalBitOffset;
513 void ASTDeclReader::ReadFunctionDefinition(FunctionDecl *FD) {
514 if (Record.readInt()) {
515 Reader.DefinitionSource[FD] =
516 Loc.F->Kind == ModuleKind::MK_MainFile ||
517 Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;
519 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
520 CD->setNumCtorInitializers(Record.readInt());
521 if (CD->getNumCtorInitializers())
522 CD->CtorInitializers = ReadGlobalOffset();
524 // Store the offset of the body so we can lazily load it later.
525 Reader.PendingBodies[FD] = GetCurrentCursorOffset();
526 HasPendingBody = true;
529 void ASTDeclReader::Visit(Decl *D) {
530 DeclVisitor<ASTDeclReader, void>::Visit(D);
532 // At this point we have deserialized and merged the decl and it is safe to
533 // update its canonical decl to signal that the entire entity is used.
534 D->getCanonicalDecl()->Used |= IsDeclMarkedUsed;
535 IsDeclMarkedUsed = false;
537 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
538 if (auto *TInfo = DD->getTypeSourceInfo())
539 Record.readTypeLoc(TInfo->getTypeLoc());
542 if (auto *TD = dyn_cast<TypeDecl>(D)) {
543 // We have a fully initialized TypeDecl. Read its type now.
544 TD->setTypeForDecl(Reader.GetType(DeferredTypeID).getTypePtrOrNull());
546 // If this is a tag declaration with a typedef name for linkage, it's safe
547 // to load that typedef now.
548 if (NamedDeclForTagDecl)
549 cast<TagDecl>(D)->TypedefNameDeclOrQualifier =
550 cast<TypedefNameDecl>(Reader.GetDecl(NamedDeclForTagDecl));
551 } else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
552 // if we have a fully initialized TypeDecl, we can safely read its type now.
553 ID->TypeForDecl = Reader.GetType(DeferredTypeID).getTypePtrOrNull();
554 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
555 // FunctionDecl's body was written last after all other Stmts/Exprs.
556 // We only read it if FD doesn't already have a body (e.g., from another
557 // module).
558 // FIXME: Can we diagnose ODR violations somehow?
559 if (Record.readInt())
560 ReadFunctionDefinition(FD);
564 void ASTDeclReader::VisitDecl(Decl *D) {
565 if (D->isTemplateParameter() || D->isTemplateParameterPack() ||
566 isa<ParmVarDecl>(D) || isa<ObjCTypeParamDecl>(D)) {
567 // We don't want to deserialize the DeclContext of a template
568 // parameter or of a parameter of a function template immediately. These
569 // entities might be used in the formulation of its DeclContext (for
570 // example, a function parameter can be used in decltype() in trailing
571 // return type of the function). Use the translation unit DeclContext as a
572 // placeholder.
573 GlobalDeclID SemaDCIDForTemplateParmDecl = readDeclID();
574 GlobalDeclID LexicalDCIDForTemplateParmDecl = readDeclID();
575 if (!LexicalDCIDForTemplateParmDecl)
576 LexicalDCIDForTemplateParmDecl = SemaDCIDForTemplateParmDecl;
577 Reader.addPendingDeclContextInfo(D,
578 SemaDCIDForTemplateParmDecl,
579 LexicalDCIDForTemplateParmDecl);
580 D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
581 } else {
582 auto *SemaDC = readDeclAs<DeclContext>();
583 auto *LexicalDC = readDeclAs<DeclContext>();
584 if (!LexicalDC)
585 LexicalDC = SemaDC;
586 DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
587 // Avoid calling setLexicalDeclContext() directly because it uses
588 // Decl::getASTContext() internally which is unsafe during derialization.
589 D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
590 Reader.getContext());
592 D->setLocation(ThisDeclLoc);
593 D->InvalidDecl = Record.readInt();
594 if (Record.readInt()) { // hasAttrs
595 AttrVec Attrs;
596 Record.readAttributes(Attrs);
597 // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
598 // internally which is unsafe during derialization.
599 D->setAttrsImpl(Attrs, Reader.getContext());
601 D->setImplicit(Record.readInt());
602 D->Used = Record.readInt();
603 IsDeclMarkedUsed |= D->Used;
604 D->setReferenced(Record.readInt());
605 D->setTopLevelDeclInObjCContainer(Record.readInt());
606 D->setAccess((AccessSpecifier)Record.readInt());
607 D->FromASTFile = true;
608 auto ModuleOwnership = (Decl::ModuleOwnershipKind)Record.readInt();
609 bool ModulePrivate =
610 (ModuleOwnership == Decl::ModuleOwnershipKind::ModulePrivate);
612 // Determine whether this declaration is part of a (sub)module. If so, it
613 // may not yet be visible.
614 if (unsigned SubmoduleID = readSubmoduleID()) {
616 switch (ModuleOwnership) {
617 case Decl::ModuleOwnershipKind::Visible:
618 ModuleOwnership = Decl::ModuleOwnershipKind::VisibleWhenImported;
619 break;
620 case Decl::ModuleOwnershipKind::Unowned:
621 case Decl::ModuleOwnershipKind::VisibleWhenImported:
622 case Decl::ModuleOwnershipKind::ReachableWhenImported:
623 case Decl::ModuleOwnershipKind::ModulePrivate:
624 break;
627 D->setModuleOwnershipKind(ModuleOwnership);
628 // Store the owning submodule ID in the declaration.
629 D->setOwningModuleID(SubmoduleID);
631 if (ModulePrivate) {
632 // Module-private declarations are never visible, so there is no work to
633 // do.
634 } else if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
635 // If local visibility is being tracked, this declaration will become
636 // hidden and visible as the owning module does.
637 } else if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
638 // Mark the declaration as visible when its owning module becomes visible.
639 if (Owner->NameVisibility == Module::AllVisible)
640 D->setVisibleDespiteOwningModule();
641 else
642 Reader.HiddenNamesMap[Owner].push_back(D);
644 } else if (ModulePrivate) {
645 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
649 void ASTDeclReader::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
650 VisitDecl(D);
651 D->setLocation(readSourceLocation());
652 D->CommentKind = (PragmaMSCommentKind)Record.readInt();
653 std::string Arg = readString();
654 memcpy(D->getTrailingObjects<char>(), Arg.data(), Arg.size());
655 D->getTrailingObjects<char>()[Arg.size()] = '\0';
658 void ASTDeclReader::VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D) {
659 VisitDecl(D);
660 D->setLocation(readSourceLocation());
661 std::string Name = readString();
662 memcpy(D->getTrailingObjects<char>(), Name.data(), Name.size());
663 D->getTrailingObjects<char>()[Name.size()] = '\0';
665 D->ValueStart = Name.size() + 1;
666 std::string Value = readString();
667 memcpy(D->getTrailingObjects<char>() + D->ValueStart, Value.data(),
668 Value.size());
669 D->getTrailingObjects<char>()[D->ValueStart + Value.size()] = '\0';
672 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
673 llvm_unreachable("Translation units are not serialized");
676 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
677 VisitDecl(ND);
678 ND->setDeclName(Record.readDeclarationName());
679 AnonymousDeclNumber = Record.readInt();
682 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
683 VisitNamedDecl(TD);
684 TD->setLocStart(readSourceLocation());
685 // Delay type reading until after we have fully initialized the decl.
686 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
689 ASTDeclReader::RedeclarableResult
690 ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
691 RedeclarableResult Redecl = VisitRedeclarable(TD);
692 VisitTypeDecl(TD);
693 TypeSourceInfo *TInfo = readTypeSourceInfo();
694 if (Record.readInt()) { // isModed
695 QualType modedT = Record.readType();
696 TD->setModedTypeSourceInfo(TInfo, modedT);
697 } else
698 TD->setTypeSourceInfo(TInfo);
699 // Read and discard the declaration for which this is a typedef name for
700 // linkage, if it exists. We cannot rely on our type to pull in this decl,
701 // because it might have been merged with a type from another module and
702 // thus might not refer to our version of the declaration.
703 readDecl();
704 return Redecl;
707 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
708 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
709 mergeRedeclarable(TD, Redecl);
712 void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
713 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
714 if (auto *Template = readDeclAs<TypeAliasTemplateDecl>())
715 // Merged when we merge the template.
716 TD->setDescribedAliasTemplate(Template);
717 else
718 mergeRedeclarable(TD, Redecl);
721 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {
722 RedeclarableResult Redecl = VisitRedeclarable(TD);
723 VisitTypeDecl(TD);
725 TD->IdentifierNamespace = Record.readInt();
726 TD->setTagKind((TagDecl::TagKind)Record.readInt());
727 if (!isa<CXXRecordDecl>(TD))
728 TD->setCompleteDefinition(Record.readInt());
729 TD->setEmbeddedInDeclarator(Record.readInt());
730 TD->setFreeStanding(Record.readInt());
731 TD->setCompleteDefinitionRequired(Record.readInt());
732 TD->setBraceRange(readSourceRange());
734 switch (Record.readInt()) {
735 case 0:
736 break;
737 case 1: { // ExtInfo
738 auto *Info = new (Reader.getContext()) TagDecl::ExtInfo();
739 Record.readQualifierInfo(*Info);
740 TD->TypedefNameDeclOrQualifier = Info;
741 break;
743 case 2: // TypedefNameForAnonDecl
744 NamedDeclForTagDecl = readDeclID();
745 TypedefNameForLinkage = Record.readIdentifier();
746 break;
747 default:
748 llvm_unreachable("unexpected tag info kind");
751 if (!isa<CXXRecordDecl>(TD))
752 mergeRedeclarable(TD, Redecl);
753 return Redecl;
756 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
757 VisitTagDecl(ED);
758 if (TypeSourceInfo *TI = readTypeSourceInfo())
759 ED->setIntegerTypeSourceInfo(TI);
760 else
761 ED->setIntegerType(Record.readType());
762 ED->setPromotionType(Record.readType());
763 ED->setNumPositiveBits(Record.readInt());
764 ED->setNumNegativeBits(Record.readInt());
765 ED->setScoped(Record.readInt());
766 ED->setScopedUsingClassTag(Record.readInt());
767 ED->setFixed(Record.readInt());
769 ED->setHasODRHash(true);
770 ED->ODRHash = Record.readInt();
772 // If this is a definition subject to the ODR, and we already have a
773 // definition, merge this one into it.
774 if (ED->isCompleteDefinition() &&
775 Reader.getContext().getLangOpts().Modules &&
776 Reader.getContext().getLangOpts().CPlusPlus) {
777 EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()];
778 if (!OldDef) {
779 // This is the first time we've seen an imported definition. Look for a
780 // local definition before deciding that we are the first definition.
781 for (auto *D : merged_redecls(ED->getCanonicalDecl())) {
782 if (!D->isFromASTFile() && D->isCompleteDefinition()) {
783 OldDef = D;
784 break;
788 if (OldDef) {
789 Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));
790 ED->demoteThisDefinitionToDeclaration();
791 Reader.mergeDefinitionVisibility(OldDef, ED);
792 if (OldDef->getODRHash() != ED->getODRHash())
793 Reader.PendingEnumOdrMergeFailures[OldDef].push_back(ED);
794 } else {
795 OldDef = ED;
799 if (auto *InstED = readDeclAs<EnumDecl>()) {
800 auto TSK = (TemplateSpecializationKind)Record.readInt();
801 SourceLocation POI = readSourceLocation();
802 ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
803 ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
807 ASTDeclReader::RedeclarableResult
808 ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
809 RedeclarableResult Redecl = VisitTagDecl(RD);
810 RD->setHasFlexibleArrayMember(Record.readInt());
811 RD->setAnonymousStructOrUnion(Record.readInt());
812 RD->setHasObjectMember(Record.readInt());
813 RD->setHasVolatileMember(Record.readInt());
814 RD->setNonTrivialToPrimitiveDefaultInitialize(Record.readInt());
815 RD->setNonTrivialToPrimitiveCopy(Record.readInt());
816 RD->setNonTrivialToPrimitiveDestroy(Record.readInt());
817 RD->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(Record.readInt());
818 RD->setHasNonTrivialToPrimitiveDestructCUnion(Record.readInt());
819 RD->setHasNonTrivialToPrimitiveCopyCUnion(Record.readInt());
820 RD->setParamDestroyedInCallee(Record.readInt());
821 RD->setArgPassingRestrictions((RecordDecl::ArgPassingKind)Record.readInt());
822 return Redecl;
825 void ASTDeclReader::VisitRecordDecl(RecordDecl *RD) {
826 VisitRecordDeclImpl(RD);
828 // Maintain the invariant of a redeclaration chain containing only
829 // a single definition.
830 if (RD->isCompleteDefinition()) {
831 RecordDecl *Canon = static_cast<RecordDecl *>(RD->getCanonicalDecl());
832 RecordDecl *&OldDef = Reader.RecordDefinitions[Canon];
833 if (!OldDef) {
834 // This is the first time we've seen an imported definition. Look for a
835 // local definition before deciding that we are the first definition.
836 for (auto *D : merged_redecls(Canon)) {
837 if (!D->isFromASTFile() && D->isCompleteDefinition()) {
838 OldDef = D;
839 break;
843 if (OldDef) {
844 Reader.MergedDeclContexts.insert(std::make_pair(RD, OldDef));
845 RD->demoteThisDefinitionToDeclaration();
846 Reader.mergeDefinitionVisibility(OldDef, RD);
847 } else {
848 OldDef = RD;
853 void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
854 VisitNamedDecl(VD);
855 // For function declarations, defer reading the type in case the function has
856 // a deduced return type that references an entity declared within the
857 // function.
858 if (isa<FunctionDecl>(VD))
859 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
860 else
861 VD->setType(Record.readType());
864 void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
865 VisitValueDecl(ECD);
866 if (Record.readInt())
867 ECD->setInitExpr(Record.readExpr());
868 ECD->setInitVal(Record.readAPSInt());
869 mergeMergeable(ECD);
872 void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
873 VisitValueDecl(DD);
874 DD->setInnerLocStart(readSourceLocation());
875 if (Record.readInt()) { // hasExtInfo
876 auto *Info = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
877 Record.readQualifierInfo(*Info);
878 Info->TrailingRequiresClause = Record.readExpr();
879 DD->DeclInfo = Info;
881 QualType TSIType = Record.readType();
882 DD->setTypeSourceInfo(
883 TSIType.isNull() ? nullptr
884 : Reader.getContext().CreateTypeSourceInfo(TSIType));
887 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
888 RedeclarableResult Redecl = VisitRedeclarable(FD);
889 VisitDeclaratorDecl(FD);
891 // Attach a type to this function. Use the real type if possible, but fall
892 // back to the type as written if it involves a deduced return type.
893 if (FD->getTypeSourceInfo() &&
894 FD->getTypeSourceInfo()->getType()->castAs<FunctionType>()
895 ->getReturnType()->getContainedAutoType()) {
896 // We'll set up the real type in Visit, once we've finished loading the
897 // function.
898 FD->setType(FD->getTypeSourceInfo()->getType());
899 Reader.PendingFunctionTypes.push_back({FD, DeferredTypeID});
900 } else {
901 FD->setType(Reader.GetType(DeferredTypeID));
903 DeferredTypeID = 0;
905 FD->DNLoc = Record.readDeclarationNameLoc(FD->getDeclName());
906 FD->IdentifierNamespace = Record.readInt();
908 // FunctionDecl's body is handled last at ASTDeclReader::Visit,
909 // after everything else is read.
911 FD->setStorageClass(static_cast<StorageClass>(Record.readInt()));
912 FD->setInlineSpecified(Record.readInt());
913 FD->setImplicitlyInline(Record.readInt());
914 FD->setVirtualAsWritten(Record.readInt());
915 // We defer calling `FunctionDecl::setPure()` here as for methods of
916 // `CXXTemplateSpecializationDecl`s, we may not have connected up the
917 // definition (which is required for `setPure`).
918 const bool Pure = Record.readInt();
919 FD->setHasInheritedPrototype(Record.readInt());
920 FD->setHasWrittenPrototype(Record.readInt());
921 FD->setDeletedAsWritten(Record.readInt());
922 FD->setTrivial(Record.readInt());
923 FD->setTrivialForCall(Record.readInt());
924 FD->setDefaulted(Record.readInt());
925 FD->setExplicitlyDefaulted(Record.readInt());
926 FD->setHasImplicitReturnZero(Record.readInt());
927 FD->setConstexprKind(static_cast<ConstexprSpecKind>(Record.readInt()));
928 FD->setUsesSEHTry(Record.readInt());
929 FD->setHasSkippedBody(Record.readInt());
930 FD->setIsMultiVersion(Record.readInt());
931 FD->setLateTemplateParsed(Record.readInt());
933 FD->setCachedLinkage(static_cast<Linkage>(Record.readInt()));
934 FD->EndRangeLoc = readSourceLocation();
936 FD->ODRHash = Record.readInt();
937 FD->setHasODRHash(true);
939 if (FD->isDefaulted()) {
940 if (unsigned NumLookups = Record.readInt()) {
941 SmallVector<DeclAccessPair, 8> Lookups;
942 for (unsigned I = 0; I != NumLookups; ++I) {
943 NamedDecl *ND = Record.readDeclAs<NamedDecl>();
944 AccessSpecifier AS = (AccessSpecifier)Record.readInt();
945 Lookups.push_back(DeclAccessPair::make(ND, AS));
947 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
948 Reader.getContext(), Lookups));
952 switch ((FunctionDecl::TemplatedKind)Record.readInt()) {
953 case FunctionDecl::TK_NonTemplate:
954 mergeRedeclarable(FD, Redecl);
955 break;
956 case FunctionDecl::TK_DependentNonTemplate:
957 mergeRedeclarable(FD, Redecl);
958 FD->setInstantiatedFromDecl(readDeclAs<FunctionDecl>());
959 break;
960 case FunctionDecl::TK_FunctionTemplate:
961 // Merged when we merge the template.
962 FD->setDescribedFunctionTemplate(readDeclAs<FunctionTemplateDecl>());
963 break;
964 case FunctionDecl::TK_MemberSpecialization: {
965 auto *InstFD = readDeclAs<FunctionDecl>();
966 auto TSK = (TemplateSpecializationKind)Record.readInt();
967 SourceLocation POI = readSourceLocation();
968 FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
969 FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
970 mergeRedeclarable(FD, Redecl);
971 break;
973 case FunctionDecl::TK_FunctionTemplateSpecialization: {
974 auto *Template = readDeclAs<FunctionTemplateDecl>();
975 auto TSK = (TemplateSpecializationKind)Record.readInt();
977 // Template arguments.
978 SmallVector<TemplateArgument, 8> TemplArgs;
979 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
981 // Template args as written.
982 SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
983 SourceLocation LAngleLoc, RAngleLoc;
984 bool HasTemplateArgumentsAsWritten = Record.readInt();
985 if (HasTemplateArgumentsAsWritten) {
986 unsigned NumTemplateArgLocs = Record.readInt();
987 TemplArgLocs.reserve(NumTemplateArgLocs);
988 for (unsigned i = 0; i != NumTemplateArgLocs; ++i)
989 TemplArgLocs.push_back(Record.readTemplateArgumentLoc());
991 LAngleLoc = readSourceLocation();
992 RAngleLoc = readSourceLocation();
995 SourceLocation POI = readSourceLocation();
997 ASTContext &C = Reader.getContext();
998 TemplateArgumentList *TemplArgList
999 = TemplateArgumentList::CreateCopy(C, TemplArgs);
1000 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
1001 for (unsigned i = 0, e = TemplArgLocs.size(); i != e; ++i)
1002 TemplArgsInfo.addArgument(TemplArgLocs[i]);
1004 MemberSpecializationInfo *MSInfo = nullptr;
1005 if (Record.readInt()) {
1006 auto *FD = readDeclAs<FunctionDecl>();
1007 auto TSK = (TemplateSpecializationKind)Record.readInt();
1008 SourceLocation POI = readSourceLocation();
1010 MSInfo = new (C) MemberSpecializationInfo(FD, TSK);
1011 MSInfo->setPointOfInstantiation(POI);
1014 FunctionTemplateSpecializationInfo *FTInfo =
1015 FunctionTemplateSpecializationInfo::Create(
1016 C, FD, Template, TSK, TemplArgList,
1017 HasTemplateArgumentsAsWritten ? &TemplArgsInfo : nullptr, POI,
1018 MSInfo);
1019 FD->TemplateOrSpecialization = FTInfo;
1021 if (FD->isCanonicalDecl()) { // if canonical add to template's set.
1022 // The template that contains the specializations set. It's not safe to
1023 // use getCanonicalDecl on Template since it may still be initializing.
1024 auto *CanonTemplate = readDeclAs<FunctionTemplateDecl>();
1025 // Get the InsertPos by FindNodeOrInsertPos() instead of calling
1026 // InsertNode(FTInfo) directly to avoid the getASTContext() call in
1027 // FunctionTemplateSpecializationInfo's Profile().
1028 // We avoid getASTContext because a decl in the parent hierarchy may
1029 // be initializing.
1030 llvm::FoldingSetNodeID ID;
1031 FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs, C);
1032 void *InsertPos = nullptr;
1033 FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();
1034 FunctionTemplateSpecializationInfo *ExistingInfo =
1035 CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);
1036 if (InsertPos)
1037 CommonPtr->Specializations.InsertNode(FTInfo, InsertPos);
1038 else {
1039 assert(Reader.getContext().getLangOpts().Modules &&
1040 "already deserialized this template specialization");
1041 mergeRedeclarable(FD, ExistingInfo->getFunction(), Redecl);
1044 break;
1046 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
1047 // Templates.
1048 UnresolvedSet<8> TemplDecls;
1049 unsigned NumTemplates = Record.readInt();
1050 while (NumTemplates--)
1051 TemplDecls.addDecl(readDeclAs<NamedDecl>());
1053 // Templates args.
1054 TemplateArgumentListInfo TemplArgs;
1055 unsigned NumArgs = Record.readInt();
1056 while (NumArgs--)
1057 TemplArgs.addArgument(Record.readTemplateArgumentLoc());
1058 TemplArgs.setLAngleLoc(readSourceLocation());
1059 TemplArgs.setRAngleLoc(readSourceLocation());
1061 FD->setDependentTemplateSpecialization(Reader.getContext(),
1062 TemplDecls, TemplArgs);
1063 // These are not merged; we don't need to merge redeclarations of dependent
1064 // template friends.
1065 break;
1069 // Defer calling `setPure` until merging above has guaranteed we've set
1070 // `DefinitionData` (as this will need to access it).
1071 FD->setPure(Pure);
1073 // Read in the parameters.
1074 unsigned NumParams = Record.readInt();
1075 SmallVector<ParmVarDecl *, 16> Params;
1076 Params.reserve(NumParams);
1077 for (unsigned I = 0; I != NumParams; ++I)
1078 Params.push_back(readDeclAs<ParmVarDecl>());
1079 FD->setParams(Reader.getContext(), Params);
1082 void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
1083 VisitNamedDecl(MD);
1084 if (Record.readInt()) {
1085 // Load the body on-demand. Most clients won't care, because method
1086 // definitions rarely show up in headers.
1087 Reader.PendingBodies[MD] = GetCurrentCursorOffset();
1088 HasPendingBody = true;
1090 MD->setSelfDecl(readDeclAs<ImplicitParamDecl>());
1091 MD->setCmdDecl(readDeclAs<ImplicitParamDecl>());
1092 MD->setInstanceMethod(Record.readInt());
1093 MD->setVariadic(Record.readInt());
1094 MD->setPropertyAccessor(Record.readInt());
1095 MD->setSynthesizedAccessorStub(Record.readInt());
1096 MD->setDefined(Record.readInt());
1097 MD->setOverriding(Record.readInt());
1098 MD->setHasSkippedBody(Record.readInt());
1100 MD->setIsRedeclaration(Record.readInt());
1101 MD->setHasRedeclaration(Record.readInt());
1102 if (MD->hasRedeclaration())
1103 Reader.getContext().setObjCMethodRedeclaration(MD,
1104 readDeclAs<ObjCMethodDecl>());
1106 MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record.readInt());
1107 MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record.readInt());
1108 MD->setRelatedResultType(Record.readInt());
1109 MD->setReturnType(Record.readType());
1110 MD->setReturnTypeSourceInfo(readTypeSourceInfo());
1111 MD->DeclEndLoc = readSourceLocation();
1112 unsigned NumParams = Record.readInt();
1113 SmallVector<ParmVarDecl *, 16> Params;
1114 Params.reserve(NumParams);
1115 for (unsigned I = 0; I != NumParams; ++I)
1116 Params.push_back(readDeclAs<ParmVarDecl>());
1118 MD->setSelLocsKind((SelectorLocationsKind)Record.readInt());
1119 unsigned NumStoredSelLocs = Record.readInt();
1120 SmallVector<SourceLocation, 16> SelLocs;
1121 SelLocs.reserve(NumStoredSelLocs);
1122 for (unsigned i = 0; i != NumStoredSelLocs; ++i)
1123 SelLocs.push_back(readSourceLocation());
1125 MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
1128 void ASTDeclReader::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
1129 VisitTypedefNameDecl(D);
1131 D->Variance = Record.readInt();
1132 D->Index = Record.readInt();
1133 D->VarianceLoc = readSourceLocation();
1134 D->ColonLoc = readSourceLocation();
1137 void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
1138 VisitNamedDecl(CD);
1139 CD->setAtStartLoc(readSourceLocation());
1140 CD->setAtEndRange(readSourceRange());
1143 ObjCTypeParamList *ASTDeclReader::ReadObjCTypeParamList() {
1144 unsigned numParams = Record.readInt();
1145 if (numParams == 0)
1146 return nullptr;
1148 SmallVector<ObjCTypeParamDecl *, 4> typeParams;
1149 typeParams.reserve(numParams);
1150 for (unsigned i = 0; i != numParams; ++i) {
1151 auto *typeParam = readDeclAs<ObjCTypeParamDecl>();
1152 if (!typeParam)
1153 return nullptr;
1155 typeParams.push_back(typeParam);
1158 SourceLocation lAngleLoc = readSourceLocation();
1159 SourceLocation rAngleLoc = readSourceLocation();
1161 return ObjCTypeParamList::create(Reader.getContext(), lAngleLoc,
1162 typeParams, rAngleLoc);
1165 void ASTDeclReader::ReadObjCDefinitionData(
1166 struct ObjCInterfaceDecl::DefinitionData &Data) {
1167 // Read the superclass.
1168 Data.SuperClassTInfo = readTypeSourceInfo();
1170 Data.EndLoc = readSourceLocation();
1171 Data.HasDesignatedInitializers = Record.readInt();
1173 // Read the directly referenced protocols and their SourceLocations.
1174 unsigned NumProtocols = Record.readInt();
1175 SmallVector<ObjCProtocolDecl *, 16> Protocols;
1176 Protocols.reserve(NumProtocols);
1177 for (unsigned I = 0; I != NumProtocols; ++I)
1178 Protocols.push_back(readDeclAs<ObjCProtocolDecl>());
1179 SmallVector<SourceLocation, 16> ProtoLocs;
1180 ProtoLocs.reserve(NumProtocols);
1181 for (unsigned I = 0; I != NumProtocols; ++I)
1182 ProtoLocs.push_back(readSourceLocation());
1183 Data.ReferencedProtocols.set(Protocols.data(), NumProtocols, ProtoLocs.data(),
1184 Reader.getContext());
1186 // Read the transitive closure of protocols referenced by this class.
1187 NumProtocols = Record.readInt();
1188 Protocols.clear();
1189 Protocols.reserve(NumProtocols);
1190 for (unsigned I = 0; I != NumProtocols; ++I)
1191 Protocols.push_back(readDeclAs<ObjCProtocolDecl>());
1192 Data.AllReferencedProtocols.set(Protocols.data(), NumProtocols,
1193 Reader.getContext());
1196 void ASTDeclReader::MergeDefinitionData(ObjCInterfaceDecl *D,
1197 struct ObjCInterfaceDecl::DefinitionData &&NewDD) {
1198 struct ObjCInterfaceDecl::DefinitionData &DD = D->data();
1199 if (DD.Definition != NewDD.Definition) {
1200 Reader.MergedDeclContexts.insert(
1201 std::make_pair(NewDD.Definition, DD.Definition));
1202 Reader.mergeDefinitionVisibility(DD.Definition, NewDD.Definition);
1205 // FIXME: odr checking?
1208 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
1209 RedeclarableResult Redecl = VisitRedeclarable(ID);
1210 VisitObjCContainerDecl(ID);
1211 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
1212 mergeRedeclarable(ID, Redecl);
1214 ID->TypeParamList = ReadObjCTypeParamList();
1215 if (Record.readInt()) {
1216 // Read the definition.
1217 ID->allocateDefinitionData();
1219 ReadObjCDefinitionData(ID->data());
1220 ObjCInterfaceDecl *Canon = ID->getCanonicalDecl();
1221 if (Canon->Data.getPointer()) {
1222 // If we already have a definition, keep the definition invariant and
1223 // merge the data.
1224 MergeDefinitionData(Canon, std::move(ID->data()));
1225 ID->Data = Canon->Data;
1226 } else {
1227 // Set the definition data of the canonical declaration, so other
1228 // redeclarations will see it.
1229 ID->getCanonicalDecl()->Data = ID->Data;
1231 // We will rebuild this list lazily.
1232 ID->setIvarList(nullptr);
1235 // Note that we have deserialized a definition.
1236 Reader.PendingDefinitions.insert(ID);
1238 // Note that we've loaded this Objective-C class.
1239 Reader.ObjCClassesLoaded.push_back(ID);
1240 } else {
1241 ID->Data = ID->getCanonicalDecl()->Data;
1245 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
1246 VisitFieldDecl(IVD);
1247 IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record.readInt());
1248 // This field will be built lazily.
1249 IVD->setNextIvar(nullptr);
1250 bool synth = Record.readInt();
1251 IVD->setSynthesize(synth);
1253 // Check ivar redeclaration.
1254 if (IVD->isInvalidDecl())
1255 return;
1256 // Don't check ObjCInterfaceDecl as interfaces are named and mismatches can be
1257 // detected in VisitObjCInterfaceDecl. Here we are looking for redeclarations
1258 // in extensions.
1259 if (isa<ObjCInterfaceDecl>(IVD->getDeclContext()))
1260 return;
1261 ObjCInterfaceDecl *CanonIntf =
1262 IVD->getContainingInterface()->getCanonicalDecl();
1263 IdentifierInfo *II = IVD->getIdentifier();
1264 ObjCIvarDecl *PrevIvar = CanonIntf->lookupInstanceVariable(II);
1265 if (PrevIvar && PrevIvar != IVD) {
1266 auto *ParentExt = dyn_cast<ObjCCategoryDecl>(IVD->getDeclContext());
1267 auto *PrevParentExt =
1268 dyn_cast<ObjCCategoryDecl>(PrevIvar->getDeclContext());
1269 if (ParentExt && PrevParentExt) {
1270 // Postpone diagnostic as we should merge identical extensions from
1271 // different modules.
1272 Reader
1273 .PendingObjCExtensionIvarRedeclarations[std::make_pair(ParentExt,
1274 PrevParentExt)]
1275 .push_back(std::make_pair(IVD, PrevIvar));
1276 } else if (ParentExt || PrevParentExt) {
1277 // Duplicate ivars in extension + implementation are never compatible.
1278 // Compatibility of implementation + implementation should be handled in
1279 // VisitObjCImplementationDecl.
1280 Reader.Diag(IVD->getLocation(), diag::err_duplicate_ivar_declaration)
1281 << II;
1282 Reader.Diag(PrevIvar->getLocation(), diag::note_previous_definition);
1287 void ASTDeclReader::ReadObjCDefinitionData(
1288 struct ObjCProtocolDecl::DefinitionData &Data) {
1289 unsigned NumProtoRefs = Record.readInt();
1290 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1291 ProtoRefs.reserve(NumProtoRefs);
1292 for (unsigned I = 0; I != NumProtoRefs; ++I)
1293 ProtoRefs.push_back(readDeclAs<ObjCProtocolDecl>());
1294 SmallVector<SourceLocation, 16> ProtoLocs;
1295 ProtoLocs.reserve(NumProtoRefs);
1296 for (unsigned I = 0; I != NumProtoRefs; ++I)
1297 ProtoLocs.push_back(readSourceLocation());
1298 Data.ReferencedProtocols.set(ProtoRefs.data(), NumProtoRefs,
1299 ProtoLocs.data(), Reader.getContext());
1302 void ASTDeclReader::MergeDefinitionData(ObjCProtocolDecl *D,
1303 struct ObjCProtocolDecl::DefinitionData &&NewDD) {
1304 struct ObjCProtocolDecl::DefinitionData &DD = D->data();
1305 if (DD.Definition != NewDD.Definition) {
1306 Reader.MergedDeclContexts.insert(
1307 std::make_pair(NewDD.Definition, DD.Definition));
1308 Reader.mergeDefinitionVisibility(DD.Definition, NewDD.Definition);
1311 // FIXME: odr checking?
1314 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
1315 RedeclarableResult Redecl = VisitRedeclarable(PD);
1316 VisitObjCContainerDecl(PD);
1317 mergeRedeclarable(PD, Redecl);
1319 if (Record.readInt()) {
1320 // Read the definition.
1321 PD->allocateDefinitionData();
1323 ReadObjCDefinitionData(PD->data());
1325 ObjCProtocolDecl *Canon = PD->getCanonicalDecl();
1326 if (Canon->Data.getPointer()) {
1327 // If we already have a definition, keep the definition invariant and
1328 // merge the data.
1329 MergeDefinitionData(Canon, std::move(PD->data()));
1330 PD->Data = Canon->Data;
1331 } else {
1332 // Set the definition data of the canonical declaration, so other
1333 // redeclarations will see it.
1334 PD->getCanonicalDecl()->Data = PD->Data;
1336 // Note that we have deserialized a definition.
1337 Reader.PendingDefinitions.insert(PD);
1338 } else {
1339 PD->Data = PD->getCanonicalDecl()->Data;
1343 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
1344 VisitFieldDecl(FD);
1347 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
1348 VisitObjCContainerDecl(CD);
1349 CD->setCategoryNameLoc(readSourceLocation());
1350 CD->setIvarLBraceLoc(readSourceLocation());
1351 CD->setIvarRBraceLoc(readSourceLocation());
1353 // Note that this category has been deserialized. We do this before
1354 // deserializing the interface declaration, so that it will consider this
1355 /// category.
1356 Reader.CategoriesDeserialized.insert(CD);
1358 CD->ClassInterface = readDeclAs<ObjCInterfaceDecl>();
1359 CD->TypeParamList = ReadObjCTypeParamList();
1360 unsigned NumProtoRefs = Record.readInt();
1361 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1362 ProtoRefs.reserve(NumProtoRefs);
1363 for (unsigned I = 0; I != NumProtoRefs; ++I)
1364 ProtoRefs.push_back(readDeclAs<ObjCProtocolDecl>());
1365 SmallVector<SourceLocation, 16> ProtoLocs;
1366 ProtoLocs.reserve(NumProtoRefs);
1367 for (unsigned I = 0; I != NumProtoRefs; ++I)
1368 ProtoLocs.push_back(readSourceLocation());
1369 CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
1370 Reader.getContext());
1372 // Protocols in the class extension belong to the class.
1373 if (NumProtoRefs > 0 && CD->ClassInterface && CD->IsClassExtension())
1374 CD->ClassInterface->mergeClassExtensionProtocolList(
1375 (ObjCProtocolDecl *const *)ProtoRefs.data(), NumProtoRefs,
1376 Reader.getContext());
1379 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
1380 VisitNamedDecl(CAD);
1381 CAD->setClassInterface(readDeclAs<ObjCInterfaceDecl>());
1384 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
1385 VisitNamedDecl(D);
1386 D->setAtLoc(readSourceLocation());
1387 D->setLParenLoc(readSourceLocation());
1388 QualType T = Record.readType();
1389 TypeSourceInfo *TSI = readTypeSourceInfo();
1390 D->setType(T, TSI);
1391 D->setPropertyAttributes((ObjCPropertyAttribute::Kind)Record.readInt());
1392 D->setPropertyAttributesAsWritten(
1393 (ObjCPropertyAttribute::Kind)Record.readInt());
1394 D->setPropertyImplementation(
1395 (ObjCPropertyDecl::PropertyControl)Record.readInt());
1396 DeclarationName GetterName = Record.readDeclarationName();
1397 SourceLocation GetterLoc = readSourceLocation();
1398 D->setGetterName(GetterName.getObjCSelector(), GetterLoc);
1399 DeclarationName SetterName = Record.readDeclarationName();
1400 SourceLocation SetterLoc = readSourceLocation();
1401 D->setSetterName(SetterName.getObjCSelector(), SetterLoc);
1402 D->setGetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1403 D->setSetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1404 D->setPropertyIvarDecl(readDeclAs<ObjCIvarDecl>());
1407 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
1408 VisitObjCContainerDecl(D);
1409 D->setClassInterface(readDeclAs<ObjCInterfaceDecl>());
1412 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1413 VisitObjCImplDecl(D);
1414 D->CategoryNameLoc = readSourceLocation();
1417 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1418 VisitObjCImplDecl(D);
1419 D->setSuperClass(readDeclAs<ObjCInterfaceDecl>());
1420 D->SuperLoc = readSourceLocation();
1421 D->setIvarLBraceLoc(readSourceLocation());
1422 D->setIvarRBraceLoc(readSourceLocation());
1423 D->setHasNonZeroConstructors(Record.readInt());
1424 D->setHasDestructors(Record.readInt());
1425 D->NumIvarInitializers = Record.readInt();
1426 if (D->NumIvarInitializers)
1427 D->IvarInitializers = ReadGlobalOffset();
1430 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
1431 VisitDecl(D);
1432 D->setAtLoc(readSourceLocation());
1433 D->setPropertyDecl(readDeclAs<ObjCPropertyDecl>());
1434 D->PropertyIvarDecl = readDeclAs<ObjCIvarDecl>();
1435 D->IvarLoc = readSourceLocation();
1436 D->setGetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1437 D->setSetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1438 D->setGetterCXXConstructor(Record.readExpr());
1439 D->setSetterCXXAssignment(Record.readExpr());
1442 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
1443 VisitDeclaratorDecl(FD);
1444 FD->Mutable = Record.readInt();
1446 if (auto ISK = static_cast<FieldDecl::InitStorageKind>(Record.readInt())) {
1447 FD->InitStorage.setInt(ISK);
1448 FD->InitStorage.setPointer(ISK == FieldDecl::ISK_CapturedVLAType
1449 ? Record.readType().getAsOpaquePtr()
1450 : Record.readExpr());
1453 if (auto *BW = Record.readExpr())
1454 FD->setBitWidth(BW);
1456 if (!FD->getDeclName()) {
1457 if (auto *Tmpl = readDeclAs<FieldDecl>())
1458 Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
1460 mergeMergeable(FD);
1463 void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
1464 VisitDeclaratorDecl(PD);
1465 PD->GetterId = Record.readIdentifier();
1466 PD->SetterId = Record.readIdentifier();
1469 void ASTDeclReader::VisitMSGuidDecl(MSGuidDecl *D) {
1470 VisitValueDecl(D);
1471 D->PartVal.Part1 = Record.readInt();
1472 D->PartVal.Part2 = Record.readInt();
1473 D->PartVal.Part3 = Record.readInt();
1474 for (auto &C : D->PartVal.Part4And5)
1475 C = Record.readInt();
1477 // Add this GUID to the AST context's lookup structure, and merge if needed.
1478 if (MSGuidDecl *Existing = Reader.getContext().MSGuidDecls.GetOrInsertNode(D))
1479 Reader.getContext().setPrimaryMergedDecl(D, Existing->getCanonicalDecl());
1482 void ASTDeclReader::VisitUnnamedGlobalConstantDecl(
1483 UnnamedGlobalConstantDecl *D) {
1484 VisitValueDecl(D);
1485 D->Value = Record.readAPValue();
1487 // Add this to the AST context's lookup structure, and merge if needed.
1488 if (UnnamedGlobalConstantDecl *Existing =
1489 Reader.getContext().UnnamedGlobalConstantDecls.GetOrInsertNode(D))
1490 Reader.getContext().setPrimaryMergedDecl(D, Existing->getCanonicalDecl());
1493 void ASTDeclReader::VisitTemplateParamObjectDecl(TemplateParamObjectDecl *D) {
1494 VisitValueDecl(D);
1495 D->Value = Record.readAPValue();
1497 // Add this template parameter object to the AST context's lookup structure,
1498 // and merge if needed.
1499 if (TemplateParamObjectDecl *Existing =
1500 Reader.getContext().TemplateParamObjectDecls.GetOrInsertNode(D))
1501 Reader.getContext().setPrimaryMergedDecl(D, Existing->getCanonicalDecl());
1504 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
1505 VisitValueDecl(FD);
1507 FD->ChainingSize = Record.readInt();
1508 assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
1509 FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
1511 for (unsigned I = 0; I != FD->ChainingSize; ++I)
1512 FD->Chaining[I] = readDeclAs<NamedDecl>();
1514 mergeMergeable(FD);
1517 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
1518 RedeclarableResult Redecl = VisitRedeclarable(VD);
1519 VisitDeclaratorDecl(VD);
1521 VD->VarDeclBits.SClass = (StorageClass)Record.readInt();
1522 VD->VarDeclBits.TSCSpec = Record.readInt();
1523 VD->VarDeclBits.InitStyle = Record.readInt();
1524 VD->VarDeclBits.ARCPseudoStrong = Record.readInt();
1525 if (!isa<ParmVarDecl>(VD)) {
1526 VD->NonParmVarDeclBits.IsThisDeclarationADemotedDefinition =
1527 Record.readInt();
1528 VD->NonParmVarDeclBits.ExceptionVar = Record.readInt();
1529 VD->NonParmVarDeclBits.NRVOVariable = Record.readInt();
1530 VD->NonParmVarDeclBits.CXXForRangeDecl = Record.readInt();
1531 VD->NonParmVarDeclBits.ObjCForDecl = Record.readInt();
1532 VD->NonParmVarDeclBits.IsInline = Record.readInt();
1533 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
1534 VD->NonParmVarDeclBits.IsConstexpr = Record.readInt();
1535 VD->NonParmVarDeclBits.IsInitCapture = Record.readInt();
1536 VD->NonParmVarDeclBits.PreviousDeclInSameBlockScope = Record.readInt();
1537 VD->NonParmVarDeclBits.ImplicitParamKind = Record.readInt();
1538 VD->NonParmVarDeclBits.EscapingByref = Record.readInt();
1540 auto VarLinkage = Linkage(Record.readInt());
1541 VD->setCachedLinkage(VarLinkage);
1543 // Reconstruct the one piece of the IdentifierNamespace that we need.
1544 if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage &&
1545 VD->getLexicalDeclContext()->isFunctionOrMethod())
1546 VD->setLocalExternDecl();
1548 if (uint64_t Val = Record.readInt()) {
1549 VD->setInit(Record.readExpr());
1550 if (Val != 1) {
1551 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
1552 Eval->HasConstantInitialization = (Val & 2) != 0;
1553 Eval->HasConstantDestruction = (Val & 4) != 0;
1557 if (VD->hasAttr<BlocksAttr>() && VD->getType()->getAsCXXRecordDecl()) {
1558 Expr *CopyExpr = Record.readExpr();
1559 if (CopyExpr)
1560 Reader.getContext().setBlockVarCopyInit(VD, CopyExpr, Record.readInt());
1563 if (VD->getStorageDuration() == SD_Static && Record.readInt()) {
1564 Reader.DefinitionSource[VD] =
1565 Loc.F->Kind == ModuleKind::MK_MainFile ||
1566 Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;
1569 enum VarKind {
1570 VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
1572 switch ((VarKind)Record.readInt()) {
1573 case VarNotTemplate:
1574 // Only true variables (not parameters or implicit parameters) can be
1575 // merged; the other kinds are not really redeclarable at all.
1576 if (!isa<ParmVarDecl>(VD) && !isa<ImplicitParamDecl>(VD) &&
1577 !isa<VarTemplateSpecializationDecl>(VD))
1578 mergeRedeclarable(VD, Redecl);
1579 break;
1580 case VarTemplate:
1581 // Merged when we merge the template.
1582 VD->setDescribedVarTemplate(readDeclAs<VarTemplateDecl>());
1583 break;
1584 case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
1585 auto *Tmpl = readDeclAs<VarDecl>();
1586 auto TSK = (TemplateSpecializationKind)Record.readInt();
1587 SourceLocation POI = readSourceLocation();
1588 Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
1589 mergeRedeclarable(VD, Redecl);
1590 break;
1594 return Redecl;
1597 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1598 VisitVarDecl(PD);
1601 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1602 VisitVarDecl(PD);
1603 unsigned isObjCMethodParam = Record.readInt();
1604 unsigned scopeDepth = Record.readInt();
1605 unsigned scopeIndex = Record.readInt();
1606 unsigned declQualifier = Record.readInt();
1607 if (isObjCMethodParam) {
1608 assert(scopeDepth == 0);
1609 PD->setObjCMethodScopeInfo(scopeIndex);
1610 PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1611 } else {
1612 PD->setScopeInfo(scopeDepth, scopeIndex);
1614 PD->ParmVarDeclBits.IsKNRPromoted = Record.readInt();
1615 PD->ParmVarDeclBits.HasInheritedDefaultArg = Record.readInt();
1616 if (Record.readInt()) // hasUninstantiatedDefaultArg.
1617 PD->setUninstantiatedDefaultArg(Record.readExpr());
1619 // FIXME: If this is a redeclaration of a function from another module, handle
1620 // inheritance of default arguments.
1623 void ASTDeclReader::VisitDecompositionDecl(DecompositionDecl *DD) {
1624 VisitVarDecl(DD);
1625 auto **BDs = DD->getTrailingObjects<BindingDecl *>();
1626 for (unsigned I = 0; I != DD->NumBindings; ++I) {
1627 BDs[I] = readDeclAs<BindingDecl>();
1628 BDs[I]->setDecomposedDecl(DD);
1632 void ASTDeclReader::VisitBindingDecl(BindingDecl *BD) {
1633 VisitValueDecl(BD);
1634 BD->Binding = Record.readExpr();
1637 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1638 VisitDecl(AD);
1639 AD->setAsmString(cast<StringLiteral>(Record.readExpr()));
1640 AD->setRParenLoc(readSourceLocation());
1643 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1644 VisitDecl(BD);
1645 BD->setBody(cast_or_null<CompoundStmt>(Record.readStmt()));
1646 BD->setSignatureAsWritten(readTypeSourceInfo());
1647 unsigned NumParams = Record.readInt();
1648 SmallVector<ParmVarDecl *, 16> Params;
1649 Params.reserve(NumParams);
1650 for (unsigned I = 0; I != NumParams; ++I)
1651 Params.push_back(readDeclAs<ParmVarDecl>());
1652 BD->setParams(Params);
1654 BD->setIsVariadic(Record.readInt());
1655 BD->setBlockMissingReturnType(Record.readInt());
1656 BD->setIsConversionFromLambda(Record.readInt());
1657 BD->setDoesNotEscape(Record.readInt());
1658 BD->setCanAvoidCopyToHeap(Record.readInt());
1660 bool capturesCXXThis = Record.readInt();
1661 unsigned numCaptures = Record.readInt();
1662 SmallVector<BlockDecl::Capture, 16> captures;
1663 captures.reserve(numCaptures);
1664 for (unsigned i = 0; i != numCaptures; ++i) {
1665 auto *decl = readDeclAs<VarDecl>();
1666 unsigned flags = Record.readInt();
1667 bool byRef = (flags & 1);
1668 bool nested = (flags & 2);
1669 Expr *copyExpr = ((flags & 4) ? Record.readExpr() : nullptr);
1671 captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
1673 BD->setCaptures(Reader.getContext(), captures, capturesCXXThis);
1676 void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1677 VisitDecl(CD);
1678 unsigned ContextParamPos = Record.readInt();
1679 CD->setNothrow(Record.readInt() != 0);
1680 // Body is set by VisitCapturedStmt.
1681 for (unsigned I = 0; I < CD->NumParams; ++I) {
1682 if (I != ContextParamPos)
1683 CD->setParam(I, readDeclAs<ImplicitParamDecl>());
1684 else
1685 CD->setContextParam(I, readDeclAs<ImplicitParamDecl>());
1689 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1690 VisitDecl(D);
1691 D->setLanguage((LinkageSpecDecl::LanguageIDs)Record.readInt());
1692 D->setExternLoc(readSourceLocation());
1693 D->setRBraceLoc(readSourceLocation());
1696 void ASTDeclReader::VisitExportDecl(ExportDecl *D) {
1697 VisitDecl(D);
1698 D->RBraceLoc = readSourceLocation();
1701 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1702 VisitNamedDecl(D);
1703 D->setLocStart(readSourceLocation());
1706 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1707 RedeclarableResult Redecl = VisitRedeclarable(D);
1708 VisitNamedDecl(D);
1709 D->setInline(Record.readInt());
1710 D->LocStart = readSourceLocation();
1711 D->RBraceLoc = readSourceLocation();
1713 // Defer loading the anonymous namespace until we've finished merging
1714 // this namespace; loading it might load a later declaration of the
1715 // same namespace, and we have an invariant that older declarations
1716 // get merged before newer ones try to merge.
1717 GlobalDeclID AnonNamespace = 0;
1718 if (Redecl.getFirstID() == ThisDeclID) {
1719 AnonNamespace = readDeclID();
1720 } else {
1721 // Link this namespace back to the first declaration, which has already
1722 // been deserialized.
1723 D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
1726 mergeRedeclarable(D, Redecl);
1728 if (AnonNamespace) {
1729 // Each module has its own anonymous namespace, which is disjoint from
1730 // any other module's anonymous namespaces, so don't attach the anonymous
1731 // namespace at all.
1732 auto *Anon = cast<NamespaceDecl>(Reader.GetDecl(AnonNamespace));
1733 if (!Record.isModule())
1734 D->setAnonymousNamespace(Anon);
1738 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1739 RedeclarableResult Redecl = VisitRedeclarable(D);
1740 VisitNamedDecl(D);
1741 D->NamespaceLoc = readSourceLocation();
1742 D->IdentLoc = readSourceLocation();
1743 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1744 D->Namespace = readDeclAs<NamedDecl>();
1745 mergeRedeclarable(D, Redecl);
1748 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1749 VisitNamedDecl(D);
1750 D->setUsingLoc(readSourceLocation());
1751 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1752 D->DNLoc = Record.readDeclarationNameLoc(D->getDeclName());
1753 D->FirstUsingShadow.setPointer(readDeclAs<UsingShadowDecl>());
1754 D->setTypename(Record.readInt());
1755 if (auto *Pattern = readDeclAs<NamedDecl>())
1756 Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1757 mergeMergeable(D);
1760 void ASTDeclReader::VisitUsingEnumDecl(UsingEnumDecl *D) {
1761 VisitNamedDecl(D);
1762 D->setUsingLoc(readSourceLocation());
1763 D->setEnumLoc(readSourceLocation());
1764 D->Enum = readDeclAs<EnumDecl>();
1765 D->FirstUsingShadow.setPointer(readDeclAs<UsingShadowDecl>());
1766 if (auto *Pattern = readDeclAs<UsingEnumDecl>())
1767 Reader.getContext().setInstantiatedFromUsingEnumDecl(D, Pattern);
1768 mergeMergeable(D);
1771 void ASTDeclReader::VisitUsingPackDecl(UsingPackDecl *D) {
1772 VisitNamedDecl(D);
1773 D->InstantiatedFrom = readDeclAs<NamedDecl>();
1774 auto **Expansions = D->getTrailingObjects<NamedDecl *>();
1775 for (unsigned I = 0; I != D->NumExpansions; ++I)
1776 Expansions[I] = readDeclAs<NamedDecl>();
1777 mergeMergeable(D);
1780 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1781 RedeclarableResult Redecl = VisitRedeclarable(D);
1782 VisitNamedDecl(D);
1783 D->Underlying = readDeclAs<NamedDecl>();
1784 D->IdentifierNamespace = Record.readInt();
1785 D->UsingOrNextShadow = readDeclAs<NamedDecl>();
1786 auto *Pattern = readDeclAs<UsingShadowDecl>();
1787 if (Pattern)
1788 Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1789 mergeRedeclarable(D, Redecl);
1792 void ASTDeclReader::VisitConstructorUsingShadowDecl(
1793 ConstructorUsingShadowDecl *D) {
1794 VisitUsingShadowDecl(D);
1795 D->NominatedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1796 D->ConstructedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1797 D->IsVirtual = Record.readInt();
1800 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1801 VisitNamedDecl(D);
1802 D->UsingLoc = readSourceLocation();
1803 D->NamespaceLoc = readSourceLocation();
1804 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1805 D->NominatedNamespace = readDeclAs<NamedDecl>();
1806 D->CommonAncestor = readDeclAs<DeclContext>();
1809 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1810 VisitValueDecl(D);
1811 D->setUsingLoc(readSourceLocation());
1812 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1813 D->DNLoc = Record.readDeclarationNameLoc(D->getDeclName());
1814 D->EllipsisLoc = readSourceLocation();
1815 mergeMergeable(D);
1818 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1819 UnresolvedUsingTypenameDecl *D) {
1820 VisitTypeDecl(D);
1821 D->TypenameLocation = readSourceLocation();
1822 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1823 D->EllipsisLoc = readSourceLocation();
1824 mergeMergeable(D);
1827 void ASTDeclReader::VisitUnresolvedUsingIfExistsDecl(
1828 UnresolvedUsingIfExistsDecl *D) {
1829 VisitNamedDecl(D);
1832 void ASTDeclReader::ReadCXXDefinitionData(
1833 struct CXXRecordDecl::DefinitionData &Data, const CXXRecordDecl *D) {
1834 #define FIELD(Name, Width, Merge) \
1835 Data.Name = Record.readInt();
1836 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1838 // Note: the caller has deserialized the IsLambda bit already.
1839 Data.ODRHash = Record.readInt();
1840 Data.HasODRHash = true;
1842 if (Record.readInt()) {
1843 Reader.DefinitionSource[D] =
1844 Loc.F->Kind == ModuleKind::MK_MainFile ||
1845 Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;
1848 Data.NumBases = Record.readInt();
1849 if (Data.NumBases)
1850 Data.Bases = ReadGlobalOffset();
1851 Data.NumVBases = Record.readInt();
1852 if (Data.NumVBases)
1853 Data.VBases = ReadGlobalOffset();
1855 Record.readUnresolvedSet(Data.Conversions);
1856 Data.ComputedVisibleConversions = Record.readInt();
1857 if (Data.ComputedVisibleConversions)
1858 Record.readUnresolvedSet(Data.VisibleConversions);
1859 assert(Data.Definition && "Data.Definition should be already set!");
1860 Data.FirstFriend = readDeclID();
1862 if (Data.IsLambda) {
1863 using Capture = LambdaCapture;
1865 auto &Lambda = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1866 Lambda.DependencyKind = Record.readInt();
1867 Lambda.IsGenericLambda = Record.readInt();
1868 Lambda.CaptureDefault = Record.readInt();
1869 Lambda.NumCaptures = Record.readInt();
1870 Lambda.NumExplicitCaptures = Record.readInt();
1871 Lambda.HasKnownInternalLinkage = Record.readInt();
1872 Lambda.ManglingNumber = Record.readInt();
1873 D->setDeviceLambdaManglingNumber(Record.readInt());
1874 Lambda.ContextDecl = readDeclID();
1875 Lambda.Captures = (Capture *)Reader.getContext().Allocate(
1876 sizeof(Capture) * Lambda.NumCaptures);
1877 Capture *ToCapture = Lambda.Captures;
1878 Lambda.MethodTyInfo = readTypeSourceInfo();
1879 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1880 SourceLocation Loc = readSourceLocation();
1881 bool IsImplicit = Record.readInt();
1882 auto Kind = static_cast<LambdaCaptureKind>(Record.readInt());
1883 switch (Kind) {
1884 case LCK_StarThis:
1885 case LCK_This:
1886 case LCK_VLAType:
1887 *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation());
1888 break;
1889 case LCK_ByCopy:
1890 case LCK_ByRef:
1891 auto *Var = readDeclAs<VarDecl>();
1892 SourceLocation EllipsisLoc = readSourceLocation();
1893 *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1894 break;
1900 void ASTDeclReader::MergeDefinitionData(
1901 CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {
1902 assert(D->DefinitionData &&
1903 "merging class definition into non-definition");
1904 auto &DD = *D->DefinitionData;
1906 if (DD.Definition != MergeDD.Definition) {
1907 // Track that we merged the definitions.
1908 Reader.MergedDeclContexts.insert(std::make_pair(MergeDD.Definition,
1909 DD.Definition));
1910 Reader.PendingDefinitions.erase(MergeDD.Definition);
1911 MergeDD.Definition->setCompleteDefinition(false);
1912 Reader.mergeDefinitionVisibility(DD.Definition, MergeDD.Definition);
1913 assert(Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() &&
1914 "already loaded pending lookups for merged definition");
1917 auto PFDI = Reader.PendingFakeDefinitionData.find(&DD);
1918 if (PFDI != Reader.PendingFakeDefinitionData.end() &&
1919 PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) {
1920 // We faked up this definition data because we found a class for which we'd
1921 // not yet loaded the definition. Replace it with the real thing now.
1922 assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?");
1923 PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded;
1925 // Don't change which declaration is the definition; that is required
1926 // to be invariant once we select it.
1927 auto *Def = DD.Definition;
1928 DD = std::move(MergeDD);
1929 DD.Definition = Def;
1930 return;
1933 bool DetectedOdrViolation = false;
1935 #define FIELD(Name, Width, Merge) Merge(Name)
1936 #define MERGE_OR(Field) DD.Field |= MergeDD.Field;
1937 #define NO_MERGE(Field) \
1938 DetectedOdrViolation |= DD.Field != MergeDD.Field; \
1939 MERGE_OR(Field)
1940 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1941 NO_MERGE(IsLambda)
1942 #undef NO_MERGE
1943 #undef MERGE_OR
1945 if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
1946 DetectedOdrViolation = true;
1947 // FIXME: Issue a diagnostic if the base classes don't match when we come
1948 // to lazily load them.
1950 // FIXME: Issue a diagnostic if the list of conversion functions doesn't
1951 // match when we come to lazily load them.
1952 if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
1953 DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
1954 DD.ComputedVisibleConversions = true;
1957 // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
1958 // lazily load it.
1960 if (DD.IsLambda) {
1961 // FIXME: ODR-checking for merging lambdas (this happens, for instance,
1962 // when they occur within the body of a function template specialization).
1965 if (D->getODRHash() != MergeDD.ODRHash) {
1966 DetectedOdrViolation = true;
1969 if (DetectedOdrViolation)
1970 Reader.PendingOdrMergeFailures[DD.Definition].push_back(
1971 {MergeDD.Definition, &MergeDD});
1974 void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update) {
1975 struct CXXRecordDecl::DefinitionData *DD;
1976 ASTContext &C = Reader.getContext();
1978 // Determine whether this is a lambda closure type, so that we can
1979 // allocate the appropriate DefinitionData structure.
1980 bool IsLambda = Record.readInt();
1981 if (IsLambda)
1982 DD = new (C) CXXRecordDecl::LambdaDefinitionData(
1983 D, nullptr, CXXRecordDecl::LDK_Unknown, false, LCD_None);
1984 else
1985 DD = new (C) struct CXXRecordDecl::DefinitionData(D);
1987 CXXRecordDecl *Canon = D->getCanonicalDecl();
1988 // Set decl definition data before reading it, so that during deserialization
1989 // when we read CXXRecordDecl, it already has definition data and we don't
1990 // set fake one.
1991 if (!Canon->DefinitionData)
1992 Canon->DefinitionData = DD;
1993 D->DefinitionData = Canon->DefinitionData;
1994 ReadCXXDefinitionData(*DD, D);
1996 // We might already have a different definition for this record. This can
1997 // happen either because we're reading an update record, or because we've
1998 // already done some merging. Either way, just merge into it.
1999 if (Canon->DefinitionData != DD) {
2000 MergeDefinitionData(Canon, std::move(*DD));
2001 return;
2004 // Mark this declaration as being a definition.
2005 D->setCompleteDefinition(true);
2007 // If this is not the first declaration or is an update record, we can have
2008 // other redeclarations already. Make a note that we need to propagate the
2009 // DefinitionData pointer onto them.
2010 if (Update || Canon != D)
2011 Reader.PendingDefinitions.insert(D);
2014 ASTDeclReader::RedeclarableResult
2015 ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
2016 RedeclarableResult Redecl = VisitRecordDeclImpl(D);
2018 ASTContext &C = Reader.getContext();
2020 enum CXXRecKind {
2021 CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
2023 switch ((CXXRecKind)Record.readInt()) {
2024 case CXXRecNotTemplate:
2025 // Merged when we merge the folding set entry in the primary template.
2026 if (!isa<ClassTemplateSpecializationDecl>(D))
2027 mergeRedeclarable(D, Redecl);
2028 break;
2029 case CXXRecTemplate: {
2030 // Merged when we merge the template.
2031 auto *Template = readDeclAs<ClassTemplateDecl>();
2032 D->TemplateOrInstantiation = Template;
2033 if (!Template->getTemplatedDecl()) {
2034 // We've not actually loaded the ClassTemplateDecl yet, because we're
2035 // currently being loaded as its pattern. Rely on it to set up our
2036 // TypeForDecl (see VisitClassTemplateDecl).
2038 // Beware: we do not yet know our canonical declaration, and may still
2039 // get merged once the surrounding class template has got off the ground.
2040 DeferredTypeID = 0;
2042 break;
2044 case CXXRecMemberSpecialization: {
2045 auto *RD = readDeclAs<CXXRecordDecl>();
2046 auto TSK = (TemplateSpecializationKind)Record.readInt();
2047 SourceLocation POI = readSourceLocation();
2048 MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
2049 MSI->setPointOfInstantiation(POI);
2050 D->TemplateOrInstantiation = MSI;
2051 mergeRedeclarable(D, Redecl);
2052 break;
2056 bool WasDefinition = Record.readInt();
2057 if (WasDefinition)
2058 ReadCXXRecordDefinition(D, /*Update*/false);
2059 else
2060 // Propagate DefinitionData pointer from the canonical declaration.
2061 D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
2063 // Lazily load the key function to avoid deserializing every method so we can
2064 // compute it.
2065 if (WasDefinition) {
2066 DeclID KeyFn = readDeclID();
2067 if (KeyFn && D->isCompleteDefinition())
2068 // FIXME: This is wrong for the ARM ABI, where some other module may have
2069 // made this function no longer be a key function. We need an update
2070 // record or similar for that case.
2071 C.KeyFunctions[D] = KeyFn;
2074 return Redecl;
2077 void ASTDeclReader::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
2078 D->setExplicitSpecifier(Record.readExplicitSpec());
2079 D->Ctor = readDeclAs<CXXConstructorDecl>();
2080 VisitFunctionDecl(D);
2081 D->setIsCopyDeductionCandidate(Record.readInt());
2084 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
2085 VisitFunctionDecl(D);
2087 unsigned NumOverridenMethods = Record.readInt();
2088 if (D->isCanonicalDecl()) {
2089 while (NumOverridenMethods--) {
2090 // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
2091 // MD may be initializing.
2092 if (auto *MD = readDeclAs<CXXMethodDecl>())
2093 Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl());
2095 } else {
2096 // We don't care about which declarations this used to override; we get
2097 // the relevant information from the canonical declaration.
2098 Record.skipInts(NumOverridenMethods);
2102 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2103 // We need the inherited constructor information to merge the declaration,
2104 // so we have to read it before we call VisitCXXMethodDecl.
2105 D->setExplicitSpecifier(Record.readExplicitSpec());
2106 if (D->isInheritingConstructor()) {
2107 auto *Shadow = readDeclAs<ConstructorUsingShadowDecl>();
2108 auto *Ctor = readDeclAs<CXXConstructorDecl>();
2109 *D->getTrailingObjects<InheritedConstructor>() =
2110 InheritedConstructor(Shadow, Ctor);
2113 VisitCXXMethodDecl(D);
2116 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2117 VisitCXXMethodDecl(D);
2119 if (auto *OperatorDelete = readDeclAs<FunctionDecl>()) {
2120 CXXDestructorDecl *Canon = D->getCanonicalDecl();
2121 auto *ThisArg = Record.readExpr();
2122 // FIXME: Check consistency if we have an old and new operator delete.
2123 if (!Canon->OperatorDelete) {
2124 Canon->OperatorDelete = OperatorDelete;
2125 Canon->OperatorDeleteThisArg = ThisArg;
2130 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
2131 D->setExplicitSpecifier(Record.readExplicitSpec());
2132 VisitCXXMethodDecl(D);
2135 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
2136 VisitDecl(D);
2137 D->ImportedModule = readModule();
2138 D->setImportComplete(Record.readInt());
2139 auto *StoredLocs = D->getTrailingObjects<SourceLocation>();
2140 for (unsigned I = 0, N = Record.back(); I != N; ++I)
2141 StoredLocs[I] = readSourceLocation();
2142 Record.skipInts(1); // The number of stored source locations.
2145 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
2146 VisitDecl(D);
2147 D->setColonLoc(readSourceLocation());
2150 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
2151 VisitDecl(D);
2152 if (Record.readInt()) // hasFriendDecl
2153 D->Friend = readDeclAs<NamedDecl>();
2154 else
2155 D->Friend = readTypeSourceInfo();
2156 for (unsigned i = 0; i != D->NumTPLists; ++i)
2157 D->getTrailingObjects<TemplateParameterList *>()[i] =
2158 Record.readTemplateParameterList();
2159 D->NextFriend = readDeclID();
2160 D->UnsupportedFriend = (Record.readInt() != 0);
2161 D->FriendLoc = readSourceLocation();
2164 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2165 VisitDecl(D);
2166 unsigned NumParams = Record.readInt();
2167 D->NumParams = NumParams;
2168 D->Params = new (Reader.getContext()) TemplateParameterList *[NumParams];
2169 for (unsigned i = 0; i != NumParams; ++i)
2170 D->Params[i] = Record.readTemplateParameterList();
2171 if (Record.readInt()) // HasFriendDecl
2172 D->Friend = readDeclAs<NamedDecl>();
2173 else
2174 D->Friend = readTypeSourceInfo();
2175 D->FriendLoc = readSourceLocation();
2178 DeclID ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
2179 VisitNamedDecl(D);
2181 DeclID PatternID = readDeclID();
2182 auto *TemplatedDecl = cast_or_null<NamedDecl>(Reader.GetDecl(PatternID));
2183 TemplateParameterList *TemplateParams = Record.readTemplateParameterList();
2184 D->init(TemplatedDecl, TemplateParams);
2186 return PatternID;
2189 void ASTDeclReader::VisitConceptDecl(ConceptDecl *D) {
2190 VisitTemplateDecl(D);
2191 D->ConstraintExpr = Record.readExpr();
2192 mergeMergeable(D);
2195 void ASTDeclReader::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
2198 ASTDeclReader::RedeclarableResult
2199 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
2200 RedeclarableResult Redecl = VisitRedeclarable(D);
2202 // Make sure we've allocated the Common pointer first. We do this before
2203 // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
2204 RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
2205 if (!CanonD->Common) {
2206 CanonD->Common = CanonD->newCommon(Reader.getContext());
2207 Reader.PendingDefinitions.insert(CanonD);
2209 D->Common = CanonD->Common;
2211 // If this is the first declaration of the template, fill in the information
2212 // for the 'common' pointer.
2213 if (ThisDeclID == Redecl.getFirstID()) {
2214 if (auto *RTD = readDeclAs<RedeclarableTemplateDecl>()) {
2215 assert(RTD->getKind() == D->getKind() &&
2216 "InstantiatedFromMemberTemplate kind mismatch");
2217 D->setInstantiatedFromMemberTemplate(RTD);
2218 if (Record.readInt())
2219 D->setMemberSpecialization();
2223 DeclID PatternID = VisitTemplateDecl(D);
2224 D->IdentifierNamespace = Record.readInt();
2226 mergeRedeclarable(D, Redecl, PatternID);
2228 // If we merged the template with a prior declaration chain, merge the common
2229 // pointer.
2230 // FIXME: Actually merge here, don't just overwrite.
2231 D->Common = D->getCanonicalDecl()->Common;
2233 return Redecl;
2236 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
2237 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2239 if (ThisDeclID == Redecl.getFirstID()) {
2240 // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
2241 // the specializations.
2242 SmallVector<serialization::DeclID, 32> SpecIDs;
2243 readDeclIDList(SpecIDs);
2244 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2247 if (D->getTemplatedDecl()->TemplateOrInstantiation) {
2248 // We were loaded before our templated declaration was. We've not set up
2249 // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
2250 // it now.
2251 Reader.getContext().getInjectedClassNameType(
2252 D->getTemplatedDecl(), D->getInjectedClassNameSpecialization());
2256 void ASTDeclReader::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
2257 llvm_unreachable("BuiltinTemplates are not serialized");
2260 /// TODO: Unify with ClassTemplateDecl version?
2261 /// May require unifying ClassTemplateDecl and
2262 /// VarTemplateDecl beyond TemplateDecl...
2263 void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
2264 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2266 if (ThisDeclID == Redecl.getFirstID()) {
2267 // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
2268 // the specializations.
2269 SmallVector<serialization::DeclID, 32> SpecIDs;
2270 readDeclIDList(SpecIDs);
2271 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2275 ASTDeclReader::RedeclarableResult
2276 ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
2277 ClassTemplateSpecializationDecl *D) {
2278 RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
2280 ASTContext &C = Reader.getContext();
2281 if (Decl *InstD = readDecl()) {
2282 if (auto *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
2283 D->SpecializedTemplate = CTD;
2284 } else {
2285 SmallVector<TemplateArgument, 8> TemplArgs;
2286 Record.readTemplateArgumentList(TemplArgs);
2287 TemplateArgumentList *ArgList
2288 = TemplateArgumentList::CreateCopy(C, TemplArgs);
2289 auto *PS =
2290 new (C) ClassTemplateSpecializationDecl::
2291 SpecializedPartialSpecialization();
2292 PS->PartialSpecialization
2293 = cast<ClassTemplatePartialSpecializationDecl>(InstD);
2294 PS->TemplateArgs = ArgList;
2295 D->SpecializedTemplate = PS;
2299 SmallVector<TemplateArgument, 8> TemplArgs;
2300 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2301 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2302 D->PointOfInstantiation = readSourceLocation();
2303 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2305 bool writtenAsCanonicalDecl = Record.readInt();
2306 if (writtenAsCanonicalDecl) {
2307 auto *CanonPattern = readDeclAs<ClassTemplateDecl>();
2308 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2309 // Set this as, or find, the canonical declaration for this specialization
2310 ClassTemplateSpecializationDecl *CanonSpec;
2311 if (auto *Partial = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
2312 CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
2313 .GetOrInsertNode(Partial);
2314 } else {
2315 CanonSpec =
2316 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2318 // If there was already a canonical specialization, merge into it.
2319 if (CanonSpec != D) {
2320 mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
2322 // This declaration might be a definition. Merge with any existing
2323 // definition.
2324 if (auto *DDD = D->DefinitionData) {
2325 if (CanonSpec->DefinitionData)
2326 MergeDefinitionData(CanonSpec, std::move(*DDD));
2327 else
2328 CanonSpec->DefinitionData = D->DefinitionData;
2330 D->DefinitionData = CanonSpec->DefinitionData;
2335 // Explicit info.
2336 if (TypeSourceInfo *TyInfo = readTypeSourceInfo()) {
2337 auto *ExplicitInfo =
2338 new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
2339 ExplicitInfo->TypeAsWritten = TyInfo;
2340 ExplicitInfo->ExternLoc = readSourceLocation();
2341 ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2342 D->ExplicitInfo = ExplicitInfo;
2345 return Redecl;
2348 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
2349 ClassTemplatePartialSpecializationDecl *D) {
2350 // We need to read the template params first because redeclarable is going to
2351 // need them for profiling
2352 TemplateParameterList *Params = Record.readTemplateParameterList();
2353 D->TemplateParams = Params;
2354 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2356 RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
2358 // These are read/set from/to the first declaration.
2359 if (ThisDeclID == Redecl.getFirstID()) {
2360 D->InstantiatedFromMember.setPointer(
2361 readDeclAs<ClassTemplatePartialSpecializationDecl>());
2362 D->InstantiatedFromMember.setInt(Record.readInt());
2366 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
2367 ClassScopeFunctionSpecializationDecl *D) {
2368 VisitDecl(D);
2369 D->Specialization = readDeclAs<CXXMethodDecl>();
2370 if (Record.readInt())
2371 D->TemplateArgs = Record.readASTTemplateArgumentListInfo();
2374 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2375 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2377 if (ThisDeclID == Redecl.getFirstID()) {
2378 // This FunctionTemplateDecl owns a CommonPtr; read it.
2379 SmallVector<serialization::DeclID, 32> SpecIDs;
2380 readDeclIDList(SpecIDs);
2381 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2385 /// TODO: Unify with ClassTemplateSpecializationDecl version?
2386 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
2387 /// VarTemplate(Partial)SpecializationDecl with a new data
2388 /// structure Template(Partial)SpecializationDecl, and
2389 /// using Template(Partial)SpecializationDecl as input type.
2390 ASTDeclReader::RedeclarableResult
2391 ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
2392 VarTemplateSpecializationDecl *D) {
2393 RedeclarableResult Redecl = VisitVarDeclImpl(D);
2395 ASTContext &C = Reader.getContext();
2396 if (Decl *InstD = readDecl()) {
2397 if (auto *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
2398 D->SpecializedTemplate = VTD;
2399 } else {
2400 SmallVector<TemplateArgument, 8> TemplArgs;
2401 Record.readTemplateArgumentList(TemplArgs);
2402 TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
2403 C, TemplArgs);
2404 auto *PS =
2405 new (C)
2406 VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
2407 PS->PartialSpecialization =
2408 cast<VarTemplatePartialSpecializationDecl>(InstD);
2409 PS->TemplateArgs = ArgList;
2410 D->SpecializedTemplate = PS;
2414 // Explicit info.
2415 if (TypeSourceInfo *TyInfo = readTypeSourceInfo()) {
2416 auto *ExplicitInfo =
2417 new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
2418 ExplicitInfo->TypeAsWritten = TyInfo;
2419 ExplicitInfo->ExternLoc = readSourceLocation();
2420 ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2421 D->ExplicitInfo = ExplicitInfo;
2424 SmallVector<TemplateArgument, 8> TemplArgs;
2425 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2426 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2427 D->PointOfInstantiation = readSourceLocation();
2428 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2429 D->IsCompleteDefinition = Record.readInt();
2431 bool writtenAsCanonicalDecl = Record.readInt();
2432 if (writtenAsCanonicalDecl) {
2433 auto *CanonPattern = readDeclAs<VarTemplateDecl>();
2434 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2435 VarTemplateSpecializationDecl *CanonSpec;
2436 if (auto *Partial = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
2437 CanonSpec = CanonPattern->getCommonPtr()
2438 ->PartialSpecializations.GetOrInsertNode(Partial);
2439 } else {
2440 CanonSpec =
2441 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2443 // If we already have a matching specialization, merge it.
2444 if (CanonSpec != D)
2445 mergeRedeclarable<VarDecl>(D, CanonSpec, Redecl);
2449 return Redecl;
2452 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2453 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
2454 /// VarTemplate(Partial)SpecializationDecl with a new data
2455 /// structure Template(Partial)SpecializationDecl, and
2456 /// using Template(Partial)SpecializationDecl as input type.
2457 void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
2458 VarTemplatePartialSpecializationDecl *D) {
2459 TemplateParameterList *Params = Record.readTemplateParameterList();
2460 D->TemplateParams = Params;
2461 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2463 RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
2465 // These are read/set from/to the first declaration.
2466 if (ThisDeclID == Redecl.getFirstID()) {
2467 D->InstantiatedFromMember.setPointer(
2468 readDeclAs<VarTemplatePartialSpecializationDecl>());
2469 D->InstantiatedFromMember.setInt(Record.readInt());
2473 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
2474 VisitTypeDecl(D);
2476 D->setDeclaredWithTypename(Record.readInt());
2478 if (Record.readBool()) {
2479 NestedNameSpecifierLoc NNS = Record.readNestedNameSpecifierLoc();
2480 DeclarationNameInfo DN = Record.readDeclarationNameInfo();
2481 ConceptDecl *NamedConcept = Record.readDeclAs<ConceptDecl>();
2482 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
2483 if (Record.readBool())
2484 ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2485 Expr *ImmediatelyDeclaredConstraint = Record.readExpr();
2486 D->setTypeConstraint(NNS, DN, /*FoundDecl=*/nullptr, NamedConcept,
2487 ArgsAsWritten, ImmediatelyDeclaredConstraint);
2488 if ((D->ExpandedParameterPack = Record.readInt()))
2489 D->NumExpanded = Record.readInt();
2492 if (Record.readInt())
2493 D->setDefaultArgument(readTypeSourceInfo());
2496 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
2497 VisitDeclaratorDecl(D);
2498 // TemplateParmPosition.
2499 D->setDepth(Record.readInt());
2500 D->setPosition(Record.readInt());
2501 if (D->hasPlaceholderTypeConstraint())
2502 D->setPlaceholderTypeConstraint(Record.readExpr());
2503 if (D->isExpandedParameterPack()) {
2504 auto TypesAndInfos =
2505 D->getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
2506 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2507 new (&TypesAndInfos[I].first) QualType(Record.readType());
2508 TypesAndInfos[I].second = readTypeSourceInfo();
2510 } else {
2511 // Rest of NonTypeTemplateParmDecl.
2512 D->ParameterPack = Record.readInt();
2513 if (Record.readInt())
2514 D->setDefaultArgument(Record.readExpr());
2518 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
2519 VisitTemplateDecl(D);
2520 // TemplateParmPosition.
2521 D->setDepth(Record.readInt());
2522 D->setPosition(Record.readInt());
2523 if (D->isExpandedParameterPack()) {
2524 auto **Data = D->getTrailingObjects<TemplateParameterList *>();
2525 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2526 I != N; ++I)
2527 Data[I] = Record.readTemplateParameterList();
2528 } else {
2529 // Rest of TemplateTemplateParmDecl.
2530 D->ParameterPack = Record.readInt();
2531 if (Record.readInt())
2532 D->setDefaultArgument(Reader.getContext(),
2533 Record.readTemplateArgumentLoc());
2537 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2538 VisitRedeclarableTemplateDecl(D);
2541 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
2542 VisitDecl(D);
2543 D->AssertExprAndFailed.setPointer(Record.readExpr());
2544 D->AssertExprAndFailed.setInt(Record.readInt());
2545 D->Message = cast_or_null<StringLiteral>(Record.readExpr());
2546 D->RParenLoc = readSourceLocation();
2549 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
2550 VisitDecl(D);
2553 void ASTDeclReader::VisitLifetimeExtendedTemporaryDecl(
2554 LifetimeExtendedTemporaryDecl *D) {
2555 VisitDecl(D);
2556 D->ExtendingDecl = readDeclAs<ValueDecl>();
2557 D->ExprWithTemporary = Record.readStmt();
2558 if (Record.readInt()) {
2559 D->Value = new (D->getASTContext()) APValue(Record.readAPValue());
2560 D->getASTContext().addDestruction(D->Value);
2562 D->ManglingNumber = Record.readInt();
2563 mergeMergeable(D);
2566 std::pair<uint64_t, uint64_t>
2567 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
2568 uint64_t LexicalOffset = ReadLocalOffset();
2569 uint64_t VisibleOffset = ReadLocalOffset();
2570 return std::make_pair(LexicalOffset, VisibleOffset);
2573 template <typename T>
2574 ASTDeclReader::RedeclarableResult
2575 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
2576 DeclID FirstDeclID = readDeclID();
2577 Decl *MergeWith = nullptr;
2579 bool IsKeyDecl = ThisDeclID == FirstDeclID;
2580 bool IsFirstLocalDecl = false;
2582 uint64_t RedeclOffset = 0;
2584 // 0 indicates that this declaration was the only declaration of its entity,
2585 // and is used for space optimization.
2586 if (FirstDeclID == 0) {
2587 FirstDeclID = ThisDeclID;
2588 IsKeyDecl = true;
2589 IsFirstLocalDecl = true;
2590 } else if (unsigned N = Record.readInt()) {
2591 // This declaration was the first local declaration, but may have imported
2592 // other declarations.
2593 IsKeyDecl = N == 1;
2594 IsFirstLocalDecl = true;
2596 // We have some declarations that must be before us in our redeclaration
2597 // chain. Read them now, and remember that we ought to merge with one of
2598 // them.
2599 // FIXME: Provide a known merge target to the second and subsequent such
2600 // declaration.
2601 for (unsigned I = 0; I != N - 1; ++I)
2602 MergeWith = readDecl();
2604 RedeclOffset = ReadLocalOffset();
2605 } else {
2606 // This declaration was not the first local declaration. Read the first
2607 // local declaration now, to trigger the import of other redeclarations.
2608 (void)readDecl();
2611 auto *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
2612 if (FirstDecl != D) {
2613 // We delay loading of the redeclaration chain to avoid deeply nested calls.
2614 // We temporarily set the first (canonical) declaration as the previous one
2615 // which is the one that matters and mark the real previous DeclID to be
2616 // loaded & attached later on.
2617 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
2618 D->First = FirstDecl->getCanonicalDecl();
2621 auto *DAsT = static_cast<T *>(D);
2623 // Note that we need to load local redeclarations of this decl and build a
2624 // decl chain for them. This must happen *after* we perform the preloading
2625 // above; this ensures that the redeclaration chain is built in the correct
2626 // order.
2627 if (IsFirstLocalDecl)
2628 Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
2630 return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
2633 /// Attempts to merge the given declaration (D) with another declaration
2634 /// of the same entity.
2635 template<typename T>
2636 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
2637 RedeclarableResult &Redecl,
2638 DeclID TemplatePatternID) {
2639 // If modules are not available, there is no reason to perform this merge.
2640 if (!Reader.getContext().getLangOpts().Modules)
2641 return;
2643 // If we're not the canonical declaration, we don't need to merge.
2644 if (!DBase->isFirstDecl())
2645 return;
2647 auto *D = static_cast<T *>(DBase);
2649 if (auto *Existing = Redecl.getKnownMergeTarget())
2650 // We already know of an existing declaration we should merge with.
2651 mergeRedeclarable(D, cast<T>(Existing), Redecl, TemplatePatternID);
2652 else if (FindExistingResult ExistingRes = findExisting(D))
2653 if (T *Existing = ExistingRes)
2654 mergeRedeclarable(D, Existing, Redecl, TemplatePatternID);
2657 /// "Cast" to type T, asserting if we don't have an implicit conversion.
2658 /// We use this to put code in a template that will only be valid for certain
2659 /// instantiations.
2660 template<typename T> static T assert_cast(T t) { return t; }
2661 template<typename T> static T assert_cast(...) {
2662 llvm_unreachable("bad assert_cast");
2665 /// Merge together the pattern declarations from two template
2666 /// declarations.
2667 void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D,
2668 RedeclarableTemplateDecl *Existing,
2669 DeclID DsID, bool IsKeyDecl) {
2670 auto *DPattern = D->getTemplatedDecl();
2671 auto *ExistingPattern = Existing->getTemplatedDecl();
2672 RedeclarableResult Result(/*MergeWith*/ ExistingPattern,
2673 DPattern->getCanonicalDecl()->getGlobalID(),
2674 IsKeyDecl);
2676 if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {
2677 // Merge with any existing definition.
2678 // FIXME: This is duplicated in several places. Refactor.
2679 auto *ExistingClass =
2680 cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();
2681 if (auto *DDD = DClass->DefinitionData) {
2682 if (ExistingClass->DefinitionData) {
2683 MergeDefinitionData(ExistingClass, std::move(*DDD));
2684 } else {
2685 ExistingClass->DefinitionData = DClass->DefinitionData;
2686 // We may have skipped this before because we thought that DClass
2687 // was the canonical declaration.
2688 Reader.PendingDefinitions.insert(DClass);
2691 DClass->DefinitionData = ExistingClass->DefinitionData;
2693 return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern),
2694 Result);
2696 if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern))
2697 return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern),
2698 Result);
2699 if (auto *DVar = dyn_cast<VarDecl>(DPattern))
2700 return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result);
2701 if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern))
2702 return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern),
2703 Result);
2704 llvm_unreachable("merged an unknown kind of redeclarable template");
2707 /// Attempts to merge the given declaration (D) with another declaration
2708 /// of the same entity.
2709 template<typename T>
2710 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing,
2711 RedeclarableResult &Redecl,
2712 DeclID TemplatePatternID) {
2713 auto *D = static_cast<T *>(DBase);
2714 T *ExistingCanon = Existing->getCanonicalDecl();
2715 T *DCanon = D->getCanonicalDecl();
2716 if (ExistingCanon != DCanon) {
2717 assert(DCanon->getGlobalID() == Redecl.getFirstID() &&
2718 "already merged this declaration");
2720 // Have our redeclaration link point back at the canonical declaration
2721 // of the existing declaration, so that this declaration has the
2722 // appropriate canonical declaration.
2723 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
2724 D->First = ExistingCanon;
2725 ExistingCanon->Used |= D->Used;
2726 D->Used = false;
2728 // When we merge a namespace, update its pointer to the first namespace.
2729 // We cannot have loaded any redeclarations of this declaration yet, so
2730 // there's nothing else that needs to be updated.
2731 if (auto *Namespace = dyn_cast<NamespaceDecl>(D))
2732 Namespace->AnonOrFirstNamespaceAndInline.setPointer(
2733 assert_cast<NamespaceDecl*>(ExistingCanon));
2735 // When we merge a template, merge its pattern.
2736 if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
2737 mergeTemplatePattern(
2738 DTemplate, assert_cast<RedeclarableTemplateDecl*>(ExistingCanon),
2739 TemplatePatternID, Redecl.isKeyDecl());
2741 // If this declaration is a key declaration, make a note of that.
2742 if (Redecl.isKeyDecl())
2743 Reader.KeyDecls[ExistingCanon].push_back(Redecl.getFirstID());
2747 /// ODR-like semantics for C/ObjC allow us to merge tag types and a structural
2748 /// check in Sema guarantees the types can be merged (see C11 6.2.7/1 or C89
2749 /// 6.1.2.6/1). Although most merging is done in Sema, we need to guarantee
2750 /// that some types are mergeable during deserialization, otherwise name
2751 /// lookup fails. This is the case for EnumConstantDecl.
2752 static bool allowODRLikeMergeInC(NamedDecl *ND) {
2753 if (!ND)
2754 return false;
2755 // TODO: implement merge for other necessary decls.
2756 if (isa<EnumConstantDecl, FieldDecl, IndirectFieldDecl>(ND))
2757 return true;
2758 return false;
2761 /// Attempts to merge LifetimeExtendedTemporaryDecl with
2762 /// identical class definitions from two different modules.
2763 void ASTDeclReader::mergeMergeable(LifetimeExtendedTemporaryDecl *D) {
2764 // If modules are not available, there is no reason to perform this merge.
2765 if (!Reader.getContext().getLangOpts().Modules)
2766 return;
2768 LifetimeExtendedTemporaryDecl *LETDecl = D;
2770 LifetimeExtendedTemporaryDecl *&LookupResult =
2771 Reader.LETemporaryForMerging[std::make_pair(
2772 LETDecl->getExtendingDecl(), LETDecl->getManglingNumber())];
2773 if (LookupResult)
2774 Reader.getContext().setPrimaryMergedDecl(LETDecl,
2775 LookupResult->getCanonicalDecl());
2776 else
2777 LookupResult = LETDecl;
2780 /// Attempts to merge the given declaration (D) with another declaration
2781 /// of the same entity, for the case where the entity is not actually
2782 /// redeclarable. This happens, for instance, when merging the fields of
2783 /// identical class definitions from two different modules.
2784 template<typename T>
2785 void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
2786 // If modules are not available, there is no reason to perform this merge.
2787 if (!Reader.getContext().getLangOpts().Modules)
2788 return;
2790 // ODR-based merging is performed in C++ and in some cases (tag types) in C.
2791 // Note that C identically-named things in different translation units are
2792 // not redeclarations, but may still have compatible types, where ODR-like
2793 // semantics may apply.
2794 if (!Reader.getContext().getLangOpts().CPlusPlus &&
2795 !allowODRLikeMergeInC(dyn_cast<NamedDecl>(static_cast<T*>(D))))
2796 return;
2798 if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
2799 if (T *Existing = ExistingRes)
2800 Reader.getContext().setPrimaryMergedDecl(static_cast<T *>(D),
2801 Existing->getCanonicalDecl());
2804 void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
2805 Record.readOMPChildren(D->Data);
2806 VisitDecl(D);
2809 void ASTDeclReader::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
2810 Record.readOMPChildren(D->Data);
2811 VisitDecl(D);
2814 void ASTDeclReader::VisitOMPRequiresDecl(OMPRequiresDecl * D) {
2815 Record.readOMPChildren(D->Data);
2816 VisitDecl(D);
2819 void ASTDeclReader::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
2820 VisitValueDecl(D);
2821 D->setLocation(readSourceLocation());
2822 Expr *In = Record.readExpr();
2823 Expr *Out = Record.readExpr();
2824 D->setCombinerData(In, Out);
2825 Expr *Combiner = Record.readExpr();
2826 D->setCombiner(Combiner);
2827 Expr *Orig = Record.readExpr();
2828 Expr *Priv = Record.readExpr();
2829 D->setInitializerData(Orig, Priv);
2830 Expr *Init = Record.readExpr();
2831 auto IK = static_cast<OMPDeclareReductionDecl::InitKind>(Record.readInt());
2832 D->setInitializer(Init, IK);
2833 D->PrevDeclInScope = readDeclID();
2836 void ASTDeclReader::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
2837 Record.readOMPChildren(D->Data);
2838 VisitValueDecl(D);
2839 D->VarName = Record.readDeclarationName();
2840 D->PrevDeclInScope = readDeclID();
2843 void ASTDeclReader::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
2844 VisitVarDecl(D);
2847 //===----------------------------------------------------------------------===//
2848 // Attribute Reading
2849 //===----------------------------------------------------------------------===//
2851 namespace {
2852 class AttrReader {
2853 ASTRecordReader &Reader;
2855 public:
2856 AttrReader(ASTRecordReader &Reader) : Reader(Reader) {}
2858 uint64_t readInt() {
2859 return Reader.readInt();
2862 bool readBool() { return Reader.readBool(); }
2864 SourceRange readSourceRange() {
2865 return Reader.readSourceRange();
2868 SourceLocation readSourceLocation() {
2869 return Reader.readSourceLocation();
2872 Expr *readExpr() { return Reader.readExpr(); }
2874 std::string readString() {
2875 return Reader.readString();
2878 TypeSourceInfo *readTypeSourceInfo() {
2879 return Reader.readTypeSourceInfo();
2882 IdentifierInfo *readIdentifier() {
2883 return Reader.readIdentifier();
2886 VersionTuple readVersionTuple() {
2887 return Reader.readVersionTuple();
2890 OMPTraitInfo *readOMPTraitInfo() { return Reader.readOMPTraitInfo(); }
2892 template <typename T> T *GetLocalDeclAs(uint32_t LocalID) {
2893 return Reader.GetLocalDeclAs<T>(LocalID);
2898 Attr *ASTRecordReader::readAttr() {
2899 AttrReader Record(*this);
2900 auto V = Record.readInt();
2901 if (!V)
2902 return nullptr;
2904 Attr *New = nullptr;
2905 // Kind is stored as a 1-based integer because 0 is used to indicate a null
2906 // Attr pointer.
2907 auto Kind = static_cast<attr::Kind>(V - 1);
2908 ASTContext &Context = getContext();
2910 IdentifierInfo *AttrName = Record.readIdentifier();
2911 IdentifierInfo *ScopeName = Record.readIdentifier();
2912 SourceRange AttrRange = Record.readSourceRange();
2913 SourceLocation ScopeLoc = Record.readSourceLocation();
2914 unsigned ParsedKind = Record.readInt();
2915 unsigned Syntax = Record.readInt();
2916 unsigned SpellingIndex = Record.readInt();
2918 AttributeCommonInfo Info(AttrName, ScopeName, AttrRange, ScopeLoc,
2919 AttributeCommonInfo::Kind(ParsedKind),
2920 AttributeCommonInfo::Syntax(Syntax), SpellingIndex);
2922 #include "clang/Serialization/AttrPCHRead.inc"
2924 assert(New && "Unable to decode attribute?");
2925 return New;
2928 /// Reads attributes from the current stream position.
2929 void ASTRecordReader::readAttributes(AttrVec &Attrs) {
2930 for (unsigned I = 0, E = readInt(); I != E; ++I)
2931 if (auto *A = readAttr())
2932 Attrs.push_back(A);
2935 //===----------------------------------------------------------------------===//
2936 // ASTReader Implementation
2937 //===----------------------------------------------------------------------===//
2939 /// Note that we have loaded the declaration with the given
2940 /// Index.
2942 /// This routine notes that this declaration has already been loaded,
2943 /// so that future GetDecl calls will return this declaration rather
2944 /// than trying to load a new declaration.
2945 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
2946 assert(!DeclsLoaded[Index] && "Decl loaded twice?");
2947 DeclsLoaded[Index] = D;
2950 /// Determine whether the consumer will be interested in seeing
2951 /// this declaration (via HandleTopLevelDecl).
2953 /// This routine should return true for anything that might affect
2954 /// code generation, e.g., inline function definitions, Objective-C
2955 /// declarations with metadata, etc.
2956 static bool isConsumerInterestedIn(ASTContext &Ctx, Decl *D, bool HasBody) {
2957 // An ObjCMethodDecl is never considered as "interesting" because its
2958 // implementation container always is.
2960 // An ImportDecl or VarDecl imported from a module map module will get
2961 // emitted when we import the relevant module.
2962 if (isPartOfPerModuleInitializer(D)) {
2963 auto *M = D->getImportedOwningModule();
2964 if (M && M->Kind == Module::ModuleMapModule &&
2965 Ctx.DeclMustBeEmitted(D))
2966 return false;
2969 if (isa<FileScopeAsmDecl>(D) ||
2970 isa<ObjCProtocolDecl>(D) ||
2971 isa<ObjCImplDecl>(D) ||
2972 isa<ImportDecl>(D) ||
2973 isa<PragmaCommentDecl>(D) ||
2974 isa<PragmaDetectMismatchDecl>(D))
2975 return true;
2976 if (isa<OMPThreadPrivateDecl>(D) || isa<OMPDeclareReductionDecl>(D) ||
2977 isa<OMPDeclareMapperDecl>(D) || isa<OMPAllocateDecl>(D) ||
2978 isa<OMPRequiresDecl>(D))
2979 return !D->getDeclContext()->isFunctionOrMethod();
2980 if (const auto *Var = dyn_cast<VarDecl>(D))
2981 return Var->isFileVarDecl() &&
2982 (Var->isThisDeclarationADefinition() == VarDecl::Definition ||
2983 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Var));
2984 if (const auto *Func = dyn_cast<FunctionDecl>(D))
2985 return Func->doesThisDeclarationHaveABody() || HasBody;
2987 if (auto *ES = D->getASTContext().getExternalSource())
2988 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
2989 return true;
2991 return false;
2994 /// Get the correct cursor and offset for loading a declaration.
2995 ASTReader::RecordLocation
2996 ASTReader::DeclCursorForID(DeclID ID, SourceLocation &Loc) {
2997 GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
2998 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
2999 ModuleFile *M = I->second;
3000 const DeclOffset &DOffs =
3001 M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
3002 Loc = TranslateSourceLocation(*M, DOffs.getLocation());
3003 return RecordLocation(M, DOffs.getBitOffset(M->DeclsBlockStartOffset));
3006 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
3007 auto I = GlobalBitOffsetsMap.find(GlobalOffset);
3009 assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
3010 return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
3013 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint64_t LocalOffset) {
3014 return LocalOffset + M.GlobalBitOffset;
3017 /// Find the context in which we should search for previous declarations when
3018 /// looking for declarations to merge.
3019 DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
3020 DeclContext *DC) {
3021 if (auto *ND = dyn_cast<NamespaceDecl>(DC))
3022 return ND->getOriginalNamespace();
3024 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
3025 // Try to dig out the definition.
3026 auto *DD = RD->DefinitionData;
3027 if (!DD)
3028 DD = RD->getCanonicalDecl()->DefinitionData;
3030 // If there's no definition yet, then DC's definition is added by an update
3031 // record, but we've not yet loaded that update record. In this case, we
3032 // commit to DC being the canonical definition now, and will fix this when
3033 // we load the update record.
3034 if (!DD) {
3035 DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);
3036 RD->setCompleteDefinition(true);
3037 RD->DefinitionData = DD;
3038 RD->getCanonicalDecl()->DefinitionData = DD;
3040 // Track that we did this horrible thing so that we can fix it later.
3041 Reader.PendingFakeDefinitionData.insert(
3042 std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
3045 return DD->Definition;
3048 if (auto *RD = dyn_cast<RecordDecl>(DC))
3049 return RD->getDefinition();
3051 if (auto *ED = dyn_cast<EnumDecl>(DC))
3052 return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
3053 : nullptr;
3055 if (auto *OID = dyn_cast<ObjCInterfaceDecl>(DC))
3056 return OID->getDefinition();
3058 // We can see the TU here only if we have no Sema object. In that case,
3059 // there's no TU scope to look in, so using the DC alone is sufficient.
3060 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
3061 return TU;
3063 return nullptr;
3066 ASTDeclReader::FindExistingResult::~FindExistingResult() {
3067 // Record that we had a typedef name for linkage whether or not we merge
3068 // with that declaration.
3069 if (TypedefNameForLinkage) {
3070 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3071 Reader.ImportedTypedefNamesForLinkage.insert(
3072 std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
3073 return;
3076 if (!AddResult || Existing)
3077 return;
3079 DeclarationName Name = New->getDeclName();
3080 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3081 if (needsAnonymousDeclarationNumber(New)) {
3082 setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
3083 AnonymousDeclNumber, New);
3084 } else if (DC->isTranslationUnit() &&
3085 !Reader.getContext().getLangOpts().CPlusPlus) {
3086 if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name))
3087 Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
3088 .push_back(New);
3089 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3090 // Add the declaration to its redeclaration context so later merging
3091 // lookups will find it.
3092 MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
3096 /// Find the declaration that should be merged into, given the declaration found
3097 /// by name lookup. If we're merging an anonymous declaration within a typedef,
3098 /// we need a matching typedef, and we merge with the type inside it.
3099 static NamedDecl *getDeclForMerging(NamedDecl *Found,
3100 bool IsTypedefNameForLinkage) {
3101 if (!IsTypedefNameForLinkage)
3102 return Found;
3104 // If we found a typedef declaration that gives a name to some other
3105 // declaration, then we want that inner declaration. Declarations from
3106 // AST files are handled via ImportedTypedefNamesForLinkage.
3107 if (Found->isFromASTFile())
3108 return nullptr;
3110 if (auto *TND = dyn_cast<TypedefNameDecl>(Found))
3111 return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
3113 return nullptr;
3116 /// Find the declaration to use to populate the anonymous declaration table
3117 /// for the given lexical DeclContext. We only care about finding local
3118 /// definitions of the context; we'll merge imported ones as we go.
3119 DeclContext *
3120 ASTDeclReader::getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC) {
3121 // For classes, we track the definition as we merge.
3122 if (auto *RD = dyn_cast<CXXRecordDecl>(LexicalDC)) {
3123 auto *DD = RD->getCanonicalDecl()->DefinitionData;
3124 return DD ? DD->Definition : nullptr;
3125 } else if (auto *OID = dyn_cast<ObjCInterfaceDecl>(LexicalDC)) {
3126 return OID->getCanonicalDecl()->getDefinition();
3129 // For anything else, walk its merged redeclarations looking for a definition.
3130 // Note that we can't just call getDefinition here because the redeclaration
3131 // chain isn't wired up.
3132 for (auto *D : merged_redecls(cast<Decl>(LexicalDC))) {
3133 if (auto *FD = dyn_cast<FunctionDecl>(D))
3134 if (FD->isThisDeclarationADefinition())
3135 return FD;
3136 if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
3137 if (MD->isThisDeclarationADefinition())
3138 return MD;
3139 if (auto *RD = dyn_cast<RecordDecl>(D))
3140 if (RD->isThisDeclarationADefinition())
3141 return RD;
3144 // No merged definition yet.
3145 return nullptr;
3148 NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
3149 DeclContext *DC,
3150 unsigned Index) {
3151 // If the lexical context has been merged, look into the now-canonical
3152 // definition.
3153 auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3155 // If we've seen this before, return the canonical declaration.
3156 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3157 if (Index < Previous.size() && Previous[Index])
3158 return Previous[Index];
3160 // If this is the first time, but we have parsed a declaration of the context,
3161 // build the anonymous declaration list from the parsed declaration.
3162 auto *PrimaryDC = getPrimaryDCForAnonymousDecl(DC);
3163 if (PrimaryDC && !cast<Decl>(PrimaryDC)->isFromASTFile()) {
3164 numberAnonymousDeclsWithin(PrimaryDC, [&](NamedDecl *ND, unsigned Number) {
3165 if (Previous.size() == Number)
3166 Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
3167 else
3168 Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());
3172 return Index < Previous.size() ? Previous[Index] : nullptr;
3175 void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
3176 DeclContext *DC, unsigned Index,
3177 NamedDecl *D) {
3178 auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3180 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3181 if (Index >= Previous.size())
3182 Previous.resize(Index + 1);
3183 if (!Previous[Index])
3184 Previous[Index] = D;
3187 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
3188 DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
3189 : D->getDeclName();
3191 if (!Name && !needsAnonymousDeclarationNumber(D)) {
3192 // Don't bother trying to find unnamed declarations that are in
3193 // unmergeable contexts.
3194 FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
3195 AnonymousDeclNumber, TypedefNameForLinkage);
3196 Result.suppress();
3197 return Result;
3200 ASTContext &C = Reader.getContext();
3201 DeclContext *DC = D->getDeclContext()->getRedeclContext();
3202 if (TypedefNameForLinkage) {
3203 auto It = Reader.ImportedTypedefNamesForLinkage.find(
3204 std::make_pair(DC, TypedefNameForLinkage));
3205 if (It != Reader.ImportedTypedefNamesForLinkage.end())
3206 if (C.isSameEntity(It->second, D))
3207 return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
3208 TypedefNameForLinkage);
3209 // Go on to check in other places in case an existing typedef name
3210 // was not imported.
3213 if (needsAnonymousDeclarationNumber(D)) {
3214 // This is an anonymous declaration that we may need to merge. Look it up
3215 // in its context by number.
3216 if (auto *Existing = getAnonymousDeclForMerging(
3217 Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
3218 if (C.isSameEntity(Existing, D))
3219 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3220 TypedefNameForLinkage);
3221 } else if (DC->isTranslationUnit() &&
3222 !Reader.getContext().getLangOpts().CPlusPlus) {
3223 IdentifierResolver &IdResolver = Reader.getIdResolver();
3225 // Temporarily consider the identifier to be up-to-date. We don't want to
3226 // cause additional lookups here.
3227 class UpToDateIdentifierRAII {
3228 IdentifierInfo *II;
3229 bool WasOutToDate = false;
3231 public:
3232 explicit UpToDateIdentifierRAII(IdentifierInfo *II) : II(II) {
3233 if (II) {
3234 WasOutToDate = II->isOutOfDate();
3235 if (WasOutToDate)
3236 II->setOutOfDate(false);
3240 ~UpToDateIdentifierRAII() {
3241 if (WasOutToDate)
3242 II->setOutOfDate(true);
3244 } UpToDate(Name.getAsIdentifierInfo());
3246 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
3247 IEnd = IdResolver.end();
3248 I != IEnd; ++I) {
3249 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3250 if (C.isSameEntity(Existing, D))
3251 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3252 TypedefNameForLinkage);
3254 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3255 DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
3256 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
3257 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3258 if (C.isSameEntity(Existing, D))
3259 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3260 TypedefNameForLinkage);
3262 } else {
3263 // Not in a mergeable context.
3264 return FindExistingResult(Reader);
3267 // If this declaration is from a merged context, make a note that we need to
3268 // check that the canonical definition of that context contains the decl.
3270 // FIXME: We should do something similar if we merge two definitions of the
3271 // same template specialization into the same CXXRecordDecl.
3272 auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
3273 if (MergedDCIt != Reader.MergedDeclContexts.end() &&
3274 MergedDCIt->second == D->getDeclContext())
3275 Reader.PendingOdrMergeChecks.push_back(D);
3277 return FindExistingResult(Reader, D, /*Existing=*/nullptr,
3278 AnonymousDeclNumber, TypedefNameForLinkage);
3281 template<typename DeclT>
3282 Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
3283 return D->RedeclLink.getLatestNotUpdated();
3286 Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
3287 llvm_unreachable("getMostRecentDecl on non-redeclarable declaration");
3290 Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
3291 assert(D);
3293 switch (D->getKind()) {
3294 #define ABSTRACT_DECL(TYPE)
3295 #define DECL(TYPE, BASE) \
3296 case Decl::TYPE: \
3297 return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
3298 #include "clang/AST/DeclNodes.inc"
3300 llvm_unreachable("unknown decl kind");
3303 Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
3304 return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());
3307 void ASTDeclReader::mergeInheritableAttributes(ASTReader &Reader, Decl *D,
3308 Decl *Previous) {
3309 InheritableAttr *NewAttr = nullptr;
3310 ASTContext &Context = Reader.getContext();
3311 const auto *IA = Previous->getAttr<MSInheritanceAttr>();
3313 if (IA && !D->hasAttr<MSInheritanceAttr>()) {
3314 NewAttr = cast<InheritableAttr>(IA->clone(Context));
3315 NewAttr->setInherited(true);
3316 D->addAttr(NewAttr);
3319 const auto *AA = Previous->getAttr<AvailabilityAttr>();
3320 if (AA && !D->hasAttr<AvailabilityAttr>()) {
3321 NewAttr = AA->clone(Context);
3322 NewAttr->setInherited(true);
3323 D->addAttr(NewAttr);
3327 template<typename DeclT>
3328 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3329 Redeclarable<DeclT> *D,
3330 Decl *Previous, Decl *Canon) {
3331 D->RedeclLink.setPrevious(cast<DeclT>(Previous));
3332 D->First = cast<DeclT>(Previous)->First;
3335 namespace clang {
3337 template<>
3338 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3339 Redeclarable<VarDecl> *D,
3340 Decl *Previous, Decl *Canon) {
3341 auto *VD = static_cast<VarDecl *>(D);
3342 auto *PrevVD = cast<VarDecl>(Previous);
3343 D->RedeclLink.setPrevious(PrevVD);
3344 D->First = PrevVD->First;
3346 // We should keep at most one definition on the chain.
3347 // FIXME: Cache the definition once we've found it. Building a chain with
3348 // N definitions currently takes O(N^2) time here.
3349 if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {
3350 for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {
3351 if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {
3352 Reader.mergeDefinitionVisibility(CurD, VD);
3353 VD->demoteThisDefinitionToDeclaration();
3354 break;
3360 static bool isUndeducedReturnType(QualType T) {
3361 auto *DT = T->getContainedDeducedType();
3362 return DT && !DT->isDeduced();
3365 template<>
3366 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3367 Redeclarable<FunctionDecl> *D,
3368 Decl *Previous, Decl *Canon) {
3369 auto *FD = static_cast<FunctionDecl *>(D);
3370 auto *PrevFD = cast<FunctionDecl>(Previous);
3372 FD->RedeclLink.setPrevious(PrevFD);
3373 FD->First = PrevFD->First;
3375 // If the previous declaration is an inline function declaration, then this
3376 // declaration is too.
3377 if (PrevFD->isInlined() != FD->isInlined()) {
3378 // FIXME: [dcl.fct.spec]p4:
3379 // If a function with external linkage is declared inline in one
3380 // translation unit, it shall be declared inline in all translation
3381 // units in which it appears.
3383 // Be careful of this case:
3385 // module A:
3386 // template<typename T> struct X { void f(); };
3387 // template<typename T> inline void X<T>::f() {}
3389 // module B instantiates the declaration of X<int>::f
3390 // module C instantiates the definition of X<int>::f
3392 // If module B and C are merged, we do not have a violation of this rule.
3393 FD->setImplicitlyInline(true);
3396 auto *FPT = FD->getType()->getAs<FunctionProtoType>();
3397 auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
3398 if (FPT && PrevFPT) {
3399 // If we need to propagate an exception specification along the redecl
3400 // chain, make a note of that so that we can do so later.
3401 bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType());
3402 bool WasUnresolved =
3403 isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType());
3404 if (IsUnresolved != WasUnresolved)
3405 Reader.PendingExceptionSpecUpdates.insert(
3406 {Canon, IsUnresolved ? PrevFD : FD});
3408 // If we need to propagate a deduced return type along the redecl chain,
3409 // make a note of that so that we can do it later.
3410 bool IsUndeduced = isUndeducedReturnType(FPT->getReturnType());
3411 bool WasUndeduced = isUndeducedReturnType(PrevFPT->getReturnType());
3412 if (IsUndeduced != WasUndeduced)
3413 Reader.PendingDeducedTypeUpdates.insert(
3414 {cast<FunctionDecl>(Canon),
3415 (IsUndeduced ? PrevFPT : FPT)->getReturnType()});
3419 } // namespace clang
3421 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
3422 llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
3425 /// Inherit the default template argument from \p From to \p To. Returns
3426 /// \c false if there is no default template for \p From.
3427 template <typename ParmDecl>
3428 static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,
3429 Decl *ToD) {
3430 auto *To = cast<ParmDecl>(ToD);
3431 if (!From->hasDefaultArgument())
3432 return false;
3433 To->setInheritedDefaultArgument(Context, From);
3434 return true;
3437 static void inheritDefaultTemplateArguments(ASTContext &Context,
3438 TemplateDecl *From,
3439 TemplateDecl *To) {
3440 auto *FromTP = From->getTemplateParameters();
3441 auto *ToTP = To->getTemplateParameters();
3442 assert(FromTP->size() == ToTP->size() && "merged mismatched templates?");
3444 for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {
3445 NamedDecl *FromParam = FromTP->getParam(I);
3446 NamedDecl *ToParam = ToTP->getParam(I);
3448 if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam))
3449 inheritDefaultTemplateArgument(Context, FTTP, ToParam);
3450 else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam))
3451 inheritDefaultTemplateArgument(Context, FNTTP, ToParam);
3452 else
3453 inheritDefaultTemplateArgument(
3454 Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam);
3458 void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
3459 Decl *Previous, Decl *Canon) {
3460 assert(D && Previous);
3462 switch (D->getKind()) {
3463 #define ABSTRACT_DECL(TYPE)
3464 #define DECL(TYPE, BASE) \
3465 case Decl::TYPE: \
3466 attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
3467 break;
3468 #include "clang/AST/DeclNodes.inc"
3471 // If the declaration was visible in one module, a redeclaration of it in
3472 // another module remains visible even if it wouldn't be visible by itself.
3474 // FIXME: In this case, the declaration should only be visible if a module
3475 // that makes it visible has been imported.
3476 D->IdentifierNamespace |=
3477 Previous->IdentifierNamespace &
3478 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3480 // If the declaration declares a template, it may inherit default arguments
3481 // from the previous declaration.
3482 if (auto *TD = dyn_cast<TemplateDecl>(D))
3483 inheritDefaultTemplateArguments(Reader.getContext(),
3484 cast<TemplateDecl>(Previous), TD);
3486 // If any of the declaration in the chain contains an Inheritable attribute,
3487 // it needs to be added to all the declarations in the redeclarable chain.
3488 // FIXME: Only the logic of merging MSInheritableAttr is present, it should
3489 // be extended for all inheritable attributes.
3490 mergeInheritableAttributes(Reader, D, Previous);
3493 template<typename DeclT>
3494 void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
3495 D->RedeclLink.setLatest(cast<DeclT>(Latest));
3498 void ASTDeclReader::attachLatestDeclImpl(...) {
3499 llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
3502 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
3503 assert(D && Latest);
3505 switch (D->getKind()) {
3506 #define ABSTRACT_DECL(TYPE)
3507 #define DECL(TYPE, BASE) \
3508 case Decl::TYPE: \
3509 attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
3510 break;
3511 #include "clang/AST/DeclNodes.inc"
3515 template<typename DeclT>
3516 void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
3517 D->RedeclLink.markIncomplete();
3520 void ASTDeclReader::markIncompleteDeclChainImpl(...) {
3521 llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
3524 void ASTReader::markIncompleteDeclChain(Decl *D) {
3525 switch (D->getKind()) {
3526 #define ABSTRACT_DECL(TYPE)
3527 #define DECL(TYPE, BASE) \
3528 case Decl::TYPE: \
3529 ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
3530 break;
3531 #include "clang/AST/DeclNodes.inc"
3535 /// Read the declaration at the given offset from the AST file.
3536 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
3537 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
3538 SourceLocation DeclLoc;
3539 RecordLocation Loc = DeclCursorForID(ID, DeclLoc);
3540 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3541 // Keep track of where we are in the stream, then jump back there
3542 // after reading this declaration.
3543 SavedStreamPosition SavedPosition(DeclsCursor);
3545 ReadingKindTracker ReadingKind(Read_Decl, *this);
3547 // Note that we are loading a declaration record.
3548 Deserializing ADecl(this);
3550 auto Fail = [](const char *what, llvm::Error &&Err) {
3551 llvm::report_fatal_error(Twine("ASTReader::readDeclRecord failed ") + what +
3552 ": " + toString(std::move(Err)));
3555 if (llvm::Error JumpFailed = DeclsCursor.JumpToBit(Loc.Offset))
3556 Fail("jumping", std::move(JumpFailed));
3557 ASTRecordReader Record(*this, *Loc.F);
3558 ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);
3559 Expected<unsigned> MaybeCode = DeclsCursor.ReadCode();
3560 if (!MaybeCode)
3561 Fail("reading code", MaybeCode.takeError());
3562 unsigned Code = MaybeCode.get();
3564 ASTContext &Context = getContext();
3565 Decl *D = nullptr;
3566 Expected<unsigned> MaybeDeclCode = Record.readRecord(DeclsCursor, Code);
3567 if (!MaybeDeclCode)
3568 llvm::report_fatal_error(
3569 Twine("ASTReader::readDeclRecord failed reading decl code: ") +
3570 toString(MaybeDeclCode.takeError()));
3571 switch ((DeclCode)MaybeDeclCode.get()) {
3572 case DECL_CONTEXT_LEXICAL:
3573 case DECL_CONTEXT_VISIBLE:
3574 llvm_unreachable("Record cannot be de-serialized with readDeclRecord");
3575 case DECL_TYPEDEF:
3576 D = TypedefDecl::CreateDeserialized(Context, ID);
3577 break;
3578 case DECL_TYPEALIAS:
3579 D = TypeAliasDecl::CreateDeserialized(Context, ID);
3580 break;
3581 case DECL_ENUM:
3582 D = EnumDecl::CreateDeserialized(Context, ID);
3583 break;
3584 case DECL_RECORD:
3585 D = RecordDecl::CreateDeserialized(Context, ID);
3586 break;
3587 case DECL_ENUM_CONSTANT:
3588 D = EnumConstantDecl::CreateDeserialized(Context, ID);
3589 break;
3590 case DECL_FUNCTION:
3591 D = FunctionDecl::CreateDeserialized(Context, ID);
3592 break;
3593 case DECL_LINKAGE_SPEC:
3594 D = LinkageSpecDecl::CreateDeserialized(Context, ID);
3595 break;
3596 case DECL_EXPORT:
3597 D = ExportDecl::CreateDeserialized(Context, ID);
3598 break;
3599 case DECL_LABEL:
3600 D = LabelDecl::CreateDeserialized(Context, ID);
3601 break;
3602 case DECL_NAMESPACE:
3603 D = NamespaceDecl::CreateDeserialized(Context, ID);
3604 break;
3605 case DECL_NAMESPACE_ALIAS:
3606 D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
3607 break;
3608 case DECL_USING:
3609 D = UsingDecl::CreateDeserialized(Context, ID);
3610 break;
3611 case DECL_USING_PACK:
3612 D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt());
3613 break;
3614 case DECL_USING_SHADOW:
3615 D = UsingShadowDecl::CreateDeserialized(Context, ID);
3616 break;
3617 case DECL_USING_ENUM:
3618 D = UsingEnumDecl::CreateDeserialized(Context, ID);
3619 break;
3620 case DECL_CONSTRUCTOR_USING_SHADOW:
3621 D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID);
3622 break;
3623 case DECL_USING_DIRECTIVE:
3624 D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
3625 break;
3626 case DECL_UNRESOLVED_USING_VALUE:
3627 D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
3628 break;
3629 case DECL_UNRESOLVED_USING_TYPENAME:
3630 D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
3631 break;
3632 case DECL_UNRESOLVED_USING_IF_EXISTS:
3633 D = UnresolvedUsingIfExistsDecl::CreateDeserialized(Context, ID);
3634 break;
3635 case DECL_CXX_RECORD:
3636 D = CXXRecordDecl::CreateDeserialized(Context, ID);
3637 break;
3638 case DECL_CXX_DEDUCTION_GUIDE:
3639 D = CXXDeductionGuideDecl::CreateDeserialized(Context, ID);
3640 break;
3641 case DECL_CXX_METHOD:
3642 D = CXXMethodDecl::CreateDeserialized(Context, ID);
3643 break;
3644 case DECL_CXX_CONSTRUCTOR:
3645 D = CXXConstructorDecl::CreateDeserialized(Context, ID, Record.readInt());
3646 break;
3647 case DECL_CXX_DESTRUCTOR:
3648 D = CXXDestructorDecl::CreateDeserialized(Context, ID);
3649 break;
3650 case DECL_CXX_CONVERSION:
3651 D = CXXConversionDecl::CreateDeserialized(Context, ID);
3652 break;
3653 case DECL_ACCESS_SPEC:
3654 D = AccessSpecDecl::CreateDeserialized(Context, ID);
3655 break;
3656 case DECL_FRIEND:
3657 D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt());
3658 break;
3659 case DECL_FRIEND_TEMPLATE:
3660 D = FriendTemplateDecl::CreateDeserialized(Context, ID);
3661 break;
3662 case DECL_CLASS_TEMPLATE:
3663 D = ClassTemplateDecl::CreateDeserialized(Context, ID);
3664 break;
3665 case DECL_CLASS_TEMPLATE_SPECIALIZATION:
3666 D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3667 break;
3668 case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
3669 D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3670 break;
3671 case DECL_VAR_TEMPLATE:
3672 D = VarTemplateDecl::CreateDeserialized(Context, ID);
3673 break;
3674 case DECL_VAR_TEMPLATE_SPECIALIZATION:
3675 D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3676 break;
3677 case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
3678 D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3679 break;
3680 case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
3681 D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
3682 break;
3683 case DECL_FUNCTION_TEMPLATE:
3684 D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
3685 break;
3686 case DECL_TEMPLATE_TYPE_PARM: {
3687 bool HasTypeConstraint = Record.readInt();
3688 D = TemplateTypeParmDecl::CreateDeserialized(Context, ID,
3689 HasTypeConstraint);
3690 break;
3692 case DECL_NON_TYPE_TEMPLATE_PARM: {
3693 bool HasTypeConstraint = Record.readInt();
3694 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3695 HasTypeConstraint);
3696 break;
3698 case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK: {
3699 bool HasTypeConstraint = Record.readInt();
3700 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3701 Record.readInt(),
3702 HasTypeConstraint);
3703 break;
3705 case DECL_TEMPLATE_TEMPLATE_PARM:
3706 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
3707 break;
3708 case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
3709 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
3710 Record.readInt());
3711 break;
3712 case DECL_TYPE_ALIAS_TEMPLATE:
3713 D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
3714 break;
3715 case DECL_CONCEPT:
3716 D = ConceptDecl::CreateDeserialized(Context, ID);
3717 break;
3718 case DECL_REQUIRES_EXPR_BODY:
3719 D = RequiresExprBodyDecl::CreateDeserialized(Context, ID);
3720 break;
3721 case DECL_STATIC_ASSERT:
3722 D = StaticAssertDecl::CreateDeserialized(Context, ID);
3723 break;
3724 case DECL_OBJC_METHOD:
3725 D = ObjCMethodDecl::CreateDeserialized(Context, ID);
3726 break;
3727 case DECL_OBJC_INTERFACE:
3728 D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
3729 break;
3730 case DECL_OBJC_IVAR:
3731 D = ObjCIvarDecl::CreateDeserialized(Context, ID);
3732 break;
3733 case DECL_OBJC_PROTOCOL:
3734 D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
3735 break;
3736 case DECL_OBJC_AT_DEFS_FIELD:
3737 D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
3738 break;
3739 case DECL_OBJC_CATEGORY:
3740 D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
3741 break;
3742 case DECL_OBJC_CATEGORY_IMPL:
3743 D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
3744 break;
3745 case DECL_OBJC_IMPLEMENTATION:
3746 D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
3747 break;
3748 case DECL_OBJC_COMPATIBLE_ALIAS:
3749 D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
3750 break;
3751 case DECL_OBJC_PROPERTY:
3752 D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
3753 break;
3754 case DECL_OBJC_PROPERTY_IMPL:
3755 D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
3756 break;
3757 case DECL_FIELD:
3758 D = FieldDecl::CreateDeserialized(Context, ID);
3759 break;
3760 case DECL_INDIRECTFIELD:
3761 D = IndirectFieldDecl::CreateDeserialized(Context, ID);
3762 break;
3763 case DECL_VAR:
3764 D = VarDecl::CreateDeserialized(Context, ID);
3765 break;
3766 case DECL_IMPLICIT_PARAM:
3767 D = ImplicitParamDecl::CreateDeserialized(Context, ID);
3768 break;
3769 case DECL_PARM_VAR:
3770 D = ParmVarDecl::CreateDeserialized(Context, ID);
3771 break;
3772 case DECL_DECOMPOSITION:
3773 D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt());
3774 break;
3775 case DECL_BINDING:
3776 D = BindingDecl::CreateDeserialized(Context, ID);
3777 break;
3778 case DECL_FILE_SCOPE_ASM:
3779 D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
3780 break;
3781 case DECL_BLOCK:
3782 D = BlockDecl::CreateDeserialized(Context, ID);
3783 break;
3784 case DECL_MS_PROPERTY:
3785 D = MSPropertyDecl::CreateDeserialized(Context, ID);
3786 break;
3787 case DECL_MS_GUID:
3788 D = MSGuidDecl::CreateDeserialized(Context, ID);
3789 break;
3790 case DECL_UNNAMED_GLOBAL_CONSTANT:
3791 D = UnnamedGlobalConstantDecl::CreateDeserialized(Context, ID);
3792 break;
3793 case DECL_TEMPLATE_PARAM_OBJECT:
3794 D = TemplateParamObjectDecl::CreateDeserialized(Context, ID);
3795 break;
3796 case DECL_CAPTURED:
3797 D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt());
3798 break;
3799 case DECL_CXX_BASE_SPECIFIERS:
3800 Error("attempt to read a C++ base-specifier record as a declaration");
3801 return nullptr;
3802 case DECL_CXX_CTOR_INITIALIZERS:
3803 Error("attempt to read a C++ ctor initializer record as a declaration");
3804 return nullptr;
3805 case DECL_IMPORT:
3806 // Note: last entry of the ImportDecl record is the number of stored source
3807 // locations.
3808 D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
3809 break;
3810 case DECL_OMP_THREADPRIVATE: {
3811 Record.skipInts(1);
3812 unsigned NumChildren = Record.readInt();
3813 Record.skipInts(1);
3814 D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, NumChildren);
3815 break;
3817 case DECL_OMP_ALLOCATE: {
3818 unsigned NumClauses = Record.readInt();
3819 unsigned NumVars = Record.readInt();
3820 Record.skipInts(1);
3821 D = OMPAllocateDecl::CreateDeserialized(Context, ID, NumVars, NumClauses);
3822 break;
3824 case DECL_OMP_REQUIRES: {
3825 unsigned NumClauses = Record.readInt();
3826 Record.skipInts(2);
3827 D = OMPRequiresDecl::CreateDeserialized(Context, ID, NumClauses);
3828 break;
3830 case DECL_OMP_DECLARE_REDUCTION:
3831 D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID);
3832 break;
3833 case DECL_OMP_DECLARE_MAPPER: {
3834 unsigned NumClauses = Record.readInt();
3835 Record.skipInts(2);
3836 D = OMPDeclareMapperDecl::CreateDeserialized(Context, ID, NumClauses);
3837 break;
3839 case DECL_OMP_CAPTUREDEXPR:
3840 D = OMPCapturedExprDecl::CreateDeserialized(Context, ID);
3841 break;
3842 case DECL_PRAGMA_COMMENT:
3843 D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt());
3844 break;
3845 case DECL_PRAGMA_DETECT_MISMATCH:
3846 D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID,
3847 Record.readInt());
3848 break;
3849 case DECL_EMPTY:
3850 D = EmptyDecl::CreateDeserialized(Context, ID);
3851 break;
3852 case DECL_LIFETIME_EXTENDED_TEMPORARY:
3853 D = LifetimeExtendedTemporaryDecl::CreateDeserialized(Context, ID);
3854 break;
3855 case DECL_OBJC_TYPE_PARAM:
3856 D = ObjCTypeParamDecl::CreateDeserialized(Context, ID);
3857 break;
3860 assert(D && "Unknown declaration reading AST file");
3861 LoadedDecl(Index, D);
3862 // Set the DeclContext before doing any deserialization, to make sure internal
3863 // calls to Decl::getASTContext() by Decl's methods will find the
3864 // TranslationUnitDecl without crashing.
3865 D->setDeclContext(Context.getTranslationUnitDecl());
3866 Reader.Visit(D);
3868 // If this declaration is also a declaration context, get the
3869 // offsets for its tables of lexical and visible declarations.
3870 if (auto *DC = dyn_cast<DeclContext>(D)) {
3871 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
3872 if (Offsets.first &&
3873 ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC))
3874 return nullptr;
3875 if (Offsets.second &&
3876 ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID))
3877 return nullptr;
3879 assert(Record.getIdx() == Record.size());
3881 // Load any relevant update records.
3882 PendingUpdateRecords.push_back(
3883 PendingUpdateRecord(ID, D, /*JustLoaded=*/true));
3885 // Load the categories after recursive loading is finished.
3886 if (auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
3887 // If we already have a definition when deserializing the ObjCInterfaceDecl,
3888 // we put the Decl in PendingDefinitions so we can pull the categories here.
3889 if (Class->isThisDeclarationADefinition() ||
3890 PendingDefinitions.count(Class))
3891 loadObjCCategories(ID, Class);
3893 // If we have deserialized a declaration that has a definition the
3894 // AST consumer might need to know about, queue it.
3895 // We don't pass it to the consumer immediately because we may be in recursive
3896 // loading, and some declarations may still be initializing.
3897 PotentiallyInterestingDecls.push_back(
3898 InterestingDecl(D, Reader.hasPendingBody()));
3900 return D;
3903 void ASTReader::PassInterestingDeclsToConsumer() {
3904 assert(Consumer);
3906 if (PassingDeclsToConsumer)
3907 return;
3909 // Guard variable to avoid recursively redoing the process of passing
3910 // decls to consumer.
3911 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
3912 true);
3914 // Ensure that we've loaded all potentially-interesting declarations
3915 // that need to be eagerly loaded.
3916 for (auto ID : EagerlyDeserializedDecls)
3917 GetDecl(ID);
3918 EagerlyDeserializedDecls.clear();
3920 while (!PotentiallyInterestingDecls.empty()) {
3921 InterestingDecl D = PotentiallyInterestingDecls.front();
3922 PotentiallyInterestingDecls.pop_front();
3923 if (isConsumerInterestedIn(getContext(), D.getDecl(), D.hasPendingBody()))
3924 PassInterestingDeclToConsumer(D.getDecl());
3928 void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {
3929 // The declaration may have been modified by files later in the chain.
3930 // If this is the case, read the record containing the updates from each file
3931 // and pass it to ASTDeclReader to make the modifications.
3932 serialization::GlobalDeclID ID = Record.ID;
3933 Decl *D = Record.D;
3934 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
3935 DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
3937 SmallVector<serialization::DeclID, 8> PendingLazySpecializationIDs;
3939 if (UpdI != DeclUpdateOffsets.end()) {
3940 auto UpdateOffsets = std::move(UpdI->second);
3941 DeclUpdateOffsets.erase(UpdI);
3943 // Check if this decl was interesting to the consumer. If we just loaded
3944 // the declaration, then we know it was interesting and we skip the call
3945 // to isConsumerInterestedIn because it is unsafe to call in the
3946 // current ASTReader state.
3947 bool WasInteresting =
3948 Record.JustLoaded || isConsumerInterestedIn(getContext(), D, false);
3949 for (auto &FileAndOffset : UpdateOffsets) {
3950 ModuleFile *F = FileAndOffset.first;
3951 uint64_t Offset = FileAndOffset.second;
3952 llvm::BitstreamCursor &Cursor = F->DeclsCursor;
3953 SavedStreamPosition SavedPosition(Cursor);
3954 if (llvm::Error JumpFailed = Cursor.JumpToBit(Offset))
3955 // FIXME don't do a fatal error.
3956 llvm::report_fatal_error(
3957 Twine("ASTReader::loadDeclUpdateRecords failed jumping: ") +
3958 toString(std::move(JumpFailed)));
3959 Expected<unsigned> MaybeCode = Cursor.ReadCode();
3960 if (!MaybeCode)
3961 llvm::report_fatal_error(
3962 Twine("ASTReader::loadDeclUpdateRecords failed reading code: ") +
3963 toString(MaybeCode.takeError()));
3964 unsigned Code = MaybeCode.get();
3965 ASTRecordReader Record(*this, *F);
3966 if (Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code))
3967 assert(MaybeRecCode.get() == DECL_UPDATES &&
3968 "Expected DECL_UPDATES record!");
3969 else
3970 llvm::report_fatal_error(
3971 Twine("ASTReader::loadDeclUpdateRecords failed reading rec code: ") +
3972 toString(MaybeCode.takeError()));
3974 ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,
3975 SourceLocation());
3976 Reader.UpdateDecl(D, PendingLazySpecializationIDs);
3978 // We might have made this declaration interesting. If so, remember that
3979 // we need to hand it off to the consumer.
3980 if (!WasInteresting &&
3981 isConsumerInterestedIn(getContext(), D, Reader.hasPendingBody())) {
3982 PotentiallyInterestingDecls.push_back(
3983 InterestingDecl(D, Reader.hasPendingBody()));
3984 WasInteresting = true;
3988 // Add the lazy specializations to the template.
3989 assert((PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) ||
3990 isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) &&
3991 "Must not have pending specializations");
3992 if (auto *CTD = dyn_cast<ClassTemplateDecl>(D))
3993 ASTDeclReader::AddLazySpecializations(CTD, PendingLazySpecializationIDs);
3994 else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
3995 ASTDeclReader::AddLazySpecializations(FTD, PendingLazySpecializationIDs);
3996 else if (auto *VTD = dyn_cast<VarTemplateDecl>(D))
3997 ASTDeclReader::AddLazySpecializations(VTD, PendingLazySpecializationIDs);
3998 PendingLazySpecializationIDs.clear();
4000 // Load the pending visible updates for this decl context, if it has any.
4001 auto I = PendingVisibleUpdates.find(ID);
4002 if (I != PendingVisibleUpdates.end()) {
4003 auto VisibleUpdates = std::move(I->second);
4004 PendingVisibleUpdates.erase(I);
4006 auto *DC = cast<DeclContext>(D)->getPrimaryContext();
4007 for (const auto &Update : VisibleUpdates)
4008 Lookups[DC].Table.add(
4009 Update.Mod, Update.Data,
4010 reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
4011 DC->setHasExternalVisibleStorage(true);
4015 void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {
4016 // Attach FirstLocal to the end of the decl chain.
4017 Decl *CanonDecl = FirstLocal->getCanonicalDecl();
4018 if (FirstLocal != CanonDecl) {
4019 Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl);
4020 ASTDeclReader::attachPreviousDecl(
4021 *this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl,
4022 CanonDecl);
4025 if (!LocalOffset) {
4026 ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal);
4027 return;
4030 // Load the list of other redeclarations from this module file.
4031 ModuleFile *M = getOwningModuleFile(FirstLocal);
4032 assert(M && "imported decl from no module file");
4034 llvm::BitstreamCursor &Cursor = M->DeclsCursor;
4035 SavedStreamPosition SavedPosition(Cursor);
4036 if (llvm::Error JumpFailed = Cursor.JumpToBit(LocalOffset))
4037 llvm::report_fatal_error(
4038 Twine("ASTReader::loadPendingDeclChain failed jumping: ") +
4039 toString(std::move(JumpFailed)));
4041 RecordData Record;
4042 Expected<unsigned> MaybeCode = Cursor.ReadCode();
4043 if (!MaybeCode)
4044 llvm::report_fatal_error(
4045 Twine("ASTReader::loadPendingDeclChain failed reading code: ") +
4046 toString(MaybeCode.takeError()));
4047 unsigned Code = MaybeCode.get();
4048 if (Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record))
4049 assert(MaybeRecCode.get() == LOCAL_REDECLARATIONS &&
4050 "expected LOCAL_REDECLARATIONS record!");
4051 else
4052 llvm::report_fatal_error(
4053 Twine("ASTReader::loadPendingDeclChain failed reading rec code: ") +
4054 toString(MaybeCode.takeError()));
4056 // FIXME: We have several different dispatches on decl kind here; maybe
4057 // we should instead generate one loop per kind and dispatch up-front?
4058 Decl *MostRecent = FirstLocal;
4059 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
4060 auto *D = GetLocalDecl(*M, Record[N - I - 1]);
4061 ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl);
4062 MostRecent = D;
4064 ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
4067 namespace {
4069 /// Given an ObjC interface, goes through the modules and links to the
4070 /// interface all the categories for it.
4071 class ObjCCategoriesVisitor {
4072 ASTReader &Reader;
4073 ObjCInterfaceDecl *Interface;
4074 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
4075 ObjCCategoryDecl *Tail = nullptr;
4076 llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
4077 serialization::GlobalDeclID InterfaceID;
4078 unsigned PreviousGeneration;
4080 void add(ObjCCategoryDecl *Cat) {
4081 // Only process each category once.
4082 if (!Deserialized.erase(Cat))
4083 return;
4085 // Check for duplicate categories.
4086 if (Cat->getDeclName()) {
4087 ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
4088 if (Existing &&
4089 Reader.getOwningModuleFile(Existing)
4090 != Reader.getOwningModuleFile(Cat)) {
4091 // FIXME: We should not warn for duplicates in diamond:
4093 // MT //
4094 // / \ //
4095 // ML MR //
4096 // \ / //
4097 // MB //
4099 // If there are duplicates in ML/MR, there will be warning when
4100 // creating MB *and* when importing MB. We should not warn when
4101 // importing.
4102 Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
4103 << Interface->getDeclName() << Cat->getDeclName();
4104 Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
4105 } else if (!Existing) {
4106 // Record this category.
4107 Existing = Cat;
4111 // Add this category to the end of the chain.
4112 if (Tail)
4113 ASTDeclReader::setNextObjCCategory(Tail, Cat);
4114 else
4115 Interface->setCategoryListRaw(Cat);
4116 Tail = Cat;
4119 public:
4120 ObjCCategoriesVisitor(ASTReader &Reader,
4121 ObjCInterfaceDecl *Interface,
4122 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
4123 serialization::GlobalDeclID InterfaceID,
4124 unsigned PreviousGeneration)
4125 : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
4126 InterfaceID(InterfaceID), PreviousGeneration(PreviousGeneration) {
4127 // Populate the name -> category map with the set of known categories.
4128 for (auto *Cat : Interface->known_categories()) {
4129 if (Cat->getDeclName())
4130 NameCategoryMap[Cat->getDeclName()] = Cat;
4132 // Keep track of the tail of the category list.
4133 Tail = Cat;
4137 bool operator()(ModuleFile &M) {
4138 // If we've loaded all of the category information we care about from
4139 // this module file, we're done.
4140 if (M.Generation <= PreviousGeneration)
4141 return true;
4143 // Map global ID of the definition down to the local ID used in this
4144 // module file. If there is no such mapping, we'll find nothing here
4145 // (or in any module it imports).
4146 DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
4147 if (!LocalID)
4148 return true;
4150 // Perform a binary search to find the local redeclarations for this
4151 // declaration (if any).
4152 const ObjCCategoriesInfo Compare = { LocalID, 0 };
4153 const ObjCCategoriesInfo *Result
4154 = std::lower_bound(M.ObjCCategoriesMap,
4155 M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
4156 Compare);
4157 if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
4158 Result->DefinitionID != LocalID) {
4159 // We didn't find anything. If the class definition is in this module
4160 // file, then the module files it depends on cannot have any categories,
4161 // so suppress further lookup.
4162 return Reader.isDeclIDFromModule(InterfaceID, M);
4165 // We found something. Dig out all of the categories.
4166 unsigned Offset = Result->Offset;
4167 unsigned N = M.ObjCCategories[Offset];
4168 M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
4169 for (unsigned I = 0; I != N; ++I)
4170 add(cast_or_null<ObjCCategoryDecl>(
4171 Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
4172 return true;
4176 } // namespace
4178 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
4179 ObjCInterfaceDecl *D,
4180 unsigned PreviousGeneration) {
4181 ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
4182 PreviousGeneration);
4183 ModuleMgr.visit(Visitor);
4186 template<typename DeclT, typename Fn>
4187 static void forAllLaterRedecls(DeclT *D, Fn F) {
4188 F(D);
4190 // Check whether we've already merged D into its redeclaration chain.
4191 // MostRecent may or may not be nullptr if D has not been merged. If
4192 // not, walk the merged redecl chain and see if it's there.
4193 auto *MostRecent = D->getMostRecentDecl();
4194 bool Found = false;
4195 for (auto *Redecl = MostRecent; Redecl && !Found;
4196 Redecl = Redecl->getPreviousDecl())
4197 Found = (Redecl == D);
4199 // If this declaration is merged, apply the functor to all later decls.
4200 if (Found) {
4201 for (auto *Redecl = MostRecent; Redecl != D;
4202 Redecl = Redecl->getPreviousDecl())
4203 F(Redecl);
4207 void ASTDeclReader::UpdateDecl(Decl *D,
4208 llvm::SmallVectorImpl<serialization::DeclID> &PendingLazySpecializationIDs) {
4209 while (Record.getIdx() < Record.size()) {
4210 switch ((DeclUpdateKind)Record.readInt()) {
4211 case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
4212 auto *RD = cast<CXXRecordDecl>(D);
4213 // FIXME: If we also have an update record for instantiating the
4214 // definition of D, we need that to happen before we get here.
4215 Decl *MD = Record.readDecl();
4216 assert(MD && "couldn't read decl from update record");
4217 // FIXME: We should call addHiddenDecl instead, to add the member
4218 // to its DeclContext.
4219 RD->addedMember(MD);
4220 break;
4223 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4224 // It will be added to the template's lazy specialization set.
4225 PendingLazySpecializationIDs.push_back(readDeclID());
4226 break;
4228 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
4229 auto *Anon = readDeclAs<NamespaceDecl>();
4231 // Each module has its own anonymous namespace, which is disjoint from
4232 // any other module's anonymous namespaces, so don't attach the anonymous
4233 // namespace at all.
4234 if (!Record.isModule()) {
4235 if (auto *TU = dyn_cast<TranslationUnitDecl>(D))
4236 TU->setAnonymousNamespace(Anon);
4237 else
4238 cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
4240 break;
4243 case UPD_CXX_ADDED_VAR_DEFINITION: {
4244 auto *VD = cast<VarDecl>(D);
4245 VD->NonParmVarDeclBits.IsInline = Record.readInt();
4246 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
4247 uint64_t Val = Record.readInt();
4248 if (Val && !VD->getInit()) {
4249 VD->setInit(Record.readExpr());
4250 if (Val != 1) {
4251 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
4252 Eval->HasConstantInitialization = (Val & 2) != 0;
4253 Eval->HasConstantDestruction = (Val & 4) != 0;
4256 break;
4259 case UPD_CXX_POINT_OF_INSTANTIATION: {
4260 SourceLocation POI = Record.readSourceLocation();
4261 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
4262 VTSD->setPointOfInstantiation(POI);
4263 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
4264 VD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
4265 } else {
4266 auto *FD = cast<FunctionDecl>(D);
4267 if (auto *FTSInfo = FD->TemplateOrSpecialization
4268 .dyn_cast<FunctionTemplateSpecializationInfo *>())
4269 FTSInfo->setPointOfInstantiation(POI);
4270 else
4271 FD->TemplateOrSpecialization.get<MemberSpecializationInfo *>()
4272 ->setPointOfInstantiation(POI);
4274 break;
4277 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: {
4278 auto *Param = cast<ParmVarDecl>(D);
4280 // We have to read the default argument regardless of whether we use it
4281 // so that hypothetical further update records aren't messed up.
4282 // TODO: Add a function to skip over the next expr record.
4283 auto *DefaultArg = Record.readExpr();
4285 // Only apply the update if the parameter still has an uninstantiated
4286 // default argument.
4287 if (Param->hasUninstantiatedDefaultArg())
4288 Param->setDefaultArg(DefaultArg);
4289 break;
4292 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: {
4293 auto *FD = cast<FieldDecl>(D);
4294 auto *DefaultInit = Record.readExpr();
4296 // Only apply the update if the field still has an uninstantiated
4297 // default member initializer.
4298 if (FD->hasInClassInitializer() && !FD->getInClassInitializer()) {
4299 if (DefaultInit)
4300 FD->setInClassInitializer(DefaultInit);
4301 else
4302 // Instantiation failed. We can get here if we serialized an AST for
4303 // an invalid program.
4304 FD->removeInClassInitializer();
4306 break;
4309 case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
4310 auto *FD = cast<FunctionDecl>(D);
4311 if (Reader.PendingBodies[FD]) {
4312 // FIXME: Maybe check for ODR violations.
4313 // It's safe to stop now because this update record is always last.
4314 return;
4317 if (Record.readInt()) {
4318 // Maintain AST consistency: any later redeclarations of this function
4319 // are inline if this one is. (We might have merged another declaration
4320 // into this one.)
4321 forAllLaterRedecls(FD, [](FunctionDecl *FD) {
4322 FD->setImplicitlyInline();
4325 FD->setInnerLocStart(readSourceLocation());
4326 ReadFunctionDefinition(FD);
4327 assert(Record.getIdx() == Record.size() && "lazy body must be last");
4328 break;
4331 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4332 auto *RD = cast<CXXRecordDecl>(D);
4333 auto *OldDD = RD->getCanonicalDecl()->DefinitionData;
4334 bool HadRealDefinition =
4335 OldDD && (OldDD->Definition != RD ||
4336 !Reader.PendingFakeDefinitionData.count(OldDD));
4337 RD->setParamDestroyedInCallee(Record.readInt());
4338 RD->setArgPassingRestrictions(
4339 (RecordDecl::ArgPassingKind)Record.readInt());
4340 ReadCXXRecordDefinition(RD, /*Update*/true);
4342 // Visible update is handled separately.
4343 uint64_t LexicalOffset = ReadLocalOffset();
4344 if (!HadRealDefinition && LexicalOffset) {
4345 Record.readLexicalDeclContextStorage(LexicalOffset, RD);
4346 Reader.PendingFakeDefinitionData.erase(OldDD);
4349 auto TSK = (TemplateSpecializationKind)Record.readInt();
4350 SourceLocation POI = readSourceLocation();
4351 if (MemberSpecializationInfo *MSInfo =
4352 RD->getMemberSpecializationInfo()) {
4353 MSInfo->setTemplateSpecializationKind(TSK);
4354 MSInfo->setPointOfInstantiation(POI);
4355 } else {
4356 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4357 Spec->setTemplateSpecializationKind(TSK);
4358 Spec->setPointOfInstantiation(POI);
4360 if (Record.readInt()) {
4361 auto *PartialSpec =
4362 readDeclAs<ClassTemplatePartialSpecializationDecl>();
4363 SmallVector<TemplateArgument, 8> TemplArgs;
4364 Record.readTemplateArgumentList(TemplArgs);
4365 auto *TemplArgList = TemplateArgumentList::CreateCopy(
4366 Reader.getContext(), TemplArgs);
4368 // FIXME: If we already have a partial specialization set,
4369 // check that it matches.
4370 if (!Spec->getSpecializedTemplateOrPartial()
4371 .is<ClassTemplatePartialSpecializationDecl *>())
4372 Spec->setInstantiationOf(PartialSpec, TemplArgList);
4376 RD->setTagKind((TagTypeKind)Record.readInt());
4377 RD->setLocation(readSourceLocation());
4378 RD->setLocStart(readSourceLocation());
4379 RD->setBraceRange(readSourceRange());
4381 if (Record.readInt()) {
4382 AttrVec Attrs;
4383 Record.readAttributes(Attrs);
4384 // If the declaration already has attributes, we assume that some other
4385 // AST file already loaded them.
4386 if (!D->hasAttrs())
4387 D->setAttrsImpl(Attrs, Reader.getContext());
4389 break;
4392 case UPD_CXX_RESOLVED_DTOR_DELETE: {
4393 // Set the 'operator delete' directly to avoid emitting another update
4394 // record.
4395 auto *Del = readDeclAs<FunctionDecl>();
4396 auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl());
4397 auto *ThisArg = Record.readExpr();
4398 // FIXME: Check consistency if we have an old and new operator delete.
4399 if (!First->OperatorDelete) {
4400 First->OperatorDelete = Del;
4401 First->OperatorDeleteThisArg = ThisArg;
4403 break;
4406 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
4407 SmallVector<QualType, 8> ExceptionStorage;
4408 auto ESI = Record.readExceptionSpecInfo(ExceptionStorage);
4410 // Update this declaration's exception specification, if needed.
4411 auto *FD = cast<FunctionDecl>(D);
4412 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
4413 // FIXME: If the exception specification is already present, check that it
4414 // matches.
4415 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
4416 FD->setType(Reader.getContext().getFunctionType(
4417 FPT->getReturnType(), FPT->getParamTypes(),
4418 FPT->getExtProtoInfo().withExceptionSpec(ESI)));
4420 // When we get to the end of deserializing, see if there are other decls
4421 // that we need to propagate this exception specification onto.
4422 Reader.PendingExceptionSpecUpdates.insert(
4423 std::make_pair(FD->getCanonicalDecl(), FD));
4425 break;
4428 case UPD_CXX_DEDUCED_RETURN_TYPE: {
4429 auto *FD = cast<FunctionDecl>(D);
4430 QualType DeducedResultType = Record.readType();
4431 Reader.PendingDeducedTypeUpdates.insert(
4432 {FD->getCanonicalDecl(), DeducedResultType});
4433 break;
4436 case UPD_DECL_MARKED_USED:
4437 // Maintain AST consistency: any later redeclarations are used too.
4438 D->markUsed(Reader.getContext());
4439 break;
4441 case UPD_MANGLING_NUMBER:
4442 Reader.getContext().setManglingNumber(cast<NamedDecl>(D),
4443 Record.readInt());
4444 break;
4446 case UPD_STATIC_LOCAL_NUMBER:
4447 Reader.getContext().setStaticLocalNumber(cast<VarDecl>(D),
4448 Record.readInt());
4449 break;
4451 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4452 D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
4453 Reader.getContext(), readSourceRange(),
4454 AttributeCommonInfo::AS_Pragma));
4455 break;
4457 case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
4458 auto AllocatorKind =
4459 static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(Record.readInt());
4460 Expr *Allocator = Record.readExpr();
4461 Expr *Alignment = Record.readExpr();
4462 SourceRange SR = readSourceRange();
4463 D->addAttr(OMPAllocateDeclAttr::CreateImplicit(
4464 Reader.getContext(), AllocatorKind, Allocator, Alignment, SR,
4465 AttributeCommonInfo::AS_Pragma));
4466 break;
4469 case UPD_DECL_EXPORTED: {
4470 unsigned SubmoduleID = readSubmoduleID();
4471 auto *Exported = cast<NamedDecl>(D);
4472 Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr;
4473 Reader.getContext().mergeDefinitionIntoModule(Exported, Owner);
4474 Reader.PendingMergedDefinitionsToDeduplicate.insert(Exported);
4475 break;
4478 case UPD_DECL_MARKED_OPENMP_DECLARETARGET: {
4479 auto MapType = Record.readEnum<OMPDeclareTargetDeclAttr::MapTypeTy>();
4480 auto DevType = Record.readEnum<OMPDeclareTargetDeclAttr::DevTypeTy>();
4481 Expr *IndirectE = Record.readExpr();
4482 bool Indirect = Record.readBool();
4483 unsigned Level = Record.readInt();
4484 D->addAttr(OMPDeclareTargetDeclAttr::CreateImplicit(
4485 Reader.getContext(), MapType, DevType, IndirectE, Indirect, Level,
4486 readSourceRange(), AttributeCommonInfo::AS_Pragma));
4487 break;
4490 case UPD_ADDED_ATTR_TO_RECORD:
4491 AttrVec Attrs;
4492 Record.readAttributes(Attrs);
4493 assert(Attrs.size() == 1);
4494 D->addAttr(Attrs[0]);
4495 break;