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