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