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