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