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