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