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