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