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