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