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