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