1 //===-- ASTReader.cpp - AST File Reader -----------------------------------===// 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 defines the ASTReader class, which reads AST files. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Serialization/ASTReader.h" 15 #include "ASTCommon.h" 16 #include "ASTReaderInternals.h" 17 #include "clang/AST/ASTConsumer.h" 18 #include "clang/AST/ASTContext.h" 19 #include "clang/AST/ASTMutationListener.h" 20 #include "clang/AST/ASTUnresolvedSet.h" 21 #include "clang/AST/Decl.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclGroup.h" 24 #include "clang/AST/DeclObjC.h" 25 #include "clang/AST/DeclTemplate.h" 26 #include "clang/AST/Expr.h" 27 #include "clang/AST/ExprCXX.h" 28 #include "clang/AST/NestedNameSpecifier.h" 29 #include "clang/AST/ODRHash.h" 30 #include "clang/AST/RawCommentList.h" 31 #include "clang/AST/Type.h" 32 #include "clang/AST/TypeLocVisitor.h" 33 #include "clang/AST/UnresolvedSet.h" 34 #include "clang/Basic/CommentOptions.h" 35 #include "clang/Basic/DiagnosticOptions.h" 36 #include "clang/Basic/ExceptionSpecificationType.h" 37 #include "clang/Basic/FileManager.h" 38 #include "clang/Basic/FileSystemOptions.h" 39 #include "clang/Basic/LangOptions.h" 40 #include "clang/Basic/MemoryBufferCache.h" 41 #include "clang/Basic/ObjCRuntime.h" 42 #include "clang/Basic/OperatorKinds.h" 43 #include "clang/Basic/Sanitizers.h" 44 #include "clang/Basic/SourceManager.h" 45 #include "clang/Basic/SourceManagerInternals.h" 46 #include "clang/Basic/Specifiers.h" 47 #include "clang/Basic/TargetInfo.h" 48 #include "clang/Basic/TargetOptions.h" 49 #include "clang/Basic/TokenKinds.h" 50 #include "clang/Basic/Version.h" 51 #include "clang/Basic/VersionTuple.h" 52 #include "clang/Frontend/PCHContainerOperations.h" 53 #include "clang/Lex/HeaderSearch.h" 54 #include "clang/Lex/HeaderSearchOptions.h" 55 #include "clang/Lex/MacroInfo.h" 56 #include "clang/Lex/ModuleMap.h" 57 #include "clang/Lex/PreprocessingRecord.h" 58 #include "clang/Lex/Preprocessor.h" 59 #include "clang/Lex/PreprocessorOptions.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/Sema.h" 62 #include "clang/Sema/Weak.h" 63 #include "clang/Serialization/ASTDeserializationListener.h" 64 #include "clang/Serialization/GlobalModuleIndex.h" 65 #include "clang/Serialization/ModuleManager.h" 66 #include "clang/Serialization/SerializationDiagnostic.h" 67 #include "llvm/ADT/APFloat.h" 68 #include "llvm/ADT/APInt.h" 69 #include "llvm/ADT/APSInt.h" 70 #include "llvm/ADT/Hashing.h" 71 #include "llvm/ADT/SmallString.h" 72 #include "llvm/ADT/StringExtras.h" 73 #include "llvm/ADT/Triple.h" 74 #include "llvm/Bitcode/BitstreamReader.h" 75 #include "llvm/Support/Compression.h" 76 #include "llvm/Support/Compiler.h" 77 #include "llvm/Support/Error.h" 78 #include "llvm/Support/ErrorHandling.h" 79 #include "llvm/Support/FileSystem.h" 80 #include "llvm/Support/MemoryBuffer.h" 81 #include "llvm/Support/Path.h" 82 #include "llvm/Support/SaveAndRestore.h" 83 #include "llvm/Support/raw_ostream.h" 84 #include <algorithm> 85 #include <cassert> 86 #include <cstdint> 87 #include <cstdio> 88 #include <cstring> 89 #include <ctime> 90 #include <iterator> 91 #include <limits> 92 #include <map> 93 #include <memory> 94 #include <new> 95 #include <string> 96 #include <system_error> 97 #include <tuple> 98 #include <utility> 99 #include <vector> 100 101 using namespace clang; 102 using namespace clang::serialization; 103 using namespace clang::serialization::reader; 104 using llvm::BitstreamCursor; 105 106 //===----------------------------------------------------------------------===// 107 // ChainedASTReaderListener implementation 108 //===----------------------------------------------------------------------===// 109 110 bool 111 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) { 112 return First->ReadFullVersionInformation(FullVersion) || 113 Second->ReadFullVersionInformation(FullVersion); 114 } 115 116 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) { 117 First->ReadModuleName(ModuleName); 118 Second->ReadModuleName(ModuleName); 119 } 120 121 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) { 122 First->ReadModuleMapFile(ModuleMapPath); 123 Second->ReadModuleMapFile(ModuleMapPath); 124 } 125 126 bool 127 ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts, 128 bool Complain, 129 bool AllowCompatibleDifferences) { 130 return First->ReadLanguageOptions(LangOpts, Complain, 131 AllowCompatibleDifferences) || 132 Second->ReadLanguageOptions(LangOpts, Complain, 133 AllowCompatibleDifferences); 134 } 135 136 bool ChainedASTReaderListener::ReadTargetOptions( 137 const TargetOptions &TargetOpts, bool Complain, 138 bool AllowCompatibleDifferences) { 139 return First->ReadTargetOptions(TargetOpts, Complain, 140 AllowCompatibleDifferences) || 141 Second->ReadTargetOptions(TargetOpts, Complain, 142 AllowCompatibleDifferences); 143 } 144 145 bool ChainedASTReaderListener::ReadDiagnosticOptions( 146 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) { 147 return First->ReadDiagnosticOptions(DiagOpts, Complain) || 148 Second->ReadDiagnosticOptions(DiagOpts, Complain); 149 } 150 151 bool 152 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts, 153 bool Complain) { 154 return First->ReadFileSystemOptions(FSOpts, Complain) || 155 Second->ReadFileSystemOptions(FSOpts, Complain); 156 } 157 158 bool ChainedASTReaderListener::ReadHeaderSearchOptions( 159 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, 160 bool Complain) { 161 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 162 Complain) || 163 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 164 Complain); 165 } 166 167 bool ChainedASTReaderListener::ReadPreprocessorOptions( 168 const PreprocessorOptions &PPOpts, bool Complain, 169 std::string &SuggestedPredefines) { 170 return First->ReadPreprocessorOptions(PPOpts, Complain, 171 SuggestedPredefines) || 172 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines); 173 } 174 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M, 175 unsigned Value) { 176 First->ReadCounter(M, Value); 177 Second->ReadCounter(M, Value); 178 } 179 bool ChainedASTReaderListener::needsInputFileVisitation() { 180 return First->needsInputFileVisitation() || 181 Second->needsInputFileVisitation(); 182 } 183 bool ChainedASTReaderListener::needsSystemInputFileVisitation() { 184 return First->needsSystemInputFileVisitation() || 185 Second->needsSystemInputFileVisitation(); 186 } 187 void ChainedASTReaderListener::visitModuleFile(StringRef Filename, 188 ModuleKind Kind) { 189 First->visitModuleFile(Filename, Kind); 190 Second->visitModuleFile(Filename, Kind); 191 } 192 193 bool ChainedASTReaderListener::visitInputFile(StringRef Filename, 194 bool isSystem, 195 bool isOverridden, 196 bool isExplicitModule) { 197 bool Continue = false; 198 if (First->needsInputFileVisitation() && 199 (!isSystem || First->needsSystemInputFileVisitation())) 200 Continue |= First->visitInputFile(Filename, isSystem, isOverridden, 201 isExplicitModule); 202 if (Second->needsInputFileVisitation() && 203 (!isSystem || Second->needsSystemInputFileVisitation())) 204 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden, 205 isExplicitModule); 206 return Continue; 207 } 208 209 void ChainedASTReaderListener::readModuleFileExtension( 210 const ModuleFileExtensionMetadata &Metadata) { 211 First->readModuleFileExtension(Metadata); 212 Second->readModuleFileExtension(Metadata); 213 } 214 215 //===----------------------------------------------------------------------===// 216 // PCH validator implementation 217 //===----------------------------------------------------------------------===// 218 219 ASTReaderListener::~ASTReaderListener() {} 220 221 /// \brief Compare the given set of language options against an existing set of 222 /// language options. 223 /// 224 /// \param Diags If non-NULL, diagnostics will be emitted via this engine. 225 /// \param AllowCompatibleDifferences If true, differences between compatible 226 /// language options will be permitted. 227 /// 228 /// \returns true if the languagae options mis-match, false otherwise. 229 static bool checkLanguageOptions(const LangOptions &LangOpts, 230 const LangOptions &ExistingLangOpts, 231 DiagnosticsEngine *Diags, 232 bool AllowCompatibleDifferences = true) { 233 #define LANGOPT(Name, Bits, Default, Description) \ 234 if (ExistingLangOpts.Name != LangOpts.Name) { \ 235 if (Diags) \ 236 Diags->Report(diag::err_pch_langopt_mismatch) \ 237 << Description << LangOpts.Name << ExistingLangOpts.Name; \ 238 return true; \ 239 } 240 241 #define VALUE_LANGOPT(Name, Bits, Default, Description) \ 242 if (ExistingLangOpts.Name != LangOpts.Name) { \ 243 if (Diags) \ 244 Diags->Report(diag::err_pch_langopt_value_mismatch) \ 245 << Description; \ 246 return true; \ 247 } 248 249 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 250 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \ 251 if (Diags) \ 252 Diags->Report(diag::err_pch_langopt_value_mismatch) \ 253 << Description; \ 254 return true; \ 255 } 256 257 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \ 258 if (!AllowCompatibleDifferences) \ 259 LANGOPT(Name, Bits, Default, Description) 260 261 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \ 262 if (!AllowCompatibleDifferences) \ 263 ENUM_LANGOPT(Name, Bits, Default, Description) 264 265 #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \ 266 if (!AllowCompatibleDifferences) \ 267 VALUE_LANGOPT(Name, Bits, Default, Description) 268 269 #define BENIGN_LANGOPT(Name, Bits, Default, Description) 270 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) 271 #define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description) 272 #include "clang/Basic/LangOptions.def" 273 274 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) { 275 if (Diags) 276 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features"; 277 return true; 278 } 279 280 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) { 281 if (Diags) 282 Diags->Report(diag::err_pch_langopt_value_mismatch) 283 << "target Objective-C runtime"; 284 return true; 285 } 286 287 if (ExistingLangOpts.CommentOpts.BlockCommandNames != 288 LangOpts.CommentOpts.BlockCommandNames) { 289 if (Diags) 290 Diags->Report(diag::err_pch_langopt_value_mismatch) 291 << "block command names"; 292 return true; 293 } 294 295 // Sanitizer feature mismatches are treated as compatible differences. If 296 // compatible differences aren't allowed, we still only want to check for 297 // mismatches of non-modular sanitizers (the only ones which can affect AST 298 // generation). 299 if (!AllowCompatibleDifferences) { 300 SanitizerMask ModularSanitizers = getPPTransparentSanitizers(); 301 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize; 302 SanitizerSet ImportedSanitizers = LangOpts.Sanitize; 303 ExistingSanitizers.clear(ModularSanitizers); 304 ImportedSanitizers.clear(ModularSanitizers); 305 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) { 306 const std::string Flag = "-fsanitize="; 307 if (Diags) { 308 #define SANITIZER(NAME, ID) \ 309 { \ 310 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \ 311 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \ 312 if (InExistingModule != InImportedModule) \ 313 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \ 314 << InExistingModule << (Flag + NAME); \ 315 } 316 #include "clang/Basic/Sanitizers.def" 317 } 318 return true; 319 } 320 } 321 322 return false; 323 } 324 325 /// \brief Compare the given set of target options against an existing set of 326 /// target options. 327 /// 328 /// \param Diags If non-NULL, diagnostics will be emitted via this engine. 329 /// 330 /// \returns true if the target options mis-match, false otherwise. 331 static bool checkTargetOptions(const TargetOptions &TargetOpts, 332 const TargetOptions &ExistingTargetOpts, 333 DiagnosticsEngine *Diags, 334 bool AllowCompatibleDifferences = true) { 335 #define CHECK_TARGET_OPT(Field, Name) \ 336 if (TargetOpts.Field != ExistingTargetOpts.Field) { \ 337 if (Diags) \ 338 Diags->Report(diag::err_pch_targetopt_mismatch) \ 339 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \ 340 return true; \ 341 } 342 343 // The triple and ABI must match exactly. 344 CHECK_TARGET_OPT(Triple, "target"); 345 CHECK_TARGET_OPT(ABI, "target ABI"); 346 347 // We can tolerate different CPUs in many cases, notably when one CPU 348 // supports a strict superset of another. When allowing compatible 349 // differences skip this check. 350 if (!AllowCompatibleDifferences) 351 CHECK_TARGET_OPT(CPU, "target CPU"); 352 353 #undef CHECK_TARGET_OPT 354 355 // Compare feature sets. 356 SmallVector<StringRef, 4> ExistingFeatures( 357 ExistingTargetOpts.FeaturesAsWritten.begin(), 358 ExistingTargetOpts.FeaturesAsWritten.end()); 359 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(), 360 TargetOpts.FeaturesAsWritten.end()); 361 std::sort(ExistingFeatures.begin(), ExistingFeatures.end()); 362 std::sort(ReadFeatures.begin(), ReadFeatures.end()); 363 364 // We compute the set difference in both directions explicitly so that we can 365 // diagnose the differences differently. 366 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures; 367 std::set_difference( 368 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(), 369 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures)); 370 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(), 371 ExistingFeatures.begin(), ExistingFeatures.end(), 372 std::back_inserter(UnmatchedReadFeatures)); 373 374 // If we are allowing compatible differences and the read feature set is 375 // a strict subset of the existing feature set, there is nothing to diagnose. 376 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty()) 377 return false; 378 379 if (Diags) { 380 for (StringRef Feature : UnmatchedReadFeatures) 381 Diags->Report(diag::err_pch_targetopt_feature_mismatch) 382 << /* is-existing-feature */ false << Feature; 383 for (StringRef Feature : UnmatchedExistingFeatures) 384 Diags->Report(diag::err_pch_targetopt_feature_mismatch) 385 << /* is-existing-feature */ true << Feature; 386 } 387 388 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty(); 389 } 390 391 bool 392 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts, 393 bool Complain, 394 bool AllowCompatibleDifferences) { 395 const LangOptions &ExistingLangOpts = PP.getLangOpts(); 396 return checkLanguageOptions(LangOpts, ExistingLangOpts, 397 Complain ? &Reader.Diags : nullptr, 398 AllowCompatibleDifferences); 399 } 400 401 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts, 402 bool Complain, 403 bool AllowCompatibleDifferences) { 404 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts(); 405 return checkTargetOptions(TargetOpts, ExistingTargetOpts, 406 Complain ? &Reader.Diags : nullptr, 407 AllowCompatibleDifferences); 408 } 409 410 namespace { 411 412 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> > 413 MacroDefinitionsMap; 414 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > 415 DeclsMap; 416 417 } // end anonymous namespace 418 419 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, 420 DiagnosticsEngine &Diags, 421 bool Complain) { 422 typedef DiagnosticsEngine::Level Level; 423 424 // Check current mappings for new -Werror mappings, and the stored mappings 425 // for cases that were explicitly mapped to *not* be errors that are now 426 // errors because of options like -Werror. 427 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags }; 428 429 for (DiagnosticsEngine *MappingSource : MappingSources) { 430 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) { 431 diag::kind DiagID = DiagIDMappingPair.first; 432 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation()); 433 if (CurLevel < DiagnosticsEngine::Error) 434 continue; // not significant 435 Level StoredLevel = 436 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation()); 437 if (StoredLevel < DiagnosticsEngine::Error) { 438 if (Complain) 439 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" + 440 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str(); 441 return true; 442 } 443 } 444 } 445 446 return false; 447 } 448 449 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) { 450 diag::Severity Ext = Diags.getExtensionHandlingBehavior(); 451 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors()) 452 return true; 453 return Ext >= diag::Severity::Error; 454 } 455 456 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, 457 DiagnosticsEngine &Diags, 458 bool IsSystem, bool Complain) { 459 // Top-level options 460 if (IsSystem) { 461 if (Diags.getSuppressSystemWarnings()) 462 return false; 463 // If -Wsystem-headers was not enabled before, be conservative 464 if (StoredDiags.getSuppressSystemWarnings()) { 465 if (Complain) 466 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers"; 467 return true; 468 } 469 } 470 471 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) { 472 if (Complain) 473 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror"; 474 return true; 475 } 476 477 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() && 478 !StoredDiags.getEnableAllWarnings()) { 479 if (Complain) 480 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror"; 481 return true; 482 } 483 484 if (isExtHandlingFromDiagsError(Diags) && 485 !isExtHandlingFromDiagsError(StoredDiags)) { 486 if (Complain) 487 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors"; 488 return true; 489 } 490 491 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain); 492 } 493 494 /// Return the top import module if it is implicit, nullptr otherwise. 495 static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr, 496 Preprocessor &PP) { 497 // If the original import came from a file explicitly generated by the user, 498 // don't check the diagnostic mappings. 499 // FIXME: currently this is approximated by checking whether this is not a 500 // module import of an implicitly-loaded module file. 501 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in 502 // the transitive closure of its imports, since unrelated modules cannot be 503 // imported until after this module finishes validation. 504 ModuleFile *TopImport = &*ModuleMgr.rbegin(); 505 while (!TopImport->ImportedBy.empty()) 506 TopImport = TopImport->ImportedBy[0]; 507 if (TopImport->Kind != MK_ImplicitModule) 508 return nullptr; 509 510 StringRef ModuleName = TopImport->ModuleName; 511 assert(!ModuleName.empty() && "diagnostic options read before module name"); 512 513 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName); 514 assert(M && "missing module"); 515 return M; 516 } 517 518 bool PCHValidator::ReadDiagnosticOptions( 519 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) { 520 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics(); 521 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs()); 522 IntrusiveRefCntPtr<DiagnosticsEngine> Diags( 523 new DiagnosticsEngine(DiagIDs, DiagOpts.get())); 524 // This should never fail, because we would have processed these options 525 // before writing them to an ASTFile. 526 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false); 527 528 ModuleManager &ModuleMgr = Reader.getModuleManager(); 529 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then"); 530 531 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP); 532 if (!TopM) 533 return false; 534 535 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that 536 // contains the union of their flags. 537 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem, 538 Complain); 539 } 540 541 /// \brief Collect the macro definitions provided by the given preprocessor 542 /// options. 543 static void 544 collectMacroDefinitions(const PreprocessorOptions &PPOpts, 545 MacroDefinitionsMap &Macros, 546 SmallVectorImpl<StringRef> *MacroNames = nullptr) { 547 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) { 548 StringRef Macro = PPOpts.Macros[I].first; 549 bool IsUndef = PPOpts.Macros[I].second; 550 551 std::pair<StringRef, StringRef> MacroPair = Macro.split('='); 552 StringRef MacroName = MacroPair.first; 553 StringRef MacroBody = MacroPair.second; 554 555 // For an #undef'd macro, we only care about the name. 556 if (IsUndef) { 557 if (MacroNames && !Macros.count(MacroName)) 558 MacroNames->push_back(MacroName); 559 560 Macros[MacroName] = std::make_pair("", true); 561 continue; 562 } 563 564 // For a #define'd macro, figure out the actual definition. 565 if (MacroName.size() == Macro.size()) 566 MacroBody = "1"; 567 else { 568 // Note: GCC drops anything following an end-of-line character. 569 StringRef::size_type End = MacroBody.find_first_of("\n\r"); 570 MacroBody = MacroBody.substr(0, End); 571 } 572 573 if (MacroNames && !Macros.count(MacroName)) 574 MacroNames->push_back(MacroName); 575 Macros[MacroName] = std::make_pair(MacroBody, false); 576 } 577 } 578 579 /// \brief Check the preprocessor options deserialized from the control block 580 /// against the preprocessor options in an existing preprocessor. 581 /// 582 /// \param Diags If non-null, produce diagnostics for any mismatches incurred. 583 /// \param Validate If true, validate preprocessor options. If false, allow 584 /// macros defined by \p ExistingPPOpts to override those defined by 585 /// \p PPOpts in SuggestedPredefines. 586 static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts, 587 const PreprocessorOptions &ExistingPPOpts, 588 DiagnosticsEngine *Diags, 589 FileManager &FileMgr, 590 std::string &SuggestedPredefines, 591 const LangOptions &LangOpts, 592 bool Validate = true) { 593 // Check macro definitions. 594 MacroDefinitionsMap ASTFileMacros; 595 collectMacroDefinitions(PPOpts, ASTFileMacros); 596 MacroDefinitionsMap ExistingMacros; 597 SmallVector<StringRef, 4> ExistingMacroNames; 598 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames); 599 600 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) { 601 // Dig out the macro definition in the existing preprocessor options. 602 StringRef MacroName = ExistingMacroNames[I]; 603 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName]; 604 605 // Check whether we know anything about this macro name or not. 606 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known 607 = ASTFileMacros.find(MacroName); 608 if (!Validate || Known == ASTFileMacros.end()) { 609 // FIXME: Check whether this identifier was referenced anywhere in the 610 // AST file. If so, we should reject the AST file. Unfortunately, this 611 // information isn't in the control block. What shall we do about it? 612 613 if (Existing.second) { 614 SuggestedPredefines += "#undef "; 615 SuggestedPredefines += MacroName.str(); 616 SuggestedPredefines += '\n'; 617 } else { 618 SuggestedPredefines += "#define "; 619 SuggestedPredefines += MacroName.str(); 620 SuggestedPredefines += ' '; 621 SuggestedPredefines += Existing.first.str(); 622 SuggestedPredefines += '\n'; 623 } 624 continue; 625 } 626 627 // If the macro was defined in one but undef'd in the other, we have a 628 // conflict. 629 if (Existing.second != Known->second.second) { 630 if (Diags) { 631 Diags->Report(diag::err_pch_macro_def_undef) 632 << MacroName << Known->second.second; 633 } 634 return true; 635 } 636 637 // If the macro was #undef'd in both, or if the macro bodies are identical, 638 // it's fine. 639 if (Existing.second || Existing.first == Known->second.first) 640 continue; 641 642 // The macro bodies differ; complain. 643 if (Diags) { 644 Diags->Report(diag::err_pch_macro_def_conflict) 645 << MacroName << Known->second.first << Existing.first; 646 } 647 return true; 648 } 649 650 // Check whether we're using predefines. 651 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) { 652 if (Diags) { 653 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines; 654 } 655 return true; 656 } 657 658 // Detailed record is important since it is used for the module cache hash. 659 if (LangOpts.Modules && 660 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) { 661 if (Diags) { 662 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord; 663 } 664 return true; 665 } 666 667 // Compute the #include and #include_macros lines we need. 668 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) { 669 StringRef File = ExistingPPOpts.Includes[I]; 670 if (File == ExistingPPOpts.ImplicitPCHInclude) 671 continue; 672 673 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File) 674 != PPOpts.Includes.end()) 675 continue; 676 677 SuggestedPredefines += "#include \""; 678 SuggestedPredefines += File; 679 SuggestedPredefines += "\"\n"; 680 } 681 682 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) { 683 StringRef File = ExistingPPOpts.MacroIncludes[I]; 684 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(), 685 File) 686 != PPOpts.MacroIncludes.end()) 687 continue; 688 689 SuggestedPredefines += "#__include_macros \""; 690 SuggestedPredefines += File; 691 SuggestedPredefines += "\"\n##\n"; 692 } 693 694 return false; 695 } 696 697 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, 698 bool Complain, 699 std::string &SuggestedPredefines) { 700 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts(); 701 702 return checkPreprocessorOptions(PPOpts, ExistingPPOpts, 703 Complain? &Reader.Diags : nullptr, 704 PP.getFileManager(), 705 SuggestedPredefines, 706 PP.getLangOpts()); 707 } 708 709 bool SimpleASTReaderListener::ReadPreprocessorOptions( 710 const PreprocessorOptions &PPOpts, 711 bool Complain, 712 std::string &SuggestedPredefines) { 713 return checkPreprocessorOptions(PPOpts, 714 PP.getPreprocessorOpts(), 715 nullptr, 716 PP.getFileManager(), 717 SuggestedPredefines, 718 PP.getLangOpts(), 719 false); 720 } 721 722 /// Check the header search options deserialized from the control block 723 /// against the header search options in an existing preprocessor. 724 /// 725 /// \param Diags If non-null, produce diagnostics for any mismatches incurred. 726 static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 727 StringRef SpecificModuleCachePath, 728 StringRef ExistingModuleCachePath, 729 DiagnosticsEngine *Diags, 730 const LangOptions &LangOpts) { 731 if (LangOpts.Modules) { 732 if (SpecificModuleCachePath != ExistingModuleCachePath) { 733 if (Diags) 734 Diags->Report(diag::err_pch_modulecache_mismatch) 735 << SpecificModuleCachePath << ExistingModuleCachePath; 736 return true; 737 } 738 } 739 740 return false; 741 } 742 743 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 744 StringRef SpecificModuleCachePath, 745 bool Complain) { 746 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 747 PP.getHeaderSearchInfo().getModuleCachePath(), 748 Complain ? &Reader.Diags : nullptr, 749 PP.getLangOpts()); 750 } 751 752 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) { 753 PP.setCounterValue(Value); 754 } 755 756 //===----------------------------------------------------------------------===// 757 // AST reader implementation 758 //===----------------------------------------------------------------------===// 759 760 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener, 761 bool TakeOwnership) { 762 DeserializationListener = Listener; 763 OwnsDeserializationListener = TakeOwnership; 764 } 765 766 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) { 767 return serialization::ComputeHash(Sel); 768 } 769 770 std::pair<unsigned, unsigned> 771 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) { 772 using namespace llvm::support; 773 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d); 774 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d); 775 return std::make_pair(KeyLen, DataLen); 776 } 777 778 ASTSelectorLookupTrait::internal_key_type 779 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) { 780 using namespace llvm::support; 781 SelectorTable &SelTable = Reader.getContext().Selectors; 782 unsigned N = endian::readNext<uint16_t, little, unaligned>(d); 783 IdentifierInfo *FirstII = Reader.getLocalIdentifier( 784 F, endian::readNext<uint32_t, little, unaligned>(d)); 785 if (N == 0) 786 return SelTable.getNullarySelector(FirstII); 787 else if (N == 1) 788 return SelTable.getUnarySelector(FirstII); 789 790 SmallVector<IdentifierInfo *, 16> Args; 791 Args.push_back(FirstII); 792 for (unsigned I = 1; I != N; ++I) 793 Args.push_back(Reader.getLocalIdentifier( 794 F, endian::readNext<uint32_t, little, unaligned>(d))); 795 796 return SelTable.getSelector(N, Args.data()); 797 } 798 799 ASTSelectorLookupTrait::data_type 800 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d, 801 unsigned DataLen) { 802 using namespace llvm::support; 803 804 data_type Result; 805 806 Result.ID = Reader.getGlobalSelectorID( 807 F, endian::readNext<uint32_t, little, unaligned>(d)); 808 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d); 809 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d); 810 Result.InstanceBits = FullInstanceBits & 0x3; 811 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1; 812 Result.FactoryBits = FullFactoryBits & 0x3; 813 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1; 814 unsigned NumInstanceMethods = FullInstanceBits >> 3; 815 unsigned NumFactoryMethods = FullFactoryBits >> 3; 816 817 // Load instance methods 818 for (unsigned I = 0; I != NumInstanceMethods; ++I) { 819 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>( 820 F, endian::readNext<uint32_t, little, unaligned>(d))) 821 Result.Instance.push_back(Method); 822 } 823 824 // Load factory methods 825 for (unsigned I = 0; I != NumFactoryMethods; ++I) { 826 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>( 827 F, endian::readNext<uint32_t, little, unaligned>(d))) 828 Result.Factory.push_back(Method); 829 } 830 831 return Result; 832 } 833 834 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) { 835 return llvm::HashString(a); 836 } 837 838 std::pair<unsigned, unsigned> 839 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) { 840 using namespace llvm::support; 841 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d); 842 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d); 843 return std::make_pair(KeyLen, DataLen); 844 } 845 846 ASTIdentifierLookupTraitBase::internal_key_type 847 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) { 848 assert(n >= 2 && d[n-1] == '\0'); 849 return StringRef((const char*) d, n-1); 850 } 851 852 /// \brief Whether the given identifier is "interesting". 853 static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II, 854 bool IsModule) { 855 return II.hadMacroDefinition() || 856 II.isPoisoned() || 857 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) || 858 II.hasRevertedTokenIDToIdentifier() || 859 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) && 860 II.getFETokenInfo<void>()); 861 } 862 863 static bool readBit(unsigned &Bits) { 864 bool Value = Bits & 0x1; 865 Bits >>= 1; 866 return Value; 867 } 868 869 IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) { 870 using namespace llvm::support; 871 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d); 872 return Reader.getGlobalIdentifierID(F, RawID >> 1); 873 } 874 875 static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) { 876 if (!II.isFromAST()) { 877 II.setIsFromAST(); 878 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr; 879 if (isInterestingIdentifier(Reader, II, IsModule)) 880 II.setChangedSinceDeserialization(); 881 } 882 } 883 884 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k, 885 const unsigned char* d, 886 unsigned DataLen) { 887 using namespace llvm::support; 888 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d); 889 bool IsInteresting = RawID & 0x01; 890 891 // Wipe out the "is interesting" bit. 892 RawID = RawID >> 1; 893 894 // Build the IdentifierInfo and link the identifier ID with it. 895 IdentifierInfo *II = KnownII; 896 if (!II) { 897 II = &Reader.getIdentifierTable().getOwn(k); 898 KnownII = II; 899 } 900 markIdentifierFromAST(Reader, *II); 901 Reader.markIdentifierUpToDate(II); 902 903 IdentID ID = Reader.getGlobalIdentifierID(F, RawID); 904 if (!IsInteresting) { 905 // For uninteresting identifiers, there's nothing else to do. Just notify 906 // the reader that we've finished loading this identifier. 907 Reader.SetIdentifierInfo(ID, II); 908 return II; 909 } 910 911 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d); 912 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d); 913 bool CPlusPlusOperatorKeyword = readBit(Bits); 914 bool HasRevertedTokenIDToIdentifier = readBit(Bits); 915 bool HasRevertedBuiltin = readBit(Bits); 916 bool Poisoned = readBit(Bits); 917 bool ExtensionToken = readBit(Bits); 918 bool HadMacroDefinition = readBit(Bits); 919 920 assert(Bits == 0 && "Extra bits in the identifier?"); 921 DataLen -= 8; 922 923 // Set or check the various bits in the IdentifierInfo structure. 924 // Token IDs are read-only. 925 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier) 926 II->revertTokenIDToIdentifier(); 927 if (!F.isModule()) 928 II->setObjCOrBuiltinID(ObjCOrBuiltinID); 929 else if (HasRevertedBuiltin && II->getBuiltinID()) { 930 II->revertBuiltin(); 931 assert((II->hasRevertedBuiltin() || 932 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) && 933 "Incorrect ObjC keyword or builtin ID"); 934 } 935 assert(II->isExtensionToken() == ExtensionToken && 936 "Incorrect extension token flag"); 937 (void)ExtensionToken; 938 if (Poisoned) 939 II->setIsPoisoned(true); 940 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword && 941 "Incorrect C++ operator keyword flag"); 942 (void)CPlusPlusOperatorKeyword; 943 944 // If this identifier is a macro, deserialize the macro 945 // definition. 946 if (HadMacroDefinition) { 947 uint32_t MacroDirectivesOffset = 948 endian::readNext<uint32_t, little, unaligned>(d); 949 DataLen -= 4; 950 951 Reader.addPendingMacro(II, &F, MacroDirectivesOffset); 952 } 953 954 Reader.SetIdentifierInfo(ID, II); 955 956 // Read all of the declarations visible at global scope with this 957 // name. 958 if (DataLen > 0) { 959 SmallVector<uint32_t, 4> DeclIDs; 960 for (; DataLen > 0; DataLen -= 4) 961 DeclIDs.push_back(Reader.getGlobalDeclID( 962 F, endian::readNext<uint32_t, little, unaligned>(d))); 963 Reader.SetGloballyVisibleDecls(II, DeclIDs); 964 } 965 966 return II; 967 } 968 969 DeclarationNameKey::DeclarationNameKey(DeclarationName Name) 970 : Kind(Name.getNameKind()) { 971 switch (Kind) { 972 case DeclarationName::Identifier: 973 Data = (uint64_t)Name.getAsIdentifierInfo(); 974 break; 975 case DeclarationName::ObjCZeroArgSelector: 976 case DeclarationName::ObjCOneArgSelector: 977 case DeclarationName::ObjCMultiArgSelector: 978 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr(); 979 break; 980 case DeclarationName::CXXOperatorName: 981 Data = Name.getCXXOverloadedOperator(); 982 break; 983 case DeclarationName::CXXLiteralOperatorName: 984 Data = (uint64_t)Name.getCXXLiteralIdentifier(); 985 break; 986 case DeclarationName::CXXDeductionGuideName: 987 Data = (uint64_t)Name.getCXXDeductionGuideTemplate() 988 ->getDeclName().getAsIdentifierInfo(); 989 break; 990 case DeclarationName::CXXConstructorName: 991 case DeclarationName::CXXDestructorName: 992 case DeclarationName::CXXConversionFunctionName: 993 case DeclarationName::CXXUsingDirective: 994 Data = 0; 995 break; 996 } 997 } 998 999 unsigned DeclarationNameKey::getHash() const { 1000 llvm::FoldingSetNodeID ID; 1001 ID.AddInteger(Kind); 1002 1003 switch (Kind) { 1004 case DeclarationName::Identifier: 1005 case DeclarationName::CXXLiteralOperatorName: 1006 case DeclarationName::CXXDeductionGuideName: 1007 ID.AddString(((IdentifierInfo*)Data)->getName()); 1008 break; 1009 case DeclarationName::ObjCZeroArgSelector: 1010 case DeclarationName::ObjCOneArgSelector: 1011 case DeclarationName::ObjCMultiArgSelector: 1012 ID.AddInteger(serialization::ComputeHash(Selector(Data))); 1013 break; 1014 case DeclarationName::CXXOperatorName: 1015 ID.AddInteger((OverloadedOperatorKind)Data); 1016 break; 1017 case DeclarationName::CXXConstructorName: 1018 case DeclarationName::CXXDestructorName: 1019 case DeclarationName::CXXConversionFunctionName: 1020 case DeclarationName::CXXUsingDirective: 1021 break; 1022 } 1023 1024 return ID.ComputeHash(); 1025 } 1026 1027 ModuleFile * 1028 ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) { 1029 using namespace llvm::support; 1030 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d); 1031 return Reader.getLocalModuleFile(F, ModuleFileID); 1032 } 1033 1034 std::pair<unsigned, unsigned> 1035 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) { 1036 using namespace llvm::support; 1037 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d); 1038 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d); 1039 return std::make_pair(KeyLen, DataLen); 1040 } 1041 1042 ASTDeclContextNameLookupTrait::internal_key_type 1043 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) { 1044 using namespace llvm::support; 1045 1046 auto Kind = (DeclarationName::NameKind)*d++; 1047 uint64_t Data; 1048 switch (Kind) { 1049 case DeclarationName::Identifier: 1050 case DeclarationName::CXXLiteralOperatorName: 1051 case DeclarationName::CXXDeductionGuideName: 1052 Data = (uint64_t)Reader.getLocalIdentifier( 1053 F, endian::readNext<uint32_t, little, unaligned>(d)); 1054 break; 1055 case DeclarationName::ObjCZeroArgSelector: 1056 case DeclarationName::ObjCOneArgSelector: 1057 case DeclarationName::ObjCMultiArgSelector: 1058 Data = 1059 (uint64_t)Reader.getLocalSelector( 1060 F, endian::readNext<uint32_t, little, unaligned>( 1061 d)).getAsOpaquePtr(); 1062 break; 1063 case DeclarationName::CXXOperatorName: 1064 Data = *d++; // OverloadedOperatorKind 1065 break; 1066 case DeclarationName::CXXConstructorName: 1067 case DeclarationName::CXXDestructorName: 1068 case DeclarationName::CXXConversionFunctionName: 1069 case DeclarationName::CXXUsingDirective: 1070 Data = 0; 1071 break; 1072 } 1073 1074 return DeclarationNameKey(Kind, Data); 1075 } 1076 1077 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type, 1078 const unsigned char *d, 1079 unsigned DataLen, 1080 data_type_builder &Val) { 1081 using namespace llvm::support; 1082 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) { 1083 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d); 1084 Val.insert(Reader.getGlobalDeclID(F, LocalID)); 1085 } 1086 } 1087 1088 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M, 1089 BitstreamCursor &Cursor, 1090 uint64_t Offset, 1091 DeclContext *DC) { 1092 assert(Offset != 0); 1093 1094 SavedStreamPosition SavedPosition(Cursor); 1095 Cursor.JumpToBit(Offset); 1096 1097 RecordData Record; 1098 StringRef Blob; 1099 unsigned Code = Cursor.ReadCode(); 1100 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob); 1101 if (RecCode != DECL_CONTEXT_LEXICAL) { 1102 Error("Expected lexical block"); 1103 return true; 1104 } 1105 1106 assert(!isa<TranslationUnitDecl>(DC) && 1107 "expected a TU_UPDATE_LEXICAL record for TU"); 1108 // If we are handling a C++ class template instantiation, we can see multiple 1109 // lexical updates for the same record. It's important that we select only one 1110 // of them, so that field numbering works properly. Just pick the first one we 1111 // see. 1112 auto &Lex = LexicalDecls[DC]; 1113 if (!Lex.first) { 1114 Lex = std::make_pair( 1115 &M, llvm::makeArrayRef( 1116 reinterpret_cast<const llvm::support::unaligned_uint32_t *>( 1117 Blob.data()), 1118 Blob.size() / 4)); 1119 } 1120 DC->setHasExternalLexicalStorage(true); 1121 return false; 1122 } 1123 1124 bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M, 1125 BitstreamCursor &Cursor, 1126 uint64_t Offset, 1127 DeclID ID) { 1128 assert(Offset != 0); 1129 1130 SavedStreamPosition SavedPosition(Cursor); 1131 Cursor.JumpToBit(Offset); 1132 1133 RecordData Record; 1134 StringRef Blob; 1135 unsigned Code = Cursor.ReadCode(); 1136 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob); 1137 if (RecCode != DECL_CONTEXT_VISIBLE) { 1138 Error("Expected visible lookup table block"); 1139 return true; 1140 } 1141 1142 // We can't safely determine the primary context yet, so delay attaching the 1143 // lookup table until we're done with recursive deserialization. 1144 auto *Data = (const unsigned char*)Blob.data(); 1145 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data}); 1146 return false; 1147 } 1148 1149 void ASTReader::Error(StringRef Msg) const { 1150 Error(diag::err_fe_pch_malformed, Msg); 1151 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() && 1152 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) { 1153 Diag(diag::note_module_cache_path) 1154 << PP.getHeaderSearchInfo().getModuleCachePath(); 1155 } 1156 } 1157 1158 void ASTReader::Error(unsigned DiagID, 1159 StringRef Arg1, StringRef Arg2) const { 1160 if (Diags.isDiagnosticInFlight()) 1161 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2); 1162 else 1163 Diag(DiagID) << Arg1 << Arg2; 1164 } 1165 1166 //===----------------------------------------------------------------------===// 1167 // Source Manager Deserialization 1168 //===----------------------------------------------------------------------===// 1169 1170 /// \brief Read the line table in the source manager block. 1171 /// \returns true if there was an error. 1172 bool ASTReader::ParseLineTable(ModuleFile &F, 1173 const RecordData &Record) { 1174 unsigned Idx = 0; 1175 LineTableInfo &LineTable = SourceMgr.getLineTable(); 1176 1177 // Parse the file names 1178 std::map<int, int> FileIDs; 1179 for (unsigned I = 0; Record[Idx]; ++I) { 1180 // Extract the file name 1181 auto Filename = ReadPath(F, Record, Idx); 1182 FileIDs[I] = LineTable.getLineTableFilenameID(Filename); 1183 } 1184 ++Idx; 1185 1186 // Parse the line entries 1187 std::vector<LineEntry> Entries; 1188 while (Idx < Record.size()) { 1189 int FID = Record[Idx++]; 1190 assert(FID >= 0 && "Serialized line entries for non-local file."); 1191 // Remap FileID from 1-based old view. 1192 FID += F.SLocEntryBaseID - 1; 1193 1194 // Extract the line entries 1195 unsigned NumEntries = Record[Idx++]; 1196 assert(NumEntries && "no line entries for file ID"); 1197 Entries.clear(); 1198 Entries.reserve(NumEntries); 1199 for (unsigned I = 0; I != NumEntries; ++I) { 1200 unsigned FileOffset = Record[Idx++]; 1201 unsigned LineNo = Record[Idx++]; 1202 int FilenameID = FileIDs[Record[Idx++]]; 1203 SrcMgr::CharacteristicKind FileKind 1204 = (SrcMgr::CharacteristicKind)Record[Idx++]; 1205 unsigned IncludeOffset = Record[Idx++]; 1206 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID, 1207 FileKind, IncludeOffset)); 1208 } 1209 LineTable.AddEntry(FileID::get(FID), Entries); 1210 } 1211 1212 return false; 1213 } 1214 1215 /// \brief Read a source manager block 1216 bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) { 1217 using namespace SrcMgr; 1218 1219 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor; 1220 1221 // Set the source-location entry cursor to the current position in 1222 // the stream. This cursor will be used to read the contents of the 1223 // source manager block initially, and then lazily read 1224 // source-location entries as needed. 1225 SLocEntryCursor = F.Stream; 1226 1227 // The stream itself is going to skip over the source manager block. 1228 if (F.Stream.SkipBlock()) { 1229 Error("malformed block record in AST file"); 1230 return true; 1231 } 1232 1233 // Enter the source manager block. 1234 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) { 1235 Error("malformed source manager block record in AST file"); 1236 return true; 1237 } 1238 1239 RecordData Record; 1240 while (true) { 1241 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks(); 1242 1243 switch (E.Kind) { 1244 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 1245 case llvm::BitstreamEntry::Error: 1246 Error("malformed block record in AST file"); 1247 return true; 1248 case llvm::BitstreamEntry::EndBlock: 1249 return false; 1250 case llvm::BitstreamEntry::Record: 1251 // The interesting case. 1252 break; 1253 } 1254 1255 // Read a record. 1256 Record.clear(); 1257 StringRef Blob; 1258 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) { 1259 default: // Default behavior: ignore. 1260 break; 1261 1262 case SM_SLOC_FILE_ENTRY: 1263 case SM_SLOC_BUFFER_ENTRY: 1264 case SM_SLOC_EXPANSION_ENTRY: 1265 // Once we hit one of the source location entries, we're done. 1266 return false; 1267 } 1268 } 1269 } 1270 1271 /// \brief If a header file is not found at the path that we expect it to be 1272 /// and the PCH file was moved from its original location, try to resolve the 1273 /// file by assuming that header+PCH were moved together and the header is in 1274 /// the same place relative to the PCH. 1275 static std::string 1276 resolveFileRelativeToOriginalDir(const std::string &Filename, 1277 const std::string &OriginalDir, 1278 const std::string &CurrDir) { 1279 assert(OriginalDir != CurrDir && 1280 "No point trying to resolve the file if the PCH dir didn't change"); 1281 using namespace llvm::sys; 1282 SmallString<128> filePath(Filename); 1283 fs::make_absolute(filePath); 1284 assert(path::is_absolute(OriginalDir)); 1285 SmallString<128> currPCHPath(CurrDir); 1286 1287 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)), 1288 fileDirE = path::end(path::parent_path(filePath)); 1289 path::const_iterator origDirI = path::begin(OriginalDir), 1290 origDirE = path::end(OriginalDir); 1291 // Skip the common path components from filePath and OriginalDir. 1292 while (fileDirI != fileDirE && origDirI != origDirE && 1293 *fileDirI == *origDirI) { 1294 ++fileDirI; 1295 ++origDirI; 1296 } 1297 for (; origDirI != origDirE; ++origDirI) 1298 path::append(currPCHPath, ".."); 1299 path::append(currPCHPath, fileDirI, fileDirE); 1300 path::append(currPCHPath, path::filename(Filename)); 1301 return currPCHPath.str(); 1302 } 1303 1304 bool ASTReader::ReadSLocEntry(int ID) { 1305 if (ID == 0) 1306 return false; 1307 1308 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) { 1309 Error("source location entry ID out-of-range for AST file"); 1310 return true; 1311 } 1312 1313 // Local helper to read the (possibly-compressed) buffer data following the 1314 // entry record. 1315 auto ReadBuffer = [this]( 1316 BitstreamCursor &SLocEntryCursor, 1317 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> { 1318 RecordData Record; 1319 StringRef Blob; 1320 unsigned Code = SLocEntryCursor.ReadCode(); 1321 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob); 1322 1323 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) { 1324 if (!llvm::zlib::isAvailable()) { 1325 Error("zlib is not available"); 1326 return nullptr; 1327 } 1328 SmallString<0> Uncompressed; 1329 if (llvm::Error E = 1330 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) { 1331 Error("could not decompress embedded file contents: " + 1332 llvm::toString(std::move(E))); 1333 return nullptr; 1334 } 1335 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name); 1336 } else if (RecCode == SM_SLOC_BUFFER_BLOB) { 1337 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true); 1338 } else { 1339 Error("AST record has invalid code"); 1340 return nullptr; 1341 } 1342 }; 1343 1344 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second; 1345 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]); 1346 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor; 1347 unsigned BaseOffset = F->SLocEntryBaseOffset; 1348 1349 ++NumSLocEntriesRead; 1350 llvm::BitstreamEntry Entry = SLocEntryCursor.advance(); 1351 if (Entry.Kind != llvm::BitstreamEntry::Record) { 1352 Error("incorrectly-formatted source location entry in AST file"); 1353 return true; 1354 } 1355 1356 RecordData Record; 1357 StringRef Blob; 1358 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) { 1359 default: 1360 Error("incorrectly-formatted source location entry in AST file"); 1361 return true; 1362 1363 case SM_SLOC_FILE_ENTRY: { 1364 // We will detect whether a file changed and return 'Failure' for it, but 1365 // we will also try to fail gracefully by setting up the SLocEntry. 1366 unsigned InputID = Record[4]; 1367 InputFile IF = getInputFile(*F, InputID); 1368 const FileEntry *File = IF.getFile(); 1369 bool OverriddenBuffer = IF.isOverridden(); 1370 1371 // Note that we only check if a File was returned. If it was out-of-date 1372 // we have complained but we will continue creating a FileID to recover 1373 // gracefully. 1374 if (!File) 1375 return true; 1376 1377 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]); 1378 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) { 1379 // This is the module's main file. 1380 IncludeLoc = getImportLocation(F); 1381 } 1382 SrcMgr::CharacteristicKind 1383 FileCharacter = (SrcMgr::CharacteristicKind)Record[2]; 1384 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter, 1385 ID, BaseOffset + Record[0]); 1386 SrcMgr::FileInfo &FileInfo = 1387 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile()); 1388 FileInfo.NumCreatedFIDs = Record[5]; 1389 if (Record[3]) 1390 FileInfo.setHasLineDirectives(); 1391 1392 const DeclID *FirstDecl = F->FileSortedDecls + Record[6]; 1393 unsigned NumFileDecls = Record[7]; 1394 if (NumFileDecls) { 1395 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?"); 1396 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl, 1397 NumFileDecls)); 1398 } 1399 1400 const SrcMgr::ContentCache *ContentCache 1401 = SourceMgr.getOrCreateContentCache(File, 1402 /*isSystemFile=*/FileCharacter != SrcMgr::C_User); 1403 if (OverriddenBuffer && !ContentCache->BufferOverridden && 1404 ContentCache->ContentsEntry == ContentCache->OrigEntry && 1405 !ContentCache->getRawBuffer()) { 1406 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName()); 1407 if (!Buffer) 1408 return true; 1409 SourceMgr.overrideFileContents(File, std::move(Buffer)); 1410 } 1411 1412 break; 1413 } 1414 1415 case SM_SLOC_BUFFER_ENTRY: { 1416 const char *Name = Blob.data(); 1417 unsigned Offset = Record[0]; 1418 SrcMgr::CharacteristicKind 1419 FileCharacter = (SrcMgr::CharacteristicKind)Record[2]; 1420 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]); 1421 if (IncludeLoc.isInvalid() && F->isModule()) { 1422 IncludeLoc = getImportLocation(F); 1423 } 1424 1425 auto Buffer = ReadBuffer(SLocEntryCursor, Name); 1426 if (!Buffer) 1427 return true; 1428 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID, 1429 BaseOffset + Offset, IncludeLoc); 1430 break; 1431 } 1432 1433 case SM_SLOC_EXPANSION_ENTRY: { 1434 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]); 1435 SourceMgr.createExpansionLoc(SpellingLoc, 1436 ReadSourceLocation(*F, Record[2]), 1437 ReadSourceLocation(*F, Record[3]), 1438 Record[4], 1439 ID, 1440 BaseOffset + Record[0]); 1441 break; 1442 } 1443 } 1444 1445 return false; 1446 } 1447 1448 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) { 1449 if (ID == 0) 1450 return std::make_pair(SourceLocation(), ""); 1451 1452 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) { 1453 Error("source location entry ID out-of-range for AST file"); 1454 return std::make_pair(SourceLocation(), ""); 1455 } 1456 1457 // Find which module file this entry lands in. 1458 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second; 1459 if (!M->isModule()) 1460 return std::make_pair(SourceLocation(), ""); 1461 1462 // FIXME: Can we map this down to a particular submodule? That would be 1463 // ideal. 1464 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName)); 1465 } 1466 1467 /// \brief Find the location where the module F is imported. 1468 SourceLocation ASTReader::getImportLocation(ModuleFile *F) { 1469 if (F->ImportLoc.isValid()) 1470 return F->ImportLoc; 1471 1472 // Otherwise we have a PCH. It's considered to be "imported" at the first 1473 // location of its includer. 1474 if (F->ImportedBy.empty() || !F->ImportedBy[0]) { 1475 // Main file is the importer. 1476 assert(SourceMgr.getMainFileID().isValid() && "missing main file"); 1477 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); 1478 } 1479 return F->ImportedBy[0]->FirstLoc; 1480 } 1481 1482 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the 1483 /// specified cursor. Read the abbreviations that are at the top of the block 1484 /// and then leave the cursor pointing into the block. 1485 bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) { 1486 if (Cursor.EnterSubBlock(BlockID)) 1487 return true; 1488 1489 while (true) { 1490 uint64_t Offset = Cursor.GetCurrentBitNo(); 1491 unsigned Code = Cursor.ReadCode(); 1492 1493 // We expect all abbrevs to be at the start of the block. 1494 if (Code != llvm::bitc::DEFINE_ABBREV) { 1495 Cursor.JumpToBit(Offset); 1496 return false; 1497 } 1498 Cursor.ReadAbbrevRecord(); 1499 } 1500 } 1501 1502 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record, 1503 unsigned &Idx) { 1504 Token Tok; 1505 Tok.startToken(); 1506 Tok.setLocation(ReadSourceLocation(F, Record, Idx)); 1507 Tok.setLength(Record[Idx++]); 1508 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++])) 1509 Tok.setIdentifierInfo(II); 1510 Tok.setKind((tok::TokenKind)Record[Idx++]); 1511 Tok.setFlag((Token::TokenFlags)Record[Idx++]); 1512 return Tok; 1513 } 1514 1515 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) { 1516 BitstreamCursor &Stream = F.MacroCursor; 1517 1518 // Keep track of where we are in the stream, then jump back there 1519 // after reading this macro. 1520 SavedStreamPosition SavedPosition(Stream); 1521 1522 Stream.JumpToBit(Offset); 1523 RecordData Record; 1524 SmallVector<IdentifierInfo*, 16> MacroArgs; 1525 MacroInfo *Macro = nullptr; 1526 1527 while (true) { 1528 // Advance to the next record, but if we get to the end of the block, don't 1529 // pop it (removing all the abbreviations from the cursor) since we want to 1530 // be able to reseek within the block and read entries. 1531 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd; 1532 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags); 1533 1534 switch (Entry.Kind) { 1535 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 1536 case llvm::BitstreamEntry::Error: 1537 Error("malformed block record in AST file"); 1538 return Macro; 1539 case llvm::BitstreamEntry::EndBlock: 1540 return Macro; 1541 case llvm::BitstreamEntry::Record: 1542 // The interesting case. 1543 break; 1544 } 1545 1546 // Read a record. 1547 Record.clear(); 1548 PreprocessorRecordTypes RecType = 1549 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record); 1550 switch (RecType) { 1551 case PP_MODULE_MACRO: 1552 case PP_MACRO_DIRECTIVE_HISTORY: 1553 return Macro; 1554 1555 case PP_MACRO_OBJECT_LIKE: 1556 case PP_MACRO_FUNCTION_LIKE: { 1557 // If we already have a macro, that means that we've hit the end 1558 // of the definition of the macro we were looking for. We're 1559 // done. 1560 if (Macro) 1561 return Macro; 1562 1563 unsigned NextIndex = 1; // Skip identifier ID. 1564 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex); 1565 MacroInfo *MI = PP.AllocateMacroInfo(Loc); 1566 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex)); 1567 MI->setIsUsed(Record[NextIndex++]); 1568 MI->setUsedForHeaderGuard(Record[NextIndex++]); 1569 1570 if (RecType == PP_MACRO_FUNCTION_LIKE) { 1571 // Decode function-like macro info. 1572 bool isC99VarArgs = Record[NextIndex++]; 1573 bool isGNUVarArgs = Record[NextIndex++]; 1574 bool hasCommaPasting = Record[NextIndex++]; 1575 MacroArgs.clear(); 1576 unsigned NumArgs = Record[NextIndex++]; 1577 for (unsigned i = 0; i != NumArgs; ++i) 1578 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++])); 1579 1580 // Install function-like macro info. 1581 MI->setIsFunctionLike(); 1582 if (isC99VarArgs) MI->setIsC99Varargs(); 1583 if (isGNUVarArgs) MI->setIsGNUVarargs(); 1584 if (hasCommaPasting) MI->setHasCommaPasting(); 1585 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator()); 1586 } 1587 1588 // Remember that we saw this macro last so that we add the tokens that 1589 // form its body to it. 1590 Macro = MI; 1591 1592 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() && 1593 Record[NextIndex]) { 1594 // We have a macro definition. Register the association 1595 PreprocessedEntityID 1596 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]); 1597 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord(); 1598 PreprocessingRecord::PPEntityID PPID = 1599 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true); 1600 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>( 1601 PPRec.getPreprocessedEntity(PPID)); 1602 if (PPDef) 1603 PPRec.RegisterMacroDefinition(Macro, PPDef); 1604 } 1605 1606 ++NumMacrosRead; 1607 break; 1608 } 1609 1610 case PP_TOKEN: { 1611 // If we see a TOKEN before a PP_MACRO_*, then the file is 1612 // erroneous, just pretend we didn't see this. 1613 if (!Macro) break; 1614 1615 unsigned Idx = 0; 1616 Token Tok = ReadToken(F, Record, Idx); 1617 Macro->AddTokenToBody(Tok); 1618 break; 1619 } 1620 } 1621 } 1622 } 1623 1624 PreprocessedEntityID 1625 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, 1626 unsigned LocalID) const { 1627 if (!M.ModuleOffsetMap.empty()) 1628 ReadModuleOffsetMap(M); 1629 1630 ContinuousRangeMap<uint32_t, int, 2>::const_iterator 1631 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS); 1632 assert(I != M.PreprocessedEntityRemap.end() 1633 && "Invalid index into preprocessed entity index remap"); 1634 1635 return LocalID + I->second; 1636 } 1637 1638 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) { 1639 return llvm::hash_combine(ikey.Size, ikey.ModTime); 1640 } 1641 1642 HeaderFileInfoTrait::internal_key_type 1643 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) { 1644 internal_key_type ikey = {FE->getSize(), 1645 M.HasTimestamps ? FE->getModificationTime() : 0, 1646 FE->getName(), /*Imported*/ false}; 1647 return ikey; 1648 } 1649 1650 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) { 1651 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime)) 1652 return false; 1653 1654 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename) 1655 return true; 1656 1657 // Determine whether the actual files are equivalent. 1658 FileManager &FileMgr = Reader.getFileManager(); 1659 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* { 1660 if (!Key.Imported) 1661 return FileMgr.getFile(Key.Filename); 1662 1663 std::string Resolved = Key.Filename; 1664 Reader.ResolveImportedPath(M, Resolved); 1665 return FileMgr.getFile(Resolved); 1666 }; 1667 1668 const FileEntry *FEA = GetFile(a); 1669 const FileEntry *FEB = GetFile(b); 1670 return FEA && FEA == FEB; 1671 } 1672 1673 std::pair<unsigned, unsigned> 1674 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) { 1675 using namespace llvm::support; 1676 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d); 1677 unsigned DataLen = (unsigned) *d++; 1678 return std::make_pair(KeyLen, DataLen); 1679 } 1680 1681 HeaderFileInfoTrait::internal_key_type 1682 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) { 1683 using namespace llvm::support; 1684 internal_key_type ikey; 1685 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d)); 1686 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d)); 1687 ikey.Filename = (const char *)d; 1688 ikey.Imported = true; 1689 return ikey; 1690 } 1691 1692 HeaderFileInfoTrait::data_type 1693 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d, 1694 unsigned DataLen) { 1695 const unsigned char *End = d + DataLen; 1696 using namespace llvm::support; 1697 HeaderFileInfo HFI; 1698 unsigned Flags = *d++; 1699 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp. 1700 HFI.isImport |= (Flags >> 4) & 0x01; 1701 HFI.isPragmaOnce |= (Flags >> 3) & 0x01; 1702 HFI.DirInfo = (Flags >> 1) & 0x03; 1703 HFI.IndexHeaderMapHeader = Flags & 0x01; 1704 // FIXME: Find a better way to handle this. Maybe just store a 1705 // "has been included" flag? 1706 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d), 1707 HFI.NumIncludes); 1708 HFI.ControllingMacroID = Reader.getGlobalIdentifierID( 1709 M, endian::readNext<uint32_t, little, unaligned>(d)); 1710 if (unsigned FrameworkOffset = 1711 endian::readNext<uint32_t, little, unaligned>(d)) { 1712 // The framework offset is 1 greater than the actual offset, 1713 // since 0 is used as an indicator for "no framework name". 1714 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1); 1715 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName); 1716 } 1717 1718 assert((End - d) % 4 == 0 && 1719 "Wrong data length in HeaderFileInfo deserialization"); 1720 while (d != End) { 1721 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d); 1722 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3); 1723 LocalSMID >>= 2; 1724 1725 // This header is part of a module. Associate it with the module to enable 1726 // implicit module import. 1727 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID); 1728 Module *Mod = Reader.getSubmodule(GlobalSMID); 1729 FileManager &FileMgr = Reader.getFileManager(); 1730 ModuleMap &ModMap = 1731 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap(); 1732 1733 std::string Filename = key.Filename; 1734 if (key.Imported) 1735 Reader.ResolveImportedPath(M, Filename); 1736 // FIXME: This is not always the right filename-as-written, but we're not 1737 // going to use this information to rebuild the module, so it doesn't make 1738 // a lot of difference. 1739 Module::Header H = { key.Filename, FileMgr.getFile(Filename) }; 1740 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true); 1741 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader); 1742 } 1743 1744 // This HeaderFileInfo was externally loaded. 1745 HFI.External = true; 1746 HFI.IsValid = true; 1747 return HFI; 1748 } 1749 1750 void ASTReader::addPendingMacro(IdentifierInfo *II, 1751 ModuleFile *M, 1752 uint64_t MacroDirectivesOffset) { 1753 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard"); 1754 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset)); 1755 } 1756 1757 void ASTReader::ReadDefinedMacros() { 1758 // Note that we are loading defined macros. 1759 Deserializing Macros(this); 1760 1761 for (ModuleFile &I : llvm::reverse(ModuleMgr)) { 1762 BitstreamCursor &MacroCursor = I.MacroCursor; 1763 1764 // If there was no preprocessor block, skip this file. 1765 if (MacroCursor.getBitcodeBytes().empty()) 1766 continue; 1767 1768 BitstreamCursor Cursor = MacroCursor; 1769 Cursor.JumpToBit(I.MacroStartOffset); 1770 1771 RecordData Record; 1772 while (true) { 1773 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks(); 1774 1775 switch (E.Kind) { 1776 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 1777 case llvm::BitstreamEntry::Error: 1778 Error("malformed block record in AST file"); 1779 return; 1780 case llvm::BitstreamEntry::EndBlock: 1781 goto NextCursor; 1782 1783 case llvm::BitstreamEntry::Record: 1784 Record.clear(); 1785 switch (Cursor.readRecord(E.ID, Record)) { 1786 default: // Default behavior: ignore. 1787 break; 1788 1789 case PP_MACRO_OBJECT_LIKE: 1790 case PP_MACRO_FUNCTION_LIKE: { 1791 IdentifierInfo *II = getLocalIdentifier(I, Record[0]); 1792 if (II->isOutOfDate()) 1793 updateOutOfDateIdentifier(*II); 1794 break; 1795 } 1796 1797 case PP_TOKEN: 1798 // Ignore tokens. 1799 break; 1800 } 1801 break; 1802 } 1803 } 1804 NextCursor: ; 1805 } 1806 } 1807 1808 namespace { 1809 1810 /// \brief Visitor class used to look up identifirs in an AST file. 1811 class IdentifierLookupVisitor { 1812 StringRef Name; 1813 unsigned NameHash; 1814 unsigned PriorGeneration; 1815 unsigned &NumIdentifierLookups; 1816 unsigned &NumIdentifierLookupHits; 1817 IdentifierInfo *Found; 1818 1819 public: 1820 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration, 1821 unsigned &NumIdentifierLookups, 1822 unsigned &NumIdentifierLookupHits) 1823 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)), 1824 PriorGeneration(PriorGeneration), 1825 NumIdentifierLookups(NumIdentifierLookups), 1826 NumIdentifierLookupHits(NumIdentifierLookupHits), 1827 Found() 1828 { 1829 } 1830 1831 bool operator()(ModuleFile &M) { 1832 // If we've already searched this module file, skip it now. 1833 if (M.Generation <= PriorGeneration) 1834 return true; 1835 1836 ASTIdentifierLookupTable *IdTable 1837 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable; 1838 if (!IdTable) 1839 return false; 1840 1841 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M, 1842 Found); 1843 ++NumIdentifierLookups; 1844 ASTIdentifierLookupTable::iterator Pos = 1845 IdTable->find_hashed(Name, NameHash, &Trait); 1846 if (Pos == IdTable->end()) 1847 return false; 1848 1849 // Dereferencing the iterator has the effect of building the 1850 // IdentifierInfo node and populating it with the various 1851 // declarations it needs. 1852 ++NumIdentifierLookupHits; 1853 Found = *Pos; 1854 return true; 1855 } 1856 1857 // \brief Retrieve the identifier info found within the module 1858 // files. 1859 IdentifierInfo *getIdentifierInfo() const { return Found; } 1860 }; 1861 1862 } // end anonymous namespace 1863 1864 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) { 1865 // Note that we are loading an identifier. 1866 Deserializing AnIdentifier(this); 1867 1868 unsigned PriorGeneration = 0; 1869 if (getContext().getLangOpts().Modules) 1870 PriorGeneration = IdentifierGeneration[&II]; 1871 1872 // If there is a global index, look there first to determine which modules 1873 // provably do not have any results for this identifier. 1874 GlobalModuleIndex::HitSet Hits; 1875 GlobalModuleIndex::HitSet *HitsPtr = nullptr; 1876 if (!loadGlobalIndex()) { 1877 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) { 1878 HitsPtr = &Hits; 1879 } 1880 } 1881 1882 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration, 1883 NumIdentifierLookups, 1884 NumIdentifierLookupHits); 1885 ModuleMgr.visit(Visitor, HitsPtr); 1886 markIdentifierUpToDate(&II); 1887 } 1888 1889 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) { 1890 if (!II) 1891 return; 1892 1893 II->setOutOfDate(false); 1894 1895 // Update the generation for this identifier. 1896 if (getContext().getLangOpts().Modules) 1897 IdentifierGeneration[II] = getGeneration(); 1898 } 1899 1900 void ASTReader::resolvePendingMacro(IdentifierInfo *II, 1901 const PendingMacroInfo &PMInfo) { 1902 ModuleFile &M = *PMInfo.M; 1903 1904 BitstreamCursor &Cursor = M.MacroCursor; 1905 SavedStreamPosition SavedPosition(Cursor); 1906 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset); 1907 1908 struct ModuleMacroRecord { 1909 SubmoduleID SubModID; 1910 MacroInfo *MI; 1911 SmallVector<SubmoduleID, 8> Overrides; 1912 }; 1913 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros; 1914 1915 // We expect to see a sequence of PP_MODULE_MACRO records listing exported 1916 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete 1917 // macro histroy. 1918 RecordData Record; 1919 while (true) { 1920 llvm::BitstreamEntry Entry = 1921 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd); 1922 if (Entry.Kind != llvm::BitstreamEntry::Record) { 1923 Error("malformed block record in AST file"); 1924 return; 1925 } 1926 1927 Record.clear(); 1928 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) { 1929 case PP_MACRO_DIRECTIVE_HISTORY: 1930 break; 1931 1932 case PP_MODULE_MACRO: { 1933 ModuleMacros.push_back(ModuleMacroRecord()); 1934 auto &Info = ModuleMacros.back(); 1935 Info.SubModID = getGlobalSubmoduleID(M, Record[0]); 1936 Info.MI = getMacro(getGlobalMacroID(M, Record[1])); 1937 for (int I = 2, N = Record.size(); I != N; ++I) 1938 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I])); 1939 continue; 1940 } 1941 1942 default: 1943 Error("malformed block record in AST file"); 1944 return; 1945 } 1946 1947 // We found the macro directive history; that's the last record 1948 // for this macro. 1949 break; 1950 } 1951 1952 // Module macros are listed in reverse dependency order. 1953 { 1954 std::reverse(ModuleMacros.begin(), ModuleMacros.end()); 1955 llvm::SmallVector<ModuleMacro*, 8> Overrides; 1956 for (auto &MMR : ModuleMacros) { 1957 Overrides.clear(); 1958 for (unsigned ModID : MMR.Overrides) { 1959 Module *Mod = getSubmodule(ModID); 1960 auto *Macro = PP.getModuleMacro(Mod, II); 1961 assert(Macro && "missing definition for overridden macro"); 1962 Overrides.push_back(Macro); 1963 } 1964 1965 bool Inserted = false; 1966 Module *Owner = getSubmodule(MMR.SubModID); 1967 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted); 1968 } 1969 } 1970 1971 // Don't read the directive history for a module; we don't have anywhere 1972 // to put it. 1973 if (M.isModule()) 1974 return; 1975 1976 // Deserialize the macro directives history in reverse source-order. 1977 MacroDirective *Latest = nullptr, *Earliest = nullptr; 1978 unsigned Idx = 0, N = Record.size(); 1979 while (Idx < N) { 1980 MacroDirective *MD = nullptr; 1981 SourceLocation Loc = ReadSourceLocation(M, Record, Idx); 1982 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++]; 1983 switch (K) { 1984 case MacroDirective::MD_Define: { 1985 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++])); 1986 MD = PP.AllocateDefMacroDirective(MI, Loc); 1987 break; 1988 } 1989 case MacroDirective::MD_Undefine: { 1990 MD = PP.AllocateUndefMacroDirective(Loc); 1991 break; 1992 } 1993 case MacroDirective::MD_Visibility: 1994 bool isPublic = Record[Idx++]; 1995 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic); 1996 break; 1997 } 1998 1999 if (!Latest) 2000 Latest = MD; 2001 if (Earliest) 2002 Earliest->setPrevious(MD); 2003 Earliest = MD; 2004 } 2005 2006 if (Latest) 2007 PP.setLoadedMacroDirective(II, Earliest, Latest); 2008 } 2009 2010 ASTReader::InputFileInfo 2011 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) { 2012 // Go find this input file. 2013 BitstreamCursor &Cursor = F.InputFilesCursor; 2014 SavedStreamPosition SavedPosition(Cursor); 2015 Cursor.JumpToBit(F.InputFileOffsets[ID-1]); 2016 2017 unsigned Code = Cursor.ReadCode(); 2018 RecordData Record; 2019 StringRef Blob; 2020 2021 unsigned Result = Cursor.readRecord(Code, Record, &Blob); 2022 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE && 2023 "invalid record type for input file"); 2024 (void)Result; 2025 2026 assert(Record[0] == ID && "Bogus stored ID or offset"); 2027 InputFileInfo R; 2028 R.StoredSize = static_cast<off_t>(Record[1]); 2029 R.StoredTime = static_cast<time_t>(Record[2]); 2030 R.Overridden = static_cast<bool>(Record[3]); 2031 R.Transient = static_cast<bool>(Record[4]); 2032 R.Filename = Blob; 2033 ResolveImportedPath(F, R.Filename); 2034 return R; 2035 } 2036 2037 static unsigned moduleKindForDiagnostic(ModuleKind Kind); 2038 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) { 2039 // If this ID is bogus, just return an empty input file. 2040 if (ID == 0 || ID > F.InputFilesLoaded.size()) 2041 return InputFile(); 2042 2043 // If we've already loaded this input file, return it. 2044 if (F.InputFilesLoaded[ID-1].getFile()) 2045 return F.InputFilesLoaded[ID-1]; 2046 2047 if (F.InputFilesLoaded[ID-1].isNotFound()) 2048 return InputFile(); 2049 2050 // Go find this input file. 2051 BitstreamCursor &Cursor = F.InputFilesCursor; 2052 SavedStreamPosition SavedPosition(Cursor); 2053 Cursor.JumpToBit(F.InputFileOffsets[ID-1]); 2054 2055 InputFileInfo FI = readInputFileInfo(F, ID); 2056 off_t StoredSize = FI.StoredSize; 2057 time_t StoredTime = FI.StoredTime; 2058 bool Overridden = FI.Overridden; 2059 bool Transient = FI.Transient; 2060 StringRef Filename = FI.Filename; 2061 2062 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false); 2063 2064 // If we didn't find the file, resolve it relative to the 2065 // original directory from which this AST file was created. 2066 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() && 2067 F.OriginalDir != CurrentDir) { 2068 std::string Resolved = resolveFileRelativeToOriginalDir(Filename, 2069 F.OriginalDir, 2070 CurrentDir); 2071 if (!Resolved.empty()) 2072 File = FileMgr.getFile(Resolved); 2073 } 2074 2075 // For an overridden file, create a virtual file with the stored 2076 // size/timestamp. 2077 if ((Overridden || Transient) && File == nullptr) 2078 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime); 2079 2080 if (File == nullptr) { 2081 if (Complain) { 2082 std::string ErrorStr = "could not find file '"; 2083 ErrorStr += Filename; 2084 ErrorStr += "' referenced by AST file '"; 2085 ErrorStr += F.FileName; 2086 ErrorStr += "'"; 2087 Error(ErrorStr); 2088 } 2089 // Record that we didn't find the file. 2090 F.InputFilesLoaded[ID-1] = InputFile::getNotFound(); 2091 return InputFile(); 2092 } 2093 2094 // Check if there was a request to override the contents of the file 2095 // that was part of the precompiled header. Overridding such a file 2096 // can lead to problems when lexing using the source locations from the 2097 // PCH. 2098 SourceManager &SM = getSourceManager(); 2099 // FIXME: Reject if the overrides are different. 2100 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) { 2101 if (Complain) 2102 Error(diag::err_fe_pch_file_overridden, Filename); 2103 // After emitting the diagnostic, recover by disabling the override so 2104 // that the original file will be used. 2105 // 2106 // FIXME: This recovery is just as broken as the original state; there may 2107 // be another precompiled module that's using the overridden contents, or 2108 // we might be half way through parsing it. Instead, we should treat the 2109 // overridden contents as belonging to a separate FileEntry. 2110 SM.disableFileContentsOverride(File); 2111 // The FileEntry is a virtual file entry with the size of the contents 2112 // that would override the original contents. Set it to the original's 2113 // size/time. 2114 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File), 2115 StoredSize, StoredTime); 2116 } 2117 2118 bool IsOutOfDate = false; 2119 2120 // For an overridden file, there is nothing to validate. 2121 if (!Overridden && // 2122 (StoredSize != File->getSize() || 2123 (StoredTime && StoredTime != File->getModificationTime() && 2124 !DisableValidation) 2125 )) { 2126 if (Complain) { 2127 // Build a list of the PCH imports that got us here (in reverse). 2128 SmallVector<ModuleFile *, 4> ImportStack(1, &F); 2129 while (ImportStack.back()->ImportedBy.size() > 0) 2130 ImportStack.push_back(ImportStack.back()->ImportedBy[0]); 2131 2132 // The top-level PCH is stale. 2133 StringRef TopLevelPCHName(ImportStack.back()->FileName); 2134 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind); 2135 if (DiagnosticKind == 0) 2136 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName); 2137 else if (DiagnosticKind == 1) 2138 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName); 2139 else 2140 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName); 2141 2142 // Print the import stack. 2143 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) { 2144 Diag(diag::note_pch_required_by) 2145 << Filename << ImportStack[0]->FileName; 2146 for (unsigned I = 1; I < ImportStack.size(); ++I) 2147 Diag(diag::note_pch_required_by) 2148 << ImportStack[I-1]->FileName << ImportStack[I]->FileName; 2149 } 2150 2151 if (!Diags.isDiagnosticInFlight()) 2152 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName; 2153 } 2154 2155 IsOutOfDate = true; 2156 } 2157 // FIXME: If the file is overridden and we've already opened it, 2158 // issue an error (or split it into a separate FileEntry). 2159 2160 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate); 2161 2162 // Note that we've loaded this input file. 2163 F.InputFilesLoaded[ID-1] = IF; 2164 return IF; 2165 } 2166 2167 /// \brief If we are loading a relocatable PCH or module file, and the filename 2168 /// is not an absolute path, add the system or module root to the beginning of 2169 /// the file name. 2170 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) { 2171 // Resolve relative to the base directory, if we have one. 2172 if (!M.BaseDirectory.empty()) 2173 return ResolveImportedPath(Filename, M.BaseDirectory); 2174 } 2175 2176 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) { 2177 if (Filename.empty() || llvm::sys::path::is_absolute(Filename)) 2178 return; 2179 2180 SmallString<128> Buffer; 2181 llvm::sys::path::append(Buffer, Prefix, Filename); 2182 Filename.assign(Buffer.begin(), Buffer.end()); 2183 } 2184 2185 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) { 2186 switch (ARR) { 2187 case ASTReader::Failure: return true; 2188 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing); 2189 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate); 2190 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch); 2191 case ASTReader::ConfigurationMismatch: 2192 return !(Caps & ASTReader::ARR_ConfigurationMismatch); 2193 case ASTReader::HadErrors: return true; 2194 case ASTReader::Success: return false; 2195 } 2196 2197 llvm_unreachable("unknown ASTReadResult"); 2198 } 2199 2200 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock( 2201 BitstreamCursor &Stream, unsigned ClientLoadCapabilities, 2202 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener, 2203 std::string &SuggestedPredefines) { 2204 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) 2205 return Failure; 2206 2207 // Read all of the records in the options block. 2208 RecordData Record; 2209 ASTReadResult Result = Success; 2210 while (true) { 2211 llvm::BitstreamEntry Entry = Stream.advance(); 2212 2213 switch (Entry.Kind) { 2214 case llvm::BitstreamEntry::Error: 2215 case llvm::BitstreamEntry::SubBlock: 2216 return Failure; 2217 2218 case llvm::BitstreamEntry::EndBlock: 2219 return Result; 2220 2221 case llvm::BitstreamEntry::Record: 2222 // The interesting case. 2223 break; 2224 } 2225 2226 // Read and process a record. 2227 Record.clear(); 2228 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) { 2229 case LANGUAGE_OPTIONS: { 2230 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2231 if (ParseLanguageOptions(Record, Complain, Listener, 2232 AllowCompatibleConfigurationMismatch)) 2233 Result = ConfigurationMismatch; 2234 break; 2235 } 2236 2237 case TARGET_OPTIONS: { 2238 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2239 if (ParseTargetOptions(Record, Complain, Listener, 2240 AllowCompatibleConfigurationMismatch)) 2241 Result = ConfigurationMismatch; 2242 break; 2243 } 2244 2245 case FILE_SYSTEM_OPTIONS: { 2246 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2247 if (!AllowCompatibleConfigurationMismatch && 2248 ParseFileSystemOptions(Record, Complain, Listener)) 2249 Result = ConfigurationMismatch; 2250 break; 2251 } 2252 2253 case HEADER_SEARCH_OPTIONS: { 2254 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2255 if (!AllowCompatibleConfigurationMismatch && 2256 ParseHeaderSearchOptions(Record, Complain, Listener)) 2257 Result = ConfigurationMismatch; 2258 break; 2259 } 2260 2261 case PREPROCESSOR_OPTIONS: 2262 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0; 2263 if (!AllowCompatibleConfigurationMismatch && 2264 ParsePreprocessorOptions(Record, Complain, Listener, 2265 SuggestedPredefines)) 2266 Result = ConfigurationMismatch; 2267 break; 2268 } 2269 } 2270 } 2271 2272 ASTReader::ASTReadResult 2273 ASTReader::ReadControlBlock(ModuleFile &F, 2274 SmallVectorImpl<ImportedModule> &Loaded, 2275 const ModuleFile *ImportedBy, 2276 unsigned ClientLoadCapabilities) { 2277 BitstreamCursor &Stream = F.Stream; 2278 ASTReadResult Result = Success; 2279 2280 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) { 2281 Error("malformed block record in AST file"); 2282 return Failure; 2283 } 2284 2285 // Lambda to read the unhashed control block the first time it's called. 2286 // 2287 // For PCM files, the unhashed control block cannot be read until after the 2288 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still 2289 // need to look ahead before reading the IMPORTS record. For consistency, 2290 // this block is always read somehow (see BitstreamEntry::EndBlock). 2291 bool HasReadUnhashedControlBlock = false; 2292 auto readUnhashedControlBlockOnce = [&]() { 2293 if (!HasReadUnhashedControlBlock) { 2294 HasReadUnhashedControlBlock = true; 2295 if (ASTReadResult Result = 2296 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities)) 2297 return Result; 2298 } 2299 return Success; 2300 }; 2301 2302 // Read all of the records and blocks in the control block. 2303 RecordData Record; 2304 unsigned NumInputs = 0; 2305 unsigned NumUserInputs = 0; 2306 while (true) { 2307 llvm::BitstreamEntry Entry = Stream.advance(); 2308 2309 switch (Entry.Kind) { 2310 case llvm::BitstreamEntry::Error: 2311 Error("malformed block record in AST file"); 2312 return Failure; 2313 case llvm::BitstreamEntry::EndBlock: { 2314 // Validate the module before returning. This call catches an AST with 2315 // no module name and no imports. 2316 if (ASTReadResult Result = readUnhashedControlBlockOnce()) 2317 return Result; 2318 2319 // Validate input files. 2320 const HeaderSearchOptions &HSOpts = 2321 PP.getHeaderSearchInfo().getHeaderSearchOpts(); 2322 2323 // All user input files reside at the index range [0, NumUserInputs), and 2324 // system input files reside at [NumUserInputs, NumInputs). For explicitly 2325 // loaded module files, ignore missing inputs. 2326 if (!DisableValidation && F.Kind != MK_ExplicitModule && 2327 F.Kind != MK_PrebuiltModule) { 2328 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0; 2329 2330 // If we are reading a module, we will create a verification timestamp, 2331 // so we verify all input files. Otherwise, verify only user input 2332 // files. 2333 2334 unsigned N = NumUserInputs; 2335 if (ValidateSystemInputs || 2336 (HSOpts.ModulesValidateOncePerBuildSession && 2337 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp && 2338 F.Kind == MK_ImplicitModule)) 2339 N = NumInputs; 2340 2341 for (unsigned I = 0; I < N; ++I) { 2342 InputFile IF = getInputFile(F, I+1, Complain); 2343 if (!IF.getFile() || IF.isOutOfDate()) 2344 return OutOfDate; 2345 } 2346 } 2347 2348 if (Listener) 2349 Listener->visitModuleFile(F.FileName, F.Kind); 2350 2351 if (Listener && Listener->needsInputFileVisitation()) { 2352 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs 2353 : NumUserInputs; 2354 for (unsigned I = 0; I < N; ++I) { 2355 bool IsSystem = I >= NumUserInputs; 2356 InputFileInfo FI = readInputFileInfo(F, I+1); 2357 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden, 2358 F.Kind == MK_ExplicitModule || 2359 F.Kind == MK_PrebuiltModule); 2360 } 2361 } 2362 2363 return Result; 2364 } 2365 2366 case llvm::BitstreamEntry::SubBlock: 2367 switch (Entry.ID) { 2368 case INPUT_FILES_BLOCK_ID: 2369 F.InputFilesCursor = Stream; 2370 if (Stream.SkipBlock() || // Skip with the main cursor 2371 // Read the abbreviations 2372 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) { 2373 Error("malformed block record in AST file"); 2374 return Failure; 2375 } 2376 continue; 2377 2378 case OPTIONS_BLOCK_ID: 2379 // If we're reading the first module for this group, check its options 2380 // are compatible with ours. For modules it imports, no further checking 2381 // is required, because we checked them when we built it. 2382 if (Listener && !ImportedBy) { 2383 // Should we allow the configuration of the module file to differ from 2384 // the configuration of the current translation unit in a compatible 2385 // way? 2386 // 2387 // FIXME: Allow this for files explicitly specified with -include-pch. 2388 bool AllowCompatibleConfigurationMismatch = 2389 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule; 2390 2391 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities, 2392 AllowCompatibleConfigurationMismatch, 2393 *Listener, SuggestedPredefines); 2394 if (Result == Failure) { 2395 Error("malformed block record in AST file"); 2396 return Result; 2397 } 2398 2399 if (DisableValidation || 2400 (AllowConfigurationMismatch && Result == ConfigurationMismatch)) 2401 Result = Success; 2402 2403 // If we can't load the module, exit early since we likely 2404 // will rebuild the module anyway. The stream may be in the 2405 // middle of a block. 2406 if (Result != Success) 2407 return Result; 2408 } else if (Stream.SkipBlock()) { 2409 Error("malformed block record in AST file"); 2410 return Failure; 2411 } 2412 continue; 2413 2414 default: 2415 if (Stream.SkipBlock()) { 2416 Error("malformed block record in AST file"); 2417 return Failure; 2418 } 2419 continue; 2420 } 2421 2422 case llvm::BitstreamEntry::Record: 2423 // The interesting case. 2424 break; 2425 } 2426 2427 // Read and process a record. 2428 Record.clear(); 2429 StringRef Blob; 2430 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) { 2431 case METADATA: { 2432 if (Record[0] != VERSION_MAJOR && !DisableValidation) { 2433 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) 2434 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old 2435 : diag::err_pch_version_too_new); 2436 return VersionMismatch; 2437 } 2438 2439 bool hasErrors = Record[6]; 2440 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) { 2441 Diag(diag::err_pch_with_compiler_errors); 2442 return HadErrors; 2443 } 2444 if (hasErrors) { 2445 Diags.ErrorOccurred = true; 2446 Diags.UncompilableErrorOccurred = true; 2447 Diags.UnrecoverableErrorOccurred = true; 2448 } 2449 2450 F.RelocatablePCH = Record[4]; 2451 // Relative paths in a relocatable PCH are relative to our sysroot. 2452 if (F.RelocatablePCH) 2453 F.BaseDirectory = isysroot.empty() ? "/" : isysroot; 2454 2455 F.HasTimestamps = Record[5]; 2456 2457 const std::string &CurBranch = getClangFullRepositoryVersion(); 2458 StringRef ASTBranch = Blob; 2459 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) { 2460 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) 2461 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch; 2462 return VersionMismatch; 2463 } 2464 break; 2465 } 2466 2467 case IMPORTS: { 2468 // Validate the AST before processing any imports (otherwise, untangling 2469 // them can be error-prone and expensive). A module will have a name and 2470 // will already have been validated, but this catches the PCH case. 2471 if (ASTReadResult Result = readUnhashedControlBlockOnce()) 2472 return Result; 2473 2474 // Load each of the imported PCH files. 2475 unsigned Idx = 0, N = Record.size(); 2476 while (Idx < N) { 2477 // Read information about the AST file. 2478 ModuleKind ImportedKind = (ModuleKind)Record[Idx++]; 2479 // The import location will be the local one for now; we will adjust 2480 // all import locations of module imports after the global source 2481 // location info are setup, in ReadAST. 2482 SourceLocation ImportLoc = 2483 ReadUntranslatedSourceLocation(Record[Idx++]); 2484 off_t StoredSize = (off_t)Record[Idx++]; 2485 time_t StoredModTime = (time_t)Record[Idx++]; 2486 ASTFileSignature StoredSignature = { 2487 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++], 2488 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++], 2489 (uint32_t)Record[Idx++]}}}; 2490 auto ImportedFile = ReadPath(F, Record, Idx); 2491 2492 // If our client can't cope with us being out of date, we can't cope with 2493 // our dependency being missing. 2494 unsigned Capabilities = ClientLoadCapabilities; 2495 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 2496 Capabilities &= ~ARR_Missing; 2497 2498 // Load the AST file. 2499 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, 2500 Loaded, StoredSize, StoredModTime, 2501 StoredSignature, Capabilities); 2502 2503 // If we diagnosed a problem, produce a backtrace. 2504 if (isDiagnosedResult(Result, Capabilities)) 2505 Diag(diag::note_module_file_imported_by) 2506 << F.FileName << !F.ModuleName.empty() << F.ModuleName; 2507 2508 switch (Result) { 2509 case Failure: return Failure; 2510 // If we have to ignore the dependency, we'll have to ignore this too. 2511 case Missing: 2512 case OutOfDate: return OutOfDate; 2513 case VersionMismatch: return VersionMismatch; 2514 case ConfigurationMismatch: return ConfigurationMismatch; 2515 case HadErrors: return HadErrors; 2516 case Success: break; 2517 } 2518 } 2519 break; 2520 } 2521 2522 case ORIGINAL_FILE: 2523 F.OriginalSourceFileID = FileID::get(Record[0]); 2524 F.ActualOriginalSourceFileName = Blob; 2525 F.OriginalSourceFileName = F.ActualOriginalSourceFileName; 2526 ResolveImportedPath(F, F.OriginalSourceFileName); 2527 break; 2528 2529 case ORIGINAL_FILE_ID: 2530 F.OriginalSourceFileID = FileID::get(Record[0]); 2531 break; 2532 2533 case ORIGINAL_PCH_DIR: 2534 F.OriginalDir = Blob; 2535 break; 2536 2537 case MODULE_NAME: 2538 F.ModuleName = Blob; 2539 if (Listener) 2540 Listener->ReadModuleName(F.ModuleName); 2541 2542 // Validate the AST as soon as we have a name so we can exit early on 2543 // failure. 2544 if (ASTReadResult Result = readUnhashedControlBlockOnce()) 2545 return Result; 2546 2547 break; 2548 2549 case MODULE_DIRECTORY: { 2550 assert(!F.ModuleName.empty() && 2551 "MODULE_DIRECTORY found before MODULE_NAME"); 2552 // If we've already loaded a module map file covering this module, we may 2553 // have a better path for it (relative to the current build). 2554 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName); 2555 if (M && M->Directory) { 2556 // If we're implicitly loading a module, the base directory can't 2557 // change between the build and use. 2558 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) { 2559 const DirectoryEntry *BuildDir = 2560 PP.getFileManager().getDirectory(Blob); 2561 if (!BuildDir || BuildDir != M->Directory) { 2562 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 2563 Diag(diag::err_imported_module_relocated) 2564 << F.ModuleName << Blob << M->Directory->getName(); 2565 return OutOfDate; 2566 } 2567 } 2568 F.BaseDirectory = M->Directory->getName(); 2569 } else { 2570 F.BaseDirectory = Blob; 2571 } 2572 break; 2573 } 2574 2575 case MODULE_MAP_FILE: 2576 if (ASTReadResult Result = 2577 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities)) 2578 return Result; 2579 break; 2580 2581 case INPUT_FILE_OFFSETS: 2582 NumInputs = Record[0]; 2583 NumUserInputs = Record[1]; 2584 F.InputFileOffsets = 2585 (const llvm::support::unaligned_uint64_t *)Blob.data(); 2586 F.InputFilesLoaded.resize(NumInputs); 2587 F.NumUserInputFiles = NumUserInputs; 2588 break; 2589 } 2590 } 2591 } 2592 2593 ASTReader::ASTReadResult 2594 ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { 2595 BitstreamCursor &Stream = F.Stream; 2596 2597 if (Stream.EnterSubBlock(AST_BLOCK_ID)) { 2598 Error("malformed block record in AST file"); 2599 return Failure; 2600 } 2601 2602 // Read all of the records and blocks for the AST file. 2603 RecordData Record; 2604 while (true) { 2605 llvm::BitstreamEntry Entry = Stream.advance(); 2606 2607 switch (Entry.Kind) { 2608 case llvm::BitstreamEntry::Error: 2609 Error("error at end of module block in AST file"); 2610 return Failure; 2611 case llvm::BitstreamEntry::EndBlock: { 2612 // Outside of C++, we do not store a lookup map for the translation unit. 2613 // Instead, mark it as needing a lookup map to be built if this module 2614 // contains any declarations lexically within it (which it always does!). 2615 // This usually has no cost, since we very rarely need the lookup map for 2616 // the translation unit outside C++. 2617 DeclContext *DC = Context.getTranslationUnitDecl(); 2618 if (DC->hasExternalLexicalStorage() && 2619 !getContext().getLangOpts().CPlusPlus) 2620 DC->setMustBuildLookupTable(); 2621 2622 return Success; 2623 } 2624 case llvm::BitstreamEntry::SubBlock: 2625 switch (Entry.ID) { 2626 case DECLTYPES_BLOCK_ID: 2627 // We lazily load the decls block, but we want to set up the 2628 // DeclsCursor cursor to point into it. Clone our current bitcode 2629 // cursor to it, enter the block and read the abbrevs in that block. 2630 // With the main cursor, we just skip over it. 2631 F.DeclsCursor = Stream; 2632 if (Stream.SkipBlock() || // Skip with the main cursor. 2633 // Read the abbrevs. 2634 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) { 2635 Error("malformed block record in AST file"); 2636 return Failure; 2637 } 2638 break; 2639 2640 case PREPROCESSOR_BLOCK_ID: 2641 F.MacroCursor = Stream; 2642 if (!PP.getExternalSource()) 2643 PP.setExternalSource(this); 2644 2645 if (Stream.SkipBlock() || 2646 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) { 2647 Error("malformed block record in AST file"); 2648 return Failure; 2649 } 2650 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo(); 2651 break; 2652 2653 case PREPROCESSOR_DETAIL_BLOCK_ID: 2654 F.PreprocessorDetailCursor = Stream; 2655 if (Stream.SkipBlock() || 2656 ReadBlockAbbrevs(F.PreprocessorDetailCursor, 2657 PREPROCESSOR_DETAIL_BLOCK_ID)) { 2658 Error("malformed preprocessor detail record in AST file"); 2659 return Failure; 2660 } 2661 F.PreprocessorDetailStartOffset 2662 = F.PreprocessorDetailCursor.GetCurrentBitNo(); 2663 2664 if (!PP.getPreprocessingRecord()) 2665 PP.createPreprocessingRecord(); 2666 if (!PP.getPreprocessingRecord()->getExternalSource()) 2667 PP.getPreprocessingRecord()->SetExternalSource(*this); 2668 break; 2669 2670 case SOURCE_MANAGER_BLOCK_ID: 2671 if (ReadSourceManagerBlock(F)) 2672 return Failure; 2673 break; 2674 2675 case SUBMODULE_BLOCK_ID: 2676 if (ASTReadResult Result = 2677 ReadSubmoduleBlock(F, ClientLoadCapabilities)) 2678 return Result; 2679 break; 2680 2681 case COMMENTS_BLOCK_ID: { 2682 BitstreamCursor C = Stream; 2683 if (Stream.SkipBlock() || 2684 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) { 2685 Error("malformed comments block in AST file"); 2686 return Failure; 2687 } 2688 CommentsCursors.push_back(std::make_pair(C, &F)); 2689 break; 2690 } 2691 2692 default: 2693 if (Stream.SkipBlock()) { 2694 Error("malformed block record in AST file"); 2695 return Failure; 2696 } 2697 break; 2698 } 2699 continue; 2700 2701 case llvm::BitstreamEntry::Record: 2702 // The interesting case. 2703 break; 2704 } 2705 2706 // Read and process a record. 2707 Record.clear(); 2708 StringRef Blob; 2709 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) { 2710 default: // Default behavior: ignore. 2711 break; 2712 2713 case TYPE_OFFSET: { 2714 if (F.LocalNumTypes != 0) { 2715 Error("duplicate TYPE_OFFSET record in AST file"); 2716 return Failure; 2717 } 2718 F.TypeOffsets = (const uint32_t *)Blob.data(); 2719 F.LocalNumTypes = Record[0]; 2720 unsigned LocalBaseTypeIndex = Record[1]; 2721 F.BaseTypeIndex = getTotalNumTypes(); 2722 2723 if (F.LocalNumTypes > 0) { 2724 // Introduce the global -> local mapping for types within this module. 2725 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F)); 2726 2727 // Introduce the local -> global mapping for types within this module. 2728 F.TypeRemap.insertOrReplace( 2729 std::make_pair(LocalBaseTypeIndex, 2730 F.BaseTypeIndex - LocalBaseTypeIndex)); 2731 2732 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes); 2733 } 2734 break; 2735 } 2736 2737 case DECL_OFFSET: { 2738 if (F.LocalNumDecls != 0) { 2739 Error("duplicate DECL_OFFSET record in AST file"); 2740 return Failure; 2741 } 2742 F.DeclOffsets = (const DeclOffset *)Blob.data(); 2743 F.LocalNumDecls = Record[0]; 2744 unsigned LocalBaseDeclID = Record[1]; 2745 F.BaseDeclID = getTotalNumDecls(); 2746 2747 if (F.LocalNumDecls > 0) { 2748 // Introduce the global -> local mapping for declarations within this 2749 // module. 2750 GlobalDeclMap.insert( 2751 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F)); 2752 2753 // Introduce the local -> global mapping for declarations within this 2754 // module. 2755 F.DeclRemap.insertOrReplace( 2756 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID)); 2757 2758 // Introduce the global -> local mapping for declarations within this 2759 // module. 2760 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID; 2761 2762 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls); 2763 } 2764 break; 2765 } 2766 2767 case TU_UPDATE_LEXICAL: { 2768 DeclContext *TU = Context.getTranslationUnitDecl(); 2769 LexicalContents Contents( 2770 reinterpret_cast<const llvm::support::unaligned_uint32_t *>( 2771 Blob.data()), 2772 static_cast<unsigned int>(Blob.size() / 4)); 2773 TULexicalDecls.push_back(std::make_pair(&F, Contents)); 2774 TU->setHasExternalLexicalStorage(true); 2775 break; 2776 } 2777 2778 case UPDATE_VISIBLE: { 2779 unsigned Idx = 0; 2780 serialization::DeclID ID = ReadDeclID(F, Record, Idx); 2781 auto *Data = (const unsigned char*)Blob.data(); 2782 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data}); 2783 // If we've already loaded the decl, perform the updates when we finish 2784 // loading this block. 2785 if (Decl *D = GetExistingDecl(ID)) 2786 PendingUpdateRecords.push_back( 2787 PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); 2788 break; 2789 } 2790 2791 case IDENTIFIER_TABLE: 2792 F.IdentifierTableData = Blob.data(); 2793 if (Record[0]) { 2794 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create( 2795 (const unsigned char *)F.IdentifierTableData + Record[0], 2796 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t), 2797 (const unsigned char *)F.IdentifierTableData, 2798 ASTIdentifierLookupTrait(*this, F)); 2799 2800 PP.getIdentifierTable().setExternalIdentifierLookup(this); 2801 } 2802 break; 2803 2804 case IDENTIFIER_OFFSET: { 2805 if (F.LocalNumIdentifiers != 0) { 2806 Error("duplicate IDENTIFIER_OFFSET record in AST file"); 2807 return Failure; 2808 } 2809 F.IdentifierOffsets = (const uint32_t *)Blob.data(); 2810 F.LocalNumIdentifiers = Record[0]; 2811 unsigned LocalBaseIdentifierID = Record[1]; 2812 F.BaseIdentifierID = getTotalNumIdentifiers(); 2813 2814 if (F.LocalNumIdentifiers > 0) { 2815 // Introduce the global -> local mapping for identifiers within this 2816 // module. 2817 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1, 2818 &F)); 2819 2820 // Introduce the local -> global mapping for identifiers within this 2821 // module. 2822 F.IdentifierRemap.insertOrReplace( 2823 std::make_pair(LocalBaseIdentifierID, 2824 F.BaseIdentifierID - LocalBaseIdentifierID)); 2825 2826 IdentifiersLoaded.resize(IdentifiersLoaded.size() 2827 + F.LocalNumIdentifiers); 2828 } 2829 break; 2830 } 2831 2832 case INTERESTING_IDENTIFIERS: 2833 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end()); 2834 break; 2835 2836 case EAGERLY_DESERIALIZED_DECLS: 2837 // FIXME: Skip reading this record if our ASTConsumer doesn't care 2838 // about "interesting" decls (for instance, if we're building a module). 2839 for (unsigned I = 0, N = Record.size(); I != N; ++I) 2840 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I])); 2841 break; 2842 2843 case MODULAR_CODEGEN_DECLS: 2844 // FIXME: Skip reading this record if our ASTConsumer doesn't care about 2845 // them (ie: if we're not codegenerating this module). 2846 if (F.Kind == MK_MainFile) 2847 for (unsigned I = 0, N = Record.size(); I != N; ++I) 2848 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I])); 2849 break; 2850 2851 case SPECIAL_TYPES: 2852 if (SpecialTypes.empty()) { 2853 for (unsigned I = 0, N = Record.size(); I != N; ++I) 2854 SpecialTypes.push_back(getGlobalTypeID(F, Record[I])); 2855 break; 2856 } 2857 2858 if (SpecialTypes.size() != Record.size()) { 2859 Error("invalid special-types record"); 2860 return Failure; 2861 } 2862 2863 for (unsigned I = 0, N = Record.size(); I != N; ++I) { 2864 serialization::TypeID ID = getGlobalTypeID(F, Record[I]); 2865 if (!SpecialTypes[I]) 2866 SpecialTypes[I] = ID; 2867 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate 2868 // merge step? 2869 } 2870 break; 2871 2872 case STATISTICS: 2873 TotalNumStatements += Record[0]; 2874 TotalNumMacros += Record[1]; 2875 TotalLexicalDeclContexts += Record[2]; 2876 TotalVisibleDeclContexts += Record[3]; 2877 break; 2878 2879 case UNUSED_FILESCOPED_DECLS: 2880 for (unsigned I = 0, N = Record.size(); I != N; ++I) 2881 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I])); 2882 break; 2883 2884 case DELEGATING_CTORS: 2885 for (unsigned I = 0, N = Record.size(); I != N; ++I) 2886 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I])); 2887 break; 2888 2889 case WEAK_UNDECLARED_IDENTIFIERS: 2890 if (Record.size() % 4 != 0) { 2891 Error("invalid weak identifiers record"); 2892 return Failure; 2893 } 2894 2895 // FIXME: Ignore weak undeclared identifiers from non-original PCH 2896 // files. This isn't the way to do it :) 2897 WeakUndeclaredIdentifiers.clear(); 2898 2899 // Translate the weak, undeclared identifiers into global IDs. 2900 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) { 2901 WeakUndeclaredIdentifiers.push_back( 2902 getGlobalIdentifierID(F, Record[I++])); 2903 WeakUndeclaredIdentifiers.push_back( 2904 getGlobalIdentifierID(F, Record[I++])); 2905 WeakUndeclaredIdentifiers.push_back( 2906 ReadSourceLocation(F, Record, I).getRawEncoding()); 2907 WeakUndeclaredIdentifiers.push_back(Record[I++]); 2908 } 2909 break; 2910 2911 case SELECTOR_OFFSETS: { 2912 F.SelectorOffsets = (const uint32_t *)Blob.data(); 2913 F.LocalNumSelectors = Record[0]; 2914 unsigned LocalBaseSelectorID = Record[1]; 2915 F.BaseSelectorID = getTotalNumSelectors(); 2916 2917 if (F.LocalNumSelectors > 0) { 2918 // Introduce the global -> local mapping for selectors within this 2919 // module. 2920 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F)); 2921 2922 // Introduce the local -> global mapping for selectors within this 2923 // module. 2924 F.SelectorRemap.insertOrReplace( 2925 std::make_pair(LocalBaseSelectorID, 2926 F.BaseSelectorID - LocalBaseSelectorID)); 2927 2928 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors); 2929 } 2930 break; 2931 } 2932 2933 case METHOD_POOL: 2934 F.SelectorLookupTableData = (const unsigned char *)Blob.data(); 2935 if (Record[0]) 2936 F.SelectorLookupTable 2937 = ASTSelectorLookupTable::Create( 2938 F.SelectorLookupTableData + Record[0], 2939 F.SelectorLookupTableData, 2940 ASTSelectorLookupTrait(*this, F)); 2941 TotalNumMethodPoolEntries += Record[1]; 2942 break; 2943 2944 case REFERENCED_SELECTOR_POOL: 2945 if (!Record.empty()) { 2946 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) { 2947 ReferencedSelectorsData.push_back(getGlobalSelectorID(F, 2948 Record[Idx++])); 2949 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx). 2950 getRawEncoding()); 2951 } 2952 } 2953 break; 2954 2955 case PP_CONDITIONAL_STACK: 2956 if (!Record.empty()) { 2957 SmallVector<PPConditionalInfo, 4> ConditionalStack; 2958 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) { 2959 auto Loc = ReadSourceLocation(F, Record, Idx); 2960 bool WasSkipping = Record[Idx++]; 2961 bool FoundNonSkip = Record[Idx++]; 2962 bool FoundElse = Record[Idx++]; 2963 ConditionalStack.push_back( 2964 {Loc, WasSkipping, FoundNonSkip, FoundElse}); 2965 } 2966 PP.setReplayablePreambleConditionalStack(ConditionalStack); 2967 } 2968 break; 2969 2970 case PP_COUNTER_VALUE: 2971 if (!Record.empty() && Listener) 2972 Listener->ReadCounter(F, Record[0]); 2973 break; 2974 2975 case FILE_SORTED_DECLS: 2976 F.FileSortedDecls = (const DeclID *)Blob.data(); 2977 F.NumFileSortedDecls = Record[0]; 2978 break; 2979 2980 case SOURCE_LOCATION_OFFSETS: { 2981 F.SLocEntryOffsets = (const uint32_t *)Blob.data(); 2982 F.LocalNumSLocEntries = Record[0]; 2983 unsigned SLocSpaceSize = Record[1]; 2984 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) = 2985 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries, 2986 SLocSpaceSize); 2987 if (!F.SLocEntryBaseID) { 2988 Error("ran out of source locations"); 2989 break; 2990 } 2991 // Make our entry in the range map. BaseID is negative and growing, so 2992 // we invert it. Because we invert it, though, we need the other end of 2993 // the range. 2994 unsigned RangeStart = 2995 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1; 2996 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F)); 2997 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset); 2998 2999 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing. 3000 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0); 3001 GlobalSLocOffsetMap.insert( 3002 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset 3003 - SLocSpaceSize,&F)); 3004 3005 // Initialize the remapping table. 3006 // Invalid stays invalid. 3007 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0)); 3008 // This module. Base was 2 when being compiled. 3009 F.SLocRemap.insertOrReplace(std::make_pair(2U, 3010 static_cast<int>(F.SLocEntryBaseOffset - 2))); 3011 3012 TotalNumSLocEntries += F.LocalNumSLocEntries; 3013 break; 3014 } 3015 3016 case MODULE_OFFSET_MAP: 3017 F.ModuleOffsetMap = Blob; 3018 break; 3019 3020 case SOURCE_MANAGER_LINE_TABLE: 3021 if (ParseLineTable(F, Record)) 3022 return Failure; 3023 break; 3024 3025 case SOURCE_LOCATION_PRELOADS: { 3026 // Need to transform from the local view (1-based IDs) to the global view, 3027 // which is based off F.SLocEntryBaseID. 3028 if (!F.PreloadSLocEntries.empty()) { 3029 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file"); 3030 return Failure; 3031 } 3032 3033 F.PreloadSLocEntries.swap(Record); 3034 break; 3035 } 3036 3037 case EXT_VECTOR_DECLS: 3038 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3039 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I])); 3040 break; 3041 3042 case VTABLE_USES: 3043 if (Record.size() % 3 != 0) { 3044 Error("Invalid VTABLE_USES record"); 3045 return Failure; 3046 } 3047 3048 // Later tables overwrite earlier ones. 3049 // FIXME: Modules will have some trouble with this. This is clearly not 3050 // the right way to do this. 3051 VTableUses.clear(); 3052 3053 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) { 3054 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++])); 3055 VTableUses.push_back( 3056 ReadSourceLocation(F, Record, Idx).getRawEncoding()); 3057 VTableUses.push_back(Record[Idx++]); 3058 } 3059 break; 3060 3061 case PENDING_IMPLICIT_INSTANTIATIONS: 3062 if (PendingInstantiations.size() % 2 != 0) { 3063 Error("Invalid existing PendingInstantiations"); 3064 return Failure; 3065 } 3066 3067 if (Record.size() % 2 != 0) { 3068 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block"); 3069 return Failure; 3070 } 3071 3072 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) { 3073 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++])); 3074 PendingInstantiations.push_back( 3075 ReadSourceLocation(F, Record, I).getRawEncoding()); 3076 } 3077 break; 3078 3079 case SEMA_DECL_REFS: 3080 if (Record.size() != 3) { 3081 Error("Invalid SEMA_DECL_REFS block"); 3082 return Failure; 3083 } 3084 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3085 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I])); 3086 break; 3087 3088 case PPD_ENTITIES_OFFSETS: { 3089 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data(); 3090 assert(Blob.size() % sizeof(PPEntityOffset) == 0); 3091 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset); 3092 3093 unsigned LocalBasePreprocessedEntityID = Record[0]; 3094 3095 unsigned StartingID; 3096 if (!PP.getPreprocessingRecord()) 3097 PP.createPreprocessingRecord(); 3098 if (!PP.getPreprocessingRecord()->getExternalSource()) 3099 PP.getPreprocessingRecord()->SetExternalSource(*this); 3100 StartingID 3101 = PP.getPreprocessingRecord() 3102 ->allocateLoadedEntities(F.NumPreprocessedEntities); 3103 F.BasePreprocessedEntityID = StartingID; 3104 3105 if (F.NumPreprocessedEntities > 0) { 3106 // Introduce the global -> local mapping for preprocessed entities in 3107 // this module. 3108 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F)); 3109 3110 // Introduce the local -> global mapping for preprocessed entities in 3111 // this module. 3112 F.PreprocessedEntityRemap.insertOrReplace( 3113 std::make_pair(LocalBasePreprocessedEntityID, 3114 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID)); 3115 } 3116 3117 break; 3118 } 3119 3120 case DECL_UPDATE_OFFSETS: { 3121 if (Record.size() % 2 != 0) { 3122 Error("invalid DECL_UPDATE_OFFSETS block in AST file"); 3123 return Failure; 3124 } 3125 for (unsigned I = 0, N = Record.size(); I != N; I += 2) { 3126 GlobalDeclID ID = getGlobalDeclID(F, Record[I]); 3127 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1])); 3128 3129 // If we've already loaded the decl, perform the updates when we finish 3130 // loading this block. 3131 if (Decl *D = GetExistingDecl(ID)) 3132 PendingUpdateRecords.push_back( 3133 PendingUpdateRecord(ID, D, /*JustLoaded=*/false)); 3134 } 3135 break; 3136 } 3137 3138 case OBJC_CATEGORIES_MAP: { 3139 if (F.LocalNumObjCCategoriesInMap != 0) { 3140 Error("duplicate OBJC_CATEGORIES_MAP record in AST file"); 3141 return Failure; 3142 } 3143 3144 F.LocalNumObjCCategoriesInMap = Record[0]; 3145 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data(); 3146 break; 3147 } 3148 3149 case OBJC_CATEGORIES: 3150 F.ObjCCategories.swap(Record); 3151 break; 3152 3153 case CUDA_SPECIAL_DECL_REFS: 3154 // Later tables overwrite earlier ones. 3155 // FIXME: Modules will have trouble with this. 3156 CUDASpecialDeclRefs.clear(); 3157 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3158 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I])); 3159 break; 3160 3161 case HEADER_SEARCH_TABLE: { 3162 F.HeaderFileInfoTableData = Blob.data(); 3163 F.LocalNumHeaderFileInfos = Record[1]; 3164 if (Record[0]) { 3165 F.HeaderFileInfoTable 3166 = HeaderFileInfoLookupTable::Create( 3167 (const unsigned char *)F.HeaderFileInfoTableData + Record[0], 3168 (const unsigned char *)F.HeaderFileInfoTableData, 3169 HeaderFileInfoTrait(*this, F, 3170 &PP.getHeaderSearchInfo(), 3171 Blob.data() + Record[2])); 3172 3173 PP.getHeaderSearchInfo().SetExternalSource(this); 3174 if (!PP.getHeaderSearchInfo().getExternalLookup()) 3175 PP.getHeaderSearchInfo().SetExternalLookup(this); 3176 } 3177 break; 3178 } 3179 3180 case FP_PRAGMA_OPTIONS: 3181 // Later tables overwrite earlier ones. 3182 FPPragmaOptions.swap(Record); 3183 break; 3184 3185 case OPENCL_EXTENSIONS: 3186 for (unsigned I = 0, E = Record.size(); I != E; ) { 3187 auto Name = ReadString(Record, I); 3188 auto &Opt = OpenCLExtensions.OptMap[Name]; 3189 Opt.Supported = Record[I++] != 0; 3190 Opt.Enabled = Record[I++] != 0; 3191 Opt.Avail = Record[I++]; 3192 Opt.Core = Record[I++]; 3193 } 3194 break; 3195 3196 case OPENCL_EXTENSION_TYPES: 3197 for (unsigned I = 0, E = Record.size(); I != E;) { 3198 auto TypeID = static_cast<::TypeID>(Record[I++]); 3199 auto *Type = GetType(TypeID).getTypePtr(); 3200 auto NumExt = static_cast<unsigned>(Record[I++]); 3201 for (unsigned II = 0; II != NumExt; ++II) { 3202 auto Ext = ReadString(Record, I); 3203 OpenCLTypeExtMap[Type].insert(Ext); 3204 } 3205 } 3206 break; 3207 3208 case OPENCL_EXTENSION_DECLS: 3209 for (unsigned I = 0, E = Record.size(); I != E;) { 3210 auto DeclID = static_cast<::DeclID>(Record[I++]); 3211 auto *Decl = GetDecl(DeclID); 3212 auto NumExt = static_cast<unsigned>(Record[I++]); 3213 for (unsigned II = 0; II != NumExt; ++II) { 3214 auto Ext = ReadString(Record, I); 3215 OpenCLDeclExtMap[Decl].insert(Ext); 3216 } 3217 } 3218 break; 3219 3220 case TENTATIVE_DEFINITIONS: 3221 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3222 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I])); 3223 break; 3224 3225 case KNOWN_NAMESPACES: 3226 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3227 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I])); 3228 break; 3229 3230 case UNDEFINED_BUT_USED: 3231 if (UndefinedButUsed.size() % 2 != 0) { 3232 Error("Invalid existing UndefinedButUsed"); 3233 return Failure; 3234 } 3235 3236 if (Record.size() % 2 != 0) { 3237 Error("invalid undefined-but-used record"); 3238 return Failure; 3239 } 3240 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) { 3241 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++])); 3242 UndefinedButUsed.push_back( 3243 ReadSourceLocation(F, Record, I).getRawEncoding()); 3244 } 3245 break; 3246 case DELETE_EXPRS_TO_ANALYZE: 3247 for (unsigned I = 0, N = Record.size(); I != N;) { 3248 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++])); 3249 const uint64_t Count = Record[I++]; 3250 DelayedDeleteExprs.push_back(Count); 3251 for (uint64_t C = 0; C < Count; ++C) { 3252 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding()); 3253 bool IsArrayForm = Record[I++] == 1; 3254 DelayedDeleteExprs.push_back(IsArrayForm); 3255 } 3256 } 3257 break; 3258 3259 case IMPORTED_MODULES: { 3260 if (!F.isModule()) { 3261 // If we aren't loading a module (which has its own exports), make 3262 // all of the imported modules visible. 3263 // FIXME: Deal with macros-only imports. 3264 for (unsigned I = 0, N = Record.size(); I != N; /**/) { 3265 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]); 3266 SourceLocation Loc = ReadSourceLocation(F, Record, I); 3267 if (GlobalID) { 3268 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc)); 3269 if (DeserializationListener) 3270 DeserializationListener->ModuleImportRead(GlobalID, Loc); 3271 } 3272 } 3273 } 3274 break; 3275 } 3276 3277 case MACRO_OFFSET: { 3278 if (F.LocalNumMacros != 0) { 3279 Error("duplicate MACRO_OFFSET record in AST file"); 3280 return Failure; 3281 } 3282 F.MacroOffsets = (const uint32_t *)Blob.data(); 3283 F.LocalNumMacros = Record[0]; 3284 unsigned LocalBaseMacroID = Record[1]; 3285 F.BaseMacroID = getTotalNumMacros(); 3286 3287 if (F.LocalNumMacros > 0) { 3288 // Introduce the global -> local mapping for macros within this module. 3289 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F)); 3290 3291 // Introduce the local -> global mapping for macros within this module. 3292 F.MacroRemap.insertOrReplace( 3293 std::make_pair(LocalBaseMacroID, 3294 F.BaseMacroID - LocalBaseMacroID)); 3295 3296 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros); 3297 } 3298 break; 3299 } 3300 3301 case LATE_PARSED_TEMPLATE: { 3302 LateParsedTemplates.append(Record.begin(), Record.end()); 3303 break; 3304 } 3305 3306 case OPTIMIZE_PRAGMA_OPTIONS: 3307 if (Record.size() != 1) { 3308 Error("invalid pragma optimize record"); 3309 return Failure; 3310 } 3311 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]); 3312 break; 3313 3314 case MSSTRUCT_PRAGMA_OPTIONS: 3315 if (Record.size() != 1) { 3316 Error("invalid pragma ms_struct record"); 3317 return Failure; 3318 } 3319 PragmaMSStructState = Record[0]; 3320 break; 3321 3322 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS: 3323 if (Record.size() != 2) { 3324 Error("invalid pragma ms_struct record"); 3325 return Failure; 3326 } 3327 PragmaMSPointersToMembersState = Record[0]; 3328 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]); 3329 break; 3330 3331 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES: 3332 for (unsigned I = 0, N = Record.size(); I != N; ++I) 3333 UnusedLocalTypedefNameCandidates.push_back( 3334 getGlobalDeclID(F, Record[I])); 3335 break; 3336 3337 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH: 3338 if (Record.size() != 1) { 3339 Error("invalid cuda pragma options record"); 3340 return Failure; 3341 } 3342 ForceCUDAHostDeviceDepth = Record[0]; 3343 break; 3344 3345 case PACK_PRAGMA_OPTIONS: { 3346 if (Record.size() < 3) { 3347 Error("invalid pragma pack record"); 3348 return Failure; 3349 } 3350 PragmaPackCurrentValue = Record[0]; 3351 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]); 3352 unsigned NumStackEntries = Record[2]; 3353 unsigned Idx = 3; 3354 // Reset the stack when importing a new module. 3355 PragmaPackStack.clear(); 3356 for (unsigned I = 0; I < NumStackEntries; ++I) { 3357 PragmaPackStackEntry Entry; 3358 Entry.Value = Record[Idx++]; 3359 Entry.Location = ReadSourceLocation(F, Record[Idx++]); 3360 PragmaPackStrings.push_back(ReadString(Record, Idx)); 3361 Entry.SlotLabel = PragmaPackStrings.back(); 3362 PragmaPackStack.push_back(Entry); 3363 } 3364 break; 3365 } 3366 } 3367 } 3368 } 3369 3370 void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const { 3371 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read"); 3372 3373 // Additional remapping information. 3374 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data(); 3375 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size(); 3376 F.ModuleOffsetMap = StringRef(); 3377 3378 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders. 3379 if (F.SLocRemap.find(0) == F.SLocRemap.end()) { 3380 F.SLocRemap.insert(std::make_pair(0U, 0)); 3381 F.SLocRemap.insert(std::make_pair(2U, 1)); 3382 } 3383 3384 // Continuous range maps we may be updating in our module. 3385 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder 3386 RemapBuilder; 3387 RemapBuilder SLocRemap(F.SLocRemap); 3388 RemapBuilder IdentifierRemap(F.IdentifierRemap); 3389 RemapBuilder MacroRemap(F.MacroRemap); 3390 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap); 3391 RemapBuilder SubmoduleRemap(F.SubmoduleRemap); 3392 RemapBuilder SelectorRemap(F.SelectorRemap); 3393 RemapBuilder DeclRemap(F.DeclRemap); 3394 RemapBuilder TypeRemap(F.TypeRemap); 3395 3396 while (Data < DataEnd) { 3397 // FIXME: Looking up dependency modules by filename is horrible. 3398 using namespace llvm::support; 3399 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data); 3400 StringRef Name = StringRef((const char*)Data, Len); 3401 Data += Len; 3402 ModuleFile *OM = ModuleMgr.lookup(Name); 3403 if (!OM) { 3404 std::string Msg = 3405 "SourceLocation remap refers to unknown module, cannot find "; 3406 Msg.append(Name); 3407 Error(Msg); 3408 return; 3409 } 3410 3411 uint32_t SLocOffset = 3412 endian::readNext<uint32_t, little, unaligned>(Data); 3413 uint32_t IdentifierIDOffset = 3414 endian::readNext<uint32_t, little, unaligned>(Data); 3415 uint32_t MacroIDOffset = 3416 endian::readNext<uint32_t, little, unaligned>(Data); 3417 uint32_t PreprocessedEntityIDOffset = 3418 endian::readNext<uint32_t, little, unaligned>(Data); 3419 uint32_t SubmoduleIDOffset = 3420 endian::readNext<uint32_t, little, unaligned>(Data); 3421 uint32_t SelectorIDOffset = 3422 endian::readNext<uint32_t, little, unaligned>(Data); 3423 uint32_t DeclIDOffset = 3424 endian::readNext<uint32_t, little, unaligned>(Data); 3425 uint32_t TypeIndexOffset = 3426 endian::readNext<uint32_t, little, unaligned>(Data); 3427 3428 uint32_t None = std::numeric_limits<uint32_t>::max(); 3429 3430 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset, 3431 RemapBuilder &Remap) { 3432 if (Offset != None) 3433 Remap.insert(std::make_pair(Offset, 3434 static_cast<int>(BaseOffset - Offset))); 3435 }; 3436 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap); 3437 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap); 3438 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap); 3439 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID, 3440 PreprocessedEntityRemap); 3441 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap); 3442 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap); 3443 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap); 3444 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap); 3445 3446 // Global -> local mappings. 3447 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset; 3448 } 3449 } 3450 3451 ASTReader::ASTReadResult 3452 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F, 3453 const ModuleFile *ImportedBy, 3454 unsigned ClientLoadCapabilities) { 3455 unsigned Idx = 0; 3456 F.ModuleMapPath = ReadPath(F, Record, Idx); 3457 3458 // Try to resolve ModuleName in the current header search context and 3459 // verify that it is found in the same module map file as we saved. If the 3460 // top-level AST file is a main file, skip this check because there is no 3461 // usable header search context. 3462 assert(!F.ModuleName.empty() && 3463 "MODULE_NAME should come before MODULE_MAP_FILE"); 3464 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) { 3465 // An implicitly-loaded module file should have its module listed in some 3466 // module map file that we've already loaded. 3467 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName); 3468 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 3469 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr; 3470 if (!ModMap) { 3471 assert(ImportedBy && "top-level import should be verified"); 3472 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) { 3473 if (auto *ASTFE = M ? M->getASTFile() : nullptr) 3474 // This module was defined by an imported (explicit) module. 3475 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName 3476 << ASTFE->getName(); 3477 else 3478 // This module was built with a different module map. 3479 Diag(diag::err_imported_module_not_found) 3480 << F.ModuleName << F.FileName << ImportedBy->FileName 3481 << F.ModuleMapPath; 3482 } 3483 return OutOfDate; 3484 } 3485 3486 assert(M->Name == F.ModuleName && "found module with different name"); 3487 3488 // Check the primary module map file. 3489 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath); 3490 if (StoredModMap == nullptr || StoredModMap != ModMap) { 3491 assert(ModMap && "found module is missing module map file"); 3492 assert(ImportedBy && "top-level import should be verified"); 3493 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 3494 Diag(diag::err_imported_module_modmap_changed) 3495 << F.ModuleName << ImportedBy->FileName 3496 << ModMap->getName() << F.ModuleMapPath; 3497 return OutOfDate; 3498 } 3499 3500 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps; 3501 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) { 3502 // FIXME: we should use input files rather than storing names. 3503 std::string Filename = ReadPath(F, Record, Idx); 3504 const FileEntry *F = 3505 FileMgr.getFile(Filename, false, false); 3506 if (F == nullptr) { 3507 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 3508 Error("could not find file '" + Filename +"' referenced by AST file"); 3509 return OutOfDate; 3510 } 3511 AdditionalStoredMaps.insert(F); 3512 } 3513 3514 // Check any additional module map files (e.g. module.private.modulemap) 3515 // that are not in the pcm. 3516 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) { 3517 for (const FileEntry *ModMap : *AdditionalModuleMaps) { 3518 // Remove files that match 3519 // Note: SmallPtrSet::erase is really remove 3520 if (!AdditionalStoredMaps.erase(ModMap)) { 3521 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 3522 Diag(diag::err_module_different_modmap) 3523 << F.ModuleName << /*new*/0 << ModMap->getName(); 3524 return OutOfDate; 3525 } 3526 } 3527 } 3528 3529 // Check any additional module map files that are in the pcm, but not 3530 // found in header search. Cases that match are already removed. 3531 for (const FileEntry *ModMap : AdditionalStoredMaps) { 3532 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 3533 Diag(diag::err_module_different_modmap) 3534 << F.ModuleName << /*not new*/1 << ModMap->getName(); 3535 return OutOfDate; 3536 } 3537 } 3538 3539 if (Listener) 3540 Listener->ReadModuleMapFile(F.ModuleMapPath); 3541 return Success; 3542 } 3543 3544 3545 /// \brief Move the given method to the back of the global list of methods. 3546 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) { 3547 // Find the entry for this selector in the method pool. 3548 Sema::GlobalMethodPool::iterator Known 3549 = S.MethodPool.find(Method->getSelector()); 3550 if (Known == S.MethodPool.end()) 3551 return; 3552 3553 // Retrieve the appropriate method list. 3554 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first 3555 : Known->second.second; 3556 bool Found = false; 3557 for (ObjCMethodList *List = &Start; List; List = List->getNext()) { 3558 if (!Found) { 3559 if (List->getMethod() == Method) { 3560 Found = true; 3561 } else { 3562 // Keep searching. 3563 continue; 3564 } 3565 } 3566 3567 if (List->getNext()) 3568 List->setMethod(List->getNext()->getMethod()); 3569 else 3570 List->setMethod(Method); 3571 } 3572 } 3573 3574 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) { 3575 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?"); 3576 for (Decl *D : Names) { 3577 bool wasHidden = D->isHidden(); 3578 D->setVisibleDespiteOwningModule(); 3579 3580 if (wasHidden && SemaObj) { 3581 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) { 3582 moveMethodToBackOfGlobalList(*SemaObj, Method); 3583 } 3584 } 3585 } 3586 } 3587 3588 void ASTReader::makeModuleVisible(Module *Mod, 3589 Module::NameVisibilityKind NameVisibility, 3590 SourceLocation ImportLoc) { 3591 llvm::SmallPtrSet<Module *, 4> Visited; 3592 SmallVector<Module *, 4> Stack; 3593 Stack.push_back(Mod); 3594 while (!Stack.empty()) { 3595 Mod = Stack.pop_back_val(); 3596 3597 if (NameVisibility <= Mod->NameVisibility) { 3598 // This module already has this level of visibility (or greater), so 3599 // there is nothing more to do. 3600 continue; 3601 } 3602 3603 if (!Mod->isAvailable()) { 3604 // Modules that aren't available cannot be made visible. 3605 continue; 3606 } 3607 3608 // Update the module's name visibility. 3609 Mod->NameVisibility = NameVisibility; 3610 3611 // If we've already deserialized any names from this module, 3612 // mark them as visible. 3613 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod); 3614 if (Hidden != HiddenNamesMap.end()) { 3615 auto HiddenNames = std::move(*Hidden); 3616 HiddenNamesMap.erase(Hidden); 3617 makeNamesVisible(HiddenNames.second, HiddenNames.first); 3618 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() && 3619 "making names visible added hidden names"); 3620 } 3621 3622 // Push any exported modules onto the stack to be marked as visible. 3623 SmallVector<Module *, 16> Exports; 3624 Mod->getExportedModules(Exports); 3625 for (SmallVectorImpl<Module *>::iterator 3626 I = Exports.begin(), E = Exports.end(); I != E; ++I) { 3627 Module *Exported = *I; 3628 if (Visited.insert(Exported).second) 3629 Stack.push_back(Exported); 3630 } 3631 } 3632 } 3633 3634 /// We've merged the definition \p MergedDef into the existing definition 3635 /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made 3636 /// visible. 3637 void ASTReader::mergeDefinitionVisibility(NamedDecl *Def, 3638 NamedDecl *MergedDef) { 3639 // FIXME: This doesn't correctly handle the case where MergedDef is visible 3640 // in modules other than its owning module. We should instead give the 3641 // ASTContext a list of merged definitions for Def. 3642 if (Def->isHidden()) { 3643 // If MergedDef is visible or becomes visible, make the definition visible. 3644 if (!MergedDef->isHidden()) 3645 Def->setVisibleDespiteOwningModule(); 3646 else if (getContext().getLangOpts().ModulesLocalVisibility) { 3647 getContext().mergeDefinitionIntoModule( 3648 Def, MergedDef->getImportedOwningModule(), 3649 /*NotifyListeners*/ false); 3650 PendingMergedDefinitionsToDeduplicate.insert(Def); 3651 } else { 3652 auto SubmoduleID = MergedDef->getOwningModuleID(); 3653 assert(SubmoduleID && "hidden definition in no module"); 3654 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def); 3655 } 3656 } 3657 } 3658 3659 bool ASTReader::loadGlobalIndex() { 3660 if (GlobalIndex) 3661 return false; 3662 3663 if (TriedLoadingGlobalIndex || !UseGlobalIndex || 3664 !Context.getLangOpts().Modules) 3665 return true; 3666 3667 // Try to load the global index. 3668 TriedLoadingGlobalIndex = true; 3669 StringRef ModuleCachePath 3670 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath(); 3671 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result 3672 = GlobalModuleIndex::readIndex(ModuleCachePath); 3673 if (!Result.first) 3674 return true; 3675 3676 GlobalIndex.reset(Result.first); 3677 ModuleMgr.setGlobalIndex(GlobalIndex.get()); 3678 return false; 3679 } 3680 3681 bool ASTReader::isGlobalIndexUnavailable() const { 3682 return Context.getLangOpts().Modules && UseGlobalIndex && 3683 !hasGlobalIndex() && TriedLoadingGlobalIndex; 3684 } 3685 3686 static void updateModuleTimestamp(ModuleFile &MF) { 3687 // Overwrite the timestamp file contents so that file's mtime changes. 3688 std::string TimestampFilename = MF.getTimestampFilename(); 3689 std::error_code EC; 3690 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text); 3691 if (EC) 3692 return; 3693 OS << "Timestamp file\n"; 3694 OS.close(); 3695 OS.clear_error(); // Avoid triggering a fatal error. 3696 } 3697 3698 /// \brief Given a cursor at the start of an AST file, scan ahead and drop the 3699 /// cursor into the start of the given block ID, returning false on success and 3700 /// true on failure. 3701 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) { 3702 while (true) { 3703 llvm::BitstreamEntry Entry = Cursor.advance(); 3704 switch (Entry.Kind) { 3705 case llvm::BitstreamEntry::Error: 3706 case llvm::BitstreamEntry::EndBlock: 3707 return true; 3708 3709 case llvm::BitstreamEntry::Record: 3710 // Ignore top-level records. 3711 Cursor.skipRecord(Entry.ID); 3712 break; 3713 3714 case llvm::BitstreamEntry::SubBlock: 3715 if (Entry.ID == BlockID) { 3716 if (Cursor.EnterSubBlock(BlockID)) 3717 return true; 3718 // Found it! 3719 return false; 3720 } 3721 3722 if (Cursor.SkipBlock()) 3723 return true; 3724 } 3725 } 3726 } 3727 3728 ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName, 3729 ModuleKind Type, 3730 SourceLocation ImportLoc, 3731 unsigned ClientLoadCapabilities, 3732 SmallVectorImpl<ImportedSubmodule> *Imported) { 3733 llvm::SaveAndRestore<SourceLocation> 3734 SetCurImportLocRAII(CurrentImportLoc, ImportLoc); 3735 3736 // Defer any pending actions until we get to the end of reading the AST file. 3737 Deserializing AnASTFile(this); 3738 3739 // Bump the generation number. 3740 unsigned PreviousGeneration = incrementGeneration(Context); 3741 3742 unsigned NumModules = ModuleMgr.size(); 3743 SmallVector<ImportedModule, 4> Loaded; 3744 switch (ASTReadResult ReadResult = 3745 ReadASTCore(FileName, Type, ImportLoc, 3746 /*ImportedBy=*/nullptr, Loaded, 0, 0, 3747 ASTFileSignature(), ClientLoadCapabilities)) { 3748 case Failure: 3749 case Missing: 3750 case OutOfDate: 3751 case VersionMismatch: 3752 case ConfigurationMismatch: 3753 case HadErrors: { 3754 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet; 3755 for (const ImportedModule &IM : Loaded) 3756 LoadedSet.insert(IM.Mod); 3757 3758 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet, 3759 Context.getLangOpts().Modules 3760 ? &PP.getHeaderSearchInfo().getModuleMap() 3761 : nullptr); 3762 3763 // If we find that any modules are unusable, the global index is going 3764 // to be out-of-date. Just remove it. 3765 GlobalIndex.reset(); 3766 ModuleMgr.setGlobalIndex(nullptr); 3767 return ReadResult; 3768 } 3769 case Success: 3770 break; 3771 } 3772 3773 // Here comes stuff that we only do once the entire chain is loaded. 3774 3775 // Load the AST blocks of all of the modules that we loaded. 3776 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(), 3777 MEnd = Loaded.end(); 3778 M != MEnd; ++M) { 3779 ModuleFile &F = *M->Mod; 3780 3781 // Read the AST block. 3782 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities)) 3783 return Result; 3784 3785 // Read the extension blocks. 3786 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) { 3787 if (ASTReadResult Result = ReadExtensionBlock(F)) 3788 return Result; 3789 } 3790 3791 // Once read, set the ModuleFile bit base offset and update the size in 3792 // bits of all files we've seen. 3793 F.GlobalBitOffset = TotalModulesSizeInBits; 3794 TotalModulesSizeInBits += F.SizeInBits; 3795 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F)); 3796 3797 // Preload SLocEntries. 3798 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) { 3799 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID; 3800 // Load it through the SourceManager and don't call ReadSLocEntry() 3801 // directly because the entry may have already been loaded in which case 3802 // calling ReadSLocEntry() directly would trigger an assertion in 3803 // SourceManager. 3804 SourceMgr.getLoadedSLocEntryByID(Index); 3805 } 3806 3807 // Map the original source file ID into the ID space of the current 3808 // compilation. 3809 if (F.OriginalSourceFileID.isValid()) { 3810 F.OriginalSourceFileID = FileID::get( 3811 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1); 3812 } 3813 3814 // Preload all the pending interesting identifiers by marking them out of 3815 // date. 3816 for (auto Offset : F.PreloadIdentifierOffsets) { 3817 const unsigned char *Data = reinterpret_cast<const unsigned char *>( 3818 F.IdentifierTableData + Offset); 3819 3820 ASTIdentifierLookupTrait Trait(*this, F); 3821 auto KeyDataLen = Trait.ReadKeyDataLength(Data); 3822 auto Key = Trait.ReadKey(Data, KeyDataLen.first); 3823 auto &II = PP.getIdentifierTable().getOwn(Key); 3824 II.setOutOfDate(true); 3825 3826 // Mark this identifier as being from an AST file so that we can track 3827 // whether we need to serialize it. 3828 markIdentifierFromAST(*this, II); 3829 3830 // Associate the ID with the identifier so that the writer can reuse it. 3831 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first); 3832 SetIdentifierInfo(ID, &II); 3833 } 3834 } 3835 3836 // Setup the import locations and notify the module manager that we've 3837 // committed to these module files. 3838 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(), 3839 MEnd = Loaded.end(); 3840 M != MEnd; ++M) { 3841 ModuleFile &F = *M->Mod; 3842 3843 ModuleMgr.moduleFileAccepted(&F); 3844 3845 // Set the import location. 3846 F.DirectImportLoc = ImportLoc; 3847 // FIXME: We assume that locations from PCH / preamble do not need 3848 // any translation. 3849 if (!M->ImportedBy) 3850 F.ImportLoc = M->ImportLoc; 3851 else 3852 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc); 3853 } 3854 3855 if (!Context.getLangOpts().CPlusPlus || 3856 (Type != MK_ImplicitModule && Type != MK_ExplicitModule && 3857 Type != MK_PrebuiltModule)) { 3858 // Mark all of the identifiers in the identifier table as being out of date, 3859 // so that various accessors know to check the loaded modules when the 3860 // identifier is used. 3861 // 3862 // For C++ modules, we don't need information on many identifiers (just 3863 // those that provide macros or are poisoned), so we mark all of 3864 // the interesting ones via PreloadIdentifierOffsets. 3865 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(), 3866 IdEnd = PP.getIdentifierTable().end(); 3867 Id != IdEnd; ++Id) 3868 Id->second->setOutOfDate(true); 3869 } 3870 // Mark selectors as out of date. 3871 for (auto Sel : SelectorGeneration) 3872 SelectorOutOfDate[Sel.first] = true; 3873 3874 // Resolve any unresolved module exports. 3875 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) { 3876 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I]; 3877 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID); 3878 Module *ResolvedMod = getSubmodule(GlobalID); 3879 3880 switch (Unresolved.Kind) { 3881 case UnresolvedModuleRef::Conflict: 3882 if (ResolvedMod) { 3883 Module::Conflict Conflict; 3884 Conflict.Other = ResolvedMod; 3885 Conflict.Message = Unresolved.String.str(); 3886 Unresolved.Mod->Conflicts.push_back(Conflict); 3887 } 3888 continue; 3889 3890 case UnresolvedModuleRef::Import: 3891 if (ResolvedMod) 3892 Unresolved.Mod->Imports.insert(ResolvedMod); 3893 continue; 3894 3895 case UnresolvedModuleRef::Export: 3896 if (ResolvedMod || Unresolved.IsWildcard) 3897 Unresolved.Mod->Exports.push_back( 3898 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard)); 3899 continue; 3900 } 3901 } 3902 UnresolvedModuleRefs.clear(); 3903 3904 if (Imported) 3905 Imported->append(ImportedModules.begin(), 3906 ImportedModules.end()); 3907 3908 // FIXME: How do we load the 'use'd modules? They may not be submodules. 3909 // Might be unnecessary as use declarations are only used to build the 3910 // module itself. 3911 3912 InitializeContext(); 3913 3914 if (SemaObj) 3915 UpdateSema(); 3916 3917 if (DeserializationListener) 3918 DeserializationListener->ReaderInitialized(this); 3919 3920 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule(); 3921 if (PrimaryModule.OriginalSourceFileID.isValid()) { 3922 // If this AST file is a precompiled preamble, then set the 3923 // preamble file ID of the source manager to the file source file 3924 // from which the preamble was built. 3925 if (Type == MK_Preamble) { 3926 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID); 3927 } else if (Type == MK_MainFile) { 3928 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID); 3929 } 3930 } 3931 3932 // For any Objective-C class definitions we have already loaded, make sure 3933 // that we load any additional categories. 3934 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) { 3935 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(), 3936 ObjCClassesLoaded[I], 3937 PreviousGeneration); 3938 } 3939 3940 if (PP.getHeaderSearchInfo() 3941 .getHeaderSearchOpts() 3942 .ModulesValidateOncePerBuildSession) { 3943 // Now we are certain that the module and all modules it depends on are 3944 // up to date. Create or update timestamp files for modules that are 3945 // located in the module cache (not for PCH files that could be anywhere 3946 // in the filesystem). 3947 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) { 3948 ImportedModule &M = Loaded[I]; 3949 if (M.Mod->Kind == MK_ImplicitModule) { 3950 updateModuleTimestamp(*M.Mod); 3951 } 3952 } 3953 } 3954 3955 return Success; 3956 } 3957 3958 static ASTFileSignature readASTFileSignature(StringRef PCH); 3959 3960 /// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'. 3961 static bool startsWithASTFileMagic(BitstreamCursor &Stream) { 3962 return Stream.canSkipToPos(4) && 3963 Stream.Read(8) == 'C' && 3964 Stream.Read(8) == 'P' && 3965 Stream.Read(8) == 'C' && 3966 Stream.Read(8) == 'H'; 3967 } 3968 3969 static unsigned moduleKindForDiagnostic(ModuleKind Kind) { 3970 switch (Kind) { 3971 case MK_PCH: 3972 return 0; // PCH 3973 case MK_ImplicitModule: 3974 case MK_ExplicitModule: 3975 case MK_PrebuiltModule: 3976 return 1; // module 3977 case MK_MainFile: 3978 case MK_Preamble: 3979 return 2; // main source file 3980 } 3981 llvm_unreachable("unknown module kind"); 3982 } 3983 3984 ASTReader::ASTReadResult 3985 ASTReader::ReadASTCore(StringRef FileName, 3986 ModuleKind Type, 3987 SourceLocation ImportLoc, 3988 ModuleFile *ImportedBy, 3989 SmallVectorImpl<ImportedModule> &Loaded, 3990 off_t ExpectedSize, time_t ExpectedModTime, 3991 ASTFileSignature ExpectedSignature, 3992 unsigned ClientLoadCapabilities) { 3993 ModuleFile *M; 3994 std::string ErrorStr; 3995 ModuleManager::AddModuleResult AddResult 3996 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy, 3997 getGeneration(), ExpectedSize, ExpectedModTime, 3998 ExpectedSignature, readASTFileSignature, 3999 M, ErrorStr); 4000 4001 switch (AddResult) { 4002 case ModuleManager::AlreadyLoaded: 4003 return Success; 4004 4005 case ModuleManager::NewlyLoaded: 4006 // Load module file below. 4007 break; 4008 4009 case ModuleManager::Missing: 4010 // The module file was missing; if the client can handle that, return 4011 // it. 4012 if (ClientLoadCapabilities & ARR_Missing) 4013 return Missing; 4014 4015 // Otherwise, return an error. 4016 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type) 4017 << FileName << !ErrorStr.empty() 4018 << ErrorStr; 4019 return Failure; 4020 4021 case ModuleManager::OutOfDate: 4022 // We couldn't load the module file because it is out-of-date. If the 4023 // client can handle out-of-date, return it. 4024 if (ClientLoadCapabilities & ARR_OutOfDate) 4025 return OutOfDate; 4026 4027 // Otherwise, return an error. 4028 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type) 4029 << FileName << !ErrorStr.empty() 4030 << ErrorStr; 4031 return Failure; 4032 } 4033 4034 assert(M && "Missing module file"); 4035 4036 // FIXME: This seems rather a hack. Should CurrentDir be part of the 4037 // module? 4038 if (FileName != "-") { 4039 CurrentDir = llvm::sys::path::parent_path(FileName); 4040 if (CurrentDir.empty()) CurrentDir = "."; 4041 } 4042 4043 ModuleFile &F = *M; 4044 BitstreamCursor &Stream = F.Stream; 4045 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer)); 4046 F.SizeInBits = F.Buffer->getBufferSize() * 8; 4047 4048 // Sniff for the signature. 4049 if (!startsWithASTFileMagic(Stream)) { 4050 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type) 4051 << FileName; 4052 return Failure; 4053 } 4054 4055 // This is used for compatibility with older PCH formats. 4056 bool HaveReadControlBlock = false; 4057 while (true) { 4058 llvm::BitstreamEntry Entry = Stream.advance(); 4059 4060 switch (Entry.Kind) { 4061 case llvm::BitstreamEntry::Error: 4062 case llvm::BitstreamEntry::Record: 4063 case llvm::BitstreamEntry::EndBlock: 4064 Error("invalid record at top-level of AST file"); 4065 return Failure; 4066 4067 case llvm::BitstreamEntry::SubBlock: 4068 break; 4069 } 4070 4071 switch (Entry.ID) { 4072 case CONTROL_BLOCK_ID: 4073 HaveReadControlBlock = true; 4074 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) { 4075 case Success: 4076 // Check that we didn't try to load a non-module AST file as a module. 4077 // 4078 // FIXME: Should we also perform the converse check? Loading a module as 4079 // a PCH file sort of works, but it's a bit wonky. 4080 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule || 4081 Type == MK_PrebuiltModule) && 4082 F.ModuleName.empty()) { 4083 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure; 4084 if (Result != OutOfDate || 4085 (ClientLoadCapabilities & ARR_OutOfDate) == 0) 4086 Diag(diag::err_module_file_not_module) << FileName; 4087 return Result; 4088 } 4089 break; 4090 4091 case Failure: return Failure; 4092 case Missing: return Missing; 4093 case OutOfDate: return OutOfDate; 4094 case VersionMismatch: return VersionMismatch; 4095 case ConfigurationMismatch: return ConfigurationMismatch; 4096 case HadErrors: return HadErrors; 4097 } 4098 break; 4099 4100 case AST_BLOCK_ID: 4101 if (!HaveReadControlBlock) { 4102 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0) 4103 Diag(diag::err_pch_version_too_old); 4104 return VersionMismatch; 4105 } 4106 4107 // Record that we've loaded this module. 4108 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc)); 4109 return Success; 4110 4111 case UNHASHED_CONTROL_BLOCK_ID: 4112 // This block is handled using look-ahead during ReadControlBlock. We 4113 // shouldn't get here! 4114 Error("malformed block record in AST file"); 4115 return Failure; 4116 4117 default: 4118 if (Stream.SkipBlock()) { 4119 Error("malformed block record in AST file"); 4120 return Failure; 4121 } 4122 break; 4123 } 4124 } 4125 4126 return Success; 4127 } 4128 4129 ASTReader::ASTReadResult 4130 ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy, 4131 unsigned ClientLoadCapabilities) { 4132 const HeaderSearchOptions &HSOpts = 4133 PP.getHeaderSearchInfo().getHeaderSearchOpts(); 4134 bool AllowCompatibleConfigurationMismatch = 4135 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule; 4136 4137 ASTReadResult Result = readUnhashedControlBlockImpl( 4138 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch, 4139 Listener.get(), 4140 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions); 4141 4142 // If F was directly imported by another module, it's implicitly validated by 4143 // the importing module. 4144 if (DisableValidation || WasImportedBy || 4145 (AllowConfigurationMismatch && Result == ConfigurationMismatch)) 4146 return Success; 4147 4148 if (Result == Failure) { 4149 Error("malformed block record in AST file"); 4150 return Failure; 4151 } 4152 4153 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) { 4154 // If this module has already been finalized in the PCMCache, we're stuck 4155 // with it; we can only load a single version of each module. 4156 // 4157 // This can happen when a module is imported in two contexts: in one, as a 4158 // user module; in another, as a system module (due to an import from 4159 // another module marked with the [system] flag). It usually indicates a 4160 // bug in the module map: this module should also be marked with [system]. 4161 // 4162 // If -Wno-system-headers (the default), and the first import is as a 4163 // system module, then validation will fail during the as-user import, 4164 // since -Werror flags won't have been validated. However, it's reasonable 4165 // to treat this consistently as a system module. 4166 // 4167 // If -Wsystem-headers, the PCM on disk was built with 4168 // -Wno-system-headers, and the first import is as a user module, then 4169 // validation will fail during the as-system import since the PCM on disk 4170 // doesn't guarantee that -Werror was respected. However, the -Werror 4171 // flags were checked during the initial as-user import. 4172 if (PCMCache.isBufferFinal(F.FileName)) { 4173 Diag(diag::warn_module_system_bit_conflict) << F.FileName; 4174 return Success; 4175 } 4176 } 4177 4178 return Result; 4179 } 4180 4181 ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl( 4182 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities, 4183 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener, 4184 bool ValidateDiagnosticOptions) { 4185 // Initialize a stream. 4186 BitstreamCursor Stream(StreamData); 4187 4188 // Sniff for the signature. 4189 if (!startsWithASTFileMagic(Stream)) 4190 return Failure; 4191 4192 // Scan for the UNHASHED_CONTROL_BLOCK_ID block. 4193 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID)) 4194 return Failure; 4195 4196 // Read all of the records in the options block. 4197 RecordData Record; 4198 ASTReadResult Result = Success; 4199 while (1) { 4200 llvm::BitstreamEntry Entry = Stream.advance(); 4201 4202 switch (Entry.Kind) { 4203 case llvm::BitstreamEntry::Error: 4204 case llvm::BitstreamEntry::SubBlock: 4205 return Failure; 4206 4207 case llvm::BitstreamEntry::EndBlock: 4208 return Result; 4209 4210 case llvm::BitstreamEntry::Record: 4211 // The interesting case. 4212 break; 4213 } 4214 4215 // Read and process a record. 4216 Record.clear(); 4217 switch ( 4218 (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) { 4219 case SIGNATURE: { 4220 if (F) 4221 std::copy(Record.begin(), Record.end(), F->Signature.data()); 4222 break; 4223 } 4224 case DIAGNOSTIC_OPTIONS: { 4225 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0; 4226 if (Listener && ValidateDiagnosticOptions && 4227 !AllowCompatibleConfigurationMismatch && 4228 ParseDiagnosticOptions(Record, Complain, *Listener)) 4229 Result = OutOfDate; // Don't return early. Read the signature. 4230 break; 4231 } 4232 case DIAG_PRAGMA_MAPPINGS: 4233 if (!F) 4234 break; 4235 if (F->PragmaDiagMappings.empty()) 4236 F->PragmaDiagMappings.swap(Record); 4237 else 4238 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(), 4239 Record.begin(), Record.end()); 4240 break; 4241 } 4242 } 4243 } 4244 4245 /// Parse a record and blob containing module file extension metadata. 4246 static bool parseModuleFileExtensionMetadata( 4247 const SmallVectorImpl<uint64_t> &Record, 4248 StringRef Blob, 4249 ModuleFileExtensionMetadata &Metadata) { 4250 if (Record.size() < 4) return true; 4251 4252 Metadata.MajorVersion = Record[0]; 4253 Metadata.MinorVersion = Record[1]; 4254 4255 unsigned BlockNameLen = Record[2]; 4256 unsigned UserInfoLen = Record[3]; 4257 4258 if (BlockNameLen + UserInfoLen > Blob.size()) return true; 4259 4260 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen); 4261 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen, 4262 Blob.data() + BlockNameLen + UserInfoLen); 4263 return false; 4264 } 4265 4266 ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) { 4267 BitstreamCursor &Stream = F.Stream; 4268 4269 RecordData Record; 4270 while (true) { 4271 llvm::BitstreamEntry Entry = Stream.advance(); 4272 switch (Entry.Kind) { 4273 case llvm::BitstreamEntry::SubBlock: 4274 if (Stream.SkipBlock()) 4275 return Failure; 4276 4277 continue; 4278 4279 case llvm::BitstreamEntry::EndBlock: 4280 return Success; 4281 4282 case llvm::BitstreamEntry::Error: 4283 return HadErrors; 4284 4285 case llvm::BitstreamEntry::Record: 4286 break; 4287 } 4288 4289 Record.clear(); 4290 StringRef Blob; 4291 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob); 4292 switch (RecCode) { 4293 case EXTENSION_METADATA: { 4294 ModuleFileExtensionMetadata Metadata; 4295 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) 4296 return Failure; 4297 4298 // Find a module file extension with this block name. 4299 auto Known = ModuleFileExtensions.find(Metadata.BlockName); 4300 if (Known == ModuleFileExtensions.end()) break; 4301 4302 // Form a reader. 4303 if (auto Reader = Known->second->createExtensionReader(Metadata, *this, 4304 F, Stream)) { 4305 F.ExtensionReaders.push_back(std::move(Reader)); 4306 } 4307 4308 break; 4309 } 4310 } 4311 } 4312 4313 return Success; 4314 } 4315 4316 void ASTReader::InitializeContext() { 4317 // If there's a listener, notify them that we "read" the translation unit. 4318 if (DeserializationListener) 4319 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID, 4320 Context.getTranslationUnitDecl()); 4321 4322 // FIXME: Find a better way to deal with collisions between these 4323 // built-in types. Right now, we just ignore the problem. 4324 4325 // Load the special types. 4326 if (SpecialTypes.size() >= NumSpecialTypeIDs) { 4327 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) { 4328 if (!Context.CFConstantStringTypeDecl) 4329 Context.setCFConstantStringType(GetType(String)); 4330 } 4331 4332 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) { 4333 QualType FileType = GetType(File); 4334 if (FileType.isNull()) { 4335 Error("FILE type is NULL"); 4336 return; 4337 } 4338 4339 if (!Context.FILEDecl) { 4340 if (const TypedefType *Typedef = FileType->getAs<TypedefType>()) 4341 Context.setFILEDecl(Typedef->getDecl()); 4342 else { 4343 const TagType *Tag = FileType->getAs<TagType>(); 4344 if (!Tag) { 4345 Error("Invalid FILE type in AST file"); 4346 return; 4347 } 4348 Context.setFILEDecl(Tag->getDecl()); 4349 } 4350 } 4351 } 4352 4353 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) { 4354 QualType Jmp_bufType = GetType(Jmp_buf); 4355 if (Jmp_bufType.isNull()) { 4356 Error("jmp_buf type is NULL"); 4357 return; 4358 } 4359 4360 if (!Context.jmp_bufDecl) { 4361 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>()) 4362 Context.setjmp_bufDecl(Typedef->getDecl()); 4363 else { 4364 const TagType *Tag = Jmp_bufType->getAs<TagType>(); 4365 if (!Tag) { 4366 Error("Invalid jmp_buf type in AST file"); 4367 return; 4368 } 4369 Context.setjmp_bufDecl(Tag->getDecl()); 4370 } 4371 } 4372 } 4373 4374 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) { 4375 QualType Sigjmp_bufType = GetType(Sigjmp_buf); 4376 if (Sigjmp_bufType.isNull()) { 4377 Error("sigjmp_buf type is NULL"); 4378 return; 4379 } 4380 4381 if (!Context.sigjmp_bufDecl) { 4382 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>()) 4383 Context.setsigjmp_bufDecl(Typedef->getDecl()); 4384 else { 4385 const TagType *Tag = Sigjmp_bufType->getAs<TagType>(); 4386 assert(Tag && "Invalid sigjmp_buf type in AST file"); 4387 Context.setsigjmp_bufDecl(Tag->getDecl()); 4388 } 4389 } 4390 } 4391 4392 if (unsigned ObjCIdRedef 4393 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) { 4394 if (Context.ObjCIdRedefinitionType.isNull()) 4395 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef); 4396 } 4397 4398 if (unsigned ObjCClassRedef 4399 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) { 4400 if (Context.ObjCClassRedefinitionType.isNull()) 4401 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef); 4402 } 4403 4404 if (unsigned ObjCSelRedef 4405 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) { 4406 if (Context.ObjCSelRedefinitionType.isNull()) 4407 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef); 4408 } 4409 4410 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) { 4411 QualType Ucontext_tType = GetType(Ucontext_t); 4412 if (Ucontext_tType.isNull()) { 4413 Error("ucontext_t type is NULL"); 4414 return; 4415 } 4416 4417 if (!Context.ucontext_tDecl) { 4418 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>()) 4419 Context.setucontext_tDecl(Typedef->getDecl()); 4420 else { 4421 const TagType *Tag = Ucontext_tType->getAs<TagType>(); 4422 assert(Tag && "Invalid ucontext_t type in AST file"); 4423 Context.setucontext_tDecl(Tag->getDecl()); 4424 } 4425 } 4426 } 4427 } 4428 4429 ReadPragmaDiagnosticMappings(Context.getDiagnostics()); 4430 4431 // If there were any CUDA special declarations, deserialize them. 4432 if (!CUDASpecialDeclRefs.empty()) { 4433 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!"); 4434 Context.setcudaConfigureCallDecl( 4435 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0]))); 4436 } 4437 4438 // Re-export any modules that were imported by a non-module AST file. 4439 // FIXME: This does not make macro-only imports visible again. 4440 for (auto &Import : ImportedModules) { 4441 if (Module *Imported = getSubmodule(Import.ID)) { 4442 makeModuleVisible(Imported, Module::AllVisible, 4443 /*ImportLoc=*/Import.ImportLoc); 4444 if (Import.ImportLoc.isValid()) 4445 PP.makeModuleVisible(Imported, Import.ImportLoc); 4446 // FIXME: should we tell Sema to make the module visible too? 4447 } 4448 } 4449 ImportedModules.clear(); 4450 } 4451 4452 void ASTReader::finalizeForWriting() { 4453 // Nothing to do for now. 4454 } 4455 4456 /// \brief Reads and return the signature record from \p PCH's control block, or 4457 /// else returns 0. 4458 static ASTFileSignature readASTFileSignature(StringRef PCH) { 4459 BitstreamCursor Stream(PCH); 4460 if (!startsWithASTFileMagic(Stream)) 4461 return ASTFileSignature(); 4462 4463 // Scan for the UNHASHED_CONTROL_BLOCK_ID block. 4464 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID)) 4465 return ASTFileSignature(); 4466 4467 // Scan for SIGNATURE inside the diagnostic options block. 4468 ASTReader::RecordData Record; 4469 while (true) { 4470 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 4471 if (Entry.Kind != llvm::BitstreamEntry::Record) 4472 return ASTFileSignature(); 4473 4474 Record.clear(); 4475 StringRef Blob; 4476 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob)) 4477 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2], 4478 (uint32_t)Record[3], (uint32_t)Record[4]}}}; 4479 } 4480 } 4481 4482 /// \brief Retrieve the name of the original source file name 4483 /// directly from the AST file, without actually loading the AST 4484 /// file. 4485 std::string ASTReader::getOriginalSourceFile( 4486 const std::string &ASTFileName, FileManager &FileMgr, 4487 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) { 4488 // Open the AST file. 4489 auto Buffer = FileMgr.getBufferForFile(ASTFileName); 4490 if (!Buffer) { 4491 Diags.Report(diag::err_fe_unable_to_read_pch_file) 4492 << ASTFileName << Buffer.getError().message(); 4493 return std::string(); 4494 } 4495 4496 // Initialize the stream 4497 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer)); 4498 4499 // Sniff for the signature. 4500 if (!startsWithASTFileMagic(Stream)) { 4501 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName; 4502 return std::string(); 4503 } 4504 4505 // Scan for the CONTROL_BLOCK_ID block. 4506 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) { 4507 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; 4508 return std::string(); 4509 } 4510 4511 // Scan for ORIGINAL_FILE inside the control block. 4512 RecordData Record; 4513 while (true) { 4514 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 4515 if (Entry.Kind == llvm::BitstreamEntry::EndBlock) 4516 return std::string(); 4517 4518 if (Entry.Kind != llvm::BitstreamEntry::Record) { 4519 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; 4520 return std::string(); 4521 } 4522 4523 Record.clear(); 4524 StringRef Blob; 4525 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE) 4526 return Blob.str(); 4527 } 4528 } 4529 4530 namespace { 4531 4532 class SimplePCHValidator : public ASTReaderListener { 4533 const LangOptions &ExistingLangOpts; 4534 const TargetOptions &ExistingTargetOpts; 4535 const PreprocessorOptions &ExistingPPOpts; 4536 std::string ExistingModuleCachePath; 4537 FileManager &FileMgr; 4538 4539 public: 4540 SimplePCHValidator(const LangOptions &ExistingLangOpts, 4541 const TargetOptions &ExistingTargetOpts, 4542 const PreprocessorOptions &ExistingPPOpts, 4543 StringRef ExistingModuleCachePath, 4544 FileManager &FileMgr) 4545 : ExistingLangOpts(ExistingLangOpts), 4546 ExistingTargetOpts(ExistingTargetOpts), 4547 ExistingPPOpts(ExistingPPOpts), 4548 ExistingModuleCachePath(ExistingModuleCachePath), 4549 FileMgr(FileMgr) 4550 { 4551 } 4552 4553 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, 4554 bool AllowCompatibleDifferences) override { 4555 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr, 4556 AllowCompatibleDifferences); 4557 } 4558 4559 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, 4560 bool AllowCompatibleDifferences) override { 4561 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr, 4562 AllowCompatibleDifferences); 4563 } 4564 4565 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 4566 StringRef SpecificModuleCachePath, 4567 bool Complain) override { 4568 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 4569 ExistingModuleCachePath, 4570 nullptr, ExistingLangOpts); 4571 } 4572 4573 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, 4574 bool Complain, 4575 std::string &SuggestedPredefines) override { 4576 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr, 4577 SuggestedPredefines, ExistingLangOpts); 4578 } 4579 }; 4580 4581 } // end anonymous namespace 4582 4583 bool ASTReader::readASTFileControlBlock( 4584 StringRef Filename, FileManager &FileMgr, 4585 const PCHContainerReader &PCHContainerRdr, 4586 bool FindModuleFileExtensions, 4587 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) { 4588 // Open the AST file. 4589 // FIXME: This allows use of the VFS; we do not allow use of the 4590 // VFS when actually loading a module. 4591 auto Buffer = FileMgr.getBufferForFile(Filename); 4592 if (!Buffer) { 4593 return true; 4594 } 4595 4596 // Initialize the stream 4597 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer); 4598 BitstreamCursor Stream(Bytes); 4599 4600 // Sniff for the signature. 4601 if (!startsWithASTFileMagic(Stream)) 4602 return true; 4603 4604 // Scan for the CONTROL_BLOCK_ID block. 4605 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) 4606 return true; 4607 4608 bool NeedsInputFiles = Listener.needsInputFileVisitation(); 4609 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation(); 4610 bool NeedsImports = Listener.needsImportVisitation(); 4611 BitstreamCursor InputFilesCursor; 4612 4613 RecordData Record; 4614 std::string ModuleDir; 4615 bool DoneWithControlBlock = false; 4616 while (!DoneWithControlBlock) { 4617 llvm::BitstreamEntry Entry = Stream.advance(); 4618 4619 switch (Entry.Kind) { 4620 case llvm::BitstreamEntry::SubBlock: { 4621 switch (Entry.ID) { 4622 case OPTIONS_BLOCK_ID: { 4623 std::string IgnoredSuggestedPredefines; 4624 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate, 4625 /*AllowCompatibleConfigurationMismatch*/ false, 4626 Listener, IgnoredSuggestedPredefines) != Success) 4627 return true; 4628 break; 4629 } 4630 4631 case INPUT_FILES_BLOCK_ID: 4632 InputFilesCursor = Stream; 4633 if (Stream.SkipBlock() || 4634 (NeedsInputFiles && 4635 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))) 4636 return true; 4637 break; 4638 4639 default: 4640 if (Stream.SkipBlock()) 4641 return true; 4642 break; 4643 } 4644 4645 continue; 4646 } 4647 4648 case llvm::BitstreamEntry::EndBlock: 4649 DoneWithControlBlock = true; 4650 break; 4651 4652 case llvm::BitstreamEntry::Error: 4653 return true; 4654 4655 case llvm::BitstreamEntry::Record: 4656 break; 4657 } 4658 4659 if (DoneWithControlBlock) break; 4660 4661 Record.clear(); 4662 StringRef Blob; 4663 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob); 4664 switch ((ControlRecordTypes)RecCode) { 4665 case METADATA: { 4666 if (Record[0] != VERSION_MAJOR) 4667 return true; 4668 4669 if (Listener.ReadFullVersionInformation(Blob)) 4670 return true; 4671 4672 break; 4673 } 4674 case MODULE_NAME: 4675 Listener.ReadModuleName(Blob); 4676 break; 4677 case MODULE_DIRECTORY: 4678 ModuleDir = Blob; 4679 break; 4680 case MODULE_MAP_FILE: { 4681 unsigned Idx = 0; 4682 auto Path = ReadString(Record, Idx); 4683 ResolveImportedPath(Path, ModuleDir); 4684 Listener.ReadModuleMapFile(Path); 4685 break; 4686 } 4687 case INPUT_FILE_OFFSETS: { 4688 if (!NeedsInputFiles) 4689 break; 4690 4691 unsigned NumInputFiles = Record[0]; 4692 unsigned NumUserFiles = Record[1]; 4693 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data(); 4694 for (unsigned I = 0; I != NumInputFiles; ++I) { 4695 // Go find this input file. 4696 bool isSystemFile = I >= NumUserFiles; 4697 4698 if (isSystemFile && !NeedsSystemInputFiles) 4699 break; // the rest are system input files 4700 4701 BitstreamCursor &Cursor = InputFilesCursor; 4702 SavedStreamPosition SavedPosition(Cursor); 4703 Cursor.JumpToBit(InputFileOffs[I]); 4704 4705 unsigned Code = Cursor.ReadCode(); 4706 RecordData Record; 4707 StringRef Blob; 4708 bool shouldContinue = false; 4709 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) { 4710 case INPUT_FILE: 4711 bool Overridden = static_cast<bool>(Record[3]); 4712 std::string Filename = Blob; 4713 ResolveImportedPath(Filename, ModuleDir); 4714 shouldContinue = Listener.visitInputFile( 4715 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false); 4716 break; 4717 } 4718 if (!shouldContinue) 4719 break; 4720 } 4721 break; 4722 } 4723 4724 case IMPORTS: { 4725 if (!NeedsImports) 4726 break; 4727 4728 unsigned Idx = 0, N = Record.size(); 4729 while (Idx < N) { 4730 // Read information about the AST file. 4731 Idx += 5; // ImportLoc, Size, ModTime, Signature 4732 std::string Filename = ReadString(Record, Idx); 4733 ResolveImportedPath(Filename, ModuleDir); 4734 Listener.visitImport(Filename); 4735 } 4736 break; 4737 } 4738 4739 default: 4740 // No other validation to perform. 4741 break; 4742 } 4743 } 4744 4745 // Look for module file extension blocks, if requested. 4746 if (FindModuleFileExtensions) { 4747 BitstreamCursor SavedStream = Stream; 4748 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) { 4749 bool DoneWithExtensionBlock = false; 4750 while (!DoneWithExtensionBlock) { 4751 llvm::BitstreamEntry Entry = Stream.advance(); 4752 4753 switch (Entry.Kind) { 4754 case llvm::BitstreamEntry::SubBlock: 4755 if (Stream.SkipBlock()) 4756 return true; 4757 4758 continue; 4759 4760 case llvm::BitstreamEntry::EndBlock: 4761 DoneWithExtensionBlock = true; 4762 continue; 4763 4764 case llvm::BitstreamEntry::Error: 4765 return true; 4766 4767 case llvm::BitstreamEntry::Record: 4768 break; 4769 } 4770 4771 Record.clear(); 4772 StringRef Blob; 4773 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob); 4774 switch (RecCode) { 4775 case EXTENSION_METADATA: { 4776 ModuleFileExtensionMetadata Metadata; 4777 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) 4778 return true; 4779 4780 Listener.readModuleFileExtension(Metadata); 4781 break; 4782 } 4783 } 4784 } 4785 } 4786 Stream = SavedStream; 4787 } 4788 4789 // Scan for the UNHASHED_CONTROL_BLOCK_ID block. 4790 if (readUnhashedControlBlockImpl( 4791 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate, 4792 /*AllowCompatibleConfigurationMismatch*/ false, &Listener, 4793 ValidateDiagnosticOptions) != Success) 4794 return true; 4795 4796 return false; 4797 } 4798 4799 bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, 4800 const PCHContainerReader &PCHContainerRdr, 4801 const LangOptions &LangOpts, 4802 const TargetOptions &TargetOpts, 4803 const PreprocessorOptions &PPOpts, 4804 StringRef ExistingModuleCachePath) { 4805 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, 4806 ExistingModuleCachePath, FileMgr); 4807 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr, 4808 /*FindModuleFileExtensions=*/false, 4809 validator, 4810 /*ValidateDiagnosticOptions=*/true); 4811 } 4812 4813 ASTReader::ASTReadResult 4814 ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { 4815 // Enter the submodule block. 4816 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) { 4817 Error("malformed submodule block record in AST file"); 4818 return Failure; 4819 } 4820 4821 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap(); 4822 bool First = true; 4823 Module *CurrentModule = nullptr; 4824 Module::ModuleKind ModuleKind = Module::ModuleMapModule; 4825 RecordData Record; 4826 while (true) { 4827 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks(); 4828 4829 switch (Entry.Kind) { 4830 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 4831 case llvm::BitstreamEntry::Error: 4832 Error("malformed block record in AST file"); 4833 return Failure; 4834 case llvm::BitstreamEntry::EndBlock: 4835 return Success; 4836 case llvm::BitstreamEntry::Record: 4837 // The interesting case. 4838 break; 4839 } 4840 4841 // Read a record. 4842 StringRef Blob; 4843 Record.clear(); 4844 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob); 4845 4846 if ((Kind == SUBMODULE_METADATA) != First) { 4847 Error("submodule metadata record should be at beginning of block"); 4848 return Failure; 4849 } 4850 First = false; 4851 4852 // Submodule information is only valid if we have a current module. 4853 // FIXME: Should we error on these cases? 4854 if (!CurrentModule && Kind != SUBMODULE_METADATA && 4855 Kind != SUBMODULE_DEFINITION) 4856 continue; 4857 4858 switch (Kind) { 4859 default: // Default behavior: ignore. 4860 break; 4861 4862 case SUBMODULE_DEFINITION: { 4863 if (Record.size() < 8) { 4864 Error("malformed module definition"); 4865 return Failure; 4866 } 4867 4868 StringRef Name = Blob; 4869 unsigned Idx = 0; 4870 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]); 4871 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]); 4872 bool IsFramework = Record[Idx++]; 4873 bool IsExplicit = Record[Idx++]; 4874 bool IsSystem = Record[Idx++]; 4875 bool IsExternC = Record[Idx++]; 4876 bool InferSubmodules = Record[Idx++]; 4877 bool InferExplicitSubmodules = Record[Idx++]; 4878 bool InferExportWildcard = Record[Idx++]; 4879 bool ConfigMacrosExhaustive = Record[Idx++]; 4880 4881 Module *ParentModule = nullptr; 4882 if (Parent) 4883 ParentModule = getSubmodule(Parent); 4884 4885 // Retrieve this (sub)module from the module map, creating it if 4886 // necessary. 4887 CurrentModule = 4888 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit) 4889 .first; 4890 4891 // FIXME: set the definition loc for CurrentModule, or call 4892 // ModMap.setInferredModuleAllowedBy() 4893 4894 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS; 4895 if (GlobalIndex >= SubmodulesLoaded.size() || 4896 SubmodulesLoaded[GlobalIndex]) { 4897 Error("too many submodules"); 4898 return Failure; 4899 } 4900 4901 if (!ParentModule) { 4902 if (const FileEntry *CurFile = CurrentModule->getASTFile()) { 4903 if (CurFile != F.File) { 4904 if (!Diags.isDiagnosticInFlight()) { 4905 Diag(diag::err_module_file_conflict) 4906 << CurrentModule->getTopLevelModuleName() 4907 << CurFile->getName() 4908 << F.File->getName(); 4909 } 4910 return Failure; 4911 } 4912 } 4913 4914 CurrentModule->setASTFile(F.File); 4915 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath; 4916 } 4917 4918 CurrentModule->Kind = ModuleKind; 4919 CurrentModule->Signature = F.Signature; 4920 CurrentModule->IsFromModuleFile = true; 4921 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem; 4922 CurrentModule->IsExternC = IsExternC; 4923 CurrentModule->InferSubmodules = InferSubmodules; 4924 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules; 4925 CurrentModule->InferExportWildcard = InferExportWildcard; 4926 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive; 4927 if (DeserializationListener) 4928 DeserializationListener->ModuleRead(GlobalID, CurrentModule); 4929 4930 SubmodulesLoaded[GlobalIndex] = CurrentModule; 4931 4932 // Clear out data that will be replaced by what is in the module file. 4933 CurrentModule->LinkLibraries.clear(); 4934 CurrentModule->ConfigMacros.clear(); 4935 CurrentModule->UnresolvedConflicts.clear(); 4936 CurrentModule->Conflicts.clear(); 4937 4938 // The module is available unless it's missing a requirement; relevant 4939 // requirements will be (re-)added by SUBMODULE_REQUIRES records. 4940 // Missing headers that were present when the module was built do not 4941 // make it unavailable -- if we got this far, this must be an explicitly 4942 // imported module file. 4943 CurrentModule->Requirements.clear(); 4944 CurrentModule->MissingHeaders.clear(); 4945 CurrentModule->IsMissingRequirement = 4946 ParentModule && ParentModule->IsMissingRequirement; 4947 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement; 4948 break; 4949 } 4950 4951 case SUBMODULE_UMBRELLA_HEADER: { 4952 std::string Filename = Blob; 4953 ResolveImportedPath(F, Filename); 4954 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) { 4955 if (!CurrentModule->getUmbrellaHeader()) 4956 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob); 4957 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) { 4958 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 4959 Error("mismatched umbrella headers in submodule"); 4960 return OutOfDate; 4961 } 4962 } 4963 break; 4964 } 4965 4966 case SUBMODULE_HEADER: 4967 case SUBMODULE_EXCLUDED_HEADER: 4968 case SUBMODULE_PRIVATE_HEADER: 4969 // We lazily associate headers with their modules via the HeaderInfo table. 4970 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead 4971 // of complete filenames or remove it entirely. 4972 break; 4973 4974 case SUBMODULE_TEXTUAL_HEADER: 4975 case SUBMODULE_PRIVATE_TEXTUAL_HEADER: 4976 // FIXME: Textual headers are not marked in the HeaderInfo table. Load 4977 // them here. 4978 break; 4979 4980 case SUBMODULE_TOPHEADER: { 4981 CurrentModule->addTopHeaderFilename(Blob); 4982 break; 4983 } 4984 4985 case SUBMODULE_UMBRELLA_DIR: { 4986 std::string Dirname = Blob; 4987 ResolveImportedPath(F, Dirname); 4988 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) { 4989 if (!CurrentModule->getUmbrellaDir()) 4990 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob); 4991 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) { 4992 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) 4993 Error("mismatched umbrella directories in submodule"); 4994 return OutOfDate; 4995 } 4996 } 4997 break; 4998 } 4999 5000 case SUBMODULE_METADATA: { 5001 F.BaseSubmoduleID = getTotalNumSubmodules(); 5002 F.LocalNumSubmodules = Record[0]; 5003 unsigned LocalBaseSubmoduleID = Record[1]; 5004 if (F.LocalNumSubmodules > 0) { 5005 // Introduce the global -> local mapping for submodules within this 5006 // module. 5007 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F)); 5008 5009 // Introduce the local -> global mapping for submodules within this 5010 // module. 5011 F.SubmoduleRemap.insertOrReplace( 5012 std::make_pair(LocalBaseSubmoduleID, 5013 F.BaseSubmoduleID - LocalBaseSubmoduleID)); 5014 5015 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules); 5016 } 5017 ModuleKind = (Module::ModuleKind)Record[2]; 5018 break; 5019 } 5020 5021 case SUBMODULE_IMPORTS: { 5022 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) { 5023 UnresolvedModuleRef Unresolved; 5024 Unresolved.File = &F; 5025 Unresolved.Mod = CurrentModule; 5026 Unresolved.ID = Record[Idx]; 5027 Unresolved.Kind = UnresolvedModuleRef::Import; 5028 Unresolved.IsWildcard = false; 5029 UnresolvedModuleRefs.push_back(Unresolved); 5030 } 5031 break; 5032 } 5033 5034 case SUBMODULE_EXPORTS: { 5035 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) { 5036 UnresolvedModuleRef Unresolved; 5037 Unresolved.File = &F; 5038 Unresolved.Mod = CurrentModule; 5039 Unresolved.ID = Record[Idx]; 5040 Unresolved.Kind = UnresolvedModuleRef::Export; 5041 Unresolved.IsWildcard = Record[Idx + 1]; 5042 UnresolvedModuleRefs.push_back(Unresolved); 5043 } 5044 5045 // Once we've loaded the set of exports, there's no reason to keep 5046 // the parsed, unresolved exports around. 5047 CurrentModule->UnresolvedExports.clear(); 5048 break; 5049 } 5050 case SUBMODULE_REQUIRES: { 5051 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(), 5052 Context.getTargetInfo()); 5053 break; 5054 } 5055 5056 case SUBMODULE_LINK_LIBRARY: 5057 CurrentModule->LinkLibraries.push_back( 5058 Module::LinkLibrary(Blob, Record[0])); 5059 break; 5060 5061 case SUBMODULE_CONFIG_MACRO: 5062 CurrentModule->ConfigMacros.push_back(Blob.str()); 5063 break; 5064 5065 case SUBMODULE_CONFLICT: { 5066 UnresolvedModuleRef Unresolved; 5067 Unresolved.File = &F; 5068 Unresolved.Mod = CurrentModule; 5069 Unresolved.ID = Record[0]; 5070 Unresolved.Kind = UnresolvedModuleRef::Conflict; 5071 Unresolved.IsWildcard = false; 5072 Unresolved.String = Blob; 5073 UnresolvedModuleRefs.push_back(Unresolved); 5074 break; 5075 } 5076 5077 case SUBMODULE_INITIALIZERS: 5078 SmallVector<uint32_t, 16> Inits; 5079 for (auto &ID : Record) 5080 Inits.push_back(getGlobalDeclID(F, ID)); 5081 Context.addLazyModuleInitializers(CurrentModule, Inits); 5082 break; 5083 } 5084 } 5085 } 5086 5087 /// \brief Parse the record that corresponds to a LangOptions data 5088 /// structure. 5089 /// 5090 /// This routine parses the language options from the AST file and then gives 5091 /// them to the AST listener if one is set. 5092 /// 5093 /// \returns true if the listener deems the file unacceptable, false otherwise. 5094 bool ASTReader::ParseLanguageOptions(const RecordData &Record, 5095 bool Complain, 5096 ASTReaderListener &Listener, 5097 bool AllowCompatibleDifferences) { 5098 LangOptions LangOpts; 5099 unsigned Idx = 0; 5100 #define LANGOPT(Name, Bits, Default, Description) \ 5101 LangOpts.Name = Record[Idx++]; 5102 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 5103 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++])); 5104 #include "clang/Basic/LangOptions.def" 5105 #define SANITIZER(NAME, ID) \ 5106 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]); 5107 #include "clang/Basic/Sanitizers.def" 5108 5109 for (unsigned N = Record[Idx++]; N; --N) 5110 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx)); 5111 5112 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++]; 5113 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx); 5114 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion); 5115 5116 LangOpts.CurrentModule = ReadString(Record, Idx); 5117 5118 // Comment options. 5119 for (unsigned N = Record[Idx++]; N; --N) { 5120 LangOpts.CommentOpts.BlockCommandNames.push_back( 5121 ReadString(Record, Idx)); 5122 } 5123 LangOpts.CommentOpts.ParseAllComments = Record[Idx++]; 5124 5125 // OpenMP offloading options. 5126 for (unsigned N = Record[Idx++]; N; --N) { 5127 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx))); 5128 } 5129 5130 LangOpts.OMPHostIRFile = ReadString(Record, Idx); 5131 5132 return Listener.ReadLanguageOptions(LangOpts, Complain, 5133 AllowCompatibleDifferences); 5134 } 5135 5136 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain, 5137 ASTReaderListener &Listener, 5138 bool AllowCompatibleDifferences) { 5139 unsigned Idx = 0; 5140 TargetOptions TargetOpts; 5141 TargetOpts.Triple = ReadString(Record, Idx); 5142 TargetOpts.CPU = ReadString(Record, Idx); 5143 TargetOpts.ABI = ReadString(Record, Idx); 5144 for (unsigned N = Record[Idx++]; N; --N) { 5145 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx)); 5146 } 5147 for (unsigned N = Record[Idx++]; N; --N) { 5148 TargetOpts.Features.push_back(ReadString(Record, Idx)); 5149 } 5150 5151 return Listener.ReadTargetOptions(TargetOpts, Complain, 5152 AllowCompatibleDifferences); 5153 } 5154 5155 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain, 5156 ASTReaderListener &Listener) { 5157 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions); 5158 unsigned Idx = 0; 5159 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++]; 5160 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 5161 DiagOpts->set##Name(static_cast<Type>(Record[Idx++])); 5162 #include "clang/Basic/DiagnosticOptions.def" 5163 5164 for (unsigned N = Record[Idx++]; N; --N) 5165 DiagOpts->Warnings.push_back(ReadString(Record, Idx)); 5166 for (unsigned N = Record[Idx++]; N; --N) 5167 DiagOpts->Remarks.push_back(ReadString(Record, Idx)); 5168 5169 return Listener.ReadDiagnosticOptions(DiagOpts, Complain); 5170 } 5171 5172 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain, 5173 ASTReaderListener &Listener) { 5174 FileSystemOptions FSOpts; 5175 unsigned Idx = 0; 5176 FSOpts.WorkingDir = ReadString(Record, Idx); 5177 return Listener.ReadFileSystemOptions(FSOpts, Complain); 5178 } 5179 5180 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record, 5181 bool Complain, 5182 ASTReaderListener &Listener) { 5183 HeaderSearchOptions HSOpts; 5184 unsigned Idx = 0; 5185 HSOpts.Sysroot = ReadString(Record, Idx); 5186 5187 // Include entries. 5188 for (unsigned N = Record[Idx++]; N; --N) { 5189 std::string Path = ReadString(Record, Idx); 5190 frontend::IncludeDirGroup Group 5191 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]); 5192 bool IsFramework = Record[Idx++]; 5193 bool IgnoreSysRoot = Record[Idx++]; 5194 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework, 5195 IgnoreSysRoot); 5196 } 5197 5198 // System header prefixes. 5199 for (unsigned N = Record[Idx++]; N; --N) { 5200 std::string Prefix = ReadString(Record, Idx); 5201 bool IsSystemHeader = Record[Idx++]; 5202 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader); 5203 } 5204 5205 HSOpts.ResourceDir = ReadString(Record, Idx); 5206 HSOpts.ModuleCachePath = ReadString(Record, Idx); 5207 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx); 5208 HSOpts.DisableModuleHash = Record[Idx++]; 5209 HSOpts.ImplicitModuleMaps = Record[Idx++]; 5210 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++]; 5211 HSOpts.UseBuiltinIncludes = Record[Idx++]; 5212 HSOpts.UseStandardSystemIncludes = Record[Idx++]; 5213 HSOpts.UseStandardCXXIncludes = Record[Idx++]; 5214 HSOpts.UseLibcxx = Record[Idx++]; 5215 std::string SpecificModuleCachePath = ReadString(Record, Idx); 5216 5217 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath, 5218 Complain); 5219 } 5220 5221 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record, 5222 bool Complain, 5223 ASTReaderListener &Listener, 5224 std::string &SuggestedPredefines) { 5225 PreprocessorOptions PPOpts; 5226 unsigned Idx = 0; 5227 5228 // Macro definitions/undefs 5229 for (unsigned N = Record[Idx++]; N; --N) { 5230 std::string Macro = ReadString(Record, Idx); 5231 bool IsUndef = Record[Idx++]; 5232 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef)); 5233 } 5234 5235 // Includes 5236 for (unsigned N = Record[Idx++]; N; --N) { 5237 PPOpts.Includes.push_back(ReadString(Record, Idx)); 5238 } 5239 5240 // Macro Includes 5241 for (unsigned N = Record[Idx++]; N; --N) { 5242 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx)); 5243 } 5244 5245 PPOpts.UsePredefines = Record[Idx++]; 5246 PPOpts.DetailedRecord = Record[Idx++]; 5247 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx); 5248 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx); 5249 PPOpts.ObjCXXARCStandardLibrary = 5250 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]); 5251 SuggestedPredefines.clear(); 5252 return Listener.ReadPreprocessorOptions(PPOpts, Complain, 5253 SuggestedPredefines); 5254 } 5255 5256 std::pair<ModuleFile *, unsigned> 5257 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) { 5258 GlobalPreprocessedEntityMapType::iterator 5259 I = GlobalPreprocessedEntityMap.find(GlobalIndex); 5260 assert(I != GlobalPreprocessedEntityMap.end() && 5261 "Corrupted global preprocessed entity map"); 5262 ModuleFile *M = I->second; 5263 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID; 5264 return std::make_pair(M, LocalIndex); 5265 } 5266 5267 llvm::iterator_range<PreprocessingRecord::iterator> 5268 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const { 5269 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord()) 5270 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID, 5271 Mod.NumPreprocessedEntities); 5272 5273 return llvm::make_range(PreprocessingRecord::iterator(), 5274 PreprocessingRecord::iterator()); 5275 } 5276 5277 llvm::iterator_range<ASTReader::ModuleDeclIterator> 5278 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) { 5279 return llvm::make_range( 5280 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls), 5281 ModuleDeclIterator(this, &Mod, 5282 Mod.FileSortedDecls + Mod.NumFileSortedDecls)); 5283 } 5284 5285 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) { 5286 PreprocessedEntityID PPID = Index+1; 5287 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index); 5288 ModuleFile &M = *PPInfo.first; 5289 unsigned LocalIndex = PPInfo.second; 5290 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex]; 5291 5292 if (!PP.getPreprocessingRecord()) { 5293 Error("no preprocessing record"); 5294 return nullptr; 5295 } 5296 5297 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor); 5298 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset); 5299 5300 llvm::BitstreamEntry Entry = 5301 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd); 5302 if (Entry.Kind != llvm::BitstreamEntry::Record) 5303 return nullptr; 5304 5305 // Read the record. 5306 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()), 5307 TranslateSourceLocation(M, PPOffs.getEnd())); 5308 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord(); 5309 StringRef Blob; 5310 RecordData Record; 5311 PreprocessorDetailRecordTypes RecType = 5312 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord( 5313 Entry.ID, Record, &Blob); 5314 switch (RecType) { 5315 case PPD_MACRO_EXPANSION: { 5316 bool isBuiltin = Record[0]; 5317 IdentifierInfo *Name = nullptr; 5318 MacroDefinitionRecord *Def = nullptr; 5319 if (isBuiltin) 5320 Name = getLocalIdentifier(M, Record[1]); 5321 else { 5322 PreprocessedEntityID GlobalID = 5323 getGlobalPreprocessedEntityID(M, Record[1]); 5324 Def = cast<MacroDefinitionRecord>( 5325 PPRec.getLoadedPreprocessedEntity(GlobalID - 1)); 5326 } 5327 5328 MacroExpansion *ME; 5329 if (isBuiltin) 5330 ME = new (PPRec) MacroExpansion(Name, Range); 5331 else 5332 ME = new (PPRec) MacroExpansion(Def, Range); 5333 5334 return ME; 5335 } 5336 5337 case PPD_MACRO_DEFINITION: { 5338 // Decode the identifier info and then check again; if the macro is 5339 // still defined and associated with the identifier, 5340 IdentifierInfo *II = getLocalIdentifier(M, Record[0]); 5341 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range); 5342 5343 if (DeserializationListener) 5344 DeserializationListener->MacroDefinitionRead(PPID, MD); 5345 5346 return MD; 5347 } 5348 5349 case PPD_INCLUSION_DIRECTIVE: { 5350 const char *FullFileNameStart = Blob.data() + Record[0]; 5351 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]); 5352 const FileEntry *File = nullptr; 5353 if (!FullFileName.empty()) 5354 File = PP.getFileManager().getFile(FullFileName); 5355 5356 // FIXME: Stable encoding 5357 InclusionDirective::InclusionKind Kind 5358 = static_cast<InclusionDirective::InclusionKind>(Record[2]); 5359 InclusionDirective *ID 5360 = new (PPRec) InclusionDirective(PPRec, Kind, 5361 StringRef(Blob.data(), Record[0]), 5362 Record[1], Record[3], 5363 File, 5364 Range); 5365 return ID; 5366 } 5367 } 5368 5369 llvm_unreachable("Invalid PreprocessorDetailRecordTypes"); 5370 } 5371 5372 /// \brief \arg SLocMapI points at a chunk of a module that contains no 5373 /// preprocessed entities or the entities it contains are not the ones we are 5374 /// looking for. Find the next module that contains entities and return the ID 5375 /// of the first entry. 5376 PreprocessedEntityID ASTReader::findNextPreprocessedEntity( 5377 GlobalSLocOffsetMapType::const_iterator SLocMapI) const { 5378 ++SLocMapI; 5379 for (GlobalSLocOffsetMapType::const_iterator 5380 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) { 5381 ModuleFile &M = *SLocMapI->second; 5382 if (M.NumPreprocessedEntities) 5383 return M.BasePreprocessedEntityID; 5384 } 5385 5386 return getTotalNumPreprocessedEntities(); 5387 } 5388 5389 namespace { 5390 5391 struct PPEntityComp { 5392 const ASTReader &Reader; 5393 ModuleFile &M; 5394 5395 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { } 5396 5397 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const { 5398 SourceLocation LHS = getLoc(L); 5399 SourceLocation RHS = getLoc(R); 5400 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 5401 } 5402 5403 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const { 5404 SourceLocation LHS = getLoc(L); 5405 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 5406 } 5407 5408 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const { 5409 SourceLocation RHS = getLoc(R); 5410 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 5411 } 5412 5413 SourceLocation getLoc(const PPEntityOffset &PPE) const { 5414 return Reader.TranslateSourceLocation(M, PPE.getBegin()); 5415 } 5416 }; 5417 5418 } // end anonymous namespace 5419 5420 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc, 5421 bool EndsAfter) const { 5422 if (SourceMgr.isLocalSourceLocation(Loc)) 5423 return getTotalNumPreprocessedEntities(); 5424 5425 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find( 5426 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1); 5427 assert(SLocMapI != GlobalSLocOffsetMap.end() && 5428 "Corrupted global sloc offset map"); 5429 5430 if (SLocMapI->second->NumPreprocessedEntities == 0) 5431 return findNextPreprocessedEntity(SLocMapI); 5432 5433 ModuleFile &M = *SLocMapI->second; 5434 typedef const PPEntityOffset *pp_iterator; 5435 pp_iterator pp_begin = M.PreprocessedEntityOffsets; 5436 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities; 5437 5438 size_t Count = M.NumPreprocessedEntities; 5439 size_t Half; 5440 pp_iterator First = pp_begin; 5441 pp_iterator PPI; 5442 5443 if (EndsAfter) { 5444 PPI = std::upper_bound(pp_begin, pp_end, Loc, 5445 PPEntityComp(*this, M)); 5446 } else { 5447 // Do a binary search manually instead of using std::lower_bound because 5448 // The end locations of entities may be unordered (when a macro expansion 5449 // is inside another macro argument), but for this case it is not important 5450 // whether we get the first macro expansion or its containing macro. 5451 while (Count > 0) { 5452 Half = Count / 2; 5453 PPI = First; 5454 std::advance(PPI, Half); 5455 if (SourceMgr.isBeforeInTranslationUnit( 5456 TranslateSourceLocation(M, PPI->getEnd()), Loc)) { 5457 First = PPI; 5458 ++First; 5459 Count = Count - Half - 1; 5460 } else 5461 Count = Half; 5462 } 5463 } 5464 5465 if (PPI == pp_end) 5466 return findNextPreprocessedEntity(SLocMapI); 5467 5468 return M.BasePreprocessedEntityID + (PPI - pp_begin); 5469 } 5470 5471 /// \brief Returns a pair of [Begin, End) indices of preallocated 5472 /// preprocessed entities that \arg Range encompasses. 5473 std::pair<unsigned, unsigned> 5474 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) { 5475 if (Range.isInvalid()) 5476 return std::make_pair(0,0); 5477 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin())); 5478 5479 PreprocessedEntityID BeginID = 5480 findPreprocessedEntity(Range.getBegin(), false); 5481 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true); 5482 return std::make_pair(BeginID, EndID); 5483 } 5484 5485 /// \brief Optionally returns true or false if the preallocated preprocessed 5486 /// entity with index \arg Index came from file \arg FID. 5487 Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index, 5488 FileID FID) { 5489 if (FID.isInvalid()) 5490 return false; 5491 5492 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index); 5493 ModuleFile &M = *PPInfo.first; 5494 unsigned LocalIndex = PPInfo.second; 5495 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex]; 5496 5497 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin()); 5498 if (Loc.isInvalid()) 5499 return false; 5500 5501 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID)) 5502 return true; 5503 else 5504 return false; 5505 } 5506 5507 namespace { 5508 5509 /// \brief Visitor used to search for information about a header file. 5510 class HeaderFileInfoVisitor { 5511 const FileEntry *FE; 5512 5513 Optional<HeaderFileInfo> HFI; 5514 5515 public: 5516 explicit HeaderFileInfoVisitor(const FileEntry *FE) 5517 : FE(FE) { } 5518 5519 bool operator()(ModuleFile &M) { 5520 HeaderFileInfoLookupTable *Table 5521 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable); 5522 if (!Table) 5523 return false; 5524 5525 // Look in the on-disk hash table for an entry for this file name. 5526 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE); 5527 if (Pos == Table->end()) 5528 return false; 5529 5530 HFI = *Pos; 5531 return true; 5532 } 5533 5534 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; } 5535 }; 5536 5537 } // end anonymous namespace 5538 5539 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) { 5540 HeaderFileInfoVisitor Visitor(FE); 5541 ModuleMgr.visit(Visitor); 5542 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) 5543 return *HFI; 5544 5545 return HeaderFileInfo(); 5546 } 5547 5548 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) { 5549 using DiagState = DiagnosticsEngine::DiagState; 5550 SmallVector<DiagState *, 32> DiagStates; 5551 5552 for (ModuleFile &F : ModuleMgr) { 5553 unsigned Idx = 0; 5554 auto &Record = F.PragmaDiagMappings; 5555 if (Record.empty()) 5556 continue; 5557 5558 DiagStates.clear(); 5559 5560 auto ReadDiagState = 5561 [&](const DiagState &BasedOn, SourceLocation Loc, 5562 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * { 5563 unsigned BackrefID = Record[Idx++]; 5564 if (BackrefID != 0) 5565 return DiagStates[BackrefID - 1]; 5566 5567 // A new DiagState was created here. 5568 Diag.DiagStates.push_back(BasedOn); 5569 DiagState *NewState = &Diag.DiagStates.back(); 5570 DiagStates.push_back(NewState); 5571 unsigned Size = Record[Idx++]; 5572 assert(Idx + Size * 2 <= Record.size() && 5573 "Invalid data, not enough diag/map pairs"); 5574 while (Size--) { 5575 unsigned DiagID = Record[Idx++]; 5576 DiagnosticMapping NewMapping = 5577 DiagnosticMapping::deserialize(Record[Idx++]); 5578 if (!NewMapping.isPragma() && !IncludeNonPragmaStates) 5579 continue; 5580 5581 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID); 5582 5583 // If this mapping was specified as a warning but the severity was 5584 // upgraded due to diagnostic settings, simulate the current diagnostic 5585 // settings (and use a warning). 5586 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) { 5587 NewMapping.setSeverity(diag::Severity::Warning); 5588 NewMapping.setUpgradedFromWarning(false); 5589 } 5590 5591 Mapping = NewMapping; 5592 } 5593 return NewState; 5594 }; 5595 5596 // Read the first state. 5597 DiagState *FirstState; 5598 if (F.Kind == MK_ImplicitModule) { 5599 // Implicitly-built modules are reused with different diagnostic 5600 // settings. Use the initial diagnostic state from Diag to simulate this 5601 // compilation's diagnostic settings. 5602 FirstState = Diag.DiagStatesByLoc.FirstDiagState; 5603 DiagStates.push_back(FirstState); 5604 5605 // Skip the initial diagnostic state from the serialized module. 5606 assert(Record[1] == 0 && 5607 "Invalid data, unexpected backref in initial state"); 5608 Idx = 3 + Record[2] * 2; 5609 assert(Idx < Record.size() && 5610 "Invalid data, not enough state change pairs in initial state"); 5611 } else if (F.isModule()) { 5612 // For an explicit module, preserve the flags from the module build 5613 // command line (-w, -Weverything, -Werror, ...) along with any explicit 5614 // -Wblah flags. 5615 unsigned Flags = Record[Idx++]; 5616 DiagState Initial; 5617 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1; 5618 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1; 5619 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1; 5620 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1; 5621 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1; 5622 Initial.ExtBehavior = (diag::Severity)Flags; 5623 FirstState = ReadDiagState(Initial, SourceLocation(), true); 5624 5625 // Set up the root buffer of the module to start with the initial 5626 // diagnostic state of the module itself, to cover files that contain no 5627 // explicit transitions (for which we did not serialize anything). 5628 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID] 5629 .StateTransitions.push_back({FirstState, 0}); 5630 } else { 5631 // For prefix ASTs, start with whatever the user configured on the 5632 // command line. 5633 Idx++; // Skip flags. 5634 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, 5635 SourceLocation(), false); 5636 } 5637 5638 // Read the state transitions. 5639 unsigned NumLocations = Record[Idx++]; 5640 while (NumLocations--) { 5641 assert(Idx < Record.size() && 5642 "Invalid data, missing pragma diagnostic states"); 5643 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]); 5644 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc); 5645 assert(IDAndOffset.second == 0 && "not a start location for a FileID"); 5646 unsigned Transitions = Record[Idx++]; 5647 5648 // Note that we don't need to set up Parent/ParentOffset here, because 5649 // we won't be changing the diagnostic state within imported FileIDs 5650 // (other than perhaps appending to the main source file, which has no 5651 // parent). 5652 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first]; 5653 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions); 5654 for (unsigned I = 0; I != Transitions; ++I) { 5655 unsigned Offset = Record[Idx++]; 5656 auto *State = 5657 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false); 5658 F.StateTransitions.push_back({State, Offset}); 5659 } 5660 } 5661 5662 // Read the final state. 5663 assert(Idx < Record.size() && 5664 "Invalid data, missing final pragma diagnostic state"); 5665 SourceLocation CurStateLoc = 5666 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]); 5667 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false); 5668 5669 if (!F.isModule()) { 5670 Diag.DiagStatesByLoc.CurDiagState = CurState; 5671 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc; 5672 5673 // Preserve the property that the imaginary root file describes the 5674 // current state. 5675 auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions; 5676 if (T.empty()) 5677 T.push_back({CurState, 0}); 5678 else 5679 T[0].State = CurState; 5680 } 5681 5682 // Don't try to read these mappings again. 5683 Record.clear(); 5684 } 5685 } 5686 5687 /// \brief Get the correct cursor and offset for loading a type. 5688 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) { 5689 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index); 5690 assert(I != GlobalTypeMap.end() && "Corrupted global type map"); 5691 ModuleFile *M = I->second; 5692 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]); 5693 } 5694 5695 /// \brief Read and return the type with the given index.. 5696 /// 5697 /// The index is the type ID, shifted and minus the number of predefs. This 5698 /// routine actually reads the record corresponding to the type at the given 5699 /// location. It is a helper routine for GetType, which deals with reading type 5700 /// IDs. 5701 QualType ASTReader::readTypeRecord(unsigned Index) { 5702 RecordLocation Loc = TypeCursorForIndex(Index); 5703 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor; 5704 5705 // Keep track of where we are in the stream, then jump back there 5706 // after reading this type. 5707 SavedStreamPosition SavedPosition(DeclsCursor); 5708 5709 ReadingKindTracker ReadingKind(Read_Type, *this); 5710 5711 // Note that we are loading a type record. 5712 Deserializing AType(this); 5713 5714 unsigned Idx = 0; 5715 DeclsCursor.JumpToBit(Loc.Offset); 5716 RecordData Record; 5717 unsigned Code = DeclsCursor.ReadCode(); 5718 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) { 5719 case TYPE_EXT_QUAL: { 5720 if (Record.size() != 2) { 5721 Error("Incorrect encoding of extended qualifier type"); 5722 return QualType(); 5723 } 5724 QualType Base = readType(*Loc.F, Record, Idx); 5725 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]); 5726 return Context.getQualifiedType(Base, Quals); 5727 } 5728 5729 case TYPE_COMPLEX: { 5730 if (Record.size() != 1) { 5731 Error("Incorrect encoding of complex type"); 5732 return QualType(); 5733 } 5734 QualType ElemType = readType(*Loc.F, Record, Idx); 5735 return Context.getComplexType(ElemType); 5736 } 5737 5738 case TYPE_POINTER: { 5739 if (Record.size() != 1) { 5740 Error("Incorrect encoding of pointer type"); 5741 return QualType(); 5742 } 5743 QualType PointeeType = readType(*Loc.F, Record, Idx); 5744 return Context.getPointerType(PointeeType); 5745 } 5746 5747 case TYPE_DECAYED: { 5748 if (Record.size() != 1) { 5749 Error("Incorrect encoding of decayed type"); 5750 return QualType(); 5751 } 5752 QualType OriginalType = readType(*Loc.F, Record, Idx); 5753 QualType DT = Context.getAdjustedParameterType(OriginalType); 5754 if (!isa<DecayedType>(DT)) 5755 Error("Decayed type does not decay"); 5756 return DT; 5757 } 5758 5759 case TYPE_ADJUSTED: { 5760 if (Record.size() != 2) { 5761 Error("Incorrect encoding of adjusted type"); 5762 return QualType(); 5763 } 5764 QualType OriginalTy = readType(*Loc.F, Record, Idx); 5765 QualType AdjustedTy = readType(*Loc.F, Record, Idx); 5766 return Context.getAdjustedType(OriginalTy, AdjustedTy); 5767 } 5768 5769 case TYPE_BLOCK_POINTER: { 5770 if (Record.size() != 1) { 5771 Error("Incorrect encoding of block pointer type"); 5772 return QualType(); 5773 } 5774 QualType PointeeType = readType(*Loc.F, Record, Idx); 5775 return Context.getBlockPointerType(PointeeType); 5776 } 5777 5778 case TYPE_LVALUE_REFERENCE: { 5779 if (Record.size() != 2) { 5780 Error("Incorrect encoding of lvalue reference type"); 5781 return QualType(); 5782 } 5783 QualType PointeeType = readType(*Loc.F, Record, Idx); 5784 return Context.getLValueReferenceType(PointeeType, Record[1]); 5785 } 5786 5787 case TYPE_RVALUE_REFERENCE: { 5788 if (Record.size() != 1) { 5789 Error("Incorrect encoding of rvalue reference type"); 5790 return QualType(); 5791 } 5792 QualType PointeeType = readType(*Loc.F, Record, Idx); 5793 return Context.getRValueReferenceType(PointeeType); 5794 } 5795 5796 case TYPE_MEMBER_POINTER: { 5797 if (Record.size() != 2) { 5798 Error("Incorrect encoding of member pointer type"); 5799 return QualType(); 5800 } 5801 QualType PointeeType = readType(*Loc.F, Record, Idx); 5802 QualType ClassType = readType(*Loc.F, Record, Idx); 5803 if (PointeeType.isNull() || ClassType.isNull()) 5804 return QualType(); 5805 5806 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr()); 5807 } 5808 5809 case TYPE_CONSTANT_ARRAY: { 5810 QualType ElementType = readType(*Loc.F, Record, Idx); 5811 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1]; 5812 unsigned IndexTypeQuals = Record[2]; 5813 unsigned Idx = 3; 5814 llvm::APInt Size = ReadAPInt(Record, Idx); 5815 return Context.getConstantArrayType(ElementType, Size, 5816 ASM, IndexTypeQuals); 5817 } 5818 5819 case TYPE_INCOMPLETE_ARRAY: { 5820 QualType ElementType = readType(*Loc.F, Record, Idx); 5821 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1]; 5822 unsigned IndexTypeQuals = Record[2]; 5823 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals); 5824 } 5825 5826 case TYPE_VARIABLE_ARRAY: { 5827 QualType ElementType = readType(*Loc.F, Record, Idx); 5828 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1]; 5829 unsigned IndexTypeQuals = Record[2]; 5830 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]); 5831 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]); 5832 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F), 5833 ASM, IndexTypeQuals, 5834 SourceRange(LBLoc, RBLoc)); 5835 } 5836 5837 case TYPE_VECTOR: { 5838 if (Record.size() != 3) { 5839 Error("incorrect encoding of vector type in AST file"); 5840 return QualType(); 5841 } 5842 5843 QualType ElementType = readType(*Loc.F, Record, Idx); 5844 unsigned NumElements = Record[1]; 5845 unsigned VecKind = Record[2]; 5846 return Context.getVectorType(ElementType, NumElements, 5847 (VectorType::VectorKind)VecKind); 5848 } 5849 5850 case TYPE_EXT_VECTOR: { 5851 if (Record.size() != 3) { 5852 Error("incorrect encoding of extended vector type in AST file"); 5853 return QualType(); 5854 } 5855 5856 QualType ElementType = readType(*Loc.F, Record, Idx); 5857 unsigned NumElements = Record[1]; 5858 return Context.getExtVectorType(ElementType, NumElements); 5859 } 5860 5861 case TYPE_FUNCTION_NO_PROTO: { 5862 if (Record.size() != 7) { 5863 Error("incorrect encoding of no-proto function type"); 5864 return QualType(); 5865 } 5866 QualType ResultType = readType(*Loc.F, Record, Idx); 5867 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3], 5868 (CallingConv)Record[4], Record[5], Record[6]); 5869 return Context.getFunctionNoProtoType(ResultType, Info); 5870 } 5871 5872 case TYPE_FUNCTION_PROTO: { 5873 QualType ResultType = readType(*Loc.F, Record, Idx); 5874 5875 FunctionProtoType::ExtProtoInfo EPI; 5876 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1], 5877 /*hasregparm*/ Record[2], 5878 /*regparm*/ Record[3], 5879 static_cast<CallingConv>(Record[4]), 5880 /*produces*/ Record[5], 5881 /*nocallersavedregs*/ Record[6]); 5882 5883 unsigned Idx = 7; 5884 5885 EPI.Variadic = Record[Idx++]; 5886 EPI.HasTrailingReturn = Record[Idx++]; 5887 EPI.TypeQuals = Record[Idx++]; 5888 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]); 5889 SmallVector<QualType, 8> ExceptionStorage; 5890 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx); 5891 5892 unsigned NumParams = Record[Idx++]; 5893 SmallVector<QualType, 16> ParamTypes; 5894 for (unsigned I = 0; I != NumParams; ++I) 5895 ParamTypes.push_back(readType(*Loc.F, Record, Idx)); 5896 5897 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos; 5898 if (Idx != Record.size()) { 5899 for (unsigned I = 0; I != NumParams; ++I) 5900 ExtParameterInfos.push_back( 5901 FunctionProtoType::ExtParameterInfo 5902 ::getFromOpaqueValue(Record[Idx++])); 5903 EPI.ExtParameterInfos = ExtParameterInfos.data(); 5904 } 5905 5906 assert(Idx == Record.size()); 5907 5908 return Context.getFunctionType(ResultType, ParamTypes, EPI); 5909 } 5910 5911 case TYPE_UNRESOLVED_USING: { 5912 unsigned Idx = 0; 5913 return Context.getTypeDeclType( 5914 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx)); 5915 } 5916 5917 case TYPE_TYPEDEF: { 5918 if (Record.size() != 2) { 5919 Error("incorrect encoding of typedef type"); 5920 return QualType(); 5921 } 5922 unsigned Idx = 0; 5923 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx); 5924 QualType Canonical = readType(*Loc.F, Record, Idx); 5925 if (!Canonical.isNull()) 5926 Canonical = Context.getCanonicalType(Canonical); 5927 return Context.getTypedefType(Decl, Canonical); 5928 } 5929 5930 case TYPE_TYPEOF_EXPR: 5931 return Context.getTypeOfExprType(ReadExpr(*Loc.F)); 5932 5933 case TYPE_TYPEOF: { 5934 if (Record.size() != 1) { 5935 Error("incorrect encoding of typeof(type) in AST file"); 5936 return QualType(); 5937 } 5938 QualType UnderlyingType = readType(*Loc.F, Record, Idx); 5939 return Context.getTypeOfType(UnderlyingType); 5940 } 5941 5942 case TYPE_DECLTYPE: { 5943 QualType UnderlyingType = readType(*Loc.F, Record, Idx); 5944 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType); 5945 } 5946 5947 case TYPE_UNARY_TRANSFORM: { 5948 QualType BaseType = readType(*Loc.F, Record, Idx); 5949 QualType UnderlyingType = readType(*Loc.F, Record, Idx); 5950 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2]; 5951 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind); 5952 } 5953 5954 case TYPE_AUTO: { 5955 QualType Deduced = readType(*Loc.F, Record, Idx); 5956 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++]; 5957 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false; 5958 return Context.getAutoType(Deduced, Keyword, IsDependent); 5959 } 5960 5961 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: { 5962 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx); 5963 QualType Deduced = readType(*Loc.F, Record, Idx); 5964 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false; 5965 return Context.getDeducedTemplateSpecializationType(Name, Deduced, 5966 IsDependent); 5967 } 5968 5969 case TYPE_RECORD: { 5970 if (Record.size() != 2) { 5971 Error("incorrect encoding of record type"); 5972 return QualType(); 5973 } 5974 unsigned Idx = 0; 5975 bool IsDependent = Record[Idx++]; 5976 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx); 5977 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl()); 5978 QualType T = Context.getRecordType(RD); 5979 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent); 5980 return T; 5981 } 5982 5983 case TYPE_ENUM: { 5984 if (Record.size() != 2) { 5985 Error("incorrect encoding of enum type"); 5986 return QualType(); 5987 } 5988 unsigned Idx = 0; 5989 bool IsDependent = Record[Idx++]; 5990 QualType T 5991 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx)); 5992 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent); 5993 return T; 5994 } 5995 5996 case TYPE_ATTRIBUTED: { 5997 if (Record.size() != 3) { 5998 Error("incorrect encoding of attributed type"); 5999 return QualType(); 6000 } 6001 QualType modifiedType = readType(*Loc.F, Record, Idx); 6002 QualType equivalentType = readType(*Loc.F, Record, Idx); 6003 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]); 6004 return Context.getAttributedType(kind, modifiedType, equivalentType); 6005 } 6006 6007 case TYPE_PAREN: { 6008 if (Record.size() != 1) { 6009 Error("incorrect encoding of paren type"); 6010 return QualType(); 6011 } 6012 QualType InnerType = readType(*Loc.F, Record, Idx); 6013 return Context.getParenType(InnerType); 6014 } 6015 6016 case TYPE_PACK_EXPANSION: { 6017 if (Record.size() != 2) { 6018 Error("incorrect encoding of pack expansion type"); 6019 return QualType(); 6020 } 6021 QualType Pattern = readType(*Loc.F, Record, Idx); 6022 if (Pattern.isNull()) 6023 return QualType(); 6024 Optional<unsigned> NumExpansions; 6025 if (Record[1]) 6026 NumExpansions = Record[1] - 1; 6027 return Context.getPackExpansionType(Pattern, NumExpansions); 6028 } 6029 6030 case TYPE_ELABORATED: { 6031 unsigned Idx = 0; 6032 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++]; 6033 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx); 6034 QualType NamedType = readType(*Loc.F, Record, Idx); 6035 return Context.getElaboratedType(Keyword, NNS, NamedType); 6036 } 6037 6038 case TYPE_OBJC_INTERFACE: { 6039 unsigned Idx = 0; 6040 ObjCInterfaceDecl *ItfD 6041 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx); 6042 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl()); 6043 } 6044 6045 case TYPE_OBJC_TYPE_PARAM: { 6046 unsigned Idx = 0; 6047 ObjCTypeParamDecl *Decl 6048 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx); 6049 unsigned NumProtos = Record[Idx++]; 6050 SmallVector<ObjCProtocolDecl*, 4> Protos; 6051 for (unsigned I = 0; I != NumProtos; ++I) 6052 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx)); 6053 return Context.getObjCTypeParamType(Decl, Protos); 6054 } 6055 case TYPE_OBJC_OBJECT: { 6056 unsigned Idx = 0; 6057 QualType Base = readType(*Loc.F, Record, Idx); 6058 unsigned NumTypeArgs = Record[Idx++]; 6059 SmallVector<QualType, 4> TypeArgs; 6060 for (unsigned I = 0; I != NumTypeArgs; ++I) 6061 TypeArgs.push_back(readType(*Loc.F, Record, Idx)); 6062 unsigned NumProtos = Record[Idx++]; 6063 SmallVector<ObjCProtocolDecl*, 4> Protos; 6064 for (unsigned I = 0; I != NumProtos; ++I) 6065 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx)); 6066 bool IsKindOf = Record[Idx++]; 6067 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf); 6068 } 6069 6070 case TYPE_OBJC_OBJECT_POINTER: { 6071 unsigned Idx = 0; 6072 QualType Pointee = readType(*Loc.F, Record, Idx); 6073 return Context.getObjCObjectPointerType(Pointee); 6074 } 6075 6076 case TYPE_SUBST_TEMPLATE_TYPE_PARM: { 6077 unsigned Idx = 0; 6078 QualType Parm = readType(*Loc.F, Record, Idx); 6079 QualType Replacement = readType(*Loc.F, Record, Idx); 6080 return Context.getSubstTemplateTypeParmType( 6081 cast<TemplateTypeParmType>(Parm), 6082 Context.getCanonicalType(Replacement)); 6083 } 6084 6085 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: { 6086 unsigned Idx = 0; 6087 QualType Parm = readType(*Loc.F, Record, Idx); 6088 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx); 6089 return Context.getSubstTemplateTypeParmPackType( 6090 cast<TemplateTypeParmType>(Parm), 6091 ArgPack); 6092 } 6093 6094 case TYPE_INJECTED_CLASS_NAME: { 6095 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx); 6096 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable 6097 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable 6098 // for AST reading, too much interdependencies. 6099 const Type *T = nullptr; 6100 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) { 6101 if (const Type *Existing = DI->getTypeForDecl()) { 6102 T = Existing; 6103 break; 6104 } 6105 } 6106 if (!T) { 6107 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST); 6108 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) 6109 DI->setTypeForDecl(T); 6110 } 6111 return QualType(T, 0); 6112 } 6113 6114 case TYPE_TEMPLATE_TYPE_PARM: { 6115 unsigned Idx = 0; 6116 unsigned Depth = Record[Idx++]; 6117 unsigned Index = Record[Idx++]; 6118 bool Pack = Record[Idx++]; 6119 TemplateTypeParmDecl *D 6120 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx); 6121 return Context.getTemplateTypeParmType(Depth, Index, Pack, D); 6122 } 6123 6124 case TYPE_DEPENDENT_NAME: { 6125 unsigned Idx = 0; 6126 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++]; 6127 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx); 6128 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx); 6129 QualType Canon = readType(*Loc.F, Record, Idx); 6130 if (!Canon.isNull()) 6131 Canon = Context.getCanonicalType(Canon); 6132 return Context.getDependentNameType(Keyword, NNS, Name, Canon); 6133 } 6134 6135 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: { 6136 unsigned Idx = 0; 6137 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++]; 6138 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx); 6139 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx); 6140 unsigned NumArgs = Record[Idx++]; 6141 SmallVector<TemplateArgument, 8> Args; 6142 Args.reserve(NumArgs); 6143 while (NumArgs--) 6144 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx)); 6145 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name, 6146 Args); 6147 } 6148 6149 case TYPE_DEPENDENT_SIZED_ARRAY: { 6150 unsigned Idx = 0; 6151 6152 // ArrayType 6153 QualType ElementType = readType(*Loc.F, Record, Idx); 6154 ArrayType::ArraySizeModifier ASM 6155 = (ArrayType::ArraySizeModifier)Record[Idx++]; 6156 unsigned IndexTypeQuals = Record[Idx++]; 6157 6158 // DependentSizedArrayType 6159 Expr *NumElts = ReadExpr(*Loc.F); 6160 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx); 6161 6162 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM, 6163 IndexTypeQuals, Brackets); 6164 } 6165 6166 case TYPE_TEMPLATE_SPECIALIZATION: { 6167 unsigned Idx = 0; 6168 bool IsDependent = Record[Idx++]; 6169 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx); 6170 SmallVector<TemplateArgument, 8> Args; 6171 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx); 6172 QualType Underlying = readType(*Loc.F, Record, Idx); 6173 QualType T; 6174 if (Underlying.isNull()) 6175 T = Context.getCanonicalTemplateSpecializationType(Name, Args); 6176 else 6177 T = Context.getTemplateSpecializationType(Name, Args, Underlying); 6178 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent); 6179 return T; 6180 } 6181 6182 case TYPE_ATOMIC: { 6183 if (Record.size() != 1) { 6184 Error("Incorrect encoding of atomic type"); 6185 return QualType(); 6186 } 6187 QualType ValueType = readType(*Loc.F, Record, Idx); 6188 return Context.getAtomicType(ValueType); 6189 } 6190 6191 case TYPE_PIPE: { 6192 if (Record.size() != 2) { 6193 Error("Incorrect encoding of pipe type"); 6194 return QualType(); 6195 } 6196 6197 // Reading the pipe element type. 6198 QualType ElementType = readType(*Loc.F, Record, Idx); 6199 unsigned ReadOnly = Record[1]; 6200 return Context.getPipeType(ElementType, ReadOnly); 6201 } 6202 6203 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: { 6204 unsigned Idx = 0; 6205 6206 // DependentSizedExtVectorType 6207 QualType ElementType = readType(*Loc.F, Record, Idx); 6208 Expr *SizeExpr = ReadExpr(*Loc.F); 6209 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx); 6210 6211 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr, 6212 AttrLoc); 6213 } 6214 } 6215 llvm_unreachable("Invalid TypeCode!"); 6216 } 6217 6218 void ASTReader::readExceptionSpec(ModuleFile &ModuleFile, 6219 SmallVectorImpl<QualType> &Exceptions, 6220 FunctionProtoType::ExceptionSpecInfo &ESI, 6221 const RecordData &Record, unsigned &Idx) { 6222 ExceptionSpecificationType EST = 6223 static_cast<ExceptionSpecificationType>(Record[Idx++]); 6224 ESI.Type = EST; 6225 if (EST == EST_Dynamic) { 6226 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I) 6227 Exceptions.push_back(readType(ModuleFile, Record, Idx)); 6228 ESI.Exceptions = Exceptions; 6229 } else if (EST == EST_ComputedNoexcept) { 6230 ESI.NoexceptExpr = ReadExpr(ModuleFile); 6231 } else if (EST == EST_Uninstantiated) { 6232 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx); 6233 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx); 6234 } else if (EST == EST_Unevaluated) { 6235 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx); 6236 } 6237 } 6238 6239 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> { 6240 ModuleFile *F; 6241 ASTReader *Reader; 6242 const ASTReader::RecordData &Record; 6243 unsigned &Idx; 6244 6245 SourceLocation ReadSourceLocation() { 6246 return Reader->ReadSourceLocation(*F, Record, Idx); 6247 } 6248 6249 TypeSourceInfo *GetTypeSourceInfo() { 6250 return Reader->GetTypeSourceInfo(*F, Record, Idx); 6251 } 6252 6253 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() { 6254 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx); 6255 } 6256 6257 public: 6258 TypeLocReader(ModuleFile &F, ASTReader &Reader, 6259 const ASTReader::RecordData &Record, unsigned &Idx) 6260 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {} 6261 6262 // We want compile-time assurance that we've enumerated all of 6263 // these, so unfortunately we have to declare them first, then 6264 // define them out-of-line. 6265 #define ABSTRACT_TYPELOC(CLASS, PARENT) 6266 #define TYPELOC(CLASS, PARENT) \ 6267 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc); 6268 #include "clang/AST/TypeLocNodes.def" 6269 6270 void VisitFunctionTypeLoc(FunctionTypeLoc); 6271 void VisitArrayTypeLoc(ArrayTypeLoc); 6272 }; 6273 6274 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 6275 // nothing to do 6276 } 6277 6278 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 6279 TL.setBuiltinLoc(ReadSourceLocation()); 6280 if (TL.needsExtraLocalData()) { 6281 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++])); 6282 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++])); 6283 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++])); 6284 TL.setModeAttr(Record[Idx++]); 6285 } 6286 } 6287 6288 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) { 6289 TL.setNameLoc(ReadSourceLocation()); 6290 } 6291 6292 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) { 6293 TL.setStarLoc(ReadSourceLocation()); 6294 } 6295 6296 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) { 6297 // nothing to do 6298 } 6299 6300 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 6301 // nothing to do 6302 } 6303 6304 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 6305 TL.setCaretLoc(ReadSourceLocation()); 6306 } 6307 6308 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 6309 TL.setAmpLoc(ReadSourceLocation()); 6310 } 6311 6312 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 6313 TL.setAmpAmpLoc(ReadSourceLocation()); 6314 } 6315 6316 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 6317 TL.setStarLoc(ReadSourceLocation()); 6318 TL.setClassTInfo(GetTypeSourceInfo()); 6319 } 6320 6321 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) { 6322 TL.setLBracketLoc(ReadSourceLocation()); 6323 TL.setRBracketLoc(ReadSourceLocation()); 6324 if (Record[Idx++]) 6325 TL.setSizeExpr(Reader->ReadExpr(*F)); 6326 else 6327 TL.setSizeExpr(nullptr); 6328 } 6329 6330 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) { 6331 VisitArrayTypeLoc(TL); 6332 } 6333 6334 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) { 6335 VisitArrayTypeLoc(TL); 6336 } 6337 6338 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) { 6339 VisitArrayTypeLoc(TL); 6340 } 6341 6342 void TypeLocReader::VisitDependentSizedArrayTypeLoc( 6343 DependentSizedArrayTypeLoc TL) { 6344 VisitArrayTypeLoc(TL); 6345 } 6346 6347 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc( 6348 DependentSizedExtVectorTypeLoc TL) { 6349 TL.setNameLoc(ReadSourceLocation()); 6350 } 6351 6352 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) { 6353 TL.setNameLoc(ReadSourceLocation()); 6354 } 6355 6356 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { 6357 TL.setNameLoc(ReadSourceLocation()); 6358 } 6359 6360 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) { 6361 TL.setLocalRangeBegin(ReadSourceLocation()); 6362 TL.setLParenLoc(ReadSourceLocation()); 6363 TL.setRParenLoc(ReadSourceLocation()); 6364 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx), 6365 Reader->ReadSourceLocation(*F, Record, Idx))); 6366 TL.setLocalRangeEnd(ReadSourceLocation()); 6367 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) { 6368 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx)); 6369 } 6370 } 6371 6372 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) { 6373 VisitFunctionTypeLoc(TL); 6374 } 6375 6376 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) { 6377 VisitFunctionTypeLoc(TL); 6378 } 6379 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 6380 TL.setNameLoc(ReadSourceLocation()); 6381 } 6382 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 6383 TL.setNameLoc(ReadSourceLocation()); 6384 } 6385 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 6386 TL.setTypeofLoc(ReadSourceLocation()); 6387 TL.setLParenLoc(ReadSourceLocation()); 6388 TL.setRParenLoc(ReadSourceLocation()); 6389 } 6390 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 6391 TL.setTypeofLoc(ReadSourceLocation()); 6392 TL.setLParenLoc(ReadSourceLocation()); 6393 TL.setRParenLoc(ReadSourceLocation()); 6394 TL.setUnderlyingTInfo(GetTypeSourceInfo()); 6395 } 6396 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 6397 TL.setNameLoc(ReadSourceLocation()); 6398 } 6399 6400 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 6401 TL.setKWLoc(ReadSourceLocation()); 6402 TL.setLParenLoc(ReadSourceLocation()); 6403 TL.setRParenLoc(ReadSourceLocation()); 6404 TL.setUnderlyingTInfo(GetTypeSourceInfo()); 6405 } 6406 6407 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) { 6408 TL.setNameLoc(ReadSourceLocation()); 6409 } 6410 6411 void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc( 6412 DeducedTemplateSpecializationTypeLoc TL) { 6413 TL.setTemplateNameLoc(ReadSourceLocation()); 6414 } 6415 6416 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) { 6417 TL.setNameLoc(ReadSourceLocation()); 6418 } 6419 6420 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { 6421 TL.setNameLoc(ReadSourceLocation()); 6422 } 6423 6424 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) { 6425 TL.setAttrNameLoc(ReadSourceLocation()); 6426 if (TL.hasAttrOperand()) { 6427 SourceRange range; 6428 range.setBegin(ReadSourceLocation()); 6429 range.setEnd(ReadSourceLocation()); 6430 TL.setAttrOperandParensRange(range); 6431 } 6432 if (TL.hasAttrExprOperand()) { 6433 if (Record[Idx++]) 6434 TL.setAttrExprOperand(Reader->ReadExpr(*F)); 6435 else 6436 TL.setAttrExprOperand(nullptr); 6437 } else if (TL.hasAttrEnumOperand()) 6438 TL.setAttrEnumOperandLoc(ReadSourceLocation()); 6439 } 6440 6441 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 6442 TL.setNameLoc(ReadSourceLocation()); 6443 } 6444 6445 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc( 6446 SubstTemplateTypeParmTypeLoc TL) { 6447 TL.setNameLoc(ReadSourceLocation()); 6448 } 6449 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc( 6450 SubstTemplateTypeParmPackTypeLoc TL) { 6451 TL.setNameLoc(ReadSourceLocation()); 6452 } 6453 void TypeLocReader::VisitTemplateSpecializationTypeLoc( 6454 TemplateSpecializationTypeLoc TL) { 6455 TL.setTemplateKeywordLoc(ReadSourceLocation()); 6456 TL.setTemplateNameLoc(ReadSourceLocation()); 6457 TL.setLAngleLoc(ReadSourceLocation()); 6458 TL.setRAngleLoc(ReadSourceLocation()); 6459 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 6460 TL.setArgLocInfo( 6461 i, 6462 Reader->GetTemplateArgumentLocInfo( 6463 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx)); 6464 } 6465 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) { 6466 TL.setLParenLoc(ReadSourceLocation()); 6467 TL.setRParenLoc(ReadSourceLocation()); 6468 } 6469 6470 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 6471 TL.setElaboratedKeywordLoc(ReadSourceLocation()); 6472 TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); 6473 } 6474 6475 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 6476 TL.setNameLoc(ReadSourceLocation()); 6477 } 6478 6479 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 6480 TL.setElaboratedKeywordLoc(ReadSourceLocation()); 6481 TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); 6482 TL.setNameLoc(ReadSourceLocation()); 6483 } 6484 6485 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc( 6486 DependentTemplateSpecializationTypeLoc TL) { 6487 TL.setElaboratedKeywordLoc(ReadSourceLocation()); 6488 TL.setQualifierLoc(ReadNestedNameSpecifierLoc()); 6489 TL.setTemplateKeywordLoc(ReadSourceLocation()); 6490 TL.setTemplateNameLoc(ReadSourceLocation()); 6491 TL.setLAngleLoc(ReadSourceLocation()); 6492 TL.setRAngleLoc(ReadSourceLocation()); 6493 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) 6494 TL.setArgLocInfo( 6495 I, 6496 Reader->GetTemplateArgumentLocInfo( 6497 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx)); 6498 } 6499 6500 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { 6501 TL.setEllipsisLoc(ReadSourceLocation()); 6502 } 6503 6504 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 6505 TL.setNameLoc(ReadSourceLocation()); 6506 } 6507 6508 void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) { 6509 if (TL.getNumProtocols()) { 6510 TL.setProtocolLAngleLoc(ReadSourceLocation()); 6511 TL.setProtocolRAngleLoc(ReadSourceLocation()); 6512 } 6513 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 6514 TL.setProtocolLoc(i, ReadSourceLocation()); 6515 } 6516 6517 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 6518 TL.setHasBaseTypeAsWritten(Record[Idx++]); 6519 TL.setTypeArgsLAngleLoc(ReadSourceLocation()); 6520 TL.setTypeArgsRAngleLoc(ReadSourceLocation()); 6521 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i) 6522 TL.setTypeArgTInfo(i, GetTypeSourceInfo()); 6523 TL.setProtocolLAngleLoc(ReadSourceLocation()); 6524 TL.setProtocolRAngleLoc(ReadSourceLocation()); 6525 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 6526 TL.setProtocolLoc(i, ReadSourceLocation()); 6527 } 6528 6529 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 6530 TL.setStarLoc(ReadSourceLocation()); 6531 } 6532 6533 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) { 6534 TL.setKWLoc(ReadSourceLocation()); 6535 TL.setLParenLoc(ReadSourceLocation()); 6536 TL.setRParenLoc(ReadSourceLocation()); 6537 } 6538 6539 void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) { 6540 TL.setKWLoc(ReadSourceLocation()); 6541 } 6542 6543 TypeSourceInfo * 6544 ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record, 6545 unsigned &Idx) { 6546 QualType InfoTy = readType(F, Record, Idx); 6547 if (InfoTy.isNull()) 6548 return nullptr; 6549 6550 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy); 6551 TypeLocReader TLR(F, *this, Record, Idx); 6552 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc()) 6553 TLR.Visit(TL); 6554 return TInfo; 6555 } 6556 6557 QualType ASTReader::GetType(TypeID ID) { 6558 unsigned FastQuals = ID & Qualifiers::FastMask; 6559 unsigned Index = ID >> Qualifiers::FastWidth; 6560 6561 if (Index < NUM_PREDEF_TYPE_IDS) { 6562 QualType T; 6563 switch ((PredefinedTypeIDs)Index) { 6564 case PREDEF_TYPE_NULL_ID: 6565 return QualType(); 6566 case PREDEF_TYPE_VOID_ID: 6567 T = Context.VoidTy; 6568 break; 6569 case PREDEF_TYPE_BOOL_ID: 6570 T = Context.BoolTy; 6571 break; 6572 6573 case PREDEF_TYPE_CHAR_U_ID: 6574 case PREDEF_TYPE_CHAR_S_ID: 6575 // FIXME: Check that the signedness of CharTy is correct! 6576 T = Context.CharTy; 6577 break; 6578 6579 case PREDEF_TYPE_UCHAR_ID: 6580 T = Context.UnsignedCharTy; 6581 break; 6582 case PREDEF_TYPE_USHORT_ID: 6583 T = Context.UnsignedShortTy; 6584 break; 6585 case PREDEF_TYPE_UINT_ID: 6586 T = Context.UnsignedIntTy; 6587 break; 6588 case PREDEF_TYPE_ULONG_ID: 6589 T = Context.UnsignedLongTy; 6590 break; 6591 case PREDEF_TYPE_ULONGLONG_ID: 6592 T = Context.UnsignedLongLongTy; 6593 break; 6594 case PREDEF_TYPE_UINT128_ID: 6595 T = Context.UnsignedInt128Ty; 6596 break; 6597 case PREDEF_TYPE_SCHAR_ID: 6598 T = Context.SignedCharTy; 6599 break; 6600 case PREDEF_TYPE_WCHAR_ID: 6601 T = Context.WCharTy; 6602 break; 6603 case PREDEF_TYPE_SHORT_ID: 6604 T = Context.ShortTy; 6605 break; 6606 case PREDEF_TYPE_INT_ID: 6607 T = Context.IntTy; 6608 break; 6609 case PREDEF_TYPE_LONG_ID: 6610 T = Context.LongTy; 6611 break; 6612 case PREDEF_TYPE_LONGLONG_ID: 6613 T = Context.LongLongTy; 6614 break; 6615 case PREDEF_TYPE_INT128_ID: 6616 T = Context.Int128Ty; 6617 break; 6618 case PREDEF_TYPE_HALF_ID: 6619 T = Context.HalfTy; 6620 break; 6621 case PREDEF_TYPE_FLOAT_ID: 6622 T = Context.FloatTy; 6623 break; 6624 case PREDEF_TYPE_DOUBLE_ID: 6625 T = Context.DoubleTy; 6626 break; 6627 case PREDEF_TYPE_LONGDOUBLE_ID: 6628 T = Context.LongDoubleTy; 6629 break; 6630 case PREDEF_TYPE_FLOAT128_ID: 6631 T = Context.Float128Ty; 6632 break; 6633 case PREDEF_TYPE_OVERLOAD_ID: 6634 T = Context.OverloadTy; 6635 break; 6636 case PREDEF_TYPE_BOUND_MEMBER: 6637 T = Context.BoundMemberTy; 6638 break; 6639 case PREDEF_TYPE_PSEUDO_OBJECT: 6640 T = Context.PseudoObjectTy; 6641 break; 6642 case PREDEF_TYPE_DEPENDENT_ID: 6643 T = Context.DependentTy; 6644 break; 6645 case PREDEF_TYPE_UNKNOWN_ANY: 6646 T = Context.UnknownAnyTy; 6647 break; 6648 case PREDEF_TYPE_NULLPTR_ID: 6649 T = Context.NullPtrTy; 6650 break; 6651 case PREDEF_TYPE_CHAR16_ID: 6652 T = Context.Char16Ty; 6653 break; 6654 case PREDEF_TYPE_CHAR32_ID: 6655 T = Context.Char32Ty; 6656 break; 6657 case PREDEF_TYPE_OBJC_ID: 6658 T = Context.ObjCBuiltinIdTy; 6659 break; 6660 case PREDEF_TYPE_OBJC_CLASS: 6661 T = Context.ObjCBuiltinClassTy; 6662 break; 6663 case PREDEF_TYPE_OBJC_SEL: 6664 T = Context.ObjCBuiltinSelTy; 6665 break; 6666 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6667 case PREDEF_TYPE_##Id##_ID: \ 6668 T = Context.SingletonId; \ 6669 break; 6670 #include "clang/Basic/OpenCLImageTypes.def" 6671 case PREDEF_TYPE_SAMPLER_ID: 6672 T = Context.OCLSamplerTy; 6673 break; 6674 case PREDEF_TYPE_EVENT_ID: 6675 T = Context.OCLEventTy; 6676 break; 6677 case PREDEF_TYPE_CLK_EVENT_ID: 6678 T = Context.OCLClkEventTy; 6679 break; 6680 case PREDEF_TYPE_QUEUE_ID: 6681 T = Context.OCLQueueTy; 6682 break; 6683 case PREDEF_TYPE_RESERVE_ID_ID: 6684 T = Context.OCLReserveIDTy; 6685 break; 6686 case PREDEF_TYPE_AUTO_DEDUCT: 6687 T = Context.getAutoDeductType(); 6688 break; 6689 6690 case PREDEF_TYPE_AUTO_RREF_DEDUCT: 6691 T = Context.getAutoRRefDeductType(); 6692 break; 6693 6694 case PREDEF_TYPE_ARC_UNBRIDGED_CAST: 6695 T = Context.ARCUnbridgedCastTy; 6696 break; 6697 6698 case PREDEF_TYPE_BUILTIN_FN: 6699 T = Context.BuiltinFnTy; 6700 break; 6701 6702 case PREDEF_TYPE_OMP_ARRAY_SECTION: 6703 T = Context.OMPArraySectionTy; 6704 break; 6705 } 6706 6707 assert(!T.isNull() && "Unknown predefined type"); 6708 return T.withFastQualifiers(FastQuals); 6709 } 6710 6711 Index -= NUM_PREDEF_TYPE_IDS; 6712 assert(Index < TypesLoaded.size() && "Type index out-of-range"); 6713 if (TypesLoaded[Index].isNull()) { 6714 TypesLoaded[Index] = readTypeRecord(Index); 6715 if (TypesLoaded[Index].isNull()) 6716 return QualType(); 6717 6718 TypesLoaded[Index]->setFromAST(); 6719 if (DeserializationListener) 6720 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID), 6721 TypesLoaded[Index]); 6722 } 6723 6724 return TypesLoaded[Index].withFastQualifiers(FastQuals); 6725 } 6726 6727 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) { 6728 return GetType(getGlobalTypeID(F, LocalID)); 6729 } 6730 6731 serialization::TypeID 6732 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const { 6733 unsigned FastQuals = LocalID & Qualifiers::FastMask; 6734 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth; 6735 6736 if (LocalIndex < NUM_PREDEF_TYPE_IDS) 6737 return LocalID; 6738 6739 if (!F.ModuleOffsetMap.empty()) 6740 ReadModuleOffsetMap(F); 6741 6742 ContinuousRangeMap<uint32_t, int, 2>::iterator I 6743 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS); 6744 assert(I != F.TypeRemap.end() && "Invalid index into type index remap"); 6745 6746 unsigned GlobalIndex = LocalIndex + I->second; 6747 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals; 6748 } 6749 6750 TemplateArgumentLocInfo 6751 ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F, 6752 TemplateArgument::ArgKind Kind, 6753 const RecordData &Record, 6754 unsigned &Index) { 6755 switch (Kind) { 6756 case TemplateArgument::Expression: 6757 return ReadExpr(F); 6758 case TemplateArgument::Type: 6759 return GetTypeSourceInfo(F, Record, Index); 6760 case TemplateArgument::Template: { 6761 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, 6762 Index); 6763 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index); 6764 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc, 6765 SourceLocation()); 6766 } 6767 case TemplateArgument::TemplateExpansion: { 6768 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, 6769 Index); 6770 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index); 6771 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index); 6772 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc, 6773 EllipsisLoc); 6774 } 6775 case TemplateArgument::Null: 6776 case TemplateArgument::Integral: 6777 case TemplateArgument::Declaration: 6778 case TemplateArgument::NullPtr: 6779 case TemplateArgument::Pack: 6780 // FIXME: Is this right? 6781 return TemplateArgumentLocInfo(); 6782 } 6783 llvm_unreachable("unexpected template argument loc"); 6784 } 6785 6786 TemplateArgumentLoc 6787 ASTReader::ReadTemplateArgumentLoc(ModuleFile &F, 6788 const RecordData &Record, unsigned &Index) { 6789 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index); 6790 6791 if (Arg.getKind() == TemplateArgument::Expression) { 6792 if (Record[Index++]) // bool InfoHasSameExpr. 6793 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr())); 6794 } 6795 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(), 6796 Record, Index)); 6797 } 6798 6799 const ASTTemplateArgumentListInfo* 6800 ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F, 6801 const RecordData &Record, 6802 unsigned &Index) { 6803 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index); 6804 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index); 6805 unsigned NumArgsAsWritten = Record[Index++]; 6806 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc); 6807 for (unsigned i = 0; i != NumArgsAsWritten; ++i) 6808 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index)); 6809 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo); 6810 } 6811 6812 Decl *ASTReader::GetExternalDecl(uint32_t ID) { 6813 return GetDecl(ID); 6814 } 6815 6816 void ASTReader::CompleteRedeclChain(const Decl *D) { 6817 if (NumCurrentElementsDeserializing) { 6818 // We arrange to not care about the complete redeclaration chain while we're 6819 // deserializing. Just remember that the AST has marked this one as complete 6820 // but that it's not actually complete yet, so we know we still need to 6821 // complete it later. 6822 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D)); 6823 return; 6824 } 6825 6826 const DeclContext *DC = D->getDeclContext()->getRedeclContext(); 6827 6828 // If this is a named declaration, complete it by looking it up 6829 // within its context. 6830 // 6831 // FIXME: Merging a function definition should merge 6832 // all mergeable entities within it. 6833 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) || 6834 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) { 6835 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) { 6836 if (!getContext().getLangOpts().CPlusPlus && 6837 isa<TranslationUnitDecl>(DC)) { 6838 // Outside of C++, we don't have a lookup table for the TU, so update 6839 // the identifier instead. (For C++ modules, we don't store decls 6840 // in the serialized identifier table, so we do the lookup in the TU.) 6841 auto *II = Name.getAsIdentifierInfo(); 6842 assert(II && "non-identifier name in C?"); 6843 if (II->isOutOfDate()) 6844 updateOutOfDateIdentifier(*II); 6845 } else 6846 DC->lookup(Name); 6847 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) { 6848 // Find all declarations of this kind from the relevant context. 6849 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) { 6850 auto *DC = cast<DeclContext>(DCDecl); 6851 SmallVector<Decl*, 8> Decls; 6852 FindExternalLexicalDecls( 6853 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls); 6854 } 6855 } 6856 } 6857 6858 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) 6859 CTSD->getSpecializedTemplate()->LoadLazySpecializations(); 6860 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) 6861 VTSD->getSpecializedTemplate()->LoadLazySpecializations(); 6862 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 6863 if (auto *Template = FD->getPrimaryTemplate()) 6864 Template->LoadLazySpecializations(); 6865 } 6866 } 6867 6868 CXXCtorInitializer ** 6869 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) { 6870 RecordLocation Loc = getLocalBitOffset(Offset); 6871 BitstreamCursor &Cursor = Loc.F->DeclsCursor; 6872 SavedStreamPosition SavedPosition(Cursor); 6873 Cursor.JumpToBit(Loc.Offset); 6874 ReadingKindTracker ReadingKind(Read_Decl, *this); 6875 6876 RecordData Record; 6877 unsigned Code = Cursor.ReadCode(); 6878 unsigned RecCode = Cursor.readRecord(Code, Record); 6879 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) { 6880 Error("malformed AST file: missing C++ ctor initializers"); 6881 return nullptr; 6882 } 6883 6884 unsigned Idx = 0; 6885 return ReadCXXCtorInitializers(*Loc.F, Record, Idx); 6886 } 6887 6888 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) { 6889 RecordLocation Loc = getLocalBitOffset(Offset); 6890 BitstreamCursor &Cursor = Loc.F->DeclsCursor; 6891 SavedStreamPosition SavedPosition(Cursor); 6892 Cursor.JumpToBit(Loc.Offset); 6893 ReadingKindTracker ReadingKind(Read_Decl, *this); 6894 RecordData Record; 6895 unsigned Code = Cursor.ReadCode(); 6896 unsigned RecCode = Cursor.readRecord(Code, Record); 6897 if (RecCode != DECL_CXX_BASE_SPECIFIERS) { 6898 Error("malformed AST file: missing C++ base specifiers"); 6899 return nullptr; 6900 } 6901 6902 unsigned Idx = 0; 6903 unsigned NumBases = Record[Idx++]; 6904 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases); 6905 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases]; 6906 for (unsigned I = 0; I != NumBases; ++I) 6907 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx); 6908 return Bases; 6909 } 6910 6911 serialization::DeclID 6912 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const { 6913 if (LocalID < NUM_PREDEF_DECL_IDS) 6914 return LocalID; 6915 6916 if (!F.ModuleOffsetMap.empty()) 6917 ReadModuleOffsetMap(F); 6918 6919 ContinuousRangeMap<uint32_t, int, 2>::iterator I 6920 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS); 6921 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap"); 6922 6923 return LocalID + I->second; 6924 } 6925 6926 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID, 6927 ModuleFile &M) const { 6928 // Predefined decls aren't from any module. 6929 if (ID < NUM_PREDEF_DECL_IDS) 6930 return false; 6931 6932 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID && 6933 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls; 6934 } 6935 6936 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) { 6937 if (!D->isFromASTFile()) 6938 return nullptr; 6939 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID()); 6940 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map"); 6941 return I->second; 6942 } 6943 6944 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) { 6945 if (ID < NUM_PREDEF_DECL_IDS) 6946 return SourceLocation(); 6947 6948 unsigned Index = ID - NUM_PREDEF_DECL_IDS; 6949 6950 if (Index > DeclsLoaded.size()) { 6951 Error("declaration ID out-of-range for AST file"); 6952 return SourceLocation(); 6953 } 6954 6955 if (Decl *D = DeclsLoaded[Index]) 6956 return D->getLocation(); 6957 6958 SourceLocation Loc; 6959 DeclCursorForID(ID, Loc); 6960 return Loc; 6961 } 6962 6963 static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) { 6964 switch (ID) { 6965 case PREDEF_DECL_NULL_ID: 6966 return nullptr; 6967 6968 case PREDEF_DECL_TRANSLATION_UNIT_ID: 6969 return Context.getTranslationUnitDecl(); 6970 6971 case PREDEF_DECL_OBJC_ID_ID: 6972 return Context.getObjCIdDecl(); 6973 6974 case PREDEF_DECL_OBJC_SEL_ID: 6975 return Context.getObjCSelDecl(); 6976 6977 case PREDEF_DECL_OBJC_CLASS_ID: 6978 return Context.getObjCClassDecl(); 6979 6980 case PREDEF_DECL_OBJC_PROTOCOL_ID: 6981 return Context.getObjCProtocolDecl(); 6982 6983 case PREDEF_DECL_INT_128_ID: 6984 return Context.getInt128Decl(); 6985 6986 case PREDEF_DECL_UNSIGNED_INT_128_ID: 6987 return Context.getUInt128Decl(); 6988 6989 case PREDEF_DECL_OBJC_INSTANCETYPE_ID: 6990 return Context.getObjCInstanceTypeDecl(); 6991 6992 case PREDEF_DECL_BUILTIN_VA_LIST_ID: 6993 return Context.getBuiltinVaListDecl(); 6994 6995 case PREDEF_DECL_VA_LIST_TAG: 6996 return Context.getVaListTagDecl(); 6997 6998 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID: 6999 return Context.getBuiltinMSVaListDecl(); 7000 7001 case PREDEF_DECL_EXTERN_C_CONTEXT_ID: 7002 return Context.getExternCContextDecl(); 7003 7004 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID: 7005 return Context.getMakeIntegerSeqDecl(); 7006 7007 case PREDEF_DECL_CF_CONSTANT_STRING_ID: 7008 return Context.getCFConstantStringDecl(); 7009 7010 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID: 7011 return Context.getCFConstantStringTagDecl(); 7012 7013 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID: 7014 return Context.getTypePackElementDecl(); 7015 } 7016 llvm_unreachable("PredefinedDeclIDs unknown enum value"); 7017 } 7018 7019 Decl *ASTReader::GetExistingDecl(DeclID ID) { 7020 if (ID < NUM_PREDEF_DECL_IDS) { 7021 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID); 7022 if (D) { 7023 // Track that we have merged the declaration with ID \p ID into the 7024 // pre-existing predefined declaration \p D. 7025 auto &Merged = KeyDecls[D->getCanonicalDecl()]; 7026 if (Merged.empty()) 7027 Merged.push_back(ID); 7028 } 7029 return D; 7030 } 7031 7032 unsigned Index = ID - NUM_PREDEF_DECL_IDS; 7033 7034 if (Index >= DeclsLoaded.size()) { 7035 assert(0 && "declaration ID out-of-range for AST file"); 7036 Error("declaration ID out-of-range for AST file"); 7037 return nullptr; 7038 } 7039 7040 return DeclsLoaded[Index]; 7041 } 7042 7043 Decl *ASTReader::GetDecl(DeclID ID) { 7044 if (ID < NUM_PREDEF_DECL_IDS) 7045 return GetExistingDecl(ID); 7046 7047 unsigned Index = ID - NUM_PREDEF_DECL_IDS; 7048 7049 if (Index >= DeclsLoaded.size()) { 7050 assert(0 && "declaration ID out-of-range for AST file"); 7051 Error("declaration ID out-of-range for AST file"); 7052 return nullptr; 7053 } 7054 7055 if (!DeclsLoaded[Index]) { 7056 ReadDeclRecord(ID); 7057 if (DeserializationListener) 7058 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]); 7059 } 7060 7061 return DeclsLoaded[Index]; 7062 } 7063 7064 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M, 7065 DeclID GlobalID) { 7066 if (GlobalID < NUM_PREDEF_DECL_IDS) 7067 return GlobalID; 7068 7069 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID); 7070 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map"); 7071 ModuleFile *Owner = I->second; 7072 7073 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos 7074 = M.GlobalToLocalDeclIDs.find(Owner); 7075 if (Pos == M.GlobalToLocalDeclIDs.end()) 7076 return 0; 7077 7078 return GlobalID - Owner->BaseDeclID + Pos->second; 7079 } 7080 7081 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F, 7082 const RecordData &Record, 7083 unsigned &Idx) { 7084 if (Idx >= Record.size()) { 7085 Error("Corrupted AST file"); 7086 return 0; 7087 } 7088 7089 return getGlobalDeclID(F, Record[Idx++]); 7090 } 7091 7092 /// \brief Resolve the offset of a statement into a statement. 7093 /// 7094 /// This operation will read a new statement from the external 7095 /// source each time it is called, and is meant to be used via a 7096 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc). 7097 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) { 7098 // Switch case IDs are per Decl. 7099 ClearSwitchCaseIDs(); 7100 7101 // Offset here is a global offset across the entire chain. 7102 RecordLocation Loc = getLocalBitOffset(Offset); 7103 Loc.F->DeclsCursor.JumpToBit(Loc.Offset); 7104 assert(NumCurrentElementsDeserializing == 0 && 7105 "should not be called while already deserializing"); 7106 Deserializing D(this); 7107 return ReadStmtFromStream(*Loc.F); 7108 } 7109 7110 void ASTReader::FindExternalLexicalDecls( 7111 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant, 7112 SmallVectorImpl<Decl *> &Decls) { 7113 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {}; 7114 7115 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) { 7116 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries"); 7117 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) { 7118 auto K = (Decl::Kind)+LexicalDecls[I]; 7119 if (!IsKindWeWant(K)) 7120 continue; 7121 7122 auto ID = (serialization::DeclID)+LexicalDecls[I + 1]; 7123 7124 // Don't add predefined declarations to the lexical context more 7125 // than once. 7126 if (ID < NUM_PREDEF_DECL_IDS) { 7127 if (PredefsVisited[ID]) 7128 continue; 7129 7130 PredefsVisited[ID] = true; 7131 } 7132 7133 if (Decl *D = GetLocalDecl(*M, ID)) { 7134 assert(D->getKind() == K && "wrong kind for lexical decl"); 7135 if (!DC->isDeclInLexicalTraversal(D)) 7136 Decls.push_back(D); 7137 } 7138 } 7139 }; 7140 7141 if (isa<TranslationUnitDecl>(DC)) { 7142 for (auto Lexical : TULexicalDecls) 7143 Visit(Lexical.first, Lexical.second); 7144 } else { 7145 auto I = LexicalDecls.find(DC); 7146 if (I != LexicalDecls.end()) 7147 Visit(I->second.first, I->second.second); 7148 } 7149 7150 ++NumLexicalDeclContextsRead; 7151 } 7152 7153 namespace { 7154 7155 class DeclIDComp { 7156 ASTReader &Reader; 7157 ModuleFile &Mod; 7158 7159 public: 7160 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {} 7161 7162 bool operator()(LocalDeclID L, LocalDeclID R) const { 7163 SourceLocation LHS = getLocation(L); 7164 SourceLocation RHS = getLocation(R); 7165 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 7166 } 7167 7168 bool operator()(SourceLocation LHS, LocalDeclID R) const { 7169 SourceLocation RHS = getLocation(R); 7170 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 7171 } 7172 7173 bool operator()(LocalDeclID L, SourceLocation RHS) const { 7174 SourceLocation LHS = getLocation(L); 7175 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS); 7176 } 7177 7178 SourceLocation getLocation(LocalDeclID ID) const { 7179 return Reader.getSourceManager().getFileLoc( 7180 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID))); 7181 } 7182 }; 7183 7184 } // end anonymous namespace 7185 7186 void ASTReader::FindFileRegionDecls(FileID File, 7187 unsigned Offset, unsigned Length, 7188 SmallVectorImpl<Decl *> &Decls) { 7189 SourceManager &SM = getSourceManager(); 7190 7191 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File); 7192 if (I == FileDeclIDs.end()) 7193 return; 7194 7195 FileDeclsInfo &DInfo = I->second; 7196 if (DInfo.Decls.empty()) 7197 return; 7198 7199 SourceLocation 7200 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset); 7201 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length); 7202 7203 DeclIDComp DIDComp(*this, *DInfo.Mod); 7204 ArrayRef<serialization::LocalDeclID>::iterator 7205 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(), 7206 BeginLoc, DIDComp); 7207 if (BeginIt != DInfo.Decls.begin()) 7208 --BeginIt; 7209 7210 // If we are pointing at a top-level decl inside an objc container, we need 7211 // to backtrack until we find it otherwise we will fail to report that the 7212 // region overlaps with an objc container. 7213 while (BeginIt != DInfo.Decls.begin() && 7214 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt)) 7215 ->isTopLevelDeclInObjCContainer()) 7216 --BeginIt; 7217 7218 ArrayRef<serialization::LocalDeclID>::iterator 7219 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(), 7220 EndLoc, DIDComp); 7221 if (EndIt != DInfo.Decls.end()) 7222 ++EndIt; 7223 7224 for (ArrayRef<serialization::LocalDeclID>::iterator 7225 DIt = BeginIt; DIt != EndIt; ++DIt) 7226 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt))); 7227 } 7228 7229 bool 7230 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC, 7231 DeclarationName Name) { 7232 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() && 7233 "DeclContext has no visible decls in storage"); 7234 if (!Name) 7235 return false; 7236 7237 auto It = Lookups.find(DC); 7238 if (It == Lookups.end()) 7239 return false; 7240 7241 Deserializing LookupResults(this); 7242 7243 // Load the list of declarations. 7244 SmallVector<NamedDecl *, 64> Decls; 7245 for (DeclID ID : It->second.Table.find(Name)) { 7246 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID)); 7247 if (ND->getDeclName() == Name) 7248 Decls.push_back(ND); 7249 } 7250 7251 ++NumVisibleDeclContextsRead; 7252 SetExternalVisibleDeclsForName(DC, Name, Decls); 7253 return !Decls.empty(); 7254 } 7255 7256 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) { 7257 if (!DC->hasExternalVisibleStorage()) 7258 return; 7259 7260 auto It = Lookups.find(DC); 7261 assert(It != Lookups.end() && 7262 "have external visible storage but no lookup tables"); 7263 7264 DeclsMap Decls; 7265 7266 for (DeclID ID : It->second.Table.findAll()) { 7267 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID)); 7268 Decls[ND->getDeclName()].push_back(ND); 7269 } 7270 7271 ++NumVisibleDeclContextsRead; 7272 7273 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) { 7274 SetExternalVisibleDeclsForName(DC, I->first, I->second); 7275 } 7276 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false); 7277 } 7278 7279 const serialization::reader::DeclContextLookupTable * 7280 ASTReader::getLoadedLookupTables(DeclContext *Primary) const { 7281 auto I = Lookups.find(Primary); 7282 return I == Lookups.end() ? nullptr : &I->second; 7283 } 7284 7285 /// \brief Under non-PCH compilation the consumer receives the objc methods 7286 /// before receiving the implementation, and codegen depends on this. 7287 /// We simulate this by deserializing and passing to consumer the methods of the 7288 /// implementation before passing the deserialized implementation decl. 7289 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, 7290 ASTConsumer *Consumer) { 7291 assert(ImplD && Consumer); 7292 7293 for (auto *I : ImplD->methods()) 7294 Consumer->HandleInterestingDecl(DeclGroupRef(I)); 7295 7296 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD)); 7297 } 7298 7299 void ASTReader::PassInterestingDeclToConsumer(Decl *D) { 7300 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D)) 7301 PassObjCImplDeclToConsumer(ImplD, Consumer); 7302 else 7303 Consumer->HandleInterestingDecl(DeclGroupRef(D)); 7304 } 7305 7306 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) { 7307 this->Consumer = Consumer; 7308 7309 if (Consumer) 7310 PassInterestingDeclsToConsumer(); 7311 7312 if (DeserializationListener) 7313 DeserializationListener->ReaderInitialized(this); 7314 } 7315 7316 void ASTReader::PrintStats() { 7317 std::fprintf(stderr, "*** AST File Statistics:\n"); 7318 7319 unsigned NumTypesLoaded 7320 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(), 7321 QualType()); 7322 unsigned NumDeclsLoaded 7323 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(), 7324 (Decl *)nullptr); 7325 unsigned NumIdentifiersLoaded 7326 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(), 7327 IdentifiersLoaded.end(), 7328 (IdentifierInfo *)nullptr); 7329 unsigned NumMacrosLoaded 7330 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(), 7331 MacrosLoaded.end(), 7332 (MacroInfo *)nullptr); 7333 unsigned NumSelectorsLoaded 7334 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(), 7335 SelectorsLoaded.end(), 7336 Selector()); 7337 7338 if (unsigned TotalNumSLocEntries = getTotalNumSLocs()) 7339 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n", 7340 NumSLocEntriesRead, TotalNumSLocEntries, 7341 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100)); 7342 if (!TypesLoaded.empty()) 7343 std::fprintf(stderr, " %u/%u types read (%f%%)\n", 7344 NumTypesLoaded, (unsigned)TypesLoaded.size(), 7345 ((float)NumTypesLoaded/TypesLoaded.size() * 100)); 7346 if (!DeclsLoaded.empty()) 7347 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n", 7348 NumDeclsLoaded, (unsigned)DeclsLoaded.size(), 7349 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100)); 7350 if (!IdentifiersLoaded.empty()) 7351 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n", 7352 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(), 7353 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100)); 7354 if (!MacrosLoaded.empty()) 7355 std::fprintf(stderr, " %u/%u macros read (%f%%)\n", 7356 NumMacrosLoaded, (unsigned)MacrosLoaded.size(), 7357 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100)); 7358 if (!SelectorsLoaded.empty()) 7359 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n", 7360 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(), 7361 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100)); 7362 if (TotalNumStatements) 7363 std::fprintf(stderr, " %u/%u statements read (%f%%)\n", 7364 NumStatementsRead, TotalNumStatements, 7365 ((float)NumStatementsRead/TotalNumStatements * 100)); 7366 if (TotalNumMacros) 7367 std::fprintf(stderr, " %u/%u macros read (%f%%)\n", 7368 NumMacrosRead, TotalNumMacros, 7369 ((float)NumMacrosRead/TotalNumMacros * 100)); 7370 if (TotalLexicalDeclContexts) 7371 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n", 7372 NumLexicalDeclContextsRead, TotalLexicalDeclContexts, 7373 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts 7374 * 100)); 7375 if (TotalVisibleDeclContexts) 7376 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n", 7377 NumVisibleDeclContextsRead, TotalVisibleDeclContexts, 7378 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts 7379 * 100)); 7380 if (TotalNumMethodPoolEntries) { 7381 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n", 7382 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries, 7383 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries 7384 * 100)); 7385 } 7386 if (NumMethodPoolLookups) { 7387 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n", 7388 NumMethodPoolHits, NumMethodPoolLookups, 7389 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0)); 7390 } 7391 if (NumMethodPoolTableLookups) { 7392 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n", 7393 NumMethodPoolTableHits, NumMethodPoolTableLookups, 7394 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups 7395 * 100.0)); 7396 } 7397 7398 if (NumIdentifierLookupHits) { 7399 std::fprintf(stderr, 7400 " %u / %u identifier table lookups succeeded (%f%%)\n", 7401 NumIdentifierLookupHits, NumIdentifierLookups, 7402 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups); 7403 } 7404 7405 if (GlobalIndex) { 7406 std::fprintf(stderr, "\n"); 7407 GlobalIndex->printStats(); 7408 } 7409 7410 std::fprintf(stderr, "\n"); 7411 dump(); 7412 std::fprintf(stderr, "\n"); 7413 } 7414 7415 template<typename Key, typename ModuleFile, unsigned InitialCapacity> 7416 LLVM_DUMP_METHOD static void 7417 dumpModuleIDMap(StringRef Name, 7418 const ContinuousRangeMap<Key, ModuleFile *, 7419 InitialCapacity> &Map) { 7420 if (Map.begin() == Map.end()) 7421 return; 7422 7423 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType; 7424 llvm::errs() << Name << ":\n"; 7425 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end(); 7426 I != IEnd; ++I) { 7427 llvm::errs() << " " << I->first << " -> " << I->second->FileName 7428 << "\n"; 7429 } 7430 } 7431 7432 LLVM_DUMP_METHOD void ASTReader::dump() { 7433 llvm::errs() << "*** PCH/ModuleFile Remappings:\n"; 7434 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap); 7435 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap); 7436 dumpModuleIDMap("Global type map", GlobalTypeMap); 7437 dumpModuleIDMap("Global declaration map", GlobalDeclMap); 7438 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap); 7439 dumpModuleIDMap("Global macro map", GlobalMacroMap); 7440 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap); 7441 dumpModuleIDMap("Global selector map", GlobalSelectorMap); 7442 dumpModuleIDMap("Global preprocessed entity map", 7443 GlobalPreprocessedEntityMap); 7444 7445 llvm::errs() << "\n*** PCH/Modules Loaded:"; 7446 for (ModuleFile &M : ModuleMgr) 7447 M.dump(); 7448 } 7449 7450 /// Return the amount of memory used by memory buffers, breaking down 7451 /// by heap-backed versus mmap'ed memory. 7452 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const { 7453 for (ModuleFile &I : ModuleMgr) { 7454 if (llvm::MemoryBuffer *buf = I.Buffer) { 7455 size_t bytes = buf->getBufferSize(); 7456 switch (buf->getBufferKind()) { 7457 case llvm::MemoryBuffer::MemoryBuffer_Malloc: 7458 sizes.malloc_bytes += bytes; 7459 break; 7460 case llvm::MemoryBuffer::MemoryBuffer_MMap: 7461 sizes.mmap_bytes += bytes; 7462 break; 7463 } 7464 } 7465 } 7466 } 7467 7468 void ASTReader::InitializeSema(Sema &S) { 7469 SemaObj = &S; 7470 S.addExternalSource(this); 7471 7472 // Makes sure any declarations that were deserialized "too early" 7473 // still get added to the identifier's declaration chains. 7474 for (uint64_t ID : PreloadedDeclIDs) { 7475 NamedDecl *D = cast<NamedDecl>(GetDecl(ID)); 7476 pushExternalDeclIntoScope(D, D->getDeclName()); 7477 } 7478 PreloadedDeclIDs.clear(); 7479 7480 // FIXME: What happens if these are changed by a module import? 7481 if (!FPPragmaOptions.empty()) { 7482 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS"); 7483 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]); 7484 } 7485 7486 SemaObj->OpenCLFeatures.copy(OpenCLExtensions); 7487 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap; 7488 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap; 7489 7490 UpdateSema(); 7491 } 7492 7493 void ASTReader::UpdateSema() { 7494 assert(SemaObj && "no Sema to update"); 7495 7496 // Load the offsets of the declarations that Sema references. 7497 // They will be lazily deserialized when needed. 7498 if (!SemaDeclRefs.empty()) { 7499 assert(SemaDeclRefs.size() % 3 == 0); 7500 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) { 7501 if (!SemaObj->StdNamespace) 7502 SemaObj->StdNamespace = SemaDeclRefs[I]; 7503 if (!SemaObj->StdBadAlloc) 7504 SemaObj->StdBadAlloc = SemaDeclRefs[I+1]; 7505 if (!SemaObj->StdAlignValT) 7506 SemaObj->StdAlignValT = SemaDeclRefs[I+2]; 7507 } 7508 SemaDeclRefs.clear(); 7509 } 7510 7511 // Update the state of pragmas. Use the same API as if we had encountered the 7512 // pragma in the source. 7513 if(OptimizeOffPragmaLocation.isValid()) 7514 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation); 7515 if (PragmaMSStructState != -1) 7516 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState); 7517 if (PointersToMembersPragmaLocation.isValid()) { 7518 SemaObj->ActOnPragmaMSPointersToMembers( 7519 (LangOptions::PragmaMSPointersToMembersKind) 7520 PragmaMSPointersToMembersState, 7521 PointersToMembersPragmaLocation); 7522 } 7523 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth; 7524 7525 if (PragmaPackCurrentValue) { 7526 // The bottom of the stack might have a default value. It must be adjusted 7527 // to the current value to ensure that the packing state is preserved after 7528 // popping entries that were included/imported from a PCH/module. 7529 bool DropFirst = false; 7530 if (!PragmaPackStack.empty() && 7531 PragmaPackStack.front().Location.isInvalid()) { 7532 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue && 7533 "Expected a default alignment value"); 7534 SemaObj->PackStack.Stack.emplace_back( 7535 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue, 7536 SemaObj->PackStack.CurrentPragmaLocation); 7537 DropFirst = true; 7538 } 7539 for (const auto &Entry : 7540 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0)) 7541 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value, 7542 Entry.Location); 7543 if (PragmaPackCurrentLocation.isInvalid()) { 7544 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue && 7545 "Expected a default alignment value"); 7546 // Keep the current values. 7547 } else { 7548 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue; 7549 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation; 7550 } 7551 } 7552 } 7553 7554 IdentifierInfo *ASTReader::get(StringRef Name) { 7555 // Note that we are loading an identifier. 7556 Deserializing AnIdentifier(this); 7557 7558 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0, 7559 NumIdentifierLookups, 7560 NumIdentifierLookupHits); 7561 7562 // We don't need to do identifier table lookups in C++ modules (we preload 7563 // all interesting declarations, and don't need to use the scope for name 7564 // lookups). Perform the lookup in PCH files, though, since we don't build 7565 // a complete initial identifier table if we're carrying on from a PCH. 7566 if (Context.getLangOpts().CPlusPlus) { 7567 for (auto F : ModuleMgr.pch_modules()) 7568 if (Visitor(*F)) 7569 break; 7570 } else { 7571 // If there is a global index, look there first to determine which modules 7572 // provably do not have any results for this identifier. 7573 GlobalModuleIndex::HitSet Hits; 7574 GlobalModuleIndex::HitSet *HitsPtr = nullptr; 7575 if (!loadGlobalIndex()) { 7576 if (GlobalIndex->lookupIdentifier(Name, Hits)) { 7577 HitsPtr = &Hits; 7578 } 7579 } 7580 7581 ModuleMgr.visit(Visitor, HitsPtr); 7582 } 7583 7584 IdentifierInfo *II = Visitor.getIdentifierInfo(); 7585 markIdentifierUpToDate(II); 7586 return II; 7587 } 7588 7589 namespace clang { 7590 7591 /// \brief An identifier-lookup iterator that enumerates all of the 7592 /// identifiers stored within a set of AST files. 7593 class ASTIdentifierIterator : public IdentifierIterator { 7594 /// \brief The AST reader whose identifiers are being enumerated. 7595 const ASTReader &Reader; 7596 7597 /// \brief The current index into the chain of AST files stored in 7598 /// the AST reader. 7599 unsigned Index; 7600 7601 /// \brief The current position within the identifier lookup table 7602 /// of the current AST file. 7603 ASTIdentifierLookupTable::key_iterator Current; 7604 7605 /// \brief The end position within the identifier lookup table of 7606 /// the current AST file. 7607 ASTIdentifierLookupTable::key_iterator End; 7608 7609 /// \brief Whether to skip any modules in the ASTReader. 7610 bool SkipModules; 7611 7612 public: 7613 explicit ASTIdentifierIterator(const ASTReader &Reader, 7614 bool SkipModules = false); 7615 7616 StringRef Next() override; 7617 }; 7618 7619 } // end namespace clang 7620 7621 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader, 7622 bool SkipModules) 7623 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) { 7624 } 7625 7626 StringRef ASTIdentifierIterator::Next() { 7627 while (Current == End) { 7628 // If we have exhausted all of our AST files, we're done. 7629 if (Index == 0) 7630 return StringRef(); 7631 7632 --Index; 7633 ModuleFile &F = Reader.ModuleMgr[Index]; 7634 if (SkipModules && F.isModule()) 7635 continue; 7636 7637 ASTIdentifierLookupTable *IdTable = 7638 (ASTIdentifierLookupTable *)F.IdentifierLookupTable; 7639 Current = IdTable->key_begin(); 7640 End = IdTable->key_end(); 7641 } 7642 7643 // We have any identifiers remaining in the current AST file; return 7644 // the next one. 7645 StringRef Result = *Current; 7646 ++Current; 7647 return Result; 7648 } 7649 7650 namespace { 7651 7652 /// A utility for appending two IdentifierIterators. 7653 class ChainedIdentifierIterator : public IdentifierIterator { 7654 std::unique_ptr<IdentifierIterator> Current; 7655 std::unique_ptr<IdentifierIterator> Queued; 7656 7657 public: 7658 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First, 7659 std::unique_ptr<IdentifierIterator> Second) 7660 : Current(std::move(First)), Queued(std::move(Second)) {} 7661 7662 StringRef Next() override { 7663 if (!Current) 7664 return StringRef(); 7665 7666 StringRef result = Current->Next(); 7667 if (!result.empty()) 7668 return result; 7669 7670 // Try the queued iterator, which may itself be empty. 7671 Current.reset(); 7672 std::swap(Current, Queued); 7673 return Next(); 7674 } 7675 }; 7676 7677 } // end anonymous namespace. 7678 7679 IdentifierIterator *ASTReader::getIdentifiers() { 7680 if (!loadGlobalIndex()) { 7681 std::unique_ptr<IdentifierIterator> ReaderIter( 7682 new ASTIdentifierIterator(*this, /*SkipModules=*/true)); 7683 std::unique_ptr<IdentifierIterator> ModulesIter( 7684 GlobalIndex->createIdentifierIterator()); 7685 return new ChainedIdentifierIterator(std::move(ReaderIter), 7686 std::move(ModulesIter)); 7687 } 7688 7689 return new ASTIdentifierIterator(*this); 7690 } 7691 7692 namespace clang { 7693 namespace serialization { 7694 7695 class ReadMethodPoolVisitor { 7696 ASTReader &Reader; 7697 Selector Sel; 7698 unsigned PriorGeneration; 7699 unsigned InstanceBits; 7700 unsigned FactoryBits; 7701 bool InstanceHasMoreThanOneDecl; 7702 bool FactoryHasMoreThanOneDecl; 7703 SmallVector<ObjCMethodDecl *, 4> InstanceMethods; 7704 SmallVector<ObjCMethodDecl *, 4> FactoryMethods; 7705 7706 public: 7707 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, 7708 unsigned PriorGeneration) 7709 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration), 7710 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false), 7711 FactoryHasMoreThanOneDecl(false) {} 7712 7713 bool operator()(ModuleFile &M) { 7714 if (!M.SelectorLookupTable) 7715 return false; 7716 7717 // If we've already searched this module file, skip it now. 7718 if (M.Generation <= PriorGeneration) 7719 return true; 7720 7721 ++Reader.NumMethodPoolTableLookups; 7722 ASTSelectorLookupTable *PoolTable 7723 = (ASTSelectorLookupTable*)M.SelectorLookupTable; 7724 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel); 7725 if (Pos == PoolTable->end()) 7726 return false; 7727 7728 ++Reader.NumMethodPoolTableHits; 7729 ++Reader.NumSelectorsRead; 7730 // FIXME: Not quite happy with the statistics here. We probably should 7731 // disable this tracking when called via LoadSelector. 7732 // Also, should entries without methods count as misses? 7733 ++Reader.NumMethodPoolEntriesRead; 7734 ASTSelectorLookupTrait::data_type Data = *Pos; 7735 if (Reader.DeserializationListener) 7736 Reader.DeserializationListener->SelectorRead(Data.ID, Sel); 7737 7738 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end()); 7739 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end()); 7740 InstanceBits = Data.InstanceBits; 7741 FactoryBits = Data.FactoryBits; 7742 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl; 7743 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl; 7744 return true; 7745 } 7746 7747 /// \brief Retrieve the instance methods found by this visitor. 7748 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const { 7749 return InstanceMethods; 7750 } 7751 7752 /// \brief Retrieve the instance methods found by this visitor. 7753 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const { 7754 return FactoryMethods; 7755 } 7756 7757 unsigned getInstanceBits() const { return InstanceBits; } 7758 unsigned getFactoryBits() const { return FactoryBits; } 7759 bool instanceHasMoreThanOneDecl() const { 7760 return InstanceHasMoreThanOneDecl; 7761 } 7762 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; } 7763 }; 7764 7765 } // end namespace serialization 7766 } // end namespace clang 7767 7768 /// \brief Add the given set of methods to the method list. 7769 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods, 7770 ObjCMethodList &List) { 7771 for (unsigned I = 0, N = Methods.size(); I != N; ++I) { 7772 S.addMethodToGlobalList(&List, Methods[I]); 7773 } 7774 } 7775 7776 void ASTReader::ReadMethodPool(Selector Sel) { 7777 // Get the selector generation and update it to the current generation. 7778 unsigned &Generation = SelectorGeneration[Sel]; 7779 unsigned PriorGeneration = Generation; 7780 Generation = getGeneration(); 7781 SelectorOutOfDate[Sel] = false; 7782 7783 // Search for methods defined with this selector. 7784 ++NumMethodPoolLookups; 7785 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration); 7786 ModuleMgr.visit(Visitor); 7787 7788 if (Visitor.getInstanceMethods().empty() && 7789 Visitor.getFactoryMethods().empty()) 7790 return; 7791 7792 ++NumMethodPoolHits; 7793 7794 if (!getSema()) 7795 return; 7796 7797 Sema &S = *getSema(); 7798 Sema::GlobalMethodPool::iterator Pos 7799 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first; 7800 7801 Pos->second.first.setBits(Visitor.getInstanceBits()); 7802 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl()); 7803 Pos->second.second.setBits(Visitor.getFactoryBits()); 7804 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl()); 7805 7806 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since 7807 // when building a module we keep every method individually and may need to 7808 // update hasMoreThanOneDecl as we add the methods. 7809 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first); 7810 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second); 7811 } 7812 7813 void ASTReader::updateOutOfDateSelector(Selector Sel) { 7814 if (SelectorOutOfDate[Sel]) 7815 ReadMethodPool(Sel); 7816 } 7817 7818 void ASTReader::ReadKnownNamespaces( 7819 SmallVectorImpl<NamespaceDecl *> &Namespaces) { 7820 Namespaces.clear(); 7821 7822 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) { 7823 if (NamespaceDecl *Namespace 7824 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I]))) 7825 Namespaces.push_back(Namespace); 7826 } 7827 } 7828 7829 void ASTReader::ReadUndefinedButUsed( 7830 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) { 7831 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) { 7832 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++])); 7833 SourceLocation Loc = 7834 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]); 7835 Undefined.insert(std::make_pair(D, Loc)); 7836 } 7837 } 7838 7839 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector< 7840 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> & 7841 Exprs) { 7842 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) { 7843 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++])); 7844 uint64_t Count = DelayedDeleteExprs[Idx++]; 7845 for (uint64_t C = 0; C < Count; ++C) { 7846 SourceLocation DeleteLoc = 7847 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]); 7848 const bool IsArrayForm = DelayedDeleteExprs[Idx++]; 7849 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm)); 7850 } 7851 } 7852 } 7853 7854 void ASTReader::ReadTentativeDefinitions( 7855 SmallVectorImpl<VarDecl *> &TentativeDefs) { 7856 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) { 7857 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I])); 7858 if (Var) 7859 TentativeDefs.push_back(Var); 7860 } 7861 TentativeDefinitions.clear(); 7862 } 7863 7864 void ASTReader::ReadUnusedFileScopedDecls( 7865 SmallVectorImpl<const DeclaratorDecl *> &Decls) { 7866 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) { 7867 DeclaratorDecl *D 7868 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I])); 7869 if (D) 7870 Decls.push_back(D); 7871 } 7872 UnusedFileScopedDecls.clear(); 7873 } 7874 7875 void ASTReader::ReadDelegatingConstructors( 7876 SmallVectorImpl<CXXConstructorDecl *> &Decls) { 7877 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) { 7878 CXXConstructorDecl *D 7879 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I])); 7880 if (D) 7881 Decls.push_back(D); 7882 } 7883 DelegatingCtorDecls.clear(); 7884 } 7885 7886 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) { 7887 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) { 7888 TypedefNameDecl *D 7889 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I])); 7890 if (D) 7891 Decls.push_back(D); 7892 } 7893 ExtVectorDecls.clear(); 7894 } 7895 7896 void ASTReader::ReadUnusedLocalTypedefNameCandidates( 7897 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) { 7898 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N; 7899 ++I) { 7900 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>( 7901 GetDecl(UnusedLocalTypedefNameCandidates[I])); 7902 if (D) 7903 Decls.insert(D); 7904 } 7905 UnusedLocalTypedefNameCandidates.clear(); 7906 } 7907 7908 void ASTReader::ReadReferencedSelectors( 7909 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) { 7910 if (ReferencedSelectorsData.empty()) 7911 return; 7912 7913 // If there are @selector references added them to its pool. This is for 7914 // implementation of -Wselector. 7915 unsigned int DataSize = ReferencedSelectorsData.size()-1; 7916 unsigned I = 0; 7917 while (I < DataSize) { 7918 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]); 7919 SourceLocation SelLoc 7920 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]); 7921 Sels.push_back(std::make_pair(Sel, SelLoc)); 7922 } 7923 ReferencedSelectorsData.clear(); 7924 } 7925 7926 void ASTReader::ReadWeakUndeclaredIdentifiers( 7927 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) { 7928 if (WeakUndeclaredIdentifiers.empty()) 7929 return; 7930 7931 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) { 7932 IdentifierInfo *WeakId 7933 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]); 7934 IdentifierInfo *AliasId 7935 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]); 7936 SourceLocation Loc 7937 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]); 7938 bool Used = WeakUndeclaredIdentifiers[I++]; 7939 WeakInfo WI(AliasId, Loc); 7940 WI.setUsed(Used); 7941 WeakIDs.push_back(std::make_pair(WeakId, WI)); 7942 } 7943 WeakUndeclaredIdentifiers.clear(); 7944 } 7945 7946 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) { 7947 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) { 7948 ExternalVTableUse VT; 7949 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++])); 7950 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]); 7951 VT.DefinitionRequired = VTableUses[Idx++]; 7952 VTables.push_back(VT); 7953 } 7954 7955 VTableUses.clear(); 7956 } 7957 7958 void ASTReader::ReadPendingInstantiations( 7959 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) { 7960 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) { 7961 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++])); 7962 SourceLocation Loc 7963 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]); 7964 7965 Pending.push_back(std::make_pair(D, Loc)); 7966 } 7967 PendingInstantiations.clear(); 7968 } 7969 7970 void ASTReader::ReadLateParsedTemplates( 7971 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> 7972 &LPTMap) { 7973 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N; 7974 /* In loop */) { 7975 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++])); 7976 7977 auto LT = llvm::make_unique<LateParsedTemplate>(); 7978 LT->D = GetDecl(LateParsedTemplates[Idx++]); 7979 7980 ModuleFile *F = getOwningModuleFile(LT->D); 7981 assert(F && "No module"); 7982 7983 unsigned TokN = LateParsedTemplates[Idx++]; 7984 LT->Toks.reserve(TokN); 7985 for (unsigned T = 0; T < TokN; ++T) 7986 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx)); 7987 7988 LPTMap.insert(std::make_pair(FD, std::move(LT))); 7989 } 7990 7991 LateParsedTemplates.clear(); 7992 } 7993 7994 void ASTReader::LoadSelector(Selector Sel) { 7995 // It would be complicated to avoid reading the methods anyway. So don't. 7996 ReadMethodPool(Sel); 7997 } 7998 7999 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) { 8000 assert(ID && "Non-zero identifier ID required"); 8001 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range"); 8002 IdentifiersLoaded[ID - 1] = II; 8003 if (DeserializationListener) 8004 DeserializationListener->IdentifierRead(ID, II); 8005 } 8006 8007 /// \brief Set the globally-visible declarations associated with the given 8008 /// identifier. 8009 /// 8010 /// If the AST reader is currently in a state where the given declaration IDs 8011 /// cannot safely be resolved, they are queued until it is safe to resolve 8012 /// them. 8013 /// 8014 /// \param II an IdentifierInfo that refers to one or more globally-visible 8015 /// declarations. 8016 /// 8017 /// \param DeclIDs the set of declaration IDs with the name @p II that are 8018 /// visible at global scope. 8019 /// 8020 /// \param Decls if non-null, this vector will be populated with the set of 8021 /// deserialized declarations. These declarations will not be pushed into 8022 /// scope. 8023 void 8024 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II, 8025 const SmallVectorImpl<uint32_t> &DeclIDs, 8026 SmallVectorImpl<Decl *> *Decls) { 8027 if (NumCurrentElementsDeserializing && !Decls) { 8028 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end()); 8029 return; 8030 } 8031 8032 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) { 8033 if (!SemaObj) { 8034 // Queue this declaration so that it will be added to the 8035 // translation unit scope and identifier's declaration chain 8036 // once a Sema object is known. 8037 PreloadedDeclIDs.push_back(DeclIDs[I]); 8038 continue; 8039 } 8040 8041 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I])); 8042 8043 // If we're simply supposed to record the declarations, do so now. 8044 if (Decls) { 8045 Decls->push_back(D); 8046 continue; 8047 } 8048 8049 // Introduce this declaration into the translation-unit scope 8050 // and add it to the declaration chain for this identifier, so 8051 // that (unqualified) name lookup will find it. 8052 pushExternalDeclIntoScope(D, II); 8053 } 8054 } 8055 8056 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) { 8057 if (ID == 0) 8058 return nullptr; 8059 8060 if (IdentifiersLoaded.empty()) { 8061 Error("no identifier table in AST file"); 8062 return nullptr; 8063 } 8064 8065 ID -= 1; 8066 if (!IdentifiersLoaded[ID]) { 8067 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1); 8068 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map"); 8069 ModuleFile *M = I->second; 8070 unsigned Index = ID - M->BaseIdentifierID; 8071 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index]; 8072 8073 // All of the strings in the AST file are preceded by a 16-bit length. 8074 // Extract that 16-bit length to avoid having to execute strlen(). 8075 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as 8076 // unsigned integers. This is important to avoid integer overflow when 8077 // we cast them to 'unsigned'. 8078 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2; 8079 unsigned StrLen = (((unsigned) StrLenPtr[0]) 8080 | (((unsigned) StrLenPtr[1]) << 8)) - 1; 8081 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen)); 8082 IdentifiersLoaded[ID] = &II; 8083 markIdentifierFromAST(*this, II); 8084 if (DeserializationListener) 8085 DeserializationListener->IdentifierRead(ID + 1, &II); 8086 } 8087 8088 return IdentifiersLoaded[ID]; 8089 } 8090 8091 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) { 8092 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID)); 8093 } 8094 8095 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) { 8096 if (LocalID < NUM_PREDEF_IDENT_IDS) 8097 return LocalID; 8098 8099 if (!M.ModuleOffsetMap.empty()) 8100 ReadModuleOffsetMap(M); 8101 8102 ContinuousRangeMap<uint32_t, int, 2>::iterator I 8103 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS); 8104 assert(I != M.IdentifierRemap.end() 8105 && "Invalid index into identifier index remap"); 8106 8107 return LocalID + I->second; 8108 } 8109 8110 MacroInfo *ASTReader::getMacro(MacroID ID) { 8111 if (ID == 0) 8112 return nullptr; 8113 8114 if (MacrosLoaded.empty()) { 8115 Error("no macro table in AST file"); 8116 return nullptr; 8117 } 8118 8119 ID -= NUM_PREDEF_MACRO_IDS; 8120 if (!MacrosLoaded[ID]) { 8121 GlobalMacroMapType::iterator I 8122 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS); 8123 assert(I != GlobalMacroMap.end() && "Corrupted global macro map"); 8124 ModuleFile *M = I->second; 8125 unsigned Index = ID - M->BaseMacroID; 8126 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]); 8127 8128 if (DeserializationListener) 8129 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS, 8130 MacrosLoaded[ID]); 8131 } 8132 8133 return MacrosLoaded[ID]; 8134 } 8135 8136 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) { 8137 if (LocalID < NUM_PREDEF_MACRO_IDS) 8138 return LocalID; 8139 8140 if (!M.ModuleOffsetMap.empty()) 8141 ReadModuleOffsetMap(M); 8142 8143 ContinuousRangeMap<uint32_t, int, 2>::iterator I 8144 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS); 8145 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap"); 8146 8147 return LocalID + I->second; 8148 } 8149 8150 serialization::SubmoduleID 8151 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) { 8152 if (LocalID < NUM_PREDEF_SUBMODULE_IDS) 8153 return LocalID; 8154 8155 if (!M.ModuleOffsetMap.empty()) 8156 ReadModuleOffsetMap(M); 8157 8158 ContinuousRangeMap<uint32_t, int, 2>::iterator I 8159 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS); 8160 assert(I != M.SubmoduleRemap.end() 8161 && "Invalid index into submodule index remap"); 8162 8163 return LocalID + I->second; 8164 } 8165 8166 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) { 8167 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) { 8168 assert(GlobalID == 0 && "Unhandled global submodule ID"); 8169 return nullptr; 8170 } 8171 8172 if (GlobalID > SubmodulesLoaded.size()) { 8173 Error("submodule ID out of range in AST file"); 8174 return nullptr; 8175 } 8176 8177 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS]; 8178 } 8179 8180 Module *ASTReader::getModule(unsigned ID) { 8181 return getSubmodule(ID); 8182 } 8183 8184 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) { 8185 if (ID & 1) { 8186 // It's a module, look it up by submodule ID. 8187 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1)); 8188 return I == GlobalSubmoduleMap.end() ? nullptr : I->second; 8189 } else { 8190 // It's a prefix (preamble, PCH, ...). Look it up by index. 8191 unsigned IndexFromEnd = ID >> 1; 8192 assert(IndexFromEnd && "got reference to unknown module file"); 8193 return getModuleManager().pch_modules().end()[-IndexFromEnd]; 8194 } 8195 } 8196 8197 unsigned ASTReader::getModuleFileID(ModuleFile *F) { 8198 if (!F) 8199 return 1; 8200 8201 // For a file representing a module, use the submodule ID of the top-level 8202 // module as the file ID. For any other kind of file, the number of such 8203 // files loaded beforehand will be the same on reload. 8204 // FIXME: Is this true even if we have an explicit module file and a PCH? 8205 if (F->isModule()) 8206 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1; 8207 8208 auto PCHModules = getModuleManager().pch_modules(); 8209 auto I = std::find(PCHModules.begin(), PCHModules.end(), F); 8210 assert(I != PCHModules.end() && "emitting reference to unknown file"); 8211 return (I - PCHModules.end()) << 1; 8212 } 8213 8214 llvm::Optional<ExternalASTSource::ASTSourceDescriptor> 8215 ASTReader::getSourceDescriptor(unsigned ID) { 8216 if (const Module *M = getSubmodule(ID)) 8217 return ExternalASTSource::ASTSourceDescriptor(*M); 8218 8219 // If there is only a single PCH, return it instead. 8220 // Chained PCH are not suported. 8221 const auto &PCHChain = ModuleMgr.pch_modules(); 8222 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) { 8223 ModuleFile &MF = ModuleMgr.getPrimaryModule(); 8224 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName); 8225 StringRef FileName = llvm::sys::path::filename(MF.FileName); 8226 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName, 8227 MF.Signature); 8228 } 8229 return None; 8230 } 8231 8232 ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) { 8233 auto I = BodySource.find(FD); 8234 if (I == BodySource.end()) 8235 return EK_ReplyHazy; 8236 return I->second ? EK_Never : EK_Always; 8237 } 8238 8239 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) { 8240 return DecodeSelector(getGlobalSelectorID(M, LocalID)); 8241 } 8242 8243 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) { 8244 if (ID == 0) 8245 return Selector(); 8246 8247 if (ID > SelectorsLoaded.size()) { 8248 Error("selector ID out of range in AST file"); 8249 return Selector(); 8250 } 8251 8252 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) { 8253 // Load this selector from the selector table. 8254 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID); 8255 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map"); 8256 ModuleFile &M = *I->second; 8257 ASTSelectorLookupTrait Trait(*this, M); 8258 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS; 8259 SelectorsLoaded[ID - 1] = 8260 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0); 8261 if (DeserializationListener) 8262 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]); 8263 } 8264 8265 return SelectorsLoaded[ID - 1]; 8266 } 8267 8268 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) { 8269 return DecodeSelector(ID); 8270 } 8271 8272 uint32_t ASTReader::GetNumExternalSelectors() { 8273 // ID 0 (the null selector) is considered an external selector. 8274 return getTotalNumSelectors() + 1; 8275 } 8276 8277 serialization::SelectorID 8278 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const { 8279 if (LocalID < NUM_PREDEF_SELECTOR_IDS) 8280 return LocalID; 8281 8282 if (!M.ModuleOffsetMap.empty()) 8283 ReadModuleOffsetMap(M); 8284 8285 ContinuousRangeMap<uint32_t, int, 2>::iterator I 8286 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS); 8287 assert(I != M.SelectorRemap.end() 8288 && "Invalid index into selector index remap"); 8289 8290 return LocalID + I->second; 8291 } 8292 8293 DeclarationName 8294 ASTReader::ReadDeclarationName(ModuleFile &F, 8295 const RecordData &Record, unsigned &Idx) { 8296 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++]; 8297 switch (Kind) { 8298 case DeclarationName::Identifier: 8299 return DeclarationName(GetIdentifierInfo(F, Record, Idx)); 8300 8301 case DeclarationName::ObjCZeroArgSelector: 8302 case DeclarationName::ObjCOneArgSelector: 8303 case DeclarationName::ObjCMultiArgSelector: 8304 return DeclarationName(ReadSelector(F, Record, Idx)); 8305 8306 case DeclarationName::CXXConstructorName: 8307 return Context.DeclarationNames.getCXXConstructorName( 8308 Context.getCanonicalType(readType(F, Record, Idx))); 8309 8310 case DeclarationName::CXXDestructorName: 8311 return Context.DeclarationNames.getCXXDestructorName( 8312 Context.getCanonicalType(readType(F, Record, Idx))); 8313 8314 case DeclarationName::CXXDeductionGuideName: 8315 return Context.DeclarationNames.getCXXDeductionGuideName( 8316 ReadDeclAs<TemplateDecl>(F, Record, Idx)); 8317 8318 case DeclarationName::CXXConversionFunctionName: 8319 return Context.DeclarationNames.getCXXConversionFunctionName( 8320 Context.getCanonicalType(readType(F, Record, Idx))); 8321 8322 case DeclarationName::CXXOperatorName: 8323 return Context.DeclarationNames.getCXXOperatorName( 8324 (OverloadedOperatorKind)Record[Idx++]); 8325 8326 case DeclarationName::CXXLiteralOperatorName: 8327 return Context.DeclarationNames.getCXXLiteralOperatorName( 8328 GetIdentifierInfo(F, Record, Idx)); 8329 8330 case DeclarationName::CXXUsingDirective: 8331 return DeclarationName::getUsingDirectiveName(); 8332 } 8333 8334 llvm_unreachable("Invalid NameKind!"); 8335 } 8336 8337 void ASTReader::ReadDeclarationNameLoc(ModuleFile &F, 8338 DeclarationNameLoc &DNLoc, 8339 DeclarationName Name, 8340 const RecordData &Record, unsigned &Idx) { 8341 switch (Name.getNameKind()) { 8342 case DeclarationName::CXXConstructorName: 8343 case DeclarationName::CXXDestructorName: 8344 case DeclarationName::CXXConversionFunctionName: 8345 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx); 8346 break; 8347 8348 case DeclarationName::CXXOperatorName: 8349 DNLoc.CXXOperatorName.BeginOpNameLoc 8350 = ReadSourceLocation(F, Record, Idx).getRawEncoding(); 8351 DNLoc.CXXOperatorName.EndOpNameLoc 8352 = ReadSourceLocation(F, Record, Idx).getRawEncoding(); 8353 break; 8354 8355 case DeclarationName::CXXLiteralOperatorName: 8356 DNLoc.CXXLiteralOperatorName.OpNameLoc 8357 = ReadSourceLocation(F, Record, Idx).getRawEncoding(); 8358 break; 8359 8360 case DeclarationName::Identifier: 8361 case DeclarationName::ObjCZeroArgSelector: 8362 case DeclarationName::ObjCOneArgSelector: 8363 case DeclarationName::ObjCMultiArgSelector: 8364 case DeclarationName::CXXUsingDirective: 8365 case DeclarationName::CXXDeductionGuideName: 8366 break; 8367 } 8368 } 8369 8370 void ASTReader::ReadDeclarationNameInfo(ModuleFile &F, 8371 DeclarationNameInfo &NameInfo, 8372 const RecordData &Record, unsigned &Idx) { 8373 NameInfo.setName(ReadDeclarationName(F, Record, Idx)); 8374 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx)); 8375 DeclarationNameLoc DNLoc; 8376 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx); 8377 NameInfo.setInfo(DNLoc); 8378 } 8379 8380 void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info, 8381 const RecordData &Record, unsigned &Idx) { 8382 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx); 8383 unsigned NumTPLists = Record[Idx++]; 8384 Info.NumTemplParamLists = NumTPLists; 8385 if (NumTPLists) { 8386 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists]; 8387 for (unsigned i = 0; i != NumTPLists; ++i) 8388 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx); 8389 } 8390 } 8391 8392 TemplateName 8393 ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record, 8394 unsigned &Idx) { 8395 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++]; 8396 switch (Kind) { 8397 case TemplateName::Template: 8398 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx)); 8399 8400 case TemplateName::OverloadedTemplate: { 8401 unsigned size = Record[Idx++]; 8402 UnresolvedSet<8> Decls; 8403 while (size--) 8404 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx)); 8405 8406 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end()); 8407 } 8408 8409 case TemplateName::QualifiedTemplate: { 8410 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx); 8411 bool hasTemplKeyword = Record[Idx++]; 8412 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx); 8413 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template); 8414 } 8415 8416 case TemplateName::DependentTemplate: { 8417 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx); 8418 if (Record[Idx++]) // isIdentifier 8419 return Context.getDependentTemplateName(NNS, 8420 GetIdentifierInfo(F, Record, 8421 Idx)); 8422 return Context.getDependentTemplateName(NNS, 8423 (OverloadedOperatorKind)Record[Idx++]); 8424 } 8425 8426 case TemplateName::SubstTemplateTemplateParm: { 8427 TemplateTemplateParmDecl *param 8428 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx); 8429 if (!param) return TemplateName(); 8430 TemplateName replacement = ReadTemplateName(F, Record, Idx); 8431 return Context.getSubstTemplateTemplateParm(param, replacement); 8432 } 8433 8434 case TemplateName::SubstTemplateTemplateParmPack: { 8435 TemplateTemplateParmDecl *Param 8436 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx); 8437 if (!Param) 8438 return TemplateName(); 8439 8440 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx); 8441 if (ArgPack.getKind() != TemplateArgument::Pack) 8442 return TemplateName(); 8443 8444 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack); 8445 } 8446 } 8447 8448 llvm_unreachable("Unhandled template name kind!"); 8449 } 8450 8451 TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F, 8452 const RecordData &Record, 8453 unsigned &Idx, 8454 bool Canonicalize) { 8455 if (Canonicalize) { 8456 // The caller wants a canonical template argument. Sometimes the AST only 8457 // wants template arguments in canonical form (particularly as the template 8458 // argument lists of template specializations) so ensure we preserve that 8459 // canonical form across serialization. 8460 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false); 8461 return Context.getCanonicalTemplateArgument(Arg); 8462 } 8463 8464 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++]; 8465 switch (Kind) { 8466 case TemplateArgument::Null: 8467 return TemplateArgument(); 8468 case TemplateArgument::Type: 8469 return TemplateArgument(readType(F, Record, Idx)); 8470 case TemplateArgument::Declaration: { 8471 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx); 8472 return TemplateArgument(D, readType(F, Record, Idx)); 8473 } 8474 case TemplateArgument::NullPtr: 8475 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true); 8476 case TemplateArgument::Integral: { 8477 llvm::APSInt Value = ReadAPSInt(Record, Idx); 8478 QualType T = readType(F, Record, Idx); 8479 return TemplateArgument(Context, Value, T); 8480 } 8481 case TemplateArgument::Template: 8482 return TemplateArgument(ReadTemplateName(F, Record, Idx)); 8483 case TemplateArgument::TemplateExpansion: { 8484 TemplateName Name = ReadTemplateName(F, Record, Idx); 8485 Optional<unsigned> NumTemplateExpansions; 8486 if (unsigned NumExpansions = Record[Idx++]) 8487 NumTemplateExpansions = NumExpansions - 1; 8488 return TemplateArgument(Name, NumTemplateExpansions); 8489 } 8490 case TemplateArgument::Expression: 8491 return TemplateArgument(ReadExpr(F)); 8492 case TemplateArgument::Pack: { 8493 unsigned NumArgs = Record[Idx++]; 8494 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs]; 8495 for (unsigned I = 0; I != NumArgs; ++I) 8496 Args[I] = ReadTemplateArgument(F, Record, Idx); 8497 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs)); 8498 } 8499 } 8500 8501 llvm_unreachable("Unhandled template argument kind!"); 8502 } 8503 8504 TemplateParameterList * 8505 ASTReader::ReadTemplateParameterList(ModuleFile &F, 8506 const RecordData &Record, unsigned &Idx) { 8507 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx); 8508 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx); 8509 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx); 8510 8511 unsigned NumParams = Record[Idx++]; 8512 SmallVector<NamedDecl *, 16> Params; 8513 Params.reserve(NumParams); 8514 while (NumParams--) 8515 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx)); 8516 8517 // TODO: Concepts 8518 TemplateParameterList* TemplateParams = 8519 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc, 8520 Params, RAngleLoc, nullptr); 8521 return TemplateParams; 8522 } 8523 8524 void 8525 ASTReader:: 8526 ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs, 8527 ModuleFile &F, const RecordData &Record, 8528 unsigned &Idx, bool Canonicalize) { 8529 unsigned NumTemplateArgs = Record[Idx++]; 8530 TemplArgs.reserve(NumTemplateArgs); 8531 while (NumTemplateArgs--) 8532 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize)); 8533 } 8534 8535 /// \brief Read a UnresolvedSet structure. 8536 void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set, 8537 const RecordData &Record, unsigned &Idx) { 8538 unsigned NumDecls = Record[Idx++]; 8539 Set.reserve(Context, NumDecls); 8540 while (NumDecls--) { 8541 DeclID ID = ReadDeclID(F, Record, Idx); 8542 AccessSpecifier AS = (AccessSpecifier)Record[Idx++]; 8543 Set.addLazyDecl(Context, ID, AS); 8544 } 8545 } 8546 8547 CXXBaseSpecifier 8548 ASTReader::ReadCXXBaseSpecifier(ModuleFile &F, 8549 const RecordData &Record, unsigned &Idx) { 8550 bool isVirtual = static_cast<bool>(Record[Idx++]); 8551 bool isBaseOfClass = static_cast<bool>(Record[Idx++]); 8552 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]); 8553 bool inheritConstructors = static_cast<bool>(Record[Idx++]); 8554 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx); 8555 SourceRange Range = ReadSourceRange(F, Record, Idx); 8556 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx); 8557 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo, 8558 EllipsisLoc); 8559 Result.setInheritConstructors(inheritConstructors); 8560 return Result; 8561 } 8562 8563 CXXCtorInitializer ** 8564 ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record, 8565 unsigned &Idx) { 8566 unsigned NumInitializers = Record[Idx++]; 8567 assert(NumInitializers && "wrote ctor initializers but have no inits"); 8568 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers]; 8569 for (unsigned i = 0; i != NumInitializers; ++i) { 8570 TypeSourceInfo *TInfo = nullptr; 8571 bool IsBaseVirtual = false; 8572 FieldDecl *Member = nullptr; 8573 IndirectFieldDecl *IndirectMember = nullptr; 8574 8575 CtorInitializerType Type = (CtorInitializerType)Record[Idx++]; 8576 switch (Type) { 8577 case CTOR_INITIALIZER_BASE: 8578 TInfo = GetTypeSourceInfo(F, Record, Idx); 8579 IsBaseVirtual = Record[Idx++]; 8580 break; 8581 8582 case CTOR_INITIALIZER_DELEGATING: 8583 TInfo = GetTypeSourceInfo(F, Record, Idx); 8584 break; 8585 8586 case CTOR_INITIALIZER_MEMBER: 8587 Member = ReadDeclAs<FieldDecl>(F, Record, Idx); 8588 break; 8589 8590 case CTOR_INITIALIZER_INDIRECT_MEMBER: 8591 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx); 8592 break; 8593 } 8594 8595 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx); 8596 Expr *Init = ReadExpr(F); 8597 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx); 8598 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx); 8599 8600 CXXCtorInitializer *BOMInit; 8601 if (Type == CTOR_INITIALIZER_BASE) 8602 BOMInit = new (Context) 8603 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init, 8604 RParenLoc, MemberOrEllipsisLoc); 8605 else if (Type == CTOR_INITIALIZER_DELEGATING) 8606 BOMInit = new (Context) 8607 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc); 8608 else if (Member) 8609 BOMInit = new (Context) 8610 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc, 8611 Init, RParenLoc); 8612 else 8613 BOMInit = new (Context) 8614 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc, 8615 LParenLoc, Init, RParenLoc); 8616 8617 if (/*IsWritten*/Record[Idx++]) { 8618 unsigned SourceOrder = Record[Idx++]; 8619 BOMInit->setSourceOrder(SourceOrder); 8620 } 8621 8622 CtorInitializers[i] = BOMInit; 8623 } 8624 8625 return CtorInitializers; 8626 } 8627 8628 NestedNameSpecifier * 8629 ASTReader::ReadNestedNameSpecifier(ModuleFile &F, 8630 const RecordData &Record, unsigned &Idx) { 8631 unsigned N = Record[Idx++]; 8632 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr; 8633 for (unsigned I = 0; I != N; ++I) { 8634 NestedNameSpecifier::SpecifierKind Kind 8635 = (NestedNameSpecifier::SpecifierKind)Record[Idx++]; 8636 switch (Kind) { 8637 case NestedNameSpecifier::Identifier: { 8638 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx); 8639 NNS = NestedNameSpecifier::Create(Context, Prev, II); 8640 break; 8641 } 8642 8643 case NestedNameSpecifier::Namespace: { 8644 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx); 8645 NNS = NestedNameSpecifier::Create(Context, Prev, NS); 8646 break; 8647 } 8648 8649 case NestedNameSpecifier::NamespaceAlias: { 8650 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx); 8651 NNS = NestedNameSpecifier::Create(Context, Prev, Alias); 8652 break; 8653 } 8654 8655 case NestedNameSpecifier::TypeSpec: 8656 case NestedNameSpecifier::TypeSpecWithTemplate: { 8657 const Type *T = readType(F, Record, Idx).getTypePtrOrNull(); 8658 if (!T) 8659 return nullptr; 8660 8661 bool Template = Record[Idx++]; 8662 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T); 8663 break; 8664 } 8665 8666 case NestedNameSpecifier::Global: { 8667 NNS = NestedNameSpecifier::GlobalSpecifier(Context); 8668 // No associated value, and there can't be a prefix. 8669 break; 8670 } 8671 8672 case NestedNameSpecifier::Super: { 8673 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx); 8674 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD); 8675 break; 8676 } 8677 } 8678 Prev = NNS; 8679 } 8680 return NNS; 8681 } 8682 8683 NestedNameSpecifierLoc 8684 ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record, 8685 unsigned &Idx) { 8686 unsigned N = Record[Idx++]; 8687 NestedNameSpecifierLocBuilder Builder; 8688 for (unsigned I = 0; I != N; ++I) { 8689 NestedNameSpecifier::SpecifierKind Kind 8690 = (NestedNameSpecifier::SpecifierKind)Record[Idx++]; 8691 switch (Kind) { 8692 case NestedNameSpecifier::Identifier: { 8693 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx); 8694 SourceRange Range = ReadSourceRange(F, Record, Idx); 8695 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd()); 8696 break; 8697 } 8698 8699 case NestedNameSpecifier::Namespace: { 8700 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx); 8701 SourceRange Range = ReadSourceRange(F, Record, Idx); 8702 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd()); 8703 break; 8704 } 8705 8706 case NestedNameSpecifier::NamespaceAlias: { 8707 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx); 8708 SourceRange Range = ReadSourceRange(F, Record, Idx); 8709 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd()); 8710 break; 8711 } 8712 8713 case NestedNameSpecifier::TypeSpec: 8714 case NestedNameSpecifier::TypeSpecWithTemplate: { 8715 bool Template = Record[Idx++]; 8716 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx); 8717 if (!T) 8718 return NestedNameSpecifierLoc(); 8719 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx); 8720 8721 // FIXME: 'template' keyword location not saved anywhere, so we fake it. 8722 Builder.Extend(Context, 8723 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(), 8724 T->getTypeLoc(), ColonColonLoc); 8725 break; 8726 } 8727 8728 case NestedNameSpecifier::Global: { 8729 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx); 8730 Builder.MakeGlobal(Context, ColonColonLoc); 8731 break; 8732 } 8733 8734 case NestedNameSpecifier::Super: { 8735 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx); 8736 SourceRange Range = ReadSourceRange(F, Record, Idx); 8737 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd()); 8738 break; 8739 } 8740 } 8741 } 8742 8743 return Builder.getWithLocInContext(Context); 8744 } 8745 8746 SourceRange 8747 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record, 8748 unsigned &Idx) { 8749 SourceLocation beg = ReadSourceLocation(F, Record, Idx); 8750 SourceLocation end = ReadSourceLocation(F, Record, Idx); 8751 return SourceRange(beg, end); 8752 } 8753 8754 /// \brief Read an integral value 8755 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) { 8756 unsigned BitWidth = Record[Idx++]; 8757 unsigned NumWords = llvm::APInt::getNumWords(BitWidth); 8758 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]); 8759 Idx += NumWords; 8760 return Result; 8761 } 8762 8763 /// \brief Read a signed integral value 8764 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) { 8765 bool isUnsigned = Record[Idx++]; 8766 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned); 8767 } 8768 8769 /// \brief Read a floating-point value 8770 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, 8771 const llvm::fltSemantics &Sem, 8772 unsigned &Idx) { 8773 return llvm::APFloat(Sem, ReadAPInt(Record, Idx)); 8774 } 8775 8776 // \brief Read a string 8777 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) { 8778 unsigned Len = Record[Idx++]; 8779 std::string Result(Record.data() + Idx, Record.data() + Idx + Len); 8780 Idx += Len; 8781 return Result; 8782 } 8783 8784 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record, 8785 unsigned &Idx) { 8786 std::string Filename = ReadString(Record, Idx); 8787 ResolveImportedPath(F, Filename); 8788 return Filename; 8789 } 8790 8791 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record, 8792 unsigned &Idx) { 8793 unsigned Major = Record[Idx++]; 8794 unsigned Minor = Record[Idx++]; 8795 unsigned Subminor = Record[Idx++]; 8796 if (Minor == 0) 8797 return VersionTuple(Major); 8798 if (Subminor == 0) 8799 return VersionTuple(Major, Minor - 1); 8800 return VersionTuple(Major, Minor - 1, Subminor - 1); 8801 } 8802 8803 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F, 8804 const RecordData &Record, 8805 unsigned &Idx) { 8806 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx); 8807 return CXXTemporary::Create(Context, Decl); 8808 } 8809 8810 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const { 8811 return Diag(CurrentImportLoc, DiagID); 8812 } 8813 8814 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const { 8815 return Diags.Report(Loc, DiagID); 8816 } 8817 8818 /// \brief Retrieve the identifier table associated with the 8819 /// preprocessor. 8820 IdentifierTable &ASTReader::getIdentifierTable() { 8821 return PP.getIdentifierTable(); 8822 } 8823 8824 /// \brief Record that the given ID maps to the given switch-case 8825 /// statement. 8826 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) { 8827 assert((*CurrSwitchCaseStmts)[ID] == nullptr && 8828 "Already have a SwitchCase with this ID"); 8829 (*CurrSwitchCaseStmts)[ID] = SC; 8830 } 8831 8832 /// \brief Retrieve the switch-case statement with the given ID. 8833 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) { 8834 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID"); 8835 return (*CurrSwitchCaseStmts)[ID]; 8836 } 8837 8838 void ASTReader::ClearSwitchCaseIDs() { 8839 CurrSwitchCaseStmts->clear(); 8840 } 8841 8842 void ASTReader::ReadComments() { 8843 std::vector<RawComment *> Comments; 8844 for (SmallVectorImpl<std::pair<BitstreamCursor, 8845 serialization::ModuleFile *> >::iterator 8846 I = CommentsCursors.begin(), 8847 E = CommentsCursors.end(); 8848 I != E; ++I) { 8849 Comments.clear(); 8850 BitstreamCursor &Cursor = I->first; 8851 serialization::ModuleFile &F = *I->second; 8852 SavedStreamPosition SavedPosition(Cursor); 8853 8854 RecordData Record; 8855 while (true) { 8856 llvm::BitstreamEntry Entry = 8857 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd); 8858 8859 switch (Entry.Kind) { 8860 case llvm::BitstreamEntry::SubBlock: // Handled for us already. 8861 case llvm::BitstreamEntry::Error: 8862 Error("malformed block record in AST file"); 8863 return; 8864 case llvm::BitstreamEntry::EndBlock: 8865 goto NextCursor; 8866 case llvm::BitstreamEntry::Record: 8867 // The interesting case. 8868 break; 8869 } 8870 8871 // Read a record. 8872 Record.clear(); 8873 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) { 8874 case COMMENTS_RAW_COMMENT: { 8875 unsigned Idx = 0; 8876 SourceRange SR = ReadSourceRange(F, Record, Idx); 8877 RawComment::CommentKind Kind = 8878 (RawComment::CommentKind) Record[Idx++]; 8879 bool IsTrailingComment = Record[Idx++]; 8880 bool IsAlmostTrailingComment = Record[Idx++]; 8881 Comments.push_back(new (Context) RawComment( 8882 SR, Kind, IsTrailingComment, IsAlmostTrailingComment, 8883 Context.getLangOpts().CommentOpts.ParseAllComments)); 8884 break; 8885 } 8886 } 8887 } 8888 NextCursor: 8889 // De-serialized SourceLocations get negative FileIDs for other modules, 8890 // potentially invalidating the original order. Sort it again. 8891 std::sort(Comments.begin(), Comments.end(), 8892 BeforeThanCompare<RawComment>(SourceMgr)); 8893 Context.Comments.addDeserializedComments(Comments); 8894 } 8895 } 8896 8897 void ASTReader::visitInputFiles(serialization::ModuleFile &MF, 8898 bool IncludeSystem, bool Complain, 8899 llvm::function_ref<void(const serialization::InputFile &IF, 8900 bool isSystem)> Visitor) { 8901 unsigned NumUserInputs = MF.NumUserInputFiles; 8902 unsigned NumInputs = MF.InputFilesLoaded.size(); 8903 assert(NumUserInputs <= NumInputs); 8904 unsigned N = IncludeSystem ? NumInputs : NumUserInputs; 8905 for (unsigned I = 0; I < N; ++I) { 8906 bool IsSystem = I >= NumUserInputs; 8907 InputFile IF = getInputFile(MF, I+1, Complain); 8908 Visitor(IF, IsSystem); 8909 } 8910 } 8911 8912 std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) { 8913 // If we know the owning module, use it. 8914 if (Module *M = D->getImportedOwningModule()) 8915 return M->getFullModuleName(); 8916 8917 // Otherwise, use the name of the top-level module the decl is within. 8918 if (ModuleFile *M = getOwningModuleFile(D)) 8919 return M->ModuleName; 8920 8921 // Not from a module. 8922 return ""; 8923 } 8924 8925 void ASTReader::finishPendingActions() { 8926 while (!PendingIdentifierInfos.empty() || 8927 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() || 8928 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() || 8929 !PendingUpdateRecords.empty()) { 8930 // If any identifiers with corresponding top-level declarations have 8931 // been loaded, load those declarations now. 8932 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> > 8933 TopLevelDeclsMap; 8934 TopLevelDeclsMap TopLevelDecls; 8935 8936 while (!PendingIdentifierInfos.empty()) { 8937 IdentifierInfo *II = PendingIdentifierInfos.back().first; 8938 SmallVector<uint32_t, 4> DeclIDs = 8939 std::move(PendingIdentifierInfos.back().second); 8940 PendingIdentifierInfos.pop_back(); 8941 8942 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]); 8943 } 8944 8945 // For each decl chain that we wanted to complete while deserializing, mark 8946 // it as "still needs to be completed". 8947 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) { 8948 markIncompleteDeclChain(PendingIncompleteDeclChains[I]); 8949 } 8950 PendingIncompleteDeclChains.clear(); 8951 8952 // Load pending declaration chains. 8953 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) 8954 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second); 8955 PendingDeclChains.clear(); 8956 8957 // Make the most recent of the top-level declarations visible. 8958 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(), 8959 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) { 8960 IdentifierInfo *II = TLD->first; 8961 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) { 8962 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II); 8963 } 8964 } 8965 8966 // Load any pending macro definitions. 8967 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) { 8968 IdentifierInfo *II = PendingMacroIDs.begin()[I].first; 8969 SmallVector<PendingMacroInfo, 2> GlobalIDs; 8970 GlobalIDs.swap(PendingMacroIDs.begin()[I].second); 8971 // Initialize the macro history from chained-PCHs ahead of module imports. 8972 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs; 8973 ++IDIdx) { 8974 const PendingMacroInfo &Info = GlobalIDs[IDIdx]; 8975 if (!Info.M->isModule()) 8976 resolvePendingMacro(II, Info); 8977 } 8978 // Handle module imports. 8979 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs; 8980 ++IDIdx) { 8981 const PendingMacroInfo &Info = GlobalIDs[IDIdx]; 8982 if (Info.M->isModule()) 8983 resolvePendingMacro(II, Info); 8984 } 8985 } 8986 PendingMacroIDs.clear(); 8987 8988 // Wire up the DeclContexts for Decls that we delayed setting until 8989 // recursive loading is completed. 8990 while (!PendingDeclContextInfos.empty()) { 8991 PendingDeclContextInfo Info = PendingDeclContextInfos.front(); 8992 PendingDeclContextInfos.pop_front(); 8993 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC)); 8994 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC)); 8995 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext()); 8996 } 8997 8998 // Perform any pending declaration updates. 8999 while (!PendingUpdateRecords.empty()) { 9000 auto Update = PendingUpdateRecords.pop_back_val(); 9001 ReadingKindTracker ReadingKind(Read_Decl, *this); 9002 loadDeclUpdateRecords(Update); 9003 } 9004 } 9005 9006 // At this point, all update records for loaded decls are in place, so any 9007 // fake class definitions should have become real. 9008 assert(PendingFakeDefinitionData.empty() && 9009 "faked up a class definition but never saw the real one"); 9010 9011 // If we deserialized any C++ or Objective-C class definitions, any 9012 // Objective-C protocol definitions, or any redeclarable templates, make sure 9013 // that all redeclarations point to the definitions. Note that this can only 9014 // happen now, after the redeclaration chains have been fully wired. 9015 for (Decl *D : PendingDefinitions) { 9016 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 9017 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) { 9018 // Make sure that the TagType points at the definition. 9019 const_cast<TagType*>(TagT)->decl = TD; 9020 } 9021 9022 if (auto RD = dyn_cast<CXXRecordDecl>(D)) { 9023 for (auto *R = getMostRecentExistingDecl(RD); R; 9024 R = R->getPreviousDecl()) { 9025 assert((R == D) == 9026 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() && 9027 "declaration thinks it's the definition but it isn't"); 9028 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData; 9029 } 9030 } 9031 9032 continue; 9033 } 9034 9035 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) { 9036 // Make sure that the ObjCInterfaceType points at the definition. 9037 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl)) 9038 ->Decl = ID; 9039 9040 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl()) 9041 cast<ObjCInterfaceDecl>(R)->Data = ID->Data; 9042 9043 continue; 9044 } 9045 9046 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) { 9047 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl()) 9048 cast<ObjCProtocolDecl>(R)->Data = PD->Data; 9049 9050 continue; 9051 } 9052 9053 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl(); 9054 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl()) 9055 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common; 9056 } 9057 PendingDefinitions.clear(); 9058 9059 // Load the bodies of any functions or methods we've encountered. We do 9060 // this now (delayed) so that we can be sure that the declaration chains 9061 // have been fully wired up (hasBody relies on this). 9062 // FIXME: We shouldn't require complete redeclaration chains here. 9063 for (PendingBodiesMap::iterator PB = PendingBodies.begin(), 9064 PBEnd = PendingBodies.end(); 9065 PB != PBEnd; ++PB) { 9066 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) { 9067 // FIXME: Check for =delete/=default? 9068 // FIXME: Complain about ODR violations here? 9069 const FunctionDecl *Defn = nullptr; 9070 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) { 9071 FD->setLazyBody(PB->second); 9072 } else 9073 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD); 9074 continue; 9075 } 9076 9077 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first); 9078 if (!getContext().getLangOpts().Modules || !MD->hasBody()) 9079 MD->setLazyBody(PB->second); 9080 } 9081 PendingBodies.clear(); 9082 9083 // Do some cleanup. 9084 for (auto *ND : PendingMergedDefinitionsToDeduplicate) 9085 getContext().deduplicateMergedDefinitonsFor(ND); 9086 PendingMergedDefinitionsToDeduplicate.clear(); 9087 } 9088 9089 void ASTReader::diagnoseOdrViolations() { 9090 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty()) 9091 return; 9092 9093 // Trigger the import of the full definition of each class that had any 9094 // odr-merging problems, so we can produce better diagnostics for them. 9095 // These updates may in turn find and diagnose some ODR failures, so take 9096 // ownership of the set first. 9097 auto OdrMergeFailures = std::move(PendingOdrMergeFailures); 9098 PendingOdrMergeFailures.clear(); 9099 for (auto &Merge : OdrMergeFailures) { 9100 Merge.first->buildLookup(); 9101 Merge.first->decls_begin(); 9102 Merge.first->bases_begin(); 9103 Merge.first->vbases_begin(); 9104 for (auto *RD : Merge.second) { 9105 RD->decls_begin(); 9106 RD->bases_begin(); 9107 RD->vbases_begin(); 9108 } 9109 } 9110 9111 // For each declaration from a merged context, check that the canonical 9112 // definition of that context also contains a declaration of the same 9113 // entity. 9114 // 9115 // Caution: this loop does things that might invalidate iterators into 9116 // PendingOdrMergeChecks. Don't turn this into a range-based for loop! 9117 while (!PendingOdrMergeChecks.empty()) { 9118 NamedDecl *D = PendingOdrMergeChecks.pop_back_val(); 9119 9120 // FIXME: Skip over implicit declarations for now. This matters for things 9121 // like implicitly-declared special member functions. This isn't entirely 9122 // correct; we can end up with multiple unmerged declarations of the same 9123 // implicit entity. 9124 if (D->isImplicit()) 9125 continue; 9126 9127 DeclContext *CanonDef = D->getDeclContext(); 9128 9129 bool Found = false; 9130 const Decl *DCanon = D->getCanonicalDecl(); 9131 9132 for (auto RI : D->redecls()) { 9133 if (RI->getLexicalDeclContext() == CanonDef) { 9134 Found = true; 9135 break; 9136 } 9137 } 9138 if (Found) 9139 continue; 9140 9141 // Quick check failed, time to do the slow thing. Note, we can't just 9142 // look up the name of D in CanonDef here, because the member that is 9143 // in CanonDef might not be found by name lookup (it might have been 9144 // replaced by a more recent declaration in the lookup table), and we 9145 // can't necessarily find it in the redeclaration chain because it might 9146 // be merely mergeable, not redeclarable. 9147 llvm::SmallVector<const NamedDecl*, 4> Candidates; 9148 for (auto *CanonMember : CanonDef->decls()) { 9149 if (CanonMember->getCanonicalDecl() == DCanon) { 9150 // This can happen if the declaration is merely mergeable and not 9151 // actually redeclarable (we looked for redeclarations earlier). 9152 // 9153 // FIXME: We should be able to detect this more efficiently, without 9154 // pulling in all of the members of CanonDef. 9155 Found = true; 9156 break; 9157 } 9158 if (auto *ND = dyn_cast<NamedDecl>(CanonMember)) 9159 if (ND->getDeclName() == D->getDeclName()) 9160 Candidates.push_back(ND); 9161 } 9162 9163 if (!Found) { 9164 // The AST doesn't like TagDecls becoming invalid after they've been 9165 // completed. We only really need to mark FieldDecls as invalid here. 9166 if (!isa<TagDecl>(D)) 9167 D->setInvalidDecl(); 9168 9169 // Ensure we don't accidentally recursively enter deserialization while 9170 // we're producing our diagnostic. 9171 Deserializing RecursionGuard(this); 9172 9173 std::string CanonDefModule = 9174 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef)); 9175 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl) 9176 << D << getOwningModuleNameForDiagnostic(D) 9177 << CanonDef << CanonDefModule.empty() << CanonDefModule; 9178 9179 if (Candidates.empty()) 9180 Diag(cast<Decl>(CanonDef)->getLocation(), 9181 diag::note_module_odr_violation_no_possible_decls) << D; 9182 else { 9183 for (unsigned I = 0, N = Candidates.size(); I != N; ++I) 9184 Diag(Candidates[I]->getLocation(), 9185 diag::note_module_odr_violation_possible_decl) 9186 << Candidates[I]; 9187 } 9188 9189 DiagnosedOdrMergeFailures.insert(CanonDef); 9190 } 9191 } 9192 9193 if (OdrMergeFailures.empty()) 9194 return; 9195 9196 // Ensure we don't accidentally recursively enter deserialization while 9197 // we're producing our diagnostics. 9198 Deserializing RecursionGuard(this); 9199 9200 // Issue any pending ODR-failure diagnostics. 9201 for (auto &Merge : OdrMergeFailures) { 9202 // If we've already pointed out a specific problem with this class, don't 9203 // bother issuing a general "something's different" diagnostic. 9204 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second) 9205 continue; 9206 9207 bool Diagnosed = false; 9208 CXXRecordDecl *FirstRecord = Merge.first; 9209 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord); 9210 for (CXXRecordDecl *SecondRecord : Merge.second) { 9211 // Multiple different declarations got merged together; tell the user 9212 // where they came from. 9213 if (FirstRecord == SecondRecord) 9214 continue; 9215 9216 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord); 9217 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>; 9218 DeclHashes FirstHashes; 9219 DeclHashes SecondHashes; 9220 ODRHash Hash; 9221 9222 auto PopulateHashes = [&Hash, FirstRecord](DeclHashes &Hashes, 9223 CXXRecordDecl *Record) { 9224 for (auto *D : Record->decls()) { 9225 // Due to decl merging, the first CXXRecordDecl is the parent of 9226 // Decls in both records. 9227 if (!ODRHash::isWhitelistedDecl(D, FirstRecord)) 9228 continue; 9229 Hash.clear(); 9230 Hash.AddSubDecl(D); 9231 Hashes.emplace_back(D, Hash.CalculateHash()); 9232 } 9233 }; 9234 PopulateHashes(FirstHashes, FirstRecord); 9235 PopulateHashes(SecondHashes, SecondRecord); 9236 9237 // Used with err_module_odr_violation_mismatch_decl and 9238 // note_module_odr_violation_mismatch_decl 9239 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl 9240 enum { 9241 EndOfClass, 9242 PublicSpecifer, 9243 PrivateSpecifer, 9244 ProtectedSpecifer, 9245 StaticAssert, 9246 Field, 9247 CXXMethod, 9248 TypeAlias, 9249 TypeDef, 9250 Var, 9251 Other 9252 } FirstDiffType = Other, 9253 SecondDiffType = Other; 9254 9255 auto DifferenceSelector = [](Decl *D) { 9256 assert(D && "valid Decl required"); 9257 switch (D->getKind()) { 9258 default: 9259 return Other; 9260 case Decl::AccessSpec: 9261 switch (D->getAccess()) { 9262 case AS_public: 9263 return PublicSpecifer; 9264 case AS_private: 9265 return PrivateSpecifer; 9266 case AS_protected: 9267 return ProtectedSpecifer; 9268 case AS_none: 9269 break; 9270 } 9271 llvm_unreachable("Invalid access specifier"); 9272 case Decl::StaticAssert: 9273 return StaticAssert; 9274 case Decl::Field: 9275 return Field; 9276 case Decl::CXXMethod: 9277 return CXXMethod; 9278 case Decl::TypeAlias: 9279 return TypeAlias; 9280 case Decl::Typedef: 9281 return TypeDef; 9282 case Decl::Var: 9283 return Var; 9284 } 9285 }; 9286 9287 Decl *FirstDecl = nullptr; 9288 Decl *SecondDecl = nullptr; 9289 auto FirstIt = FirstHashes.begin(); 9290 auto SecondIt = SecondHashes.begin(); 9291 9292 // If there is a diagnoseable difference, FirstDiffType and 9293 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be 9294 // filled in if not EndOfClass. 9295 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) { 9296 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() && 9297 FirstIt->second == SecondIt->second) { 9298 ++FirstIt; 9299 ++SecondIt; 9300 continue; 9301 } 9302 9303 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first; 9304 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first; 9305 9306 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass; 9307 SecondDiffType = 9308 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass; 9309 9310 break; 9311 } 9312 9313 if (FirstDiffType == Other || SecondDiffType == Other) { 9314 // Reaching this point means an unexpected Decl was encountered 9315 // or no difference was detected. This causes a generic error 9316 // message to be emitted. 9317 Diag(FirstRecord->getLocation(), 9318 diag::err_module_odr_violation_different_definitions) 9319 << FirstRecord << FirstModule.empty() << FirstModule; 9320 9321 if (FirstDecl) { 9322 Diag(FirstDecl->getLocation(), diag::note_first_module_difference) 9323 << FirstRecord << FirstDecl->getSourceRange(); 9324 } 9325 9326 Diag(SecondRecord->getLocation(), 9327 diag::note_module_odr_violation_different_definitions) 9328 << SecondModule; 9329 9330 if (SecondDecl) { 9331 Diag(SecondDecl->getLocation(), diag::note_second_module_difference) 9332 << SecondDecl->getSourceRange(); 9333 } 9334 9335 Diagnosed = true; 9336 break; 9337 } 9338 9339 if (FirstDiffType != SecondDiffType) { 9340 SourceLocation FirstLoc; 9341 SourceRange FirstRange; 9342 if (FirstDiffType == EndOfClass) { 9343 FirstLoc = FirstRecord->getBraceRange().getEnd(); 9344 } else { 9345 FirstLoc = FirstIt->first->getLocation(); 9346 FirstRange = FirstIt->first->getSourceRange(); 9347 } 9348 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl) 9349 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange 9350 << FirstDiffType; 9351 9352 SourceLocation SecondLoc; 9353 SourceRange SecondRange; 9354 if (SecondDiffType == EndOfClass) { 9355 SecondLoc = SecondRecord->getBraceRange().getEnd(); 9356 } else { 9357 SecondLoc = SecondDecl->getLocation(); 9358 SecondRange = SecondDecl->getSourceRange(); 9359 } 9360 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl) 9361 << SecondModule << SecondRange << SecondDiffType; 9362 Diagnosed = true; 9363 break; 9364 } 9365 9366 assert(FirstDiffType == SecondDiffType); 9367 9368 // Used with err_module_odr_violation_mismatch_decl_diff and 9369 // note_module_odr_violation_mismatch_decl_diff 9370 enum ODRDeclDifference{ 9371 StaticAssertCondition, 9372 StaticAssertMessage, 9373 StaticAssertOnlyMessage, 9374 FieldName, 9375 FieldTypeName, 9376 FieldSingleBitField, 9377 FieldDifferentWidthBitField, 9378 FieldSingleMutable, 9379 FieldSingleInitializer, 9380 FieldDifferentInitializers, 9381 MethodName, 9382 MethodDeleted, 9383 MethodVirtual, 9384 MethodStatic, 9385 MethodVolatile, 9386 MethodConst, 9387 MethodInline, 9388 MethodNumberParameters, 9389 MethodParameterType, 9390 MethodParameterName, 9391 MethodParameterSingleDefaultArgument, 9392 MethodParameterDifferentDefaultArgument, 9393 TypedefName, 9394 TypedefType, 9395 VarName, 9396 VarType, 9397 VarSingleInitializer, 9398 VarDifferentInitializer, 9399 VarConstexpr, 9400 }; 9401 9402 // These lambdas have the common portions of the ODR diagnostics. This 9403 // has the same return as Diag(), so addition parameters can be passed 9404 // in with operator<< 9405 auto ODRDiagError = [FirstRecord, &FirstModule, this]( 9406 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) { 9407 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff) 9408 << FirstRecord << FirstModule.empty() << FirstModule << Range 9409 << DiffType; 9410 }; 9411 auto ODRDiagNote = [&SecondModule, this]( 9412 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) { 9413 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff) 9414 << SecondModule << Range << DiffType; 9415 }; 9416 9417 auto ComputeODRHash = [&Hash](const Stmt* S) { 9418 assert(S); 9419 Hash.clear(); 9420 Hash.AddStmt(S); 9421 return Hash.CalculateHash(); 9422 }; 9423 9424 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) { 9425 Hash.clear(); 9426 Hash.AddQualType(Ty); 9427 return Hash.CalculateHash(); 9428 }; 9429 9430 switch (FirstDiffType) { 9431 case Other: 9432 case EndOfClass: 9433 case PublicSpecifer: 9434 case PrivateSpecifer: 9435 case ProtectedSpecifer: 9436 llvm_unreachable("Invalid diff type"); 9437 9438 case StaticAssert: { 9439 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl); 9440 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl); 9441 9442 Expr *FirstExpr = FirstSA->getAssertExpr(); 9443 Expr *SecondExpr = SecondSA->getAssertExpr(); 9444 unsigned FirstODRHash = ComputeODRHash(FirstExpr); 9445 unsigned SecondODRHash = ComputeODRHash(SecondExpr); 9446 if (FirstODRHash != SecondODRHash) { 9447 ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(), 9448 StaticAssertCondition); 9449 ODRDiagNote(SecondExpr->getLocStart(), 9450 SecondExpr->getSourceRange(), StaticAssertCondition); 9451 Diagnosed = true; 9452 break; 9453 } 9454 9455 StringLiteral *FirstStr = FirstSA->getMessage(); 9456 StringLiteral *SecondStr = SecondSA->getMessage(); 9457 assert((FirstStr || SecondStr) && "Both messages cannot be empty"); 9458 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) { 9459 SourceLocation FirstLoc, SecondLoc; 9460 SourceRange FirstRange, SecondRange; 9461 if (FirstStr) { 9462 FirstLoc = FirstStr->getLocStart(); 9463 FirstRange = FirstStr->getSourceRange(); 9464 } else { 9465 FirstLoc = FirstSA->getLocStart(); 9466 FirstRange = FirstSA->getSourceRange(); 9467 } 9468 if (SecondStr) { 9469 SecondLoc = SecondStr->getLocStart(); 9470 SecondRange = SecondStr->getSourceRange(); 9471 } else { 9472 SecondLoc = SecondSA->getLocStart(); 9473 SecondRange = SecondSA->getSourceRange(); 9474 } 9475 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage) 9476 << (FirstStr == nullptr); 9477 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage) 9478 << (SecondStr == nullptr); 9479 Diagnosed = true; 9480 break; 9481 } 9482 9483 if (FirstStr && SecondStr && 9484 FirstStr->getString() != SecondStr->getString()) { 9485 ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(), 9486 StaticAssertMessage); 9487 ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(), 9488 StaticAssertMessage); 9489 Diagnosed = true; 9490 break; 9491 } 9492 break; 9493 } 9494 case Field: { 9495 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl); 9496 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl); 9497 IdentifierInfo *FirstII = FirstField->getIdentifier(); 9498 IdentifierInfo *SecondII = SecondField->getIdentifier(); 9499 if (FirstII->getName() != SecondII->getName()) { 9500 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), 9501 FieldName) 9502 << FirstII; 9503 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), 9504 FieldName) 9505 << SecondII; 9506 9507 Diagnosed = true; 9508 break; 9509 } 9510 9511 assert( 9512 Context.hasSameType(FirstField->getType(), SecondField->getType())); 9513 9514 QualType FirstType = FirstField->getType(); 9515 QualType SecondType = SecondField->getType(); 9516 if (ComputeQualTypeODRHash(FirstType) != 9517 ComputeQualTypeODRHash(SecondType)) { 9518 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), 9519 FieldTypeName) 9520 << FirstII << FirstType; 9521 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), 9522 FieldTypeName) 9523 << SecondII << SecondType; 9524 9525 Diagnosed = true; 9526 break; 9527 } 9528 9529 const bool IsFirstBitField = FirstField->isBitField(); 9530 const bool IsSecondBitField = SecondField->isBitField(); 9531 if (IsFirstBitField != IsSecondBitField) { 9532 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), 9533 FieldSingleBitField) 9534 << FirstII << IsFirstBitField; 9535 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), 9536 FieldSingleBitField) 9537 << SecondII << IsSecondBitField; 9538 Diagnosed = true; 9539 break; 9540 } 9541 9542 if (IsFirstBitField && IsSecondBitField) { 9543 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), 9544 FieldDifferentWidthBitField) 9545 << FirstII << FirstField->getBitWidth()->getSourceRange(); 9546 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), 9547 FieldDifferentWidthBitField) 9548 << SecondII << SecondField->getBitWidth()->getSourceRange(); 9549 Diagnosed = true; 9550 break; 9551 } 9552 9553 const bool IsFirstMutable = FirstField->isMutable(); 9554 const bool IsSecondMutable = SecondField->isMutable(); 9555 if (IsFirstMutable != IsSecondMutable) { 9556 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), 9557 FieldSingleMutable) 9558 << FirstII << IsFirstMutable; 9559 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), 9560 FieldSingleMutable) 9561 << SecondII << IsSecondMutable; 9562 Diagnosed = true; 9563 break; 9564 } 9565 9566 const Expr *FirstInitializer = FirstField->getInClassInitializer(); 9567 const Expr *SecondInitializer = SecondField->getInClassInitializer(); 9568 if ((!FirstInitializer && SecondInitializer) || 9569 (FirstInitializer && !SecondInitializer)) { 9570 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(), 9571 FieldSingleInitializer) 9572 << FirstII << (FirstInitializer != nullptr); 9573 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(), 9574 FieldSingleInitializer) 9575 << SecondII << (SecondInitializer != nullptr); 9576 Diagnosed = true; 9577 break; 9578 } 9579 9580 if (FirstInitializer && SecondInitializer) { 9581 unsigned FirstInitHash = ComputeODRHash(FirstInitializer); 9582 unsigned SecondInitHash = ComputeODRHash(SecondInitializer); 9583 if (FirstInitHash != SecondInitHash) { 9584 ODRDiagError(FirstField->getLocation(), 9585 FirstField->getSourceRange(), 9586 FieldDifferentInitializers) 9587 << FirstII << FirstInitializer->getSourceRange(); 9588 ODRDiagNote(SecondField->getLocation(), 9589 SecondField->getSourceRange(), 9590 FieldDifferentInitializers) 9591 << SecondII << SecondInitializer->getSourceRange(); 9592 Diagnosed = true; 9593 break; 9594 } 9595 } 9596 9597 break; 9598 } 9599 case CXXMethod: { 9600 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl); 9601 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl); 9602 auto FirstName = FirstMethod->getDeclName(); 9603 auto SecondName = SecondMethod->getDeclName(); 9604 if (FirstName != SecondName) { 9605 ODRDiagError(FirstMethod->getLocation(), 9606 FirstMethod->getSourceRange(), MethodName) 9607 << FirstName; 9608 ODRDiagNote(SecondMethod->getLocation(), 9609 SecondMethod->getSourceRange(), MethodName) 9610 << SecondName; 9611 9612 Diagnosed = true; 9613 break; 9614 } 9615 9616 const bool FirstDeleted = FirstMethod->isDeleted(); 9617 const bool SecondDeleted = SecondMethod->isDeleted(); 9618 if (FirstDeleted != SecondDeleted) { 9619 ODRDiagError(FirstMethod->getLocation(), 9620 FirstMethod->getSourceRange(), MethodDeleted) 9621 << FirstName << FirstDeleted; 9622 9623 ODRDiagNote(SecondMethod->getLocation(), 9624 SecondMethod->getSourceRange(), MethodDeleted) 9625 << SecondName << SecondDeleted; 9626 Diagnosed = true; 9627 break; 9628 } 9629 9630 const bool FirstVirtual = FirstMethod->isVirtualAsWritten(); 9631 const bool SecondVirtual = SecondMethod->isVirtualAsWritten(); 9632 const bool FirstPure = FirstMethod->isPure(); 9633 const bool SecondPure = SecondMethod->isPure(); 9634 if ((FirstVirtual || SecondVirtual) && 9635 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) { 9636 ODRDiagError(FirstMethod->getLocation(), 9637 FirstMethod->getSourceRange(), MethodVirtual) 9638 << FirstName << FirstPure << FirstVirtual; 9639 ODRDiagNote(SecondMethod->getLocation(), 9640 SecondMethod->getSourceRange(), MethodVirtual) 9641 << SecondName << SecondPure << SecondVirtual; 9642 Diagnosed = true; 9643 break; 9644 } 9645 9646 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging, 9647 // FirstDecl is the canonical Decl of SecondDecl, so the storage 9648 // class needs to be checked instead. 9649 const auto FirstStorage = FirstMethod->getStorageClass(); 9650 const auto SecondStorage = SecondMethod->getStorageClass(); 9651 const bool FirstStatic = FirstStorage == SC_Static; 9652 const bool SecondStatic = SecondStorage == SC_Static; 9653 if (FirstStatic != SecondStatic) { 9654 ODRDiagError(FirstMethod->getLocation(), 9655 FirstMethod->getSourceRange(), MethodStatic) 9656 << FirstName << FirstStatic; 9657 ODRDiagNote(SecondMethod->getLocation(), 9658 SecondMethod->getSourceRange(), MethodStatic) 9659 << SecondName << SecondStatic; 9660 Diagnosed = true; 9661 break; 9662 } 9663 9664 const bool FirstVolatile = FirstMethod->isVolatile(); 9665 const bool SecondVolatile = SecondMethod->isVolatile(); 9666 if (FirstVolatile != SecondVolatile) { 9667 ODRDiagError(FirstMethod->getLocation(), 9668 FirstMethod->getSourceRange(), MethodVolatile) 9669 << FirstName << FirstVolatile; 9670 ODRDiagNote(SecondMethod->getLocation(), 9671 SecondMethod->getSourceRange(), MethodVolatile) 9672 << SecondName << SecondVolatile; 9673 Diagnosed = true; 9674 break; 9675 } 9676 9677 const bool FirstConst = FirstMethod->isConst(); 9678 const bool SecondConst = SecondMethod->isConst(); 9679 if (FirstConst != SecondConst) { 9680 ODRDiagError(FirstMethod->getLocation(), 9681 FirstMethod->getSourceRange(), MethodConst) 9682 << FirstName << FirstConst; 9683 ODRDiagNote(SecondMethod->getLocation(), 9684 SecondMethod->getSourceRange(), MethodConst) 9685 << SecondName << SecondConst; 9686 Diagnosed = true; 9687 break; 9688 } 9689 9690 const bool FirstInline = FirstMethod->isInlineSpecified(); 9691 const bool SecondInline = SecondMethod->isInlineSpecified(); 9692 if (FirstInline != SecondInline) { 9693 ODRDiagError(FirstMethod->getLocation(), 9694 FirstMethod->getSourceRange(), MethodInline) 9695 << FirstName << FirstInline; 9696 ODRDiagNote(SecondMethod->getLocation(), 9697 SecondMethod->getSourceRange(), MethodInline) 9698 << SecondName << SecondInline; 9699 Diagnosed = true; 9700 break; 9701 } 9702 9703 const unsigned FirstNumParameters = FirstMethod->param_size(); 9704 const unsigned SecondNumParameters = SecondMethod->param_size(); 9705 if (FirstNumParameters != SecondNumParameters) { 9706 ODRDiagError(FirstMethod->getLocation(), 9707 FirstMethod->getSourceRange(), MethodNumberParameters) 9708 << FirstName << FirstNumParameters; 9709 ODRDiagNote(SecondMethod->getLocation(), 9710 SecondMethod->getSourceRange(), MethodNumberParameters) 9711 << SecondName << SecondNumParameters; 9712 Diagnosed = true; 9713 break; 9714 } 9715 9716 // Need this status boolean to know when break out of the switch. 9717 bool ParameterMismatch = false; 9718 for (unsigned I = 0; I < FirstNumParameters; ++I) { 9719 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I); 9720 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I); 9721 9722 QualType FirstParamType = FirstParam->getType(); 9723 QualType SecondParamType = SecondParam->getType(); 9724 if (FirstParamType != SecondParamType && 9725 ComputeQualTypeODRHash(FirstParamType) != 9726 ComputeQualTypeODRHash(SecondParamType)) { 9727 if (const DecayedType *ParamDecayedType = 9728 FirstParamType->getAs<DecayedType>()) { 9729 ODRDiagError(FirstMethod->getLocation(), 9730 FirstMethod->getSourceRange(), MethodParameterType) 9731 << FirstName << (I + 1) << FirstParamType << true 9732 << ParamDecayedType->getOriginalType(); 9733 } else { 9734 ODRDiagError(FirstMethod->getLocation(), 9735 FirstMethod->getSourceRange(), MethodParameterType) 9736 << FirstName << (I + 1) << FirstParamType << false; 9737 } 9738 9739 if (const DecayedType *ParamDecayedType = 9740 SecondParamType->getAs<DecayedType>()) { 9741 ODRDiagNote(SecondMethod->getLocation(), 9742 SecondMethod->getSourceRange(), MethodParameterType) 9743 << SecondName << (I + 1) << SecondParamType << true 9744 << ParamDecayedType->getOriginalType(); 9745 } else { 9746 ODRDiagNote(SecondMethod->getLocation(), 9747 SecondMethod->getSourceRange(), MethodParameterType) 9748 << SecondName << (I + 1) << SecondParamType << false; 9749 } 9750 ParameterMismatch = true; 9751 break; 9752 } 9753 9754 DeclarationName FirstParamName = FirstParam->getDeclName(); 9755 DeclarationName SecondParamName = SecondParam->getDeclName(); 9756 if (FirstParamName != SecondParamName) { 9757 ODRDiagError(FirstMethod->getLocation(), 9758 FirstMethod->getSourceRange(), MethodParameterName) 9759 << FirstName << (I + 1) << FirstParamName; 9760 ODRDiagNote(SecondMethod->getLocation(), 9761 SecondMethod->getSourceRange(), MethodParameterName) 9762 << SecondName << (I + 1) << SecondParamName; 9763 ParameterMismatch = true; 9764 break; 9765 } 9766 9767 const Expr *FirstInit = FirstParam->getInit(); 9768 const Expr *SecondInit = SecondParam->getInit(); 9769 if ((FirstInit == nullptr) != (SecondInit == nullptr)) { 9770 ODRDiagError(FirstMethod->getLocation(), 9771 FirstMethod->getSourceRange(), 9772 MethodParameterSingleDefaultArgument) 9773 << FirstName << (I + 1) << (FirstInit == nullptr) 9774 << (FirstInit ? FirstInit->getSourceRange() : SourceRange()); 9775 ODRDiagNote(SecondMethod->getLocation(), 9776 SecondMethod->getSourceRange(), 9777 MethodParameterSingleDefaultArgument) 9778 << SecondName << (I + 1) << (SecondInit == nullptr) 9779 << (SecondInit ? SecondInit->getSourceRange() : SourceRange()); 9780 ParameterMismatch = true; 9781 break; 9782 } 9783 9784 if (FirstInit && SecondInit && 9785 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) { 9786 ODRDiagError(FirstMethod->getLocation(), 9787 FirstMethod->getSourceRange(), 9788 MethodParameterDifferentDefaultArgument) 9789 << FirstName << (I + 1) << FirstInit->getSourceRange(); 9790 ODRDiagNote(SecondMethod->getLocation(), 9791 SecondMethod->getSourceRange(), 9792 MethodParameterDifferentDefaultArgument) 9793 << SecondName << (I + 1) << SecondInit->getSourceRange(); 9794 ParameterMismatch = true; 9795 break; 9796 9797 } 9798 } 9799 9800 if (ParameterMismatch) { 9801 Diagnosed = true; 9802 break; 9803 } 9804 9805 break; 9806 } 9807 case TypeAlias: 9808 case TypeDef: { 9809 TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl); 9810 TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl); 9811 auto FirstName = FirstTD->getDeclName(); 9812 auto SecondName = SecondTD->getDeclName(); 9813 if (FirstName != SecondName) { 9814 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(), 9815 TypedefName) 9816 << (FirstDiffType == TypeAlias) << FirstName; 9817 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(), 9818 TypedefName) 9819 << (FirstDiffType == TypeAlias) << SecondName; 9820 Diagnosed = true; 9821 break; 9822 } 9823 9824 QualType FirstType = FirstTD->getUnderlyingType(); 9825 QualType SecondType = SecondTD->getUnderlyingType(); 9826 if (ComputeQualTypeODRHash(FirstType) != 9827 ComputeQualTypeODRHash(SecondType)) { 9828 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(), 9829 TypedefType) 9830 << (FirstDiffType == TypeAlias) << FirstName << FirstType; 9831 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(), 9832 TypedefType) 9833 << (FirstDiffType == TypeAlias) << SecondName << SecondType; 9834 Diagnosed = true; 9835 break; 9836 } 9837 break; 9838 } 9839 case Var: { 9840 VarDecl *FirstVD = cast<VarDecl>(FirstDecl); 9841 VarDecl *SecondVD = cast<VarDecl>(SecondDecl); 9842 auto FirstName = FirstVD->getDeclName(); 9843 auto SecondName = SecondVD->getDeclName(); 9844 if (FirstName != SecondName) { 9845 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(), 9846 VarName) 9847 << FirstName; 9848 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(), 9849 VarName) 9850 << SecondName; 9851 Diagnosed = true; 9852 break; 9853 } 9854 9855 QualType FirstType = FirstVD->getType(); 9856 QualType SecondType = SecondVD->getType(); 9857 if (ComputeQualTypeODRHash(FirstType) != 9858 ComputeQualTypeODRHash(SecondType)) { 9859 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(), 9860 VarType) 9861 << FirstName << FirstType; 9862 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(), 9863 VarType) 9864 << SecondName << SecondType; 9865 Diagnosed = true; 9866 break; 9867 } 9868 9869 const Expr *FirstInit = FirstVD->getInit(); 9870 const Expr *SecondInit = SecondVD->getInit(); 9871 if ((FirstInit == nullptr) != (SecondInit == nullptr)) { 9872 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(), 9873 VarSingleInitializer) 9874 << FirstName << (FirstInit == nullptr) 9875 << (FirstInit ? FirstInit->getSourceRange(): SourceRange()); 9876 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(), 9877 VarSingleInitializer) 9878 << SecondName << (SecondInit == nullptr) 9879 << (SecondInit ? SecondInit->getSourceRange() : SourceRange()); 9880 Diagnosed = true; 9881 break; 9882 } 9883 9884 if (FirstInit && SecondInit && 9885 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) { 9886 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(), 9887 VarDifferentInitializer) 9888 << FirstName << FirstInit->getSourceRange(); 9889 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(), 9890 VarDifferentInitializer) 9891 << SecondName << SecondInit->getSourceRange(); 9892 Diagnosed = true; 9893 break; 9894 } 9895 9896 const bool FirstIsConstexpr = FirstVD->isConstexpr(); 9897 const bool SecondIsConstexpr = SecondVD->isConstexpr(); 9898 if (FirstIsConstexpr != SecondIsConstexpr) { 9899 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(), 9900 VarConstexpr) 9901 << FirstName << FirstIsConstexpr; 9902 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(), 9903 VarConstexpr) 9904 << SecondName << SecondIsConstexpr; 9905 Diagnosed = true; 9906 break; 9907 } 9908 break; 9909 } 9910 } 9911 9912 if (Diagnosed == true) 9913 continue; 9914 9915 Diag(FirstDecl->getLocation(), 9916 diag::err_module_odr_violation_mismatch_decl_unknown) 9917 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType 9918 << FirstDecl->getSourceRange(); 9919 Diag(SecondDecl->getLocation(), 9920 diag::note_module_odr_violation_mismatch_decl_unknown) 9921 << SecondModule << FirstDiffType << SecondDecl->getSourceRange(); 9922 Diagnosed = true; 9923 } 9924 9925 if (!Diagnosed) { 9926 // All definitions are updates to the same declaration. This happens if a 9927 // module instantiates the declaration of a class template specialization 9928 // and two or more other modules instantiate its definition. 9929 // 9930 // FIXME: Indicate which modules had instantiations of this definition. 9931 // FIXME: How can this even happen? 9932 Diag(Merge.first->getLocation(), 9933 diag::err_module_odr_violation_different_instantiations) 9934 << Merge.first; 9935 } 9936 } 9937 } 9938 9939 void ASTReader::StartedDeserializing() { 9940 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get()) 9941 ReadTimer->startTimer(); 9942 } 9943 9944 void ASTReader::FinishedDeserializing() { 9945 assert(NumCurrentElementsDeserializing && 9946 "FinishedDeserializing not paired with StartedDeserializing"); 9947 if (NumCurrentElementsDeserializing == 1) { 9948 // We decrease NumCurrentElementsDeserializing only after pending actions 9949 // are finished, to avoid recursively re-calling finishPendingActions(). 9950 finishPendingActions(); 9951 } 9952 --NumCurrentElementsDeserializing; 9953 9954 if (NumCurrentElementsDeserializing == 0) { 9955 // Propagate exception specification updates along redeclaration chains. 9956 while (!PendingExceptionSpecUpdates.empty()) { 9957 auto Updates = std::move(PendingExceptionSpecUpdates); 9958 PendingExceptionSpecUpdates.clear(); 9959 for (auto Update : Updates) { 9960 ProcessingUpdatesRAIIObj ProcessingUpdates(*this); 9961 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>(); 9962 auto ESI = FPT->getExtProtoInfo().ExceptionSpec; 9963 if (auto *Listener = Context.getASTMutationListener()) 9964 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second)); 9965 for (auto *Redecl : Update.second->redecls()) 9966 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI); 9967 } 9968 } 9969 9970 if (ReadTimer) 9971 ReadTimer->stopTimer(); 9972 9973 diagnoseOdrViolations(); 9974 9975 // We are not in recursive loading, so it's safe to pass the "interesting" 9976 // decls to the consumer. 9977 if (Consumer) 9978 PassInterestingDeclsToConsumer(); 9979 } 9980 } 9981 9982 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 9983 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) { 9984 // Remove any fake results before adding any real ones. 9985 auto It = PendingFakeLookupResults.find(II); 9986 if (It != PendingFakeLookupResults.end()) { 9987 for (auto *ND : It->second) 9988 SemaObj->IdResolver.RemoveDecl(ND); 9989 // FIXME: this works around module+PCH performance issue. 9990 // Rather than erase the result from the map, which is O(n), just clear 9991 // the vector of NamedDecls. 9992 It->second.clear(); 9993 } 9994 } 9995 9996 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) { 9997 SemaObj->TUScope->AddDecl(D); 9998 } else if (SemaObj->TUScope) { 9999 // Adding the decl to IdResolver may have failed because it was already in 10000 // (even though it was not added in scope). If it is already in, make sure 10001 // it gets in the scope as well. 10002 if (std::find(SemaObj->IdResolver.begin(Name), 10003 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end()) 10004 SemaObj->TUScope->AddDecl(D); 10005 } 10006 } 10007 10008 ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, 10009 const PCHContainerReader &PCHContainerRdr, 10010 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, 10011 StringRef isysroot, bool DisableValidation, 10012 bool AllowASTWithCompilerErrors, 10013 bool AllowConfigurationMismatch, bool ValidateSystemInputs, 10014 bool UseGlobalIndex, 10015 std::unique_ptr<llvm::Timer> ReadTimer) 10016 : Listener(DisableValidation 10017 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP)) 10018 : cast<ASTReaderListener>(new PCHValidator(PP, *this))), 10019 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()), 10020 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP), 10021 Context(Context), 10022 ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr), 10023 PCMCache(PP.getPCMCache()), DummyIdResolver(PP), 10024 ReadTimer(std::move(ReadTimer)), isysroot(isysroot), 10025 DisableValidation(DisableValidation), 10026 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors), 10027 AllowConfigurationMismatch(AllowConfigurationMismatch), 10028 ValidateSystemInputs(ValidateSystemInputs), 10029 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) { 10030 SourceMgr.setExternalSLocEntrySource(this); 10031 10032 for (const auto &Ext : Extensions) { 10033 auto BlockName = Ext->getExtensionMetadata().BlockName; 10034 auto Known = ModuleFileExtensions.find(BlockName); 10035 if (Known != ModuleFileExtensions.end()) { 10036 Diags.Report(diag::warn_duplicate_module_file_extension) 10037 << BlockName; 10038 continue; 10039 } 10040 10041 ModuleFileExtensions.insert({BlockName, Ext}); 10042 } 10043 } 10044 10045 ASTReader::~ASTReader() { 10046 if (OwnsDeserializationListener) 10047 delete DeserializationListener; 10048 } 10049 10050 IdentifierResolver &ASTReader::getIdResolver() { 10051 return SemaObj ? SemaObj->IdResolver : DummyIdResolver; 10052 } 10053 10054 unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor, 10055 unsigned AbbrevID) { 10056 Idx = 0; 10057 Record.clear(); 10058 return Cursor.readRecord(AbbrevID, Record); 10059 } 10060