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