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