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