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