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