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