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