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