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