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