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