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