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