1 //===--- ASTReader.cpp - AST File Reader ------------------------*- C++ -*-===// 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 "clang/Serialization/ASTDeserializationListener.h" 16 #include "ASTCommon.h" 17 #include "clang/Frontend/FrontendDiagnostic.h" 18 #include "clang/Frontend/Utils.h" 19 #include "clang/Sema/Sema.h" 20 #include "clang/Sema/Scope.h" 21 #include "clang/AST/ASTConsumer.h" 22 #include "clang/AST/ASTContext.h" 23 #include "clang/AST/DeclTemplate.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/NestedNameSpecifier.h" 27 #include "clang/AST/Type.h" 28 #include "clang/AST/TypeLocVisitor.h" 29 #include "clang/Lex/MacroInfo.h" 30 #include "clang/Lex/PreprocessingRecord.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Lex/HeaderSearch.h" 33 #include "clang/Basic/OnDiskHashTable.h" 34 #include "clang/Basic/SourceManager.h" 35 #include "clang/Basic/SourceManagerInternals.h" 36 #include "clang/Basic/FileManager.h" 37 #include "clang/Basic/FileSystemStatCache.h" 38 #include "clang/Basic/TargetInfo.h" 39 #include "clang/Basic/Version.h" 40 #include "clang/Basic/VersionTuple.h" 41 #include "llvm/ADT/StringExtras.h" 42 #include "llvm/Bitcode/BitstreamReader.h" 43 #include "llvm/Support/MemoryBuffer.h" 44 #include "llvm/Support/ErrorHandling.h" 45 #include "llvm/Support/FileSystem.h" 46 #include "llvm/Support/Path.h" 47 #include "llvm/Support/system_error.h" 48 #include <algorithm> 49 #include <iterator> 50 #include <cstdio> 51 #include <sys/stat.h> 52 #include <iostream> 53 54 using namespace clang; 55 using namespace clang::serialization; 56 57 //===----------------------------------------------------------------------===// 58 // PCH validator implementation 59 //===----------------------------------------------------------------------===// 60 61 ASTReaderListener::~ASTReaderListener() {} 62 63 bool 64 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) { 65 const LangOptions &PPLangOpts = PP.getLangOptions(); 66 #define PARSE_LANGOPT_BENIGN(Option) 67 #define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \ 68 if (PPLangOpts.Option != LangOpts.Option) { \ 69 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \ 70 return true; \ 71 } 72 73 PARSE_LANGOPT_BENIGN(Trigraphs); 74 PARSE_LANGOPT_BENIGN(BCPLComment); 75 PARSE_LANGOPT_BENIGN(DollarIdents); 76 PARSE_LANGOPT_BENIGN(AsmPreprocessor); 77 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions); 78 PARSE_LANGOPT_IMPORTANT(GNUKeywords, diag::warn_pch_gnu_keywords); 79 PARSE_LANGOPT_BENIGN(ImplicitInt); 80 PARSE_LANGOPT_BENIGN(Digraphs); 81 PARSE_LANGOPT_BENIGN(HexFloats); 82 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99); 83 PARSE_LANGOPT_IMPORTANT(C1X, diag::warn_pch_c1x); 84 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions); 85 PARSE_LANGOPT_BENIGN(MSCVersion); 86 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus); 87 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x); 88 PARSE_LANGOPT_BENIGN(CXXOperatorName); 89 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c); 90 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2); 91 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi); 92 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2); 93 PARSE_LANGOPT_IMPORTANT(AppleKext, diag::warn_pch_apple_kext); 94 PARSE_LANGOPT_IMPORTANT(ObjCDefaultSynthProperties, 95 diag::warn_pch_objc_auto_properties); 96 PARSE_LANGOPT_BENIGN(ObjCInferRelatedResultType) 97 PARSE_LANGOPT_IMPORTANT(NoConstantCFStrings, 98 diag::warn_pch_no_constant_cfstrings); 99 PARSE_LANGOPT_BENIGN(PascalStrings); 100 PARSE_LANGOPT_BENIGN(WritableStrings); 101 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions, 102 diag::warn_pch_lax_vector_conversions); 103 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec); 104 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions); 105 PARSE_LANGOPT_IMPORTANT(ObjCExceptions, diag::warn_pch_objc_exceptions); 106 PARSE_LANGOPT_IMPORTANT(CXXExceptions, diag::warn_pch_cxx_exceptions); 107 PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions); 108 PARSE_LANGOPT_IMPORTANT(MSBitfields, diag::warn_pch_ms_bitfields); 109 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime); 110 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding); 111 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins); 112 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics, 113 diag::warn_pch_thread_safe_statics); 114 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads); 115 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks); 116 PARSE_LANGOPT_BENIGN(EmitAllDecls); 117 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno); 118 PARSE_LANGOPT_BENIGN(getSignedOverflowBehavior()); 119 PARSE_LANGOPT_IMPORTANT(HeinousExtensions, 120 diag::warn_pch_heinous_extensions); 121 // FIXME: Most of the options below are benign if the macro wasn't 122 // used. Unfortunately, this means that a PCH compiled without 123 // optimization can't be used with optimization turned on, even 124 // though the only thing that changes is whether __OPTIMIZE__ was 125 // defined... but if __OPTIMIZE__ never showed up in the header, it 126 // doesn't matter. We could consider making this some special kind 127 // of check. 128 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize); 129 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size); 130 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static); 131 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level); 132 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline); 133 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline); 134 PARSE_LANGOPT_IMPORTANT(Deprecated, diag::warn_pch_deprecated); 135 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control); 136 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed); 137 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar); 138 PARSE_LANGOPT_IMPORTANT(ShortEnums, diag::warn_pch_short_enums); 139 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) { 140 Reader.Diag(diag::warn_pch_gc_mode) 141 << LangOpts.getGCMode() << PPLangOpts.getGCMode(); 142 return true; 143 } 144 PARSE_LANGOPT_BENIGN(getVisibilityMode()); 145 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(), 146 diag::warn_pch_stack_protector); 147 PARSE_LANGOPT_BENIGN(InstantiationDepth); 148 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl); 149 PARSE_LANGOPT_IMPORTANT(CUDA, diag::warn_pch_cuda); 150 PARSE_LANGOPT_BENIGN(CatchUndefined); 151 PARSE_LANGOPT_BENIGN(DefaultFPContract); 152 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors); 153 PARSE_LANGOPT_BENIGN(SpellChecking); 154 PARSE_LANGOPT_IMPORTANT(ObjCAutoRefCount, diag::warn_pch_auto_ref_count); 155 PARSE_LANGOPT_BENIGN(ObjCInferRelatedReturnType); 156 #undef PARSE_LANGOPT_IMPORTANT 157 #undef PARSE_LANGOPT_BENIGN 158 159 return false; 160 } 161 162 bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) { 163 if (Triple == PP.getTargetInfo().getTriple().str()) 164 return false; 165 166 Reader.Diag(diag::warn_pch_target_triple) 167 << Triple << PP.getTargetInfo().getTriple().str(); 168 return true; 169 } 170 171 namespace { 172 struct EmptyStringRef { 173 bool operator ()(llvm::StringRef r) const { return r.empty(); } 174 }; 175 struct EmptyBlock { 176 bool operator ()(const PCHPredefinesBlock &r) const {return r.Data.empty();} 177 }; 178 } 179 180 static bool EqualConcatenations(llvm::SmallVector<llvm::StringRef, 2> L, 181 PCHPredefinesBlocks R) { 182 // First, sum up the lengths. 183 unsigned LL = 0, RL = 0; 184 for (unsigned I = 0, N = L.size(); I != N; ++I) { 185 LL += L[I].size(); 186 } 187 for (unsigned I = 0, N = R.size(); I != N; ++I) { 188 RL += R[I].Data.size(); 189 } 190 if (LL != RL) 191 return false; 192 if (LL == 0 && RL == 0) 193 return true; 194 195 // Kick out empty parts, they confuse the algorithm below. 196 L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end()); 197 R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end()); 198 199 // Do it the hard way. At this point, both vectors must be non-empty. 200 llvm::StringRef LR = L[0], RR = R[0].Data; 201 unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size(); 202 (void) RN; 203 for (;;) { 204 // Compare the current pieces. 205 if (LR.size() == RR.size()) { 206 // If they're the same length, it's pretty easy. 207 if (LR != RR) 208 return false; 209 // Both pieces are done, advance. 210 ++LI; 211 ++RI; 212 // If either string is done, they're both done, since they're the same 213 // length. 214 if (LI == LN) { 215 assert(RI == RN && "Strings not the same length after all?"); 216 return true; 217 } 218 LR = L[LI]; 219 RR = R[RI].Data; 220 } else if (LR.size() < RR.size()) { 221 // Right piece is longer. 222 if (!RR.startswith(LR)) 223 return false; 224 ++LI; 225 assert(LI != LN && "Strings not the same length after all?"); 226 RR = RR.substr(LR.size()); 227 LR = L[LI]; 228 } else { 229 // Left piece is longer. 230 if (!LR.startswith(RR)) 231 return false; 232 ++RI; 233 assert(RI != RN && "Strings not the same length after all?"); 234 LR = LR.substr(RR.size()); 235 RR = R[RI].Data; 236 } 237 } 238 } 239 240 static std::pair<FileID, llvm::StringRef::size_type> 241 FindMacro(const PCHPredefinesBlocks &Buffers, llvm::StringRef MacroDef) { 242 std::pair<FileID, llvm::StringRef::size_type> Res; 243 for (unsigned I = 0, N = Buffers.size(); I != N; ++I) { 244 Res.second = Buffers[I].Data.find(MacroDef); 245 if (Res.second != llvm::StringRef::npos) { 246 Res.first = Buffers[I].BufferID; 247 break; 248 } 249 } 250 return Res; 251 } 252 253 bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers, 254 llvm::StringRef OriginalFileName, 255 std::string &SuggestedPredefines, 256 FileManager &FileMgr) { 257 // We are in the context of an implicit include, so the predefines buffer will 258 // have a #include entry for the PCH file itself (as normalized by the 259 // preprocessor initialization). Find it and skip over it in the checking 260 // below. 261 llvm::SmallString<256> PCHInclude; 262 PCHInclude += "#include \""; 263 PCHInclude += NormalizeDashIncludePath(OriginalFileName, FileMgr); 264 PCHInclude += "\"\n"; 265 std::pair<llvm::StringRef,llvm::StringRef> Split = 266 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str()); 267 llvm::StringRef Left = Split.first, Right = Split.second; 268 if (Left == PP.getPredefines()) { 269 Error("Missing PCH include entry!"); 270 return true; 271 } 272 273 // If the concatenation of all the PCH buffers is equal to the adjusted 274 // command line, we're done. 275 llvm::SmallVector<llvm::StringRef, 2> CommandLine; 276 CommandLine.push_back(Left); 277 CommandLine.push_back(Right); 278 if (EqualConcatenations(CommandLine, Buffers)) 279 return false; 280 281 SourceManager &SourceMgr = PP.getSourceManager(); 282 283 // The predefines buffers are different. Determine what the differences are, 284 // and whether they require us to reject the PCH file. 285 llvm::SmallVector<llvm::StringRef, 8> PCHLines; 286 for (unsigned I = 0, N = Buffers.size(); I != N; ++I) 287 Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false); 288 289 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines; 290 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false); 291 292 // Pick out implicit #includes after the PCH and don't consider them for 293 // validation; we will insert them into SuggestedPredefines so that the 294 // preprocessor includes them. 295 std::string IncludesAfterPCH; 296 llvm::SmallVector<llvm::StringRef, 8> AfterPCHLines; 297 Right.split(AfterPCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false); 298 for (unsigned i = 0, e = AfterPCHLines.size(); i != e; ++i) { 299 if (AfterPCHLines[i].startswith("#include ")) { 300 IncludesAfterPCH += AfterPCHLines[i]; 301 IncludesAfterPCH += '\n'; 302 } else { 303 CmdLineLines.push_back(AfterPCHLines[i]); 304 } 305 } 306 307 // Make sure we add the includes last into SuggestedPredefines before we 308 // exit this function. 309 struct AddIncludesRAII { 310 std::string &SuggestedPredefines; 311 std::string &IncludesAfterPCH; 312 313 AddIncludesRAII(std::string &SuggestedPredefines, 314 std::string &IncludesAfterPCH) 315 : SuggestedPredefines(SuggestedPredefines), 316 IncludesAfterPCH(IncludesAfterPCH) { } 317 ~AddIncludesRAII() { 318 SuggestedPredefines += IncludesAfterPCH; 319 } 320 } AddIncludes(SuggestedPredefines, IncludesAfterPCH); 321 322 // Sort both sets of predefined buffer lines, since we allow some extra 323 // definitions and they may appear at any point in the output. 324 std::sort(CmdLineLines.begin(), CmdLineLines.end()); 325 std::sort(PCHLines.begin(), PCHLines.end()); 326 327 // Determine which predefines that were used to build the PCH file are missing 328 // from the command line. 329 std::vector<llvm::StringRef> MissingPredefines; 330 std::set_difference(PCHLines.begin(), PCHLines.end(), 331 CmdLineLines.begin(), CmdLineLines.end(), 332 std::back_inserter(MissingPredefines)); 333 334 bool MissingDefines = false; 335 bool ConflictingDefines = false; 336 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) { 337 llvm::StringRef Missing = MissingPredefines[I]; 338 if (Missing.startswith("#include ")) { 339 // An -include was specified when generating the PCH; it is included in 340 // the PCH, just ignore it. 341 continue; 342 } 343 if (!Missing.startswith("#define ")) { 344 Reader.Diag(diag::warn_pch_compiler_options_mismatch); 345 return true; 346 } 347 348 // This is a macro definition. Determine the name of the macro we're 349 // defining. 350 std::string::size_type StartOfMacroName = strlen("#define "); 351 std::string::size_type EndOfMacroName 352 = Missing.find_first_of("( \n\r", StartOfMacroName); 353 assert(EndOfMacroName != std::string::npos && 354 "Couldn't find the end of the macro name"); 355 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName); 356 357 // Determine whether this macro was given a different definition on the 358 // command line. 359 std::string MacroDefStart = "#define " + MacroName.str(); 360 std::string::size_type MacroDefLen = MacroDefStart.size(); 361 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos 362 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(), 363 MacroDefStart); 364 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) { 365 if (!ConflictPos->startswith(MacroDefStart)) { 366 // Different macro; we're done. 367 ConflictPos = CmdLineLines.end(); 368 break; 369 } 370 371 assert(ConflictPos->size() > MacroDefLen && 372 "Invalid #define in predefines buffer?"); 373 if ((*ConflictPos)[MacroDefLen] != ' ' && 374 (*ConflictPos)[MacroDefLen] != '(') 375 continue; // Longer macro name; keep trying. 376 377 // We found a conflicting macro definition. 378 break; 379 } 380 381 if (ConflictPos != CmdLineLines.end()) { 382 Reader.Diag(diag::warn_cmdline_conflicting_macro_def) 383 << MacroName; 384 385 // Show the definition of this macro within the PCH file. 386 std::pair<FileID, llvm::StringRef::size_type> MacroLoc = 387 FindMacro(Buffers, Missing); 388 assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!"); 389 SourceLocation PCHMissingLoc = 390 SourceMgr.getLocForStartOfFile(MacroLoc.first) 391 .getFileLocWithOffset(MacroLoc.second); 392 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName; 393 394 ConflictingDefines = true; 395 continue; 396 } 397 398 // If the macro doesn't conflict, then we'll just pick up the macro 399 // definition from the PCH file. Warn the user that they made a mistake. 400 if (ConflictingDefines) 401 continue; // Don't complain if there are already conflicting defs 402 403 if (!MissingDefines) { 404 Reader.Diag(diag::warn_cmdline_missing_macro_defs); 405 MissingDefines = true; 406 } 407 408 // Show the definition of this macro within the PCH file. 409 std::pair<FileID, llvm::StringRef::size_type> MacroLoc = 410 FindMacro(Buffers, Missing); 411 assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!"); 412 SourceLocation PCHMissingLoc = 413 SourceMgr.getLocForStartOfFile(MacroLoc.first) 414 .getFileLocWithOffset(MacroLoc.second); 415 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch); 416 } 417 418 if (ConflictingDefines) 419 return true; 420 421 // Determine what predefines were introduced based on command-line 422 // parameters that were not present when building the PCH 423 // file. Extra #defines are okay, so long as the identifiers being 424 // defined were not used within the precompiled header. 425 std::vector<llvm::StringRef> ExtraPredefines; 426 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(), 427 PCHLines.begin(), PCHLines.end(), 428 std::back_inserter(ExtraPredefines)); 429 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) { 430 llvm::StringRef &Extra = ExtraPredefines[I]; 431 if (!Extra.startswith("#define ")) { 432 Reader.Diag(diag::warn_pch_compiler_options_mismatch); 433 return true; 434 } 435 436 // This is an extra macro definition. Determine the name of the 437 // macro we're defining. 438 std::string::size_type StartOfMacroName = strlen("#define "); 439 std::string::size_type EndOfMacroName 440 = Extra.find_first_of("( \n\r", StartOfMacroName); 441 assert(EndOfMacroName != std::string::npos && 442 "Couldn't find the end of the macro name"); 443 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName); 444 445 // Check whether this name was used somewhere in the PCH file. If 446 // so, defining it as a macro could change behavior, so we reject 447 // the PCH file. 448 if (IdentifierInfo *II = Reader.get(MacroName)) { 449 Reader.Diag(diag::warn_macro_name_used_in_pch) << II; 450 return true; 451 } 452 453 // Add this definition to the suggested predefines buffer. 454 SuggestedPredefines += Extra; 455 SuggestedPredefines += '\n'; 456 } 457 458 // If we get here, it's because the predefines buffer had compatible 459 // contents. Accept the PCH file. 460 return false; 461 } 462 463 void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI, 464 unsigned ID) { 465 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID); 466 ++NumHeaderInfos; 467 } 468 469 void PCHValidator::ReadCounter(unsigned Value) { 470 PP.setCounterValue(Value); 471 } 472 473 //===----------------------------------------------------------------------===// 474 // AST reader implementation 475 //===----------------------------------------------------------------------===// 476 477 void 478 ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) { 479 DeserializationListener = Listener; 480 } 481 482 483 namespace { 484 class ASTSelectorLookupTrait { 485 ASTReader &Reader; 486 487 public: 488 struct data_type { 489 SelectorID ID; 490 ObjCMethodList Instance, Factory; 491 }; 492 493 typedef Selector external_key_type; 494 typedef external_key_type internal_key_type; 495 496 explicit ASTSelectorLookupTrait(ASTReader &Reader) : Reader(Reader) { } 497 498 static bool EqualKey(const internal_key_type& a, 499 const internal_key_type& b) { 500 return a == b; 501 } 502 503 static unsigned ComputeHash(Selector Sel) { 504 return serialization::ComputeHash(Sel); 505 } 506 507 // This hopefully will just get inlined and removed by the optimizer. 508 static const internal_key_type& 509 GetInternalKey(const external_key_type& x) { return x; } 510 511 static std::pair<unsigned, unsigned> 512 ReadKeyDataLength(const unsigned char*& d) { 513 using namespace clang::io; 514 unsigned KeyLen = ReadUnalignedLE16(d); 515 unsigned DataLen = ReadUnalignedLE16(d); 516 return std::make_pair(KeyLen, DataLen); 517 } 518 519 internal_key_type ReadKey(const unsigned char* d, unsigned) { 520 using namespace clang::io; 521 SelectorTable &SelTable = Reader.getContext()->Selectors; 522 unsigned N = ReadUnalignedLE16(d); 523 IdentifierInfo *FirstII 524 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)); 525 if (N == 0) 526 return SelTable.getNullarySelector(FirstII); 527 else if (N == 1) 528 return SelTable.getUnarySelector(FirstII); 529 530 llvm::SmallVector<IdentifierInfo *, 16> Args; 531 Args.push_back(FirstII); 532 for (unsigned I = 1; I != N; ++I) 533 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d))); 534 535 return SelTable.getSelector(N, Args.data()); 536 } 537 538 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) { 539 using namespace clang::io; 540 541 data_type Result; 542 543 Result.ID = ReadUnalignedLE32(d); 544 unsigned NumInstanceMethods = ReadUnalignedLE16(d); 545 unsigned NumFactoryMethods = ReadUnalignedLE16(d); 546 547 // Load instance methods 548 ObjCMethodList *Prev = 0; 549 for (unsigned I = 0; I != NumInstanceMethods; ++I) { 550 ObjCMethodDecl *Method 551 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d))); 552 if (!Result.Instance.Method) { 553 // This is the first method, which is the easy case. 554 Result.Instance.Method = Method; 555 Prev = &Result.Instance; 556 continue; 557 } 558 559 ObjCMethodList *Mem = 560 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>(); 561 Prev->Next = new (Mem) ObjCMethodList(Method, 0); 562 Prev = Prev->Next; 563 } 564 565 // Load factory methods 566 Prev = 0; 567 for (unsigned I = 0; I != NumFactoryMethods; ++I) { 568 ObjCMethodDecl *Method 569 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d))); 570 if (!Result.Factory.Method) { 571 // This is the first method, which is the easy case. 572 Result.Factory.Method = Method; 573 Prev = &Result.Factory; 574 continue; 575 } 576 577 ObjCMethodList *Mem = 578 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>(); 579 Prev->Next = new (Mem) ObjCMethodList(Method, 0); 580 Prev = Prev->Next; 581 } 582 583 return Result; 584 } 585 }; 586 587 } // end anonymous namespace 588 589 /// \brief The on-disk hash table used for the global method pool. 590 typedef OnDiskChainedHashTable<ASTSelectorLookupTrait> 591 ASTSelectorLookupTable; 592 593 namespace clang { 594 class ASTIdentifierLookupTrait { 595 ASTReader &Reader; 596 ASTReader::PerFileData &F; 597 598 // If we know the IdentifierInfo in advance, it is here and we will 599 // not build a new one. Used when deserializing information about an 600 // identifier that was constructed before the AST file was read. 601 IdentifierInfo *KnownII; 602 603 public: 604 typedef IdentifierInfo * data_type; 605 606 typedef const std::pair<const char*, unsigned> external_key_type; 607 608 typedef external_key_type internal_key_type; 609 610 ASTIdentifierLookupTrait(ASTReader &Reader, ASTReader::PerFileData &F, 611 IdentifierInfo *II = 0) 612 : Reader(Reader), F(F), KnownII(II) { } 613 614 static bool EqualKey(const internal_key_type& a, 615 const internal_key_type& b) { 616 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0 617 : false; 618 } 619 620 static unsigned ComputeHash(const internal_key_type& a) { 621 return llvm::HashString(llvm::StringRef(a.first, a.second)); 622 } 623 624 // This hopefully will just get inlined and removed by the optimizer. 625 static const internal_key_type& 626 GetInternalKey(const external_key_type& x) { return x; } 627 628 // This hopefully will just get inlined and removed by the optimizer. 629 static const external_key_type& 630 GetExternalKey(const internal_key_type& x) { return x; } 631 632 static std::pair<unsigned, unsigned> 633 ReadKeyDataLength(const unsigned char*& d) { 634 using namespace clang::io; 635 unsigned DataLen = ReadUnalignedLE16(d); 636 unsigned KeyLen = ReadUnalignedLE16(d); 637 return std::make_pair(KeyLen, DataLen); 638 } 639 640 static std::pair<const char*, unsigned> 641 ReadKey(const unsigned char* d, unsigned n) { 642 assert(n >= 2 && d[n-1] == '\0'); 643 return std::make_pair((const char*) d, n-1); 644 } 645 646 IdentifierInfo *ReadData(const internal_key_type& k, 647 const unsigned char* d, 648 unsigned DataLen) { 649 using namespace clang::io; 650 IdentID ID = ReadUnalignedLE32(d); 651 bool IsInteresting = ID & 0x01; 652 653 // Wipe out the "is interesting" bit. 654 ID = ID >> 1; 655 656 if (!IsInteresting) { 657 // For uninteresting identifiers, just build the IdentifierInfo 658 // and associate it with the persistent ID. 659 IdentifierInfo *II = KnownII; 660 if (!II) 661 II = &Reader.getIdentifierTable().getOwn(llvm::StringRef(k.first, 662 k.second)); 663 Reader.SetIdentifierInfo(ID, II); 664 II->setIsFromAST(); 665 return II; 666 } 667 668 unsigned Bits = ReadUnalignedLE16(d); 669 bool CPlusPlusOperatorKeyword = Bits & 0x01; 670 Bits >>= 1; 671 bool HasRevertedTokenIDToIdentifier = Bits & 0x01; 672 Bits >>= 1; 673 bool Poisoned = Bits & 0x01; 674 Bits >>= 1; 675 bool ExtensionToken = Bits & 0x01; 676 Bits >>= 1; 677 bool hasMacroDefinition = Bits & 0x01; 678 Bits >>= 1; 679 unsigned ObjCOrBuiltinID = Bits & 0x3FF; 680 Bits >>= 10; 681 682 assert(Bits == 0 && "Extra bits in the identifier?"); 683 DataLen -= 6; 684 685 // Build the IdentifierInfo itself and link the identifier ID with 686 // the new IdentifierInfo. 687 IdentifierInfo *II = KnownII; 688 if (!II) 689 II = &Reader.getIdentifierTable().getOwn(llvm::StringRef(k.first, 690 k.second)); 691 Reader.SetIdentifierInfo(ID, II); 692 693 // Set or check the various bits in the IdentifierInfo structure. 694 // Token IDs are read-only. 695 if (HasRevertedTokenIDToIdentifier) 696 II->RevertTokenIDToIdentifier(); 697 II->setObjCOrBuiltinID(ObjCOrBuiltinID); 698 assert(II->isExtensionToken() == ExtensionToken && 699 "Incorrect extension token flag"); 700 (void)ExtensionToken; 701 II->setIsPoisoned(Poisoned); 702 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword && 703 "Incorrect C++ operator keyword flag"); 704 (void)CPlusPlusOperatorKeyword; 705 706 // If this identifier is a macro, deserialize the macro 707 // definition. 708 if (hasMacroDefinition) { 709 uint32_t Offset = ReadUnalignedLE32(d); 710 Reader.SetIdentifierIsMacro(II, F, Offset); 711 DataLen -= 4; 712 } 713 714 // Read all of the declarations visible at global scope with this 715 // name. 716 if (Reader.getContext() == 0) return II; 717 if (DataLen > 0) { 718 llvm::SmallVector<uint32_t, 4> DeclIDs; 719 for (; DataLen > 0; DataLen -= 4) 720 DeclIDs.push_back(ReadUnalignedLE32(d)); 721 Reader.SetGloballyVisibleDecls(II, DeclIDs); 722 } 723 724 II->setIsFromAST(); 725 return II; 726 } 727 }; 728 729 } // end anonymous namespace 730 731 /// \brief The on-disk hash table used to contain information about 732 /// all of the identifiers in the program. 733 typedef OnDiskChainedHashTable<ASTIdentifierLookupTrait> 734 ASTIdentifierLookupTable; 735 736 namespace { 737 class ASTDeclContextNameLookupTrait { 738 ASTReader &Reader; 739 740 public: 741 /// \brief Pair of begin/end iterators for DeclIDs. 742 typedef std::pair<DeclID *, DeclID *> data_type; 743 744 /// \brief Special internal key for declaration names. 745 /// The hash table creates keys for comparison; we do not create 746 /// a DeclarationName for the internal key to avoid deserializing types. 747 struct DeclNameKey { 748 DeclarationName::NameKind Kind; 749 uint64_t Data; 750 DeclNameKey() : Kind((DeclarationName::NameKind)0), Data(0) { } 751 }; 752 753 typedef DeclarationName external_key_type; 754 typedef DeclNameKey internal_key_type; 755 756 explicit ASTDeclContextNameLookupTrait(ASTReader &Reader) : Reader(Reader) { } 757 758 static bool EqualKey(const internal_key_type& a, 759 const internal_key_type& b) { 760 return a.Kind == b.Kind && a.Data == b.Data; 761 } 762 763 unsigned ComputeHash(const DeclNameKey &Key) const { 764 llvm::FoldingSetNodeID ID; 765 ID.AddInteger(Key.Kind); 766 767 switch (Key.Kind) { 768 case DeclarationName::Identifier: 769 case DeclarationName::CXXLiteralOperatorName: 770 ID.AddString(((IdentifierInfo*)Key.Data)->getName()); 771 break; 772 case DeclarationName::ObjCZeroArgSelector: 773 case DeclarationName::ObjCOneArgSelector: 774 case DeclarationName::ObjCMultiArgSelector: 775 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data))); 776 break; 777 case DeclarationName::CXXConstructorName: 778 case DeclarationName::CXXDestructorName: 779 case DeclarationName::CXXConversionFunctionName: 780 ID.AddInteger((TypeID)Key.Data); 781 break; 782 case DeclarationName::CXXOperatorName: 783 ID.AddInteger((OverloadedOperatorKind)Key.Data); 784 break; 785 case DeclarationName::CXXUsingDirective: 786 break; 787 } 788 789 return ID.ComputeHash(); 790 } 791 792 internal_key_type GetInternalKey(const external_key_type& Name) const { 793 DeclNameKey Key; 794 Key.Kind = Name.getNameKind(); 795 switch (Name.getNameKind()) { 796 case DeclarationName::Identifier: 797 Key.Data = (uint64_t)Name.getAsIdentifierInfo(); 798 break; 799 case DeclarationName::ObjCZeroArgSelector: 800 case DeclarationName::ObjCOneArgSelector: 801 case DeclarationName::ObjCMultiArgSelector: 802 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr(); 803 break; 804 case DeclarationName::CXXConstructorName: 805 case DeclarationName::CXXDestructorName: 806 case DeclarationName::CXXConversionFunctionName: 807 Key.Data = Reader.GetTypeID(Name.getCXXNameType()); 808 break; 809 case DeclarationName::CXXOperatorName: 810 Key.Data = Name.getCXXOverloadedOperator(); 811 break; 812 case DeclarationName::CXXLiteralOperatorName: 813 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier(); 814 break; 815 case DeclarationName::CXXUsingDirective: 816 break; 817 } 818 819 return Key; 820 } 821 822 external_key_type GetExternalKey(const internal_key_type& Key) const { 823 ASTContext *Context = Reader.getContext(); 824 switch (Key.Kind) { 825 case DeclarationName::Identifier: 826 return DeclarationName((IdentifierInfo*)Key.Data); 827 828 case DeclarationName::ObjCZeroArgSelector: 829 case DeclarationName::ObjCOneArgSelector: 830 case DeclarationName::ObjCMultiArgSelector: 831 return DeclarationName(Selector(Key.Data)); 832 833 case DeclarationName::CXXConstructorName: 834 return Context->DeclarationNames.getCXXConstructorName( 835 Context->getCanonicalType(Reader.GetType(Key.Data))); 836 837 case DeclarationName::CXXDestructorName: 838 return Context->DeclarationNames.getCXXDestructorName( 839 Context->getCanonicalType(Reader.GetType(Key.Data))); 840 841 case DeclarationName::CXXConversionFunctionName: 842 return Context->DeclarationNames.getCXXConversionFunctionName( 843 Context->getCanonicalType(Reader.GetType(Key.Data))); 844 845 case DeclarationName::CXXOperatorName: 846 return Context->DeclarationNames.getCXXOperatorName( 847 (OverloadedOperatorKind)Key.Data); 848 849 case DeclarationName::CXXLiteralOperatorName: 850 return Context->DeclarationNames.getCXXLiteralOperatorName( 851 (IdentifierInfo*)Key.Data); 852 853 case DeclarationName::CXXUsingDirective: 854 return DeclarationName::getUsingDirectiveName(); 855 } 856 857 llvm_unreachable("Invalid Name Kind ?"); 858 } 859 860 static std::pair<unsigned, unsigned> 861 ReadKeyDataLength(const unsigned char*& d) { 862 using namespace clang::io; 863 unsigned KeyLen = ReadUnalignedLE16(d); 864 unsigned DataLen = ReadUnalignedLE16(d); 865 return std::make_pair(KeyLen, DataLen); 866 } 867 868 internal_key_type ReadKey(const unsigned char* d, unsigned) { 869 using namespace clang::io; 870 871 DeclNameKey Key; 872 Key.Kind = (DeclarationName::NameKind)*d++; 873 switch (Key.Kind) { 874 case DeclarationName::Identifier: 875 Key.Data = (uint64_t)Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)); 876 break; 877 case DeclarationName::ObjCZeroArgSelector: 878 case DeclarationName::ObjCOneArgSelector: 879 case DeclarationName::ObjCMultiArgSelector: 880 Key.Data = 881 (uint64_t)Reader.DecodeSelector(ReadUnalignedLE32(d)).getAsOpaquePtr(); 882 break; 883 case DeclarationName::CXXConstructorName: 884 case DeclarationName::CXXDestructorName: 885 case DeclarationName::CXXConversionFunctionName: 886 Key.Data = ReadUnalignedLE32(d); // TypeID 887 break; 888 case DeclarationName::CXXOperatorName: 889 Key.Data = *d++; // OverloadedOperatorKind 890 break; 891 case DeclarationName::CXXLiteralOperatorName: 892 Key.Data = (uint64_t)Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)); 893 break; 894 case DeclarationName::CXXUsingDirective: 895 break; 896 } 897 898 return Key; 899 } 900 901 data_type ReadData(internal_key_type, const unsigned char* d, 902 unsigned DataLen) { 903 using namespace clang::io; 904 unsigned NumDecls = ReadUnalignedLE16(d); 905 DeclID *Start = (DeclID *)d; 906 return std::make_pair(Start, Start + NumDecls); 907 } 908 }; 909 910 } // end anonymous namespace 911 912 /// \brief The on-disk hash table used for the DeclContext's Name lookup table. 913 typedef OnDiskChainedHashTable<ASTDeclContextNameLookupTrait> 914 ASTDeclContextNameLookupTable; 915 916 bool ASTReader::ReadDeclContextStorage(llvm::BitstreamCursor &Cursor, 917 const std::pair<uint64_t, uint64_t> &Offsets, 918 DeclContextInfo &Info) { 919 SavedStreamPosition SavedPosition(Cursor); 920 // First the lexical decls. 921 if (Offsets.first != 0) { 922 Cursor.JumpToBit(Offsets.first); 923 924 RecordData Record; 925 const char *Blob; 926 unsigned BlobLen; 927 unsigned Code = Cursor.ReadCode(); 928 unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen); 929 if (RecCode != DECL_CONTEXT_LEXICAL) { 930 Error("Expected lexical block"); 931 return true; 932 } 933 934 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob); 935 Info.NumLexicalDecls = BlobLen / sizeof(KindDeclIDPair); 936 } else { 937 Info.LexicalDecls = 0; 938 Info.NumLexicalDecls = 0; 939 } 940 941 // Now the lookup table. 942 if (Offsets.second != 0) { 943 Cursor.JumpToBit(Offsets.second); 944 945 RecordData Record; 946 const char *Blob; 947 unsigned BlobLen; 948 unsigned Code = Cursor.ReadCode(); 949 unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen); 950 if (RecCode != DECL_CONTEXT_VISIBLE) { 951 Error("Expected visible lookup table block"); 952 return true; 953 } 954 Info.NameLookupTableData 955 = ASTDeclContextNameLookupTable::Create( 956 (const unsigned char *)Blob + Record[0], 957 (const unsigned char *)Blob, 958 ASTDeclContextNameLookupTrait(*this)); 959 } else { 960 Info.NameLookupTableData = 0; 961 } 962 963 return false; 964 } 965 966 void ASTReader::Error(llvm::StringRef Msg) { 967 Error(diag::err_fe_pch_malformed, Msg); 968 } 969 970 void ASTReader::Error(unsigned DiagID, 971 llvm::StringRef Arg1, llvm::StringRef Arg2) { 972 if (Diags.isDiagnosticInFlight()) 973 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2); 974 else 975 Diag(DiagID) << Arg1 << Arg2; 976 } 977 978 /// \brief Tell the AST listener about the predefines buffers in the chain. 979 bool ASTReader::CheckPredefinesBuffers() { 980 if (Listener) 981 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers, 982 ActualOriginalFileName, 983 SuggestedPredefines, 984 FileMgr); 985 return false; 986 } 987 988 //===----------------------------------------------------------------------===// 989 // Source Manager Deserialization 990 //===----------------------------------------------------------------------===// 991 992 /// \brief Read the line table in the source manager block. 993 /// \returns true if there was an error. 994 bool ASTReader::ParseLineTable(PerFileData &F, 995 llvm::SmallVectorImpl<uint64_t> &Record) { 996 unsigned Idx = 0; 997 LineTableInfo &LineTable = SourceMgr.getLineTable(); 998 999 // Parse the file names 1000 std::map<int, int> FileIDs; 1001 for (int I = 0, N = Record[Idx++]; I != N; ++I) { 1002 // Extract the file name 1003 unsigned FilenameLen = Record[Idx++]; 1004 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen); 1005 Idx += FilenameLen; 1006 MaybeAddSystemRootToFilename(Filename); 1007 FileIDs[I] = LineTable.getLineTableFilenameID(Filename); 1008 } 1009 1010 // Parse the line entries 1011 std::vector<LineEntry> Entries; 1012 while (Idx < Record.size()) { 1013 int FID = Record[Idx++]; 1014 assert(FID >= 0 && "Serialized line entries for non-local file."); 1015 // Remap FileID from 1-based old view. 1016 FID += F.SLocEntryBaseID - 1; 1017 1018 // Extract the line entries 1019 unsigned NumEntries = Record[Idx++]; 1020 assert(NumEntries && "Numentries is 00000"); 1021 Entries.clear(); 1022 Entries.reserve(NumEntries); 1023 for (unsigned I = 0; I != NumEntries; ++I) { 1024 unsigned FileOffset = Record[Idx++]; 1025 unsigned LineNo = Record[Idx++]; 1026 int FilenameID = FileIDs[Record[Idx++]]; 1027 SrcMgr::CharacteristicKind FileKind 1028 = (SrcMgr::CharacteristicKind)Record[Idx++]; 1029 unsigned IncludeOffset = Record[Idx++]; 1030 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID, 1031 FileKind, IncludeOffset)); 1032 } 1033 LineTable.AddEntry(FID, Entries); 1034 } 1035 1036 return false; 1037 } 1038 1039 namespace { 1040 1041 class ASTStatData { 1042 public: 1043 const ino_t ino; 1044 const dev_t dev; 1045 const mode_t mode; 1046 const time_t mtime; 1047 const off_t size; 1048 1049 ASTStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s) 1050 : ino(i), dev(d), mode(mo), mtime(m), size(s) {} 1051 }; 1052 1053 class ASTStatLookupTrait { 1054 public: 1055 typedef const char *external_key_type; 1056 typedef const char *internal_key_type; 1057 1058 typedef ASTStatData data_type; 1059 1060 static unsigned ComputeHash(const char *path) { 1061 return llvm::HashString(path); 1062 } 1063 1064 static internal_key_type GetInternalKey(const char *path) { return path; } 1065 1066 static bool EqualKey(internal_key_type a, internal_key_type b) { 1067 return strcmp(a, b) == 0; 1068 } 1069 1070 static std::pair<unsigned, unsigned> 1071 ReadKeyDataLength(const unsigned char*& d) { 1072 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d); 1073 unsigned DataLen = (unsigned) *d++; 1074 return std::make_pair(KeyLen + 1, DataLen); 1075 } 1076 1077 static internal_key_type ReadKey(const unsigned char *d, unsigned) { 1078 return (const char *)d; 1079 } 1080 1081 static data_type ReadData(const internal_key_type, const unsigned char *d, 1082 unsigned /*DataLen*/) { 1083 using namespace clang::io; 1084 1085 ino_t ino = (ino_t) ReadUnalignedLE32(d); 1086 dev_t dev = (dev_t) ReadUnalignedLE32(d); 1087 mode_t mode = (mode_t) ReadUnalignedLE16(d); 1088 time_t mtime = (time_t) ReadUnalignedLE64(d); 1089 off_t size = (off_t) ReadUnalignedLE64(d); 1090 return data_type(ino, dev, mode, mtime, size); 1091 } 1092 }; 1093 1094 /// \brief stat() cache for precompiled headers. 1095 /// 1096 /// This cache is very similar to the stat cache used by pretokenized 1097 /// headers. 1098 class ASTStatCache : public FileSystemStatCache { 1099 typedef OnDiskChainedHashTable<ASTStatLookupTrait> CacheTy; 1100 CacheTy *Cache; 1101 1102 unsigned &NumStatHits, &NumStatMisses; 1103 public: 1104 ASTStatCache(const unsigned char *Buckets, const unsigned char *Base, 1105 unsigned &NumStatHits, unsigned &NumStatMisses) 1106 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) { 1107 Cache = CacheTy::Create(Buckets, Base); 1108 } 1109 1110 ~ASTStatCache() { delete Cache; } 1111 1112 LookupResult getStat(const char *Path, struct stat &StatBuf, 1113 int *FileDescriptor) { 1114 // Do the lookup for the file's data in the AST file. 1115 CacheTy::iterator I = Cache->find(Path); 1116 1117 // If we don't get a hit in the AST file just forward to 'stat'. 1118 if (I == Cache->end()) { 1119 ++NumStatMisses; 1120 return statChained(Path, StatBuf, FileDescriptor); 1121 } 1122 1123 ++NumStatHits; 1124 ASTStatData Data = *I; 1125 1126 StatBuf.st_ino = Data.ino; 1127 StatBuf.st_dev = Data.dev; 1128 StatBuf.st_mtime = Data.mtime; 1129 StatBuf.st_mode = Data.mode; 1130 StatBuf.st_size = Data.size; 1131 return CacheExists; 1132 } 1133 }; 1134 } // end anonymous namespace 1135 1136 1137 /// \brief Read a source manager block 1138 ASTReader::ASTReadResult ASTReader::ReadSourceManagerBlock(PerFileData &F) { 1139 using namespace SrcMgr; 1140 1141 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor; 1142 1143 // Set the source-location entry cursor to the current position in 1144 // the stream. This cursor will be used to read the contents of the 1145 // source manager block initially, and then lazily read 1146 // source-location entries as needed. 1147 SLocEntryCursor = F.Stream; 1148 1149 // The stream itself is going to skip over the source manager block. 1150 if (F.Stream.SkipBlock()) { 1151 Error("malformed block record in AST file"); 1152 return Failure; 1153 } 1154 1155 // Enter the source manager block. 1156 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) { 1157 Error("malformed source manager block record in AST file"); 1158 return Failure; 1159 } 1160 1161 RecordData Record; 1162 while (true) { 1163 unsigned Code = SLocEntryCursor.ReadCode(); 1164 if (Code == llvm::bitc::END_BLOCK) { 1165 if (SLocEntryCursor.ReadBlockEnd()) { 1166 Error("error at end of Source Manager block in AST file"); 1167 return Failure; 1168 } 1169 return Success; 1170 } 1171 1172 if (Code == llvm::bitc::ENTER_SUBBLOCK) { 1173 // No known subblocks, always skip them. 1174 SLocEntryCursor.ReadSubBlockID(); 1175 if (SLocEntryCursor.SkipBlock()) { 1176 Error("malformed block record in AST file"); 1177 return Failure; 1178 } 1179 continue; 1180 } 1181 1182 if (Code == llvm::bitc::DEFINE_ABBREV) { 1183 SLocEntryCursor.ReadAbbrevRecord(); 1184 continue; 1185 } 1186 1187 // Read a record. 1188 const char *BlobStart; 1189 unsigned BlobLen; 1190 Record.clear(); 1191 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) { 1192 default: // Default behavior: ignore. 1193 break; 1194 1195 case SM_SLOC_FILE_ENTRY: 1196 case SM_SLOC_BUFFER_ENTRY: 1197 case SM_SLOC_EXPANSION_ENTRY: 1198 // Once we hit one of the source location entries, we're done. 1199 return Success; 1200 } 1201 } 1202 } 1203 1204 /// \brief If a header file is not found at the path that we expect it to be 1205 /// and the PCH file was moved from its original location, try to resolve the 1206 /// file by assuming that header+PCH were moved together and the header is in 1207 /// the same place relative to the PCH. 1208 static std::string 1209 resolveFileRelativeToOriginalDir(const std::string &Filename, 1210 const std::string &OriginalDir, 1211 const std::string &CurrDir) { 1212 assert(OriginalDir != CurrDir && 1213 "No point trying to resolve the file if the PCH dir didn't change"); 1214 using namespace llvm::sys; 1215 llvm::SmallString<128> filePath(Filename); 1216 fs::make_absolute(filePath); 1217 assert(path::is_absolute(OriginalDir)); 1218 llvm::SmallString<128> currPCHPath(CurrDir); 1219 1220 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)), 1221 fileDirE = path::end(path::parent_path(filePath)); 1222 path::const_iterator origDirI = path::begin(OriginalDir), 1223 origDirE = path::end(OriginalDir); 1224 // Skip the common path components from filePath and OriginalDir. 1225 while (fileDirI != fileDirE && origDirI != origDirE && 1226 *fileDirI == *origDirI) { 1227 ++fileDirI; 1228 ++origDirI; 1229 } 1230 for (; origDirI != origDirE; ++origDirI) 1231 path::append(currPCHPath, ".."); 1232 path::append(currPCHPath, fileDirI, fileDirE); 1233 path::append(currPCHPath, path::filename(Filename)); 1234 return currPCHPath.str(); 1235 } 1236 1237 /// \brief Read in the source location entry with the given ID. 1238 ASTReader::ASTReadResult ASTReader::ReadSLocEntryRecord(int ID) { 1239 if (ID == 0) 1240 return Success; 1241 1242 if (unsigned(-ID) - 2 >= TotalNumSLocEntries || ID > 0) { 1243 Error("source location entry ID out-of-range for AST file"); 1244 return Failure; 1245 } 1246 1247 PerFileData *F = GlobalSLocEntryMap.find(-ID)->second; 1248 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]); 1249 llvm::BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor; 1250 unsigned BaseOffset = F->SLocEntryBaseOffset; 1251 1252 ++NumSLocEntriesRead; 1253 unsigned Code = SLocEntryCursor.ReadCode(); 1254 if (Code == llvm::bitc::END_BLOCK || 1255 Code == llvm::bitc::ENTER_SUBBLOCK || 1256 Code == llvm::bitc::DEFINE_ABBREV) { 1257 Error("incorrectly-formatted source location entry in AST file"); 1258 return Failure; 1259 } 1260 1261 RecordData Record; 1262 const char *BlobStart; 1263 unsigned BlobLen; 1264 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) { 1265 default: 1266 Error("incorrectly-formatted source location entry in AST file"); 1267 return Failure; 1268 1269 case SM_SLOC_FILE_ENTRY: { 1270 std::string Filename(BlobStart, BlobStart + BlobLen); 1271 MaybeAddSystemRootToFilename(Filename); 1272 const FileEntry *File = FileMgr.getFile(Filename); 1273 if (File == 0 && !OriginalDir.empty() && !CurrentDir.empty() && 1274 OriginalDir != CurrentDir) { 1275 std::string resolved = resolveFileRelativeToOriginalDir(Filename, 1276 OriginalDir, 1277 CurrentDir); 1278 if (!resolved.empty()) 1279 File = FileMgr.getFile(resolved); 1280 } 1281 if (File == 0) 1282 File = FileMgr.getVirtualFile(Filename, (off_t)Record[4], 1283 (time_t)Record[5]); 1284 if (File == 0) { 1285 std::string ErrorStr = "could not find file '"; 1286 ErrorStr += Filename; 1287 ErrorStr += "' referenced by AST file"; 1288 Error(ErrorStr.c_str()); 1289 return Failure; 1290 } 1291 1292 if (Record.size() < 6) { 1293 Error("source location entry is incorrect"); 1294 return Failure; 1295 } 1296 1297 if (!DisableValidation && 1298 ((off_t)Record[4] != File->getSize() 1299 #if !defined(LLVM_ON_WIN32) 1300 // In our regression testing, the Windows file system seems to 1301 // have inconsistent modification times that sometimes 1302 // erroneously trigger this error-handling path. 1303 || (time_t)Record[5] != File->getModificationTime() 1304 #endif 1305 )) { 1306 Error(diag::err_fe_pch_file_modified, Filename); 1307 return Failure; 1308 } 1309 1310 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]); 1311 if (IncludeLoc.isInvalid() && F->Type != MainFile) { 1312 // This is the module's main file. 1313 IncludeLoc = getImportLocation(F); 1314 } 1315 FileID FID = SourceMgr.createFileID(File, IncludeLoc, 1316 (SrcMgr::CharacteristicKind)Record[2], 1317 ID, BaseOffset + Record[0]); 1318 if (Record[3]) 1319 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile()) 1320 .setHasLineDirectives(); 1321 1322 break; 1323 } 1324 1325 case SM_SLOC_BUFFER_ENTRY: { 1326 const char *Name = BlobStart; 1327 unsigned Offset = Record[0]; 1328 unsigned Code = SLocEntryCursor.ReadCode(); 1329 Record.clear(); 1330 unsigned RecCode 1331 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen); 1332 1333 if (RecCode != SM_SLOC_BUFFER_BLOB) { 1334 Error("AST record has invalid code"); 1335 return Failure; 1336 } 1337 1338 llvm::MemoryBuffer *Buffer 1339 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1), 1340 Name); 1341 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, 1342 BaseOffset + Offset); 1343 1344 if (strcmp(Name, "<built-in>") == 0) { 1345 PCHPredefinesBlock Block = { 1346 BufferID, 1347 llvm::StringRef(BlobStart, BlobLen - 1) 1348 }; 1349 PCHPredefinesBuffers.push_back(Block); 1350 } 1351 1352 break; 1353 } 1354 1355 case SM_SLOC_EXPANSION_ENTRY: { 1356 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]); 1357 SourceMgr.createInstantiationLoc(SpellingLoc, 1358 ReadSourceLocation(*F, Record[2]), 1359 ReadSourceLocation(*F, Record[3]), 1360 Record[4], 1361 ID, 1362 BaseOffset + Record[0]); 1363 break; 1364 } 1365 } 1366 1367 return Success; 1368 } 1369 1370 /// \brief Find the location where the module F is imported. 1371 SourceLocation ASTReader::getImportLocation(PerFileData *F) { 1372 if (F->ImportLoc.isValid()) 1373 return F->ImportLoc; 1374 // Otherwise we have a PCH. It's considered to be "imported" at the first 1375 // location of its includer. 1376 if (F->Loaders.empty() || !F->Loaders[0]) { 1377 // Main file is the importer. We assume that it is the first entry in the 1378 // entry table. We can't ask the manager, because at the time of PCH loading 1379 // the main file entry doesn't exist yet. 1380 // The very first entry is the invalid instantiation loc, which takes up 1381 // offsets 0 and 1. 1382 return SourceLocation::getFromRawEncoding(2U); 1383 } 1384 return F->Loaders[0]->FirstLoc; 1385 } 1386 1387 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the 1388 /// specified cursor. Read the abbreviations that are at the top of the block 1389 /// and then leave the cursor pointing into the block. 1390 bool ASTReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, 1391 unsigned BlockID) { 1392 if (Cursor.EnterSubBlock(BlockID)) { 1393 Error("malformed block record in AST file"); 1394 return Failure; 1395 } 1396 1397 while (true) { 1398 uint64_t Offset = Cursor.GetCurrentBitNo(); 1399 unsigned Code = Cursor.ReadCode(); 1400 1401 // We expect all abbrevs to be at the start of the block. 1402 if (Code != llvm::bitc::DEFINE_ABBREV) { 1403 Cursor.JumpToBit(Offset); 1404 return false; 1405 } 1406 Cursor.ReadAbbrevRecord(); 1407 } 1408 } 1409 1410 PreprocessedEntity *ASTReader::ReadMacroRecord(PerFileData &F, uint64_t Offset) { 1411 assert(PP && "Forgot to set Preprocessor ?"); 1412 llvm::BitstreamCursor &Stream = F.MacroCursor; 1413 1414 // Keep track of where we are in the stream, then jump back there 1415 // after reading this macro. 1416 SavedStreamPosition SavedPosition(Stream); 1417 1418 Stream.JumpToBit(Offset); 1419 RecordData Record; 1420 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs; 1421 MacroInfo *Macro = 0; 1422 1423 while (true) { 1424 unsigned Code = Stream.ReadCode(); 1425 switch (Code) { 1426 case llvm::bitc::END_BLOCK: 1427 return 0; 1428 1429 case llvm::bitc::ENTER_SUBBLOCK: 1430 // No known subblocks, always skip them. 1431 Stream.ReadSubBlockID(); 1432 if (Stream.SkipBlock()) { 1433 Error("malformed block record in AST file"); 1434 return 0; 1435 } 1436 continue; 1437 1438 case llvm::bitc::DEFINE_ABBREV: 1439 Stream.ReadAbbrevRecord(); 1440 continue; 1441 default: break; 1442 } 1443 1444 // Read a record. 1445 const char *BlobStart = 0; 1446 unsigned BlobLen = 0; 1447 Record.clear(); 1448 PreprocessorRecordTypes RecType = 1449 (PreprocessorRecordTypes)Stream.ReadRecord(Code, Record, BlobStart, 1450 BlobLen); 1451 switch (RecType) { 1452 case PP_MACRO_OBJECT_LIKE: 1453 case PP_MACRO_FUNCTION_LIKE: { 1454 // If we already have a macro, that means that we've hit the end 1455 // of the definition of the macro we were looking for. We're 1456 // done. 1457 if (Macro) 1458 return 0; 1459 1460 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]); 1461 if (II == 0) { 1462 Error("macro must have a name in AST file"); 1463 return 0; 1464 } 1465 SourceLocation Loc = ReadSourceLocation(F, Record[1]); 1466 bool isUsed = Record[2]; 1467 1468 MacroInfo *MI = PP->AllocateMacroInfo(Loc); 1469 MI->setIsUsed(isUsed); 1470 MI->setIsFromAST(); 1471 1472 unsigned NextIndex = 3; 1473 if (RecType == PP_MACRO_FUNCTION_LIKE) { 1474 // Decode function-like macro info. 1475 bool isC99VarArgs = Record[3]; 1476 bool isGNUVarArgs = Record[4]; 1477 MacroArgs.clear(); 1478 unsigned NumArgs = Record[5]; 1479 NextIndex = 6 + NumArgs; 1480 for (unsigned i = 0; i != NumArgs; ++i) 1481 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i])); 1482 1483 // Install function-like macro info. 1484 MI->setIsFunctionLike(); 1485 if (isC99VarArgs) MI->setIsC99Varargs(); 1486 if (isGNUVarArgs) MI->setIsGNUVarargs(); 1487 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(), 1488 PP->getPreprocessorAllocator()); 1489 } 1490 1491 // Finally, install the macro. 1492 PP->setMacroInfo(II, MI); 1493 1494 // Remember that we saw this macro last so that we add the tokens that 1495 // form its body to it. 1496 Macro = MI; 1497 1498 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) { 1499 // We have a macro definition. Load it now. 1500 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro, 1501 getMacroDefinition(Record[NextIndex])); 1502 } 1503 1504 ++NumMacrosRead; 1505 break; 1506 } 1507 1508 case PP_TOKEN: { 1509 // If we see a TOKEN before a PP_MACRO_*, then the file is 1510 // erroneous, just pretend we didn't see this. 1511 if (Macro == 0) break; 1512 1513 Token Tok; 1514 Tok.startToken(); 1515 Tok.setLocation(ReadSourceLocation(F, Record[0])); 1516 Tok.setLength(Record[1]); 1517 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2])) 1518 Tok.setIdentifierInfo(II); 1519 Tok.setKind((tok::TokenKind)Record[3]); 1520 Tok.setFlag((Token::TokenFlags)Record[4]); 1521 Macro->AddTokenToBody(Tok); 1522 break; 1523 } 1524 } 1525 } 1526 1527 return 0; 1528 } 1529 1530 PreprocessedEntity *ASTReader::LoadPreprocessedEntity(PerFileData &F) { 1531 assert(PP && "Forgot to set Preprocessor ?"); 1532 unsigned Code = F.PreprocessorDetailCursor.ReadCode(); 1533 switch (Code) { 1534 case llvm::bitc::END_BLOCK: 1535 return 0; 1536 1537 case llvm::bitc::ENTER_SUBBLOCK: 1538 Error("unexpected subblock record in preprocessor detail block"); 1539 return 0; 1540 1541 case llvm::bitc::DEFINE_ABBREV: 1542 Error("unexpected abbrevation record in preprocessor detail block"); 1543 return 0; 1544 1545 default: 1546 break; 1547 } 1548 1549 if (!PP->getPreprocessingRecord()) { 1550 Error("no preprocessing record"); 1551 return 0; 1552 } 1553 1554 // Read the record. 1555 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord(); 1556 const char *BlobStart = 0; 1557 unsigned BlobLen = 0; 1558 RecordData Record; 1559 PreprocessorDetailRecordTypes RecType = 1560 (PreprocessorDetailRecordTypes)F.PreprocessorDetailCursor.ReadRecord( 1561 Code, Record, BlobStart, BlobLen); 1562 switch (RecType) { 1563 case PPD_MACRO_EXPANSION: { 1564 if (PreprocessedEntity *PE = PPRec.getPreprocessedEntity(Record[0])) 1565 return PE; 1566 1567 MacroExpansion *ME = 1568 new (PPRec) MacroExpansion(DecodeIdentifierInfo(Record[3]), 1569 SourceRange(ReadSourceLocation(F, Record[1]), 1570 ReadSourceLocation(F, Record[2])), 1571 getMacroDefinition(Record[4])); 1572 PPRec.SetPreallocatedEntity(Record[0], ME); 1573 return ME; 1574 } 1575 1576 case PPD_MACRO_DEFINITION: { 1577 if (PreprocessedEntity *PE = PPRec.getPreprocessedEntity(Record[0])) 1578 return PE; 1579 1580 if (Record[1] > MacroDefinitionsLoaded.size()) { 1581 Error("out-of-bounds macro definition record"); 1582 return 0; 1583 } 1584 1585 // Decode the identifier info and then check again; if the macro is 1586 // still defined and associated with the identifier, 1587 IdentifierInfo *II = DecodeIdentifierInfo(Record[4]); 1588 if (!MacroDefinitionsLoaded[Record[1] - 1]) { 1589 MacroDefinition *MD 1590 = new (PPRec) MacroDefinition(II, 1591 ReadSourceLocation(F, Record[5]), 1592 SourceRange( 1593 ReadSourceLocation(F, Record[2]), 1594 ReadSourceLocation(F, Record[3]))); 1595 1596 PPRec.SetPreallocatedEntity(Record[0], MD); 1597 MacroDefinitionsLoaded[Record[1] - 1] = MD; 1598 1599 if (DeserializationListener) 1600 DeserializationListener->MacroDefinitionRead(Record[1], MD); 1601 } 1602 1603 return MacroDefinitionsLoaded[Record[1] - 1]; 1604 } 1605 1606 case PPD_INCLUSION_DIRECTIVE: { 1607 if (PreprocessedEntity *PE = PPRec.getPreprocessedEntity(Record[0])) 1608 return PE; 1609 1610 const char *FullFileNameStart = BlobStart + Record[3]; 1611 const FileEntry *File 1612 = PP->getFileManager().getFile(llvm::StringRef(FullFileNameStart, 1613 BlobLen - Record[3])); 1614 1615 // FIXME: Stable encoding 1616 InclusionDirective::InclusionKind Kind 1617 = static_cast<InclusionDirective::InclusionKind>(Record[5]); 1618 InclusionDirective *ID 1619 = new (PPRec) InclusionDirective(PPRec, Kind, 1620 llvm::StringRef(BlobStart, Record[3]), 1621 Record[4], 1622 File, 1623 SourceRange(ReadSourceLocation(F, Record[1]), 1624 ReadSourceLocation(F, Record[2]))); 1625 PPRec.SetPreallocatedEntity(Record[0], ID); 1626 return ID; 1627 } 1628 } 1629 1630 Error("invalid offset in preprocessor detail block"); 1631 return 0; 1632 } 1633 1634 namespace { 1635 /// \brief Trait class used to search the on-disk hash table containing all of 1636 /// the header search information. 1637 /// 1638 /// The on-disk hash table contains a mapping from each header path to 1639 /// information about that header (how many times it has been included, its 1640 /// controlling macro, etc.). Note that we actually hash based on the 1641 /// filename, and support "deep" comparisons of file names based on current 1642 /// inode numbers, so that the search can cope with non-normalized path names 1643 /// and symlinks. 1644 class HeaderFileInfoTrait { 1645 const char *SearchPath; 1646 struct stat SearchPathStatBuf; 1647 llvm::Optional<int> SearchPathStatResult; 1648 1649 int StatSimpleCache(const char *Path, struct stat *StatBuf) { 1650 if (Path == SearchPath) { 1651 if (!SearchPathStatResult) 1652 SearchPathStatResult = stat(Path, &SearchPathStatBuf); 1653 1654 *StatBuf = SearchPathStatBuf; 1655 return *SearchPathStatResult; 1656 } 1657 1658 return stat(Path, StatBuf); 1659 } 1660 1661 public: 1662 typedef const char *external_key_type; 1663 typedef const char *internal_key_type; 1664 1665 typedef HeaderFileInfo data_type; 1666 1667 HeaderFileInfoTrait(const char *SearchPath = 0) : SearchPath(SearchPath) { } 1668 1669 static unsigned ComputeHash(const char *path) { 1670 return llvm::HashString(llvm::sys::path::filename(path)); 1671 } 1672 1673 static internal_key_type GetInternalKey(const char *path) { return path; } 1674 1675 bool EqualKey(internal_key_type a, internal_key_type b) { 1676 if (strcmp(a, b) == 0) 1677 return true; 1678 1679 if (llvm::sys::path::filename(a) != llvm::sys::path::filename(b)) 1680 return false; 1681 1682 // The file names match, but the path names don't. stat() the files to 1683 // see if they are the same. 1684 struct stat StatBufA, StatBufB; 1685 if (StatSimpleCache(a, &StatBufA) || StatSimpleCache(b, &StatBufB)) 1686 return false; 1687 1688 return StatBufA.st_ino == StatBufB.st_ino; 1689 } 1690 1691 static std::pair<unsigned, unsigned> 1692 ReadKeyDataLength(const unsigned char*& d) { 1693 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d); 1694 unsigned DataLen = (unsigned) *d++; 1695 return std::make_pair(KeyLen + 1, DataLen); 1696 } 1697 1698 static internal_key_type ReadKey(const unsigned char *d, unsigned) { 1699 return (const char *)d; 1700 } 1701 1702 static data_type ReadData(const internal_key_type, const unsigned char *d, 1703 unsigned DataLen) { 1704 const unsigned char *End = d + DataLen; 1705 using namespace clang::io; 1706 HeaderFileInfo HFI; 1707 unsigned Flags = *d++; 1708 HFI.isImport = (Flags >> 4) & 0x01; 1709 HFI.isPragmaOnce = (Flags >> 3) & 0x01; 1710 HFI.DirInfo = (Flags >> 1) & 0x03; 1711 HFI.Resolved = Flags & 0x01; 1712 HFI.NumIncludes = ReadUnalignedLE16(d); 1713 HFI.ControllingMacroID = ReadUnalignedLE32(d); 1714 assert(End == d && "Wrong data length in HeaderFileInfo deserialization"); 1715 (void)End; 1716 1717 // This HeaderFileInfo was externally loaded. 1718 HFI.External = true; 1719 return HFI; 1720 } 1721 }; 1722 } 1723 1724 /// \brief The on-disk hash table used for the global method pool. 1725 typedef OnDiskChainedHashTable<HeaderFileInfoTrait> 1726 HeaderFileInfoLookupTable; 1727 1728 void ASTReader::SetIdentifierIsMacro(IdentifierInfo *II, PerFileData &F, 1729 uint64_t Offset) { 1730 // Note that this identifier has a macro definition. 1731 II->setHasMacroDefinition(true); 1732 1733 // Adjust the offset based on our position in the chain. 1734 for (unsigned I = 0, N = Chain.size(); I != N; ++I) { 1735 if (Chain[I] == &F) 1736 break; 1737 1738 Offset += Chain[I]->SizeInBits; 1739 } 1740 1741 UnreadMacroRecordOffsets[II] = Offset; 1742 } 1743 1744 void ASTReader::ReadDefinedMacros() { 1745 for (unsigned I = 0, N = Chain.size(); I != N; ++I) { 1746 PerFileData &F = *Chain[N - I - 1]; 1747 llvm::BitstreamCursor &MacroCursor = F.MacroCursor; 1748 1749 // If there was no preprocessor block, skip this file. 1750 if (!MacroCursor.getBitStreamReader()) 1751 continue; 1752 1753 llvm::BitstreamCursor Cursor = MacroCursor; 1754 Cursor.JumpToBit(F.MacroStartOffset); 1755 1756 RecordData Record; 1757 while (true) { 1758 unsigned Code = Cursor.ReadCode(); 1759 if (Code == llvm::bitc::END_BLOCK) 1760 break; 1761 1762 if (Code == llvm::bitc::ENTER_SUBBLOCK) { 1763 // No known subblocks, always skip them. 1764 Cursor.ReadSubBlockID(); 1765 if (Cursor.SkipBlock()) { 1766 Error("malformed block record in AST file"); 1767 return; 1768 } 1769 continue; 1770 } 1771 1772 if (Code == llvm::bitc::DEFINE_ABBREV) { 1773 Cursor.ReadAbbrevRecord(); 1774 continue; 1775 } 1776 1777 // Read a record. 1778 const char *BlobStart; 1779 unsigned BlobLen; 1780 Record.clear(); 1781 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) { 1782 default: // Default behavior: ignore. 1783 break; 1784 1785 case PP_MACRO_OBJECT_LIKE: 1786 case PP_MACRO_FUNCTION_LIKE: 1787 DecodeIdentifierInfo(Record[0]); 1788 break; 1789 1790 case PP_TOKEN: 1791 // Ignore tokens. 1792 break; 1793 } 1794 } 1795 } 1796 1797 // Drain the unread macro-record offsets map. 1798 while (!UnreadMacroRecordOffsets.empty()) 1799 LoadMacroDefinition(UnreadMacroRecordOffsets.begin()); 1800 } 1801 1802 void ASTReader::LoadMacroDefinition( 1803 llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos) { 1804 assert(Pos != UnreadMacroRecordOffsets.end() && "Unknown macro definition"); 1805 PerFileData *F = 0; 1806 uint64_t Offset = Pos->second; 1807 UnreadMacroRecordOffsets.erase(Pos); 1808 1809 for (unsigned I = 0, N = Chain.size(); I != N; ++I) { 1810 if (Offset < Chain[I]->SizeInBits) { 1811 F = Chain[I]; 1812 break; 1813 } 1814 1815 Offset -= Chain[I]->SizeInBits; 1816 } 1817 if (!F) { 1818 Error("Malformed macro record offset"); 1819 return; 1820 } 1821 1822 ReadMacroRecord(*F, Offset); 1823 } 1824 1825 void ASTReader::LoadMacroDefinition(IdentifierInfo *II) { 1826 llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos 1827 = UnreadMacroRecordOffsets.find(II); 1828 LoadMacroDefinition(Pos); 1829 } 1830 1831 MacroDefinition *ASTReader::getMacroDefinition(MacroID ID) { 1832 if (ID == 0 || ID > MacroDefinitionsLoaded.size()) 1833 return 0; 1834 1835 if (!MacroDefinitionsLoaded[ID - 1]) { 1836 GlobalMacroDefinitionMapType::iterator I =GlobalMacroDefinitionMap.find(ID); 1837 assert(I != GlobalMacroDefinitionMap.end() && 1838 "Corrupted global macro definition map"); 1839 PerFileData &F = *I->second.first; 1840 unsigned Index = ID - 1 + I->second.second; 1841 SavedStreamPosition SavedPosition(F.PreprocessorDetailCursor); 1842 F.PreprocessorDetailCursor.JumpToBit(F.MacroDefinitionOffsets[Index]); 1843 LoadPreprocessedEntity(F); 1844 } 1845 1846 return MacroDefinitionsLoaded[ID - 1]; 1847 } 1848 1849 const FileEntry *ASTReader::getFileEntry(llvm::StringRef filenameStrRef) { 1850 std::string Filename = filenameStrRef; 1851 MaybeAddSystemRootToFilename(Filename); 1852 const FileEntry *File = FileMgr.getFile(Filename); 1853 if (File == 0 && !OriginalDir.empty() && !CurrentDir.empty() && 1854 OriginalDir != CurrentDir) { 1855 std::string resolved = resolveFileRelativeToOriginalDir(Filename, 1856 OriginalDir, 1857 CurrentDir); 1858 if (!resolved.empty()) 1859 File = FileMgr.getFile(resolved); 1860 } 1861 1862 return File; 1863 } 1864 1865 /// \brief If we are loading a relocatable PCH file, and the filename is 1866 /// not an absolute path, add the system root to the beginning of the file 1867 /// name. 1868 void ASTReader::MaybeAddSystemRootToFilename(std::string &Filename) { 1869 // If this is not a relocatable PCH file, there's nothing to do. 1870 if (!RelocatablePCH) 1871 return; 1872 1873 if (Filename.empty() || llvm::sys::path::is_absolute(Filename)) 1874 return; 1875 1876 if (isysroot == 0) { 1877 // If no system root was given, default to '/' 1878 Filename.insert(Filename.begin(), '/'); 1879 return; 1880 } 1881 1882 unsigned Length = strlen(isysroot); 1883 if (isysroot[Length - 1] != '/') 1884 Filename.insert(Filename.begin(), '/'); 1885 1886 Filename.insert(Filename.begin(), isysroot, isysroot + Length); 1887 } 1888 1889 ASTReader::ASTReadResult 1890 ASTReader::ReadASTBlock(PerFileData &F) { 1891 llvm::BitstreamCursor &Stream = F.Stream; 1892 1893 if (Stream.EnterSubBlock(AST_BLOCK_ID)) { 1894 Error("malformed block record in AST file"); 1895 return Failure; 1896 } 1897 1898 // Read all of the records and blocks for the ASt file. 1899 RecordData Record; 1900 bool First = true; 1901 while (!Stream.AtEndOfStream()) { 1902 unsigned Code = Stream.ReadCode(); 1903 if (Code == llvm::bitc::END_BLOCK) { 1904 if (Stream.ReadBlockEnd()) { 1905 Error("error at end of module block in AST file"); 1906 return Failure; 1907 } 1908 1909 return Success; 1910 } 1911 1912 if (Code == llvm::bitc::ENTER_SUBBLOCK) { 1913 switch (Stream.ReadSubBlockID()) { 1914 case DECLTYPES_BLOCK_ID: 1915 // We lazily load the decls block, but we want to set up the 1916 // DeclsCursor cursor to point into it. Clone our current bitcode 1917 // cursor to it, enter the block and read the abbrevs in that block. 1918 // With the main cursor, we just skip over it. 1919 F.DeclsCursor = Stream; 1920 if (Stream.SkipBlock() || // Skip with the main cursor. 1921 // Read the abbrevs. 1922 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) { 1923 Error("malformed block record in AST file"); 1924 return Failure; 1925 } 1926 break; 1927 1928 case DECL_UPDATES_BLOCK_ID: 1929 if (Stream.SkipBlock()) { 1930 Error("malformed block record in AST file"); 1931 return Failure; 1932 } 1933 break; 1934 1935 case PREPROCESSOR_BLOCK_ID: 1936 F.MacroCursor = Stream; 1937 if (PP) 1938 PP->setExternalSource(this); 1939 1940 if (Stream.SkipBlock() || 1941 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) { 1942 Error("malformed block record in AST file"); 1943 return Failure; 1944 } 1945 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo(); 1946 break; 1947 1948 case PREPROCESSOR_DETAIL_BLOCK_ID: 1949 F.PreprocessorDetailCursor = Stream; 1950 if (Stream.SkipBlock() || 1951 ReadBlockAbbrevs(F.PreprocessorDetailCursor, 1952 PREPROCESSOR_DETAIL_BLOCK_ID)) { 1953 Error("malformed preprocessor detail record in AST file"); 1954 return Failure; 1955 } 1956 F.PreprocessorDetailStartOffset 1957 = F.PreprocessorDetailCursor.GetCurrentBitNo(); 1958 break; 1959 1960 case SOURCE_MANAGER_BLOCK_ID: 1961 switch (ReadSourceManagerBlock(F)) { 1962 case Success: 1963 break; 1964 1965 case Failure: 1966 Error("malformed source manager block in AST file"); 1967 return Failure; 1968 1969 case IgnorePCH: 1970 return IgnorePCH; 1971 } 1972 break; 1973 } 1974 First = false; 1975 continue; 1976 } 1977 1978 if (Code == llvm::bitc::DEFINE_ABBREV) { 1979 Stream.ReadAbbrevRecord(); 1980 continue; 1981 } 1982 1983 // Read and process a record. 1984 Record.clear(); 1985 const char *BlobStart = 0; 1986 unsigned BlobLen = 0; 1987 switch ((ASTRecordTypes)Stream.ReadRecord(Code, Record, 1988 &BlobStart, &BlobLen)) { 1989 default: // Default behavior: ignore. 1990 break; 1991 1992 case METADATA: { 1993 if (Record[0] != VERSION_MAJOR && !DisableValidation) { 1994 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old 1995 : diag::warn_pch_version_too_new); 1996 return IgnorePCH; 1997 } 1998 1999 RelocatablePCH = Record[4]; 2000 if (Listener) { 2001 std::string TargetTriple(BlobStart, BlobLen); 2002 if (Listener->ReadTargetTriple(TargetTriple)) 2003 return IgnorePCH; 2004 } 2005 break; 2006 } 2007 2008 case CHAINED_METADATA: { 2009 if (!First) { 2010 Error("CHAINED_METADATA is not first record in block"); 2011 return Failure; 2012 } 2013 if (Record[0] != VERSION_MAJOR && !DisableValidation) { 2014 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old 2015 : diag::warn_pch_version_too_new); 2016 return IgnorePCH; 2017 } 2018 2019 // Load the chained file, which is always a PCH file. 2020 switch(ReadASTCore(llvm::StringRef(BlobStart, BlobLen), PCH)) { 2021 case Failure: return Failure; 2022 // If we have to ignore the dependency, we'll have to ignore this too. 2023 case IgnorePCH: return IgnorePCH; 2024 case Success: break; 2025 } 2026 break; 2027 } 2028 2029 case TYPE_OFFSET: 2030 if (F.LocalNumTypes != 0) { 2031 Error("duplicate TYPE_OFFSET record in AST file"); 2032 return Failure; 2033 } 2034 F.TypeOffsets = (const uint32_t *)BlobStart; 2035 F.LocalNumTypes = Record[0]; 2036 break; 2037 2038 case DECL_OFFSET: 2039 if (F.LocalNumDecls != 0) { 2040 Error("duplicate DECL_OFFSET record in AST file"); 2041 return Failure; 2042 } 2043 F.DeclOffsets = (const uint32_t *)BlobStart; 2044 F.LocalNumDecls = Record[0]; 2045 2046 // Introduce the global -> local mapping for declarations within this 2047 // AST file. 2048 GlobalDeclMap.insert(std::make_pair(getTotalNumDecls() + 1, 2049 std::make_pair(&F, 2050 -getTotalNumDecls()))); 2051 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls); 2052 break; 2053 2054 case TU_UPDATE_LEXICAL: { 2055 DeclContextInfo Info = { 2056 /* No visible information */ 0, 2057 reinterpret_cast<const KindDeclIDPair *>(BlobStart), 2058 BlobLen / sizeof(KindDeclIDPair) 2059 }; 2060 DeclContextOffsets[Context ? Context->getTranslationUnitDecl() : 0] 2061 .push_back(Info); 2062 break; 2063 } 2064 2065 case UPDATE_VISIBLE: { 2066 serialization::DeclID ID = Record[0]; 2067 void *Table = ASTDeclContextNameLookupTable::Create( 2068 (const unsigned char *)BlobStart + Record[1], 2069 (const unsigned char *)BlobStart, 2070 ASTDeclContextNameLookupTrait(*this)); 2071 if (ID == 1 && Context) { // Is it the TU? 2072 DeclContextInfo Info = { 2073 Table, /* No lexical inforamtion */ 0, 0 2074 }; 2075 DeclContextOffsets[Context->getTranslationUnitDecl()].push_back(Info); 2076 } else 2077 PendingVisibleUpdates[ID].push_back(Table); 2078 break; 2079 } 2080 2081 case REDECLS_UPDATE_LATEST: { 2082 assert(Record.size() % 2 == 0 && "Expected pairs of DeclIDs"); 2083 for (unsigned i = 0, e = Record.size(); i < e; i += 2) { 2084 DeclID First = Record[i], Latest = Record[i+1]; 2085 assert((FirstLatestDeclIDs.find(First) == FirstLatestDeclIDs.end() || 2086 Latest > FirstLatestDeclIDs[First]) && 2087 "The new latest is supposed to come after the previous latest"); 2088 FirstLatestDeclIDs[First] = Latest; 2089 } 2090 break; 2091 } 2092 2093 case LANGUAGE_OPTIONS: 2094 if (ParseLanguageOptions(Record) && !DisableValidation) 2095 return IgnorePCH; 2096 break; 2097 2098 case IDENTIFIER_TABLE: 2099 F.IdentifierTableData = BlobStart; 2100 if (Record[0]) { 2101 F.IdentifierLookupTable 2102 = ASTIdentifierLookupTable::Create( 2103 (const unsigned char *)F.IdentifierTableData + Record[0], 2104 (const unsigned char *)F.IdentifierTableData, 2105 ASTIdentifierLookupTrait(*this, F)); 2106 if (PP) 2107 PP->getIdentifierTable().setExternalIdentifierLookup(this); 2108 } 2109 break; 2110 2111 case IDENTIFIER_OFFSET: 2112 if (F.LocalNumIdentifiers != 0) { 2113 Error("duplicate IDENTIFIER_OFFSET record in AST file"); 2114 return Failure; 2115 } 2116 F.IdentifierOffsets = (const uint32_t *)BlobStart; 2117 F.LocalNumIdentifiers = Record[0]; 2118 2119 // Introduce the global -> local mapping for identifiers within this AST 2120 // file 2121 GlobalIdentifierMap.insert( 2122 std::make_pair(getTotalNumIdentifiers() + 1, 2123 std::make_pair(&F, 2124 -getTotalNumIdentifiers()))); 2125 IdentifiersLoaded.resize(IdentifiersLoaded.size() +F.LocalNumIdentifiers); 2126 break; 2127 2128 case EXTERNAL_DEFINITIONS: 2129 // Optimization for the first block. 2130 if (ExternalDefinitions.empty()) 2131 ExternalDefinitions.swap(Record); 2132 else 2133 ExternalDefinitions.insert(ExternalDefinitions.end(), 2134 Record.begin(), Record.end()); 2135 break; 2136 2137 case SPECIAL_TYPES: 2138 // Optimization for the first block 2139 if (SpecialTypes.empty()) 2140 SpecialTypes.swap(Record); 2141 else 2142 SpecialTypes.insert(SpecialTypes.end(), Record.begin(), Record.end()); 2143 break; 2144 2145 case STATISTICS: 2146 TotalNumStatements += Record[0]; 2147 TotalNumMacros += Record[1]; 2148 TotalLexicalDeclContexts += Record[2]; 2149 TotalVisibleDeclContexts += Record[3]; 2150 break; 2151 2152 case UNUSED_FILESCOPED_DECLS: 2153 // Optimization for the first block. 2154 if (UnusedFileScopedDecls.empty()) 2155 UnusedFileScopedDecls.swap(Record); 2156 else 2157 UnusedFileScopedDecls.insert(UnusedFileScopedDecls.end(), 2158 Record.begin(), Record.end()); 2159 break; 2160 2161 case DELEGATING_CTORS: 2162 // Optimization for the first block. 2163 if (DelegatingCtorDecls.empty()) 2164 DelegatingCtorDecls.swap(Record); 2165 else 2166 DelegatingCtorDecls.insert(DelegatingCtorDecls.end(), 2167 Record.begin(), Record.end()); 2168 break; 2169 2170 case WEAK_UNDECLARED_IDENTIFIERS: 2171 // Later blocks overwrite earlier ones. 2172 WeakUndeclaredIdentifiers.swap(Record); 2173 break; 2174 2175 case LOCALLY_SCOPED_EXTERNAL_DECLS: 2176 // Optimization for the first block. 2177 if (LocallyScopedExternalDecls.empty()) 2178 LocallyScopedExternalDecls.swap(Record); 2179 else 2180 LocallyScopedExternalDecls.insert(LocallyScopedExternalDecls.end(), 2181 Record.begin(), Record.end()); 2182 break; 2183 2184 case SELECTOR_OFFSETS: 2185 F.SelectorOffsets = (const uint32_t *)BlobStart; 2186 F.LocalNumSelectors = Record[0]; 2187 2188 // Introduce the global -> local mapping for identifiers within this AST 2189 // file 2190 GlobalSelectorMap.insert( 2191 std::make_pair(getTotalNumSelectors() + 1, 2192 std::make_pair(&F, 2193 -getTotalNumSelectors()))); 2194 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors); 2195 break; 2196 2197 case METHOD_POOL: 2198 F.SelectorLookupTableData = (const unsigned char *)BlobStart; 2199 if (Record[0]) 2200 F.SelectorLookupTable 2201 = ASTSelectorLookupTable::Create( 2202 F.SelectorLookupTableData + Record[0], 2203 F.SelectorLookupTableData, 2204 ASTSelectorLookupTrait(*this)); 2205 TotalNumMethodPoolEntries += Record[1]; 2206 break; 2207 2208 case REFERENCED_SELECTOR_POOL: 2209 F.ReferencedSelectorsData.swap(Record); 2210 break; 2211 2212 case PP_COUNTER_VALUE: 2213 if (!Record.empty() && Listener) 2214 Listener->ReadCounter(Record[0]); 2215 break; 2216 2217 case SOURCE_LOCATION_OFFSETS: { 2218 F.SLocEntryOffsets = (const uint32_t *)BlobStart; 2219 F.LocalNumSLocEntries = Record[0]; 2220 llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) = 2221 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries, Record[1]); 2222 // Make our entry in the range map. BaseID is negative and growing, so 2223 // we invert it. Because we invert it, though, we need the other end of 2224 // the range. 2225 unsigned RangeStart = 2226 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1; 2227 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F)); 2228 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset); 2229 2230 // Initialize the remapping table. 2231 // Invalid stays invalid. 2232 F.SLocRemap.insert(std::make_pair(0U, 0)); 2233 // This module. Base was 2 when being compiled. 2234 F.SLocRemap.insert(std::make_pair(2U, 2235 static_cast<int>(F.SLocEntryBaseOffset - 2))); 2236 break; 2237 } 2238 2239 case SOURCE_LOCATION_MAP: { 2240 // Additional remapping information. 2241 const unsigned char *Data = (const unsigned char*)BlobStart; 2242 const unsigned char *DataEnd = Data + BlobLen; 2243 while(Data < DataEnd) { 2244 uint32_t Offset = io::ReadUnalignedLE32(Data); 2245 uint16_t Len = io::ReadUnalignedLE16(Data); 2246 llvm::StringRef Name = llvm::StringRef((const char*)Data, Len); 2247 PerFileData *OM = Modules.lookup(Name); 2248 if (!OM) { 2249 Error("SourceLocation remap refers to unknown module"); 2250 return Failure; 2251 } 2252 // My Offset is mapped to OM->SLocEntryBaseOffset. 2253 F.SLocRemap.insert(std::make_pair(Offset, 2254 static_cast<int>(OM->SLocEntryBaseOffset - Offset))); 2255 Data += Len; 2256 } 2257 break; 2258 } 2259 2260 2261 case SOURCE_MANAGER_LINE_TABLE: 2262 if (ParseLineTable(F, Record)) 2263 return Failure; 2264 break; 2265 2266 case FILE_SOURCE_LOCATION_OFFSETS: 2267 F.SLocFileOffsets = (const uint32_t *)BlobStart; 2268 F.LocalNumSLocFileEntries = Record[0]; 2269 break; 2270 2271 case SOURCE_LOCATION_PRELOADS: { 2272 // Need to transform from the local view (1-based IDs) to the global view, 2273 // which is based off F.SLocEntryBaseID. 2274 PreloadSLocEntries.reserve(PreloadSLocEntries.size() + Record.size()); 2275 for (unsigned I = 0, N = Record.size(); I != N; ++I) 2276 PreloadSLocEntries.push_back(int(Record[I] - 1) + F.SLocEntryBaseID); 2277 break; 2278 } 2279 2280 case STAT_CACHE: { 2281 if (!DisableStatCache) { 2282 ASTStatCache *MyStatCache = 2283 new ASTStatCache((const unsigned char *)BlobStart + Record[0], 2284 (const unsigned char *)BlobStart, 2285 NumStatHits, NumStatMisses); 2286 FileMgr.addStatCache(MyStatCache); 2287 F.StatCache = MyStatCache; 2288 } 2289 break; 2290 } 2291 2292 case EXT_VECTOR_DECLS: 2293 // Optimization for the first block. 2294 if (ExtVectorDecls.empty()) 2295 ExtVectorDecls.swap(Record); 2296 else 2297 ExtVectorDecls.insert(ExtVectorDecls.end(), 2298 Record.begin(), Record.end()); 2299 break; 2300 2301 case VTABLE_USES: 2302 // Later tables overwrite earlier ones. 2303 VTableUses.swap(Record); 2304 break; 2305 2306 case DYNAMIC_CLASSES: 2307 // Optimization for the first block. 2308 if (DynamicClasses.empty()) 2309 DynamicClasses.swap(Record); 2310 else 2311 DynamicClasses.insert(DynamicClasses.end(), 2312 Record.begin(), Record.end()); 2313 break; 2314 2315 case PENDING_IMPLICIT_INSTANTIATIONS: 2316 F.PendingInstantiations.swap(Record); 2317 break; 2318 2319 case SEMA_DECL_REFS: 2320 // Later tables overwrite earlier ones. 2321 SemaDeclRefs.swap(Record); 2322 break; 2323 2324 case ORIGINAL_FILE_NAME: 2325 // The primary AST will be the last to get here, so it will be the one 2326 // that's used. 2327 ActualOriginalFileName.assign(BlobStart, BlobLen); 2328 OriginalFileName = ActualOriginalFileName; 2329 MaybeAddSystemRootToFilename(OriginalFileName); 2330 break; 2331 2332 case ORIGINAL_FILE_ID: 2333 OriginalFileID = FileID::get(Record[0]); 2334 break; 2335 2336 case ORIGINAL_PCH_DIR: 2337 // The primary AST will be the last to get here, so it will be the one 2338 // that's used. 2339 OriginalDir.assign(BlobStart, BlobLen); 2340 break; 2341 2342 case VERSION_CONTROL_BRANCH_REVISION: { 2343 const std::string &CurBranch = getClangFullRepositoryVersion(); 2344 llvm::StringRef ASTBranch(BlobStart, BlobLen); 2345 if (llvm::StringRef(CurBranch) != ASTBranch && !DisableValidation) { 2346 Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch; 2347 return IgnorePCH; 2348 } 2349 break; 2350 } 2351 2352 case MACRO_DEFINITION_OFFSETS: 2353 F.MacroDefinitionOffsets = (const uint32_t *)BlobStart; 2354 F.NumPreallocatedPreprocessingEntities = Record[0]; 2355 F.LocalNumMacroDefinitions = Record[1]; 2356 2357 // Introduce the global -> local mapping for identifiers within this AST 2358 // file 2359 GlobalMacroDefinitionMap.insert( 2360 std::make_pair(getTotalNumMacroDefinitions() + 1, 2361 std::make_pair(&F, 2362 -getTotalNumMacroDefinitions()))); 2363 MacroDefinitionsLoaded.resize( 2364 MacroDefinitionsLoaded.size() + F.LocalNumMacroDefinitions); 2365 2366 break; 2367 2368 case DECL_UPDATE_OFFSETS: { 2369 if (Record.size() % 2 != 0) { 2370 Error("invalid DECL_UPDATE_OFFSETS block in AST file"); 2371 return Failure; 2372 } 2373 for (unsigned I = 0, N = Record.size(); I != N; I += 2) 2374 DeclUpdateOffsets[static_cast<DeclID>(Record[I])] 2375 .push_back(std::make_pair(&F, Record[I+1])); 2376 break; 2377 } 2378 2379 case DECL_REPLACEMENTS: { 2380 if (Record.size() % 2 != 0) { 2381 Error("invalid DECL_REPLACEMENTS block in AST file"); 2382 return Failure; 2383 } 2384 for (unsigned I = 0, N = Record.size(); I != N; I += 2) 2385 ReplacedDecls[static_cast<DeclID>(Record[I])] = 2386 std::make_pair(&F, Record[I+1]); 2387 break; 2388 } 2389 2390 case CXX_BASE_SPECIFIER_OFFSETS: { 2391 if (F.LocalNumCXXBaseSpecifiers != 0) { 2392 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file"); 2393 return Failure; 2394 } 2395 2396 F.LocalNumCXXBaseSpecifiers = Record[0]; 2397 F.CXXBaseSpecifiersOffsets = (const uint32_t *)BlobStart; 2398 break; 2399 } 2400 2401 case DIAG_PRAGMA_MAPPINGS: 2402 if (Record.size() % 2 != 0) { 2403 Error("invalid DIAG_USER_MAPPINGS block in AST file"); 2404 return Failure; 2405 } 2406 2407 if (F.PragmaDiagMappings.empty()) 2408 F.PragmaDiagMappings.swap(Record); 2409 else 2410 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(), 2411 Record.begin(), Record.end()); 2412 break; 2413 2414 case CUDA_SPECIAL_DECL_REFS: 2415 // Later tables overwrite earlier ones. 2416 CUDASpecialDeclRefs.swap(Record); 2417 break; 2418 2419 case HEADER_SEARCH_TABLE: 2420 F.HeaderFileInfoTableData = BlobStart; 2421 F.LocalNumHeaderFileInfos = Record[1]; 2422 if (Record[0]) { 2423 F.HeaderFileInfoTable 2424 = HeaderFileInfoLookupTable::Create( 2425 (const unsigned char *)F.HeaderFileInfoTableData + Record[0], 2426 (const unsigned char *)F.HeaderFileInfoTableData); 2427 if (PP) 2428 PP->getHeaderSearchInfo().SetExternalSource(this); 2429 } 2430 break; 2431 2432 case FP_PRAGMA_OPTIONS: 2433 // Later tables overwrite earlier ones. 2434 FPPragmaOptions.swap(Record); 2435 break; 2436 2437 case OPENCL_EXTENSIONS: 2438 // Later tables overwrite earlier ones. 2439 OpenCLExtensions.swap(Record); 2440 break; 2441 2442 case TENTATIVE_DEFINITIONS: 2443 // Optimization for the first block. 2444 if (TentativeDefinitions.empty()) 2445 TentativeDefinitions.swap(Record); 2446 else 2447 TentativeDefinitions.insert(TentativeDefinitions.end(), 2448 Record.begin(), Record.end()); 2449 break; 2450 2451 case KNOWN_NAMESPACES: 2452 // Optimization for the first block. 2453 if (KnownNamespaces.empty()) 2454 KnownNamespaces.swap(Record); 2455 else 2456 KnownNamespaces.insert(KnownNamespaces.end(), 2457 Record.begin(), Record.end()); 2458 break; 2459 } 2460 First = false; 2461 } 2462 Error("premature end of bitstream in AST file"); 2463 return Failure; 2464 } 2465 2466 ASTReader::ASTReadResult ASTReader::validateFileEntries() { 2467 for (unsigned CI = 0, CN = Chain.size(); CI != CN; ++CI) { 2468 PerFileData *F = Chain[CI]; 2469 llvm::BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor; 2470 2471 for (unsigned i = 0, e = F->LocalNumSLocFileEntries; i != e; ++i) { 2472 SLocEntryCursor.JumpToBit(F->SLocFileOffsets[i]); 2473 unsigned Code = SLocEntryCursor.ReadCode(); 2474 if (Code == llvm::bitc::END_BLOCK || 2475 Code == llvm::bitc::ENTER_SUBBLOCK || 2476 Code == llvm::bitc::DEFINE_ABBREV) { 2477 Error("incorrectly-formatted source location entry in AST file"); 2478 return Failure; 2479 } 2480 2481 RecordData Record; 2482 const char *BlobStart; 2483 unsigned BlobLen; 2484 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) { 2485 default: 2486 Error("incorrectly-formatted source location entry in AST file"); 2487 return Failure; 2488 2489 case SM_SLOC_FILE_ENTRY: { 2490 llvm::StringRef Filename(BlobStart, BlobLen); 2491 const FileEntry *File = getFileEntry(Filename); 2492 2493 if (File == 0) { 2494 std::string ErrorStr = "could not find file '"; 2495 ErrorStr += Filename; 2496 ErrorStr += "' referenced by AST file"; 2497 Error(ErrorStr.c_str()); 2498 return IgnorePCH; 2499 } 2500 2501 if (Record.size() < 6) { 2502 Error("source location entry is incorrect"); 2503 return Failure; 2504 } 2505 2506 // The stat info from the FileEntry came from the cached stat 2507 // info of the PCH, so we cannot trust it. 2508 struct stat StatBuf; 2509 if (::stat(File->getName(), &StatBuf) != 0) { 2510 StatBuf.st_size = File->getSize(); 2511 StatBuf.st_mtime = File->getModificationTime(); 2512 } 2513 2514 if (((off_t)Record[4] != StatBuf.st_size 2515 #if !defined(LLVM_ON_WIN32) 2516 // In our regression testing, the Windows file system seems to 2517 // have inconsistent modification times that sometimes 2518 // erroneously trigger this error-handling path. 2519 || (time_t)Record[5] != StatBuf.st_mtime 2520 #endif 2521 )) { 2522 Error(diag::err_fe_pch_file_modified, Filename); 2523 return IgnorePCH; 2524 } 2525 2526 break; 2527 } 2528 } 2529 } 2530 } 2531 2532 return Success; 2533 } 2534 2535 ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName, 2536 ASTFileType Type) { 2537 switch(ReadASTCore(FileName, Type)) { 2538 case Failure: return Failure; 2539 case IgnorePCH: return IgnorePCH; 2540 case Success: break; 2541 } 2542 2543 // Here comes stuff that we only do once the entire chain is loaded. 2544 2545 if (!DisableValidation) { 2546 switch(validateFileEntries()) { 2547 case Failure: return Failure; 2548 case IgnorePCH: return IgnorePCH; 2549 case Success: break; 2550 } 2551 } 2552 2553 // Allocate space for loaded slocentries, identifiers, decls and types. 2554 unsigned TotalNumTypes = 0, TotalNumPreallocatedPreprocessingEntities = 0; 2555 for (unsigned I = 0, N = Chain.size(); I != N; ++I) { 2556 TotalNumSLocEntries += Chain[I]->LocalNumSLocEntries; 2557 TotalNumTypes += Chain[I]->LocalNumTypes; 2558 TotalNumPreallocatedPreprocessingEntities += 2559 Chain[I]->NumPreallocatedPreprocessingEntities; 2560 } 2561 TypesLoaded.resize(TotalNumTypes); 2562 if (PP) { 2563 PP->getHeaderSearchInfo().SetExternalLookup(this); 2564 if (TotalNumPreallocatedPreprocessingEntities > 0) { 2565 if (!PP->getPreprocessingRecord()) 2566 PP->createPreprocessingRecord(true); 2567 PP->getPreprocessingRecord()->SetExternalSource(*this, 2568 TotalNumPreallocatedPreprocessingEntities); 2569 } 2570 } 2571 // Preload SLocEntries. 2572 for (unsigned I = 0, N = PreloadSLocEntries.size(); I != N; ++I) { 2573 ASTReadResult Result = ReadSLocEntryRecord(PreloadSLocEntries[I]); 2574 if (Result != Success) 2575 return Failure; 2576 } 2577 2578 // Check the predefines buffers. 2579 if (!DisableValidation && CheckPredefinesBuffers()) 2580 return IgnorePCH; 2581 2582 if (PP) { 2583 // Initialization of keywords and pragmas occurs before the 2584 // AST file is read, so there may be some identifiers that were 2585 // loaded into the IdentifierTable before we intercepted the 2586 // creation of identifiers. Iterate through the list of known 2587 // identifiers and determine whether we have to establish 2588 // preprocessor definitions or top-level identifier declaration 2589 // chains for those identifiers. 2590 // 2591 // We copy the IdentifierInfo pointers to a small vector first, 2592 // since de-serializing declarations or macro definitions can add 2593 // new entries into the identifier table, invalidating the 2594 // iterators. 2595 llvm::SmallVector<IdentifierInfo *, 128> Identifiers; 2596 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(), 2597 IdEnd = PP->getIdentifierTable().end(); 2598 Id != IdEnd; ++Id) 2599 Identifiers.push_back(Id->second); 2600 // We need to search the tables in all files. 2601 for (unsigned J = 0, M = Chain.size(); J != M; ++J) { 2602 ASTIdentifierLookupTable *IdTable 2603 = (ASTIdentifierLookupTable *)Chain[J]->IdentifierLookupTable; 2604 // Not all AST files necessarily have identifier tables, only the useful 2605 // ones. 2606 if (!IdTable) 2607 continue; 2608 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) { 2609 IdentifierInfo *II = Identifiers[I]; 2610 // Look in the on-disk hash tables for an entry for this identifier 2611 ASTIdentifierLookupTrait Info(*this, *Chain[J], II); 2612 std::pair<const char*,unsigned> Key(II->getNameStart(),II->getLength()); 2613 ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info); 2614 if (Pos == IdTable->end()) 2615 continue; 2616 2617 // Dereferencing the iterator has the effect of populating the 2618 // IdentifierInfo node with the various declarations it needs. 2619 (void)*Pos; 2620 } 2621 } 2622 } 2623 2624 if (Context) 2625 InitializeContext(*Context); 2626 2627 if (DeserializationListener) 2628 DeserializationListener->ReaderInitialized(this); 2629 2630 // If this AST file is a precompiled preamble, then set the main file ID of 2631 // the source manager to the file source file from which the preamble was 2632 // built. This is the only valid way to use a precompiled preamble. 2633 if (Type == Preamble) { 2634 if (OriginalFileID.isInvalid()) { 2635 SourceLocation Loc 2636 = SourceMgr.getLocation(FileMgr.getFile(getOriginalSourceFile()), 1, 1); 2637 if (Loc.isValid()) 2638 OriginalFileID = SourceMgr.getDecomposedLoc(Loc).first; 2639 } 2640 else { 2641 OriginalFileID = FileID::get(Chain[0]->SLocEntryBaseID 2642 + OriginalFileID.getOpaqueValue() - 1); 2643 } 2644 2645 if (!OriginalFileID.isInvalid()) 2646 SourceMgr.SetPreambleFileID(OriginalFileID); 2647 } 2648 2649 return Success; 2650 } 2651 2652 ASTReader::ASTReadResult ASTReader::ReadASTCore(llvm::StringRef FileName, 2653 ASTFileType Type) { 2654 PerFileData *Prev = Chain.empty() ? 0 : Chain.back(); 2655 Chain.push_back(new PerFileData(Type)); 2656 PerFileData &F = *Chain.back(); 2657 if (Prev) 2658 Prev->NextInSource = &F; 2659 else 2660 FirstInSource = &F; 2661 F.Loaders.push_back(Prev); 2662 // A non-module AST file's module name is $filename. 2663 Modules["$" + FileName.str()] = &F; 2664 2665 // Set the AST file name. 2666 F.FileName = FileName; 2667 2668 if (FileName != "-") { 2669 CurrentDir = llvm::sys::path::parent_path(FileName); 2670 if (CurrentDir.empty()) CurrentDir = "."; 2671 } 2672 2673 if (!ASTBuffers.empty()) { 2674 F.Buffer.reset(ASTBuffers.back()); 2675 ASTBuffers.pop_back(); 2676 assert(F.Buffer && "Passed null buffer"); 2677 } else { 2678 // Open the AST file. 2679 // 2680 // FIXME: This shouldn't be here, we should just take a raw_ostream. 2681 std::string ErrStr; 2682 llvm::error_code ec; 2683 if (FileName == "-") { 2684 ec = llvm::MemoryBuffer::getSTDIN(F.Buffer); 2685 if (ec) 2686 ErrStr = ec.message(); 2687 } else 2688 F.Buffer.reset(FileMgr.getBufferForFile(FileName, &ErrStr)); 2689 if (!F.Buffer) { 2690 Error(ErrStr.c_str()); 2691 return IgnorePCH; 2692 } 2693 } 2694 2695 // Initialize the stream 2696 F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(), 2697 (const unsigned char *)F.Buffer->getBufferEnd()); 2698 llvm::BitstreamCursor &Stream = F.Stream; 2699 Stream.init(F.StreamFile); 2700 F.SizeInBits = F.Buffer->getBufferSize() * 8; 2701 2702 // Sniff for the signature. 2703 if (Stream.Read(8) != 'C' || 2704 Stream.Read(8) != 'P' || 2705 Stream.Read(8) != 'C' || 2706 Stream.Read(8) != 'H') { 2707 Diag(diag::err_not_a_pch_file) << FileName; 2708 return Failure; 2709 } 2710 2711 while (!Stream.AtEndOfStream()) { 2712 unsigned Code = Stream.ReadCode(); 2713 2714 if (Code != llvm::bitc::ENTER_SUBBLOCK) { 2715 Error("invalid record at top-level of AST file"); 2716 return Failure; 2717 } 2718 2719 unsigned BlockID = Stream.ReadSubBlockID(); 2720 2721 // We only know the AST subblock ID. 2722 switch (BlockID) { 2723 case llvm::bitc::BLOCKINFO_BLOCK_ID: 2724 if (Stream.ReadBlockInfoBlock()) { 2725 Error("malformed BlockInfoBlock in AST file"); 2726 return Failure; 2727 } 2728 break; 2729 case AST_BLOCK_ID: 2730 switch (ReadASTBlock(F)) { 2731 case Success: 2732 break; 2733 2734 case Failure: 2735 return Failure; 2736 2737 case IgnorePCH: 2738 // FIXME: We could consider reading through to the end of this 2739 // AST block, skipping subblocks, to see if there are other 2740 // AST blocks elsewhere. 2741 2742 // FIXME: We can't clear loaded slocentries anymore. 2743 //SourceMgr.ClearPreallocatedSLocEntries(); 2744 2745 // Remove the stat cache. 2746 if (F.StatCache) 2747 FileMgr.removeStatCache((ASTStatCache*)F.StatCache); 2748 2749 return IgnorePCH; 2750 } 2751 break; 2752 default: 2753 if (Stream.SkipBlock()) { 2754 Error("malformed block record in AST file"); 2755 return Failure; 2756 } 2757 break; 2758 } 2759 } 2760 2761 return Success; 2762 } 2763 2764 void ASTReader::setPreprocessor(Preprocessor &pp) { 2765 PP = &pp; 2766 2767 unsigned TotalNum = 0; 2768 for (unsigned I = 0, N = Chain.size(); I != N; ++I) 2769 TotalNum += Chain[I]->NumPreallocatedPreprocessingEntities; 2770 if (TotalNum) { 2771 if (!PP->getPreprocessingRecord()) 2772 PP->createPreprocessingRecord(true); 2773 PP->getPreprocessingRecord()->SetExternalSource(*this, TotalNum); 2774 } 2775 } 2776 2777 void ASTReader::InitializeContext(ASTContext &Ctx) { 2778 Context = &Ctx; 2779 assert(Context && "Passed null context!"); 2780 2781 assert(PP && "Forgot to set Preprocessor ?"); 2782 PP->getIdentifierTable().setExternalIdentifierLookup(this); 2783 PP->getHeaderSearchInfo().SetExternalLookup(this); 2784 PP->setExternalSource(this); 2785 PP->getHeaderSearchInfo().SetExternalSource(this); 2786 2787 // If we have an update block for the TU waiting, we have to add it before 2788 // deserializing the decl. 2789 DeclContextOffsetsMap::iterator DCU = DeclContextOffsets.find(0); 2790 if (DCU != DeclContextOffsets.end()) { 2791 // Insertion could invalidate map, so grab vector. 2792 DeclContextInfos T; 2793 T.swap(DCU->second); 2794 DeclContextOffsets.erase(DCU); 2795 DeclContextOffsets[Ctx.getTranslationUnitDecl()].swap(T); 2796 } 2797 2798 // Load the translation unit declaration 2799 GetTranslationUnitDecl(); 2800 2801 // Load the special types. 2802 Context->setBuiltinVaListType( 2803 GetType(SpecialTypes[SPECIAL_TYPE_BUILTIN_VA_LIST])); 2804 if (unsigned Id = SpecialTypes[SPECIAL_TYPE_OBJC_ID]) 2805 Context->setObjCIdType(GetType(Id)); 2806 if (unsigned Sel = SpecialTypes[SPECIAL_TYPE_OBJC_SELECTOR]) 2807 Context->setObjCSelType(GetType(Sel)); 2808 if (unsigned Proto = SpecialTypes[SPECIAL_TYPE_OBJC_PROTOCOL]) 2809 Context->setObjCProtoType(GetType(Proto)); 2810 if (unsigned Class = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS]) 2811 Context->setObjCClassType(GetType(Class)); 2812 2813 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) 2814 Context->setCFConstantStringType(GetType(String)); 2815 if (unsigned FastEnum 2816 = SpecialTypes[SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE]) 2817 Context->setObjCFastEnumerationStateType(GetType(FastEnum)); 2818 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) { 2819 QualType FileType = GetType(File); 2820 if (FileType.isNull()) { 2821 Error("FILE type is NULL"); 2822 return; 2823 } 2824 if (const TypedefType *Typedef = FileType->getAs<TypedefType>()) 2825 Context->setFILEDecl(Typedef->getDecl()); 2826 else { 2827 const TagType *Tag = FileType->getAs<TagType>(); 2828 if (!Tag) { 2829 Error("Invalid FILE type in AST file"); 2830 return; 2831 } 2832 Context->setFILEDecl(Tag->getDecl()); 2833 } 2834 } 2835 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_jmp_buf]) { 2836 QualType Jmp_bufType = GetType(Jmp_buf); 2837 if (Jmp_bufType.isNull()) { 2838 Error("jmp_bug type is NULL"); 2839 return; 2840 } 2841 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>()) 2842 Context->setjmp_bufDecl(Typedef->getDecl()); 2843 else { 2844 const TagType *Tag = Jmp_bufType->getAs<TagType>(); 2845 if (!Tag) { 2846 Error("Invalid jmp_buf type in AST file"); 2847 return; 2848 } 2849 Context->setjmp_bufDecl(Tag->getDecl()); 2850 } 2851 } 2852 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_sigjmp_buf]) { 2853 QualType Sigjmp_bufType = GetType(Sigjmp_buf); 2854 if (Sigjmp_bufType.isNull()) { 2855 Error("sigjmp_buf type is NULL"); 2856 return; 2857 } 2858 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>()) 2859 Context->setsigjmp_bufDecl(Typedef->getDecl()); 2860 else { 2861 const TagType *Tag = Sigjmp_bufType->getAs<TagType>(); 2862 assert(Tag && "Invalid sigjmp_buf type in AST file"); 2863 Context->setsigjmp_bufDecl(Tag->getDecl()); 2864 } 2865 } 2866 if (unsigned ObjCIdRedef 2867 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) 2868 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef); 2869 if (unsigned ObjCClassRedef 2870 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) 2871 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef); 2872 if (unsigned String = SpecialTypes[SPECIAL_TYPE_BLOCK_DESCRIPTOR]) 2873 Context->setBlockDescriptorType(GetType(String)); 2874 if (unsigned String 2875 = SpecialTypes[SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR]) 2876 Context->setBlockDescriptorExtendedType(GetType(String)); 2877 if (unsigned ObjCSelRedef 2878 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) 2879 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef); 2880 if (unsigned String = SpecialTypes[SPECIAL_TYPE_NS_CONSTANT_STRING]) 2881 Context->setNSConstantStringType(GetType(String)); 2882 2883 if (SpecialTypes[SPECIAL_TYPE_INT128_INSTALLED]) 2884 Context->setInt128Installed(); 2885 2886 if (unsigned AutoDeduct = SpecialTypes[SPECIAL_TYPE_AUTO_DEDUCT]) 2887 Context->AutoDeductTy = GetType(AutoDeduct); 2888 if (unsigned AutoRRefDeduct = SpecialTypes[SPECIAL_TYPE_AUTO_RREF_DEDUCT]) 2889 Context->AutoRRefDeductTy = GetType(AutoRRefDeduct); 2890 2891 ReadPragmaDiagnosticMappings(Context->getDiagnostics()); 2892 2893 // If there were any CUDA special declarations, deserialize them. 2894 if (!CUDASpecialDeclRefs.empty()) { 2895 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!"); 2896 Context->setcudaConfigureCallDecl( 2897 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0]))); 2898 } 2899 } 2900 2901 /// \brief Retrieve the name of the original source file name 2902 /// directly from the AST file, without actually loading the AST 2903 /// file. 2904 std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName, 2905 FileManager &FileMgr, 2906 Diagnostic &Diags) { 2907 // Open the AST file. 2908 std::string ErrStr; 2909 llvm::OwningPtr<llvm::MemoryBuffer> Buffer; 2910 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr)); 2911 if (!Buffer) { 2912 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr; 2913 return std::string(); 2914 } 2915 2916 // Initialize the stream 2917 llvm::BitstreamReader StreamFile; 2918 llvm::BitstreamCursor Stream; 2919 StreamFile.init((const unsigned char *)Buffer->getBufferStart(), 2920 (const unsigned char *)Buffer->getBufferEnd()); 2921 Stream.init(StreamFile); 2922 2923 // Sniff for the signature. 2924 if (Stream.Read(8) != 'C' || 2925 Stream.Read(8) != 'P' || 2926 Stream.Read(8) != 'C' || 2927 Stream.Read(8) != 'H') { 2928 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName; 2929 return std::string(); 2930 } 2931 2932 RecordData Record; 2933 while (!Stream.AtEndOfStream()) { 2934 unsigned Code = Stream.ReadCode(); 2935 2936 if (Code == llvm::bitc::ENTER_SUBBLOCK) { 2937 unsigned BlockID = Stream.ReadSubBlockID(); 2938 2939 // We only know the AST subblock ID. 2940 switch (BlockID) { 2941 case AST_BLOCK_ID: 2942 if (Stream.EnterSubBlock(AST_BLOCK_ID)) { 2943 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; 2944 return std::string(); 2945 } 2946 break; 2947 2948 default: 2949 if (Stream.SkipBlock()) { 2950 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName; 2951 return std::string(); 2952 } 2953 break; 2954 } 2955 continue; 2956 } 2957 2958 if (Code == llvm::bitc::END_BLOCK) { 2959 if (Stream.ReadBlockEnd()) { 2960 Diags.Report(diag::err_fe_pch_error_at_end_block) << ASTFileName; 2961 return std::string(); 2962 } 2963 continue; 2964 } 2965 2966 if (Code == llvm::bitc::DEFINE_ABBREV) { 2967 Stream.ReadAbbrevRecord(); 2968 continue; 2969 } 2970 2971 Record.clear(); 2972 const char *BlobStart = 0; 2973 unsigned BlobLen = 0; 2974 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen) 2975 == ORIGINAL_FILE_NAME) 2976 return std::string(BlobStart, BlobLen); 2977 } 2978 2979 return std::string(); 2980 } 2981 2982 /// \brief Parse the record that corresponds to a LangOptions data 2983 /// structure. 2984 /// 2985 /// This routine parses the language options from the AST file and then gives 2986 /// them to the AST listener if one is set. 2987 /// 2988 /// \returns true if the listener deems the file unacceptable, false otherwise. 2989 bool ASTReader::ParseLanguageOptions( 2990 const llvm::SmallVectorImpl<uint64_t> &Record) { 2991 if (Listener) { 2992 LangOptions LangOpts; 2993 2994 #define PARSE_LANGOPT(Option) \ 2995 LangOpts.Option = Record[Idx]; \ 2996 ++Idx 2997 2998 unsigned Idx = 0; 2999 PARSE_LANGOPT(Trigraphs); 3000 PARSE_LANGOPT(BCPLComment); 3001 PARSE_LANGOPT(DollarIdents); 3002 PARSE_LANGOPT(AsmPreprocessor); 3003 PARSE_LANGOPT(GNUMode); 3004 PARSE_LANGOPT(GNUKeywords); 3005 PARSE_LANGOPT(ImplicitInt); 3006 PARSE_LANGOPT(Digraphs); 3007 PARSE_LANGOPT(HexFloats); 3008 PARSE_LANGOPT(C99); 3009 PARSE_LANGOPT(C1X); 3010 PARSE_LANGOPT(Microsoft); 3011 PARSE_LANGOPT(CPlusPlus); 3012 PARSE_LANGOPT(CPlusPlus0x); 3013 PARSE_LANGOPT(CXXOperatorNames); 3014 PARSE_LANGOPT(ObjC1); 3015 PARSE_LANGOPT(ObjC2); 3016 PARSE_LANGOPT(ObjCNonFragileABI); 3017 PARSE_LANGOPT(ObjCNonFragileABI2); 3018 PARSE_LANGOPT(AppleKext); 3019 PARSE_LANGOPT(ObjCDefaultSynthProperties); 3020 PARSE_LANGOPT(ObjCInferRelatedResultType); 3021 PARSE_LANGOPT(NoConstantCFStrings); 3022 PARSE_LANGOPT(PascalStrings); 3023 PARSE_LANGOPT(WritableStrings); 3024 PARSE_LANGOPT(LaxVectorConversions); 3025 PARSE_LANGOPT(AltiVec); 3026 PARSE_LANGOPT(Exceptions); 3027 PARSE_LANGOPT(ObjCExceptions); 3028 PARSE_LANGOPT(CXXExceptions); 3029 PARSE_LANGOPT(SjLjExceptions); 3030 PARSE_LANGOPT(MSBitfields); 3031 PARSE_LANGOPT(NeXTRuntime); 3032 PARSE_LANGOPT(Freestanding); 3033 PARSE_LANGOPT(NoBuiltin); 3034 PARSE_LANGOPT(ThreadsafeStatics); 3035 PARSE_LANGOPT(POSIXThreads); 3036 PARSE_LANGOPT(Blocks); 3037 PARSE_LANGOPT(EmitAllDecls); 3038 PARSE_LANGOPT(MathErrno); 3039 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy) 3040 Record[Idx++]); 3041 PARSE_LANGOPT(HeinousExtensions); 3042 PARSE_LANGOPT(Optimize); 3043 PARSE_LANGOPT(OptimizeSize); 3044 PARSE_LANGOPT(Static); 3045 PARSE_LANGOPT(PICLevel); 3046 PARSE_LANGOPT(GNUInline); 3047 PARSE_LANGOPT(NoInline); 3048 PARSE_LANGOPT(Deprecated); 3049 PARSE_LANGOPT(AccessControl); 3050 PARSE_LANGOPT(CharIsSigned); 3051 PARSE_LANGOPT(ShortWChar); 3052 PARSE_LANGOPT(ShortEnums); 3053 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]); 3054 LangOpts.setVisibilityMode((Visibility)Record[Idx++]); 3055 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode) 3056 Record[Idx++]); 3057 PARSE_LANGOPT(InstantiationDepth); 3058 PARSE_LANGOPT(OpenCL); 3059 PARSE_LANGOPT(CUDA); 3060 PARSE_LANGOPT(CatchUndefined); 3061 PARSE_LANGOPT(DefaultFPContract); 3062 PARSE_LANGOPT(ElideConstructors); 3063 PARSE_LANGOPT(SpellChecking); 3064 PARSE_LANGOPT(MRTD); 3065 PARSE_LANGOPT(ObjCAutoRefCount); 3066 #undef PARSE_LANGOPT 3067 3068 return Listener->ReadLanguageOptions(LangOpts); 3069 } 3070 3071 return false; 3072 } 3073 3074 void ASTReader::ReadPreprocessedEntities() { 3075 for (unsigned I = 0, N = Chain.size(); I != N; ++I) { 3076 PerFileData &F = *Chain[I]; 3077 if (!F.PreprocessorDetailCursor.getBitStreamReader()) 3078 continue; 3079 3080 SavedStreamPosition SavedPosition(F.PreprocessorDetailCursor); 3081 F.PreprocessorDetailCursor.JumpToBit(F.PreprocessorDetailStartOffset); 3082 while (LoadPreprocessedEntity(F)) { } 3083 } 3084 } 3085 3086 PreprocessedEntity *ASTReader::ReadPreprocessedEntityAtOffset(uint64_t Offset) { 3087 PerFileData *F = 0; 3088 for (unsigned I = 0, N = Chain.size(); I != N; ++I) { 3089 if (Offset < Chain[I]->SizeInBits) { 3090 F = Chain[I]; 3091 break; 3092 } 3093 3094 Offset -= Chain[I]->SizeInBits; 3095 } 3096 3097 if (!F) { 3098 Error("Malformed preprocessed entity offset"); 3099 return 0; 3100 } 3101 3102 // Keep track of where we are in the stream, then jump back there 3103 // after reading this entity. 3104 SavedStreamPosition SavedPosition(F->PreprocessorDetailCursor); 3105 F->PreprocessorDetailCursor.JumpToBit(Offset); 3106 return LoadPreprocessedEntity(*F); 3107 } 3108 3109 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) { 3110 HeaderFileInfoTrait Trait(FE->getName()); 3111 for (unsigned I = 0, N = Chain.size(); I != N; ++I) { 3112 PerFileData &F = *Chain[I]; 3113 HeaderFileInfoLookupTable *Table 3114 = static_cast<HeaderFileInfoLookupTable *>(F.HeaderFileInfoTable); 3115 if (!Table) 3116 continue; 3117 3118 // Look in the on-disk hash table for an entry for this file name. 3119 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE->getName(), 3120 &Trait); 3121 if (Pos == Table->end()) 3122 continue; 3123 3124 HeaderFileInfo HFI = *Pos; 3125 if (Listener) 3126 Listener->ReadHeaderFileInfo(HFI, FE->getUID()); 3127 3128 return HFI; 3129 } 3130 3131 return HeaderFileInfo(); 3132 } 3133 3134 void ASTReader::ReadPragmaDiagnosticMappings(Diagnostic &Diag) { 3135 for (unsigned I = 0, N = Chain.size(); I != N; ++I) { 3136 PerFileData &F = *Chain[I]; 3137 unsigned Idx = 0; 3138 while (Idx < F.PragmaDiagMappings.size()) { 3139 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]); 3140 while (1) { 3141 assert(Idx < F.PragmaDiagMappings.size() && 3142 "Invalid data, didn't find '-1' marking end of diag/map pairs"); 3143 if (Idx >= F.PragmaDiagMappings.size()) { 3144 break; // Something is messed up but at least avoid infinite loop in 3145 // release build. 3146 } 3147 unsigned DiagID = F.PragmaDiagMappings[Idx++]; 3148 if (DiagID == (unsigned)-1) { 3149 break; // no more diag/map pairs for this location. 3150 } 3151 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++]; 3152 Diag.setDiagnosticMapping(DiagID, Map, Loc); 3153 } 3154 } 3155 } 3156 } 3157 3158 /// \brief Get the correct cursor and offset for loading a type. 3159 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) { 3160 PerFileData *F = 0; 3161 for (unsigned I = 0, N = Chain.size(); I != N; ++I) { 3162 F = Chain[N - I - 1]; 3163 if (Index < F->LocalNumTypes) 3164 break; 3165 Index -= F->LocalNumTypes; 3166 } 3167 assert(F && F->LocalNumTypes > Index && "Broken chain"); 3168 return RecordLocation(F, F->TypeOffsets[Index]); 3169 } 3170 3171 /// \brief Read and return the type with the given index.. 3172 /// 3173 /// The index is the type ID, shifted and minus the number of predefs. This 3174 /// routine actually reads the record corresponding to the type at the given 3175 /// location. It is a helper routine for GetType, which deals with reading type 3176 /// IDs. 3177 QualType ASTReader::ReadTypeRecord(unsigned Index) { 3178 RecordLocation Loc = TypeCursorForIndex(Index); 3179 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor; 3180 3181 // Keep track of where we are in the stream, then jump back there 3182 // after reading this type. 3183 SavedStreamPosition SavedPosition(DeclsCursor); 3184 3185 ReadingKindTracker ReadingKind(Read_Type, *this); 3186 3187 // Note that we are loading a type record. 3188 Deserializing AType(this); 3189 3190 DeclsCursor.JumpToBit(Loc.Offset); 3191 RecordData Record; 3192 unsigned Code = DeclsCursor.ReadCode(); 3193 switch ((TypeCode)DeclsCursor.ReadRecord(Code, Record)) { 3194 case TYPE_EXT_QUAL: { 3195 if (Record.size() != 2) { 3196 Error("Incorrect encoding of extended qualifier type"); 3197 return QualType(); 3198 } 3199 QualType Base = GetType(Record[0]); 3200 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]); 3201 return Context->getQualifiedType(Base, Quals); 3202 } 3203 3204 case TYPE_COMPLEX: { 3205 if (Record.size() != 1) { 3206 Error("Incorrect encoding of complex type"); 3207 return QualType(); 3208 } 3209 QualType ElemType = GetType(Record[0]); 3210 return Context->getComplexType(ElemType); 3211 } 3212 3213 case TYPE_POINTER: { 3214 if (Record.size() != 1) { 3215 Error("Incorrect encoding of pointer type"); 3216 return QualType(); 3217 } 3218 QualType PointeeType = GetType(Record[0]); 3219 return Context->getPointerType(PointeeType); 3220 } 3221 3222 case TYPE_BLOCK_POINTER: { 3223 if (Record.size() != 1) { 3224 Error("Incorrect encoding of block pointer type"); 3225 return QualType(); 3226 } 3227 QualType PointeeType = GetType(Record[0]); 3228 return Context->getBlockPointerType(PointeeType); 3229 } 3230 3231 case TYPE_LVALUE_REFERENCE: { 3232 if (Record.size() != 2) { 3233 Error("Incorrect encoding of lvalue reference type"); 3234 return QualType(); 3235 } 3236 QualType PointeeType = GetType(Record[0]); 3237 return Context->getLValueReferenceType(PointeeType, Record[1]); 3238 } 3239 3240 case TYPE_RVALUE_REFERENCE: { 3241 if (Record.size() != 1) { 3242 Error("Incorrect encoding of rvalue reference type"); 3243 return QualType(); 3244 } 3245 QualType PointeeType = GetType(Record[0]); 3246 return Context->getRValueReferenceType(PointeeType); 3247 } 3248 3249 case TYPE_MEMBER_POINTER: { 3250 if (Record.size() != 2) { 3251 Error("Incorrect encoding of member pointer type"); 3252 return QualType(); 3253 } 3254 QualType PointeeType = GetType(Record[0]); 3255 QualType ClassType = GetType(Record[1]); 3256 if (PointeeType.isNull() || ClassType.isNull()) 3257 return QualType(); 3258 3259 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr()); 3260 } 3261 3262 case TYPE_CONSTANT_ARRAY: { 3263 QualType ElementType = GetType(Record[0]); 3264 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1]; 3265 unsigned IndexTypeQuals = Record[2]; 3266 unsigned Idx = 3; 3267 llvm::APInt Size = ReadAPInt(Record, Idx); 3268 return Context->getConstantArrayType(ElementType, Size, 3269 ASM, IndexTypeQuals); 3270 } 3271 3272 case TYPE_INCOMPLETE_ARRAY: { 3273 QualType ElementType = GetType(Record[0]); 3274 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1]; 3275 unsigned IndexTypeQuals = Record[2]; 3276 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals); 3277 } 3278 3279 case TYPE_VARIABLE_ARRAY: { 3280 QualType ElementType = GetType(Record[0]); 3281 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1]; 3282 unsigned IndexTypeQuals = Record[2]; 3283 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]); 3284 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]); 3285 return Context->getVariableArrayType(ElementType, ReadExpr(*Loc.F), 3286 ASM, IndexTypeQuals, 3287 SourceRange(LBLoc, RBLoc)); 3288 } 3289 3290 case TYPE_VECTOR: { 3291 if (Record.size() != 3) { 3292 Error("incorrect encoding of vector type in AST file"); 3293 return QualType(); 3294 } 3295 3296 QualType ElementType = GetType(Record[0]); 3297 unsigned NumElements = Record[1]; 3298 unsigned VecKind = Record[2]; 3299 return Context->getVectorType(ElementType, NumElements, 3300 (VectorType::VectorKind)VecKind); 3301 } 3302 3303 case TYPE_EXT_VECTOR: { 3304 if (Record.size() != 3) { 3305 Error("incorrect encoding of extended vector type in AST file"); 3306 return QualType(); 3307 } 3308 3309 QualType ElementType = GetType(Record[0]); 3310 unsigned NumElements = Record[1]; 3311 return Context->getExtVectorType(ElementType, NumElements); 3312 } 3313 3314 case TYPE_FUNCTION_NO_PROTO: { 3315 if (Record.size() != 6) { 3316 Error("incorrect encoding of no-proto function type"); 3317 return QualType(); 3318 } 3319 QualType ResultType = GetType(Record[0]); 3320 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3], 3321 (CallingConv)Record[4], Record[5]); 3322 return Context->getFunctionNoProtoType(ResultType, Info); 3323 } 3324 3325 case TYPE_FUNCTION_PROTO: { 3326 QualType ResultType = GetType(Record[0]); 3327 3328 FunctionProtoType::ExtProtoInfo EPI; 3329 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1], 3330 /*hasregparm*/ Record[2], 3331 /*regparm*/ Record[3], 3332 static_cast<CallingConv>(Record[4]), 3333 /*produces*/ Record[5]); 3334 3335 unsigned Idx = 6; 3336 unsigned NumParams = Record[Idx++]; 3337 llvm::SmallVector<QualType, 16> ParamTypes; 3338 for (unsigned I = 0; I != NumParams; ++I) 3339 ParamTypes.push_back(GetType(Record[Idx++])); 3340 3341 EPI.Variadic = Record[Idx++]; 3342 EPI.TypeQuals = Record[Idx++]; 3343 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]); 3344 ExceptionSpecificationType EST = 3345 static_cast<ExceptionSpecificationType>(Record[Idx++]); 3346 EPI.ExceptionSpecType = EST; 3347 if (EST == EST_Dynamic) { 3348 EPI.NumExceptions = Record[Idx++]; 3349 llvm::SmallVector<QualType, 2> Exceptions; 3350 for (unsigned I = 0; I != EPI.NumExceptions; ++I) 3351 Exceptions.push_back(GetType(Record[Idx++])); 3352 EPI.Exceptions = Exceptions.data(); 3353 } else if (EST == EST_ComputedNoexcept) { 3354 EPI.NoexceptExpr = ReadExpr(*Loc.F); 3355 } 3356 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams, 3357 EPI); 3358 } 3359 3360 case TYPE_UNRESOLVED_USING: 3361 return Context->getTypeDeclType( 3362 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0]))); 3363 3364 case TYPE_TYPEDEF: { 3365 if (Record.size() != 2) { 3366 Error("incorrect encoding of typedef type"); 3367 return QualType(); 3368 } 3369 TypedefNameDecl *Decl = cast<TypedefNameDecl>(GetDecl(Record[0])); 3370 QualType Canonical = GetType(Record[1]); 3371 if (!Canonical.isNull()) 3372 Canonical = Context->getCanonicalType(Canonical); 3373 return Context->getTypedefType(Decl, Canonical); 3374 } 3375 3376 case TYPE_TYPEOF_EXPR: 3377 return Context->getTypeOfExprType(ReadExpr(*Loc.F)); 3378 3379 case TYPE_TYPEOF: { 3380 if (Record.size() != 1) { 3381 Error("incorrect encoding of typeof(type) in AST file"); 3382 return QualType(); 3383 } 3384 QualType UnderlyingType = GetType(Record[0]); 3385 return Context->getTypeOfType(UnderlyingType); 3386 } 3387 3388 case TYPE_DECLTYPE: 3389 return Context->getDecltypeType(ReadExpr(*Loc.F)); 3390 3391 case TYPE_UNARY_TRANSFORM: { 3392 QualType BaseType = GetType(Record[0]); 3393 QualType UnderlyingType = GetType(Record[1]); 3394 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2]; 3395 return Context->getUnaryTransformType(BaseType, UnderlyingType, UKind); 3396 } 3397 3398 case TYPE_AUTO: 3399 return Context->getAutoType(GetType(Record[0])); 3400 3401 case TYPE_RECORD: { 3402 if (Record.size() != 2) { 3403 Error("incorrect encoding of record type"); 3404 return QualType(); 3405 } 3406 bool IsDependent = Record[0]; 3407 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1]))); 3408 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent); 3409 return T; 3410 } 3411 3412 case TYPE_ENUM: { 3413 if (Record.size() != 2) { 3414 Error("incorrect encoding of enum type"); 3415 return QualType(); 3416 } 3417 bool IsDependent = Record[0]; 3418 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1]))); 3419 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent); 3420 return T; 3421 } 3422 3423 case TYPE_ATTRIBUTED: { 3424 if (Record.size() != 3) { 3425 Error("incorrect encoding of attributed type"); 3426 return QualType(); 3427 } 3428 QualType modifiedType = GetType(Record[0]); 3429 QualType equivalentType = GetType(Record[1]); 3430 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]); 3431 return Context->getAttributedType(kind, modifiedType, equivalentType); 3432 } 3433 3434 case TYPE_PAREN: { 3435 if (Record.size() != 1) { 3436 Error("incorrect encoding of paren type"); 3437 return QualType(); 3438 } 3439 QualType InnerType = GetType(Record[0]); 3440 return Context->getParenType(InnerType); 3441 } 3442 3443 case TYPE_PACK_EXPANSION: { 3444 if (Record.size() != 2) { 3445 Error("incorrect encoding of pack expansion type"); 3446 return QualType(); 3447 } 3448 QualType Pattern = GetType(Record[0]); 3449 if (Pattern.isNull()) 3450 return QualType(); 3451 llvm::Optional<unsigned> NumExpansions; 3452 if (Record[1]) 3453 NumExpansions = Record[1] - 1; 3454 return Context->getPackExpansionType(Pattern, NumExpansions); 3455 } 3456 3457 case TYPE_ELABORATED: { 3458 unsigned Idx = 0; 3459 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++]; 3460 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx); 3461 QualType NamedType = GetType(Record[Idx++]); 3462 return Context->getElaboratedType(Keyword, NNS, NamedType); 3463 } 3464 3465 case TYPE_OBJC_INTERFACE: { 3466 unsigned Idx = 0; 3467 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++])); 3468 return Context->getObjCInterfaceType(ItfD); 3469 } 3470 3471 case TYPE_OBJC_OBJECT: { 3472 unsigned Idx = 0; 3473 QualType Base = GetType(Record[Idx++]); 3474 unsigned NumProtos = Record[Idx++]; 3475 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos; 3476 for (unsigned I = 0; I != NumProtos; ++I) 3477 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++]))); 3478 return Context->getObjCObjectType(Base, Protos.data(), NumProtos); 3479 } 3480 3481 case TYPE_OBJC_OBJECT_POINTER: { 3482 unsigned Idx = 0; 3483 QualType Pointee = GetType(Record[Idx++]); 3484 return Context->getObjCObjectPointerType(Pointee); 3485 } 3486 3487 case TYPE_SUBST_TEMPLATE_TYPE_PARM: { 3488 unsigned Idx = 0; 3489 QualType Parm = GetType(Record[Idx++]); 3490 QualType Replacement = GetType(Record[Idx++]); 3491 return 3492 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm), 3493 Replacement); 3494 } 3495 3496 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: { 3497 unsigned Idx = 0; 3498 QualType Parm = GetType(Record[Idx++]); 3499 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx); 3500 return Context->getSubstTemplateTypeParmPackType( 3501 cast<TemplateTypeParmType>(Parm), 3502 ArgPack); 3503 } 3504 3505 case TYPE_INJECTED_CLASS_NAME: { 3506 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0])); 3507 QualType TST = GetType(Record[1]); // probably derivable 3508 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable 3509 // for AST reading, too much interdependencies. 3510 return 3511 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0); 3512 } 3513 3514 case TYPE_TEMPLATE_TYPE_PARM: { 3515 unsigned Idx = 0; 3516 unsigned Depth = Record[Idx++]; 3517 unsigned Index = Record[Idx++]; 3518 bool Pack = Record[Idx++]; 3519 TemplateTypeParmDecl *D = 3520 cast_or_null<TemplateTypeParmDecl>(GetDecl(Record[Idx++])); 3521 return Context->getTemplateTypeParmType(Depth, Index, Pack, D); 3522 } 3523 3524 case TYPE_DEPENDENT_NAME: { 3525 unsigned Idx = 0; 3526 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++]; 3527 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx); 3528 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx); 3529 QualType Canon = GetType(Record[Idx++]); 3530 if (!Canon.isNull()) 3531 Canon = Context->getCanonicalType(Canon); 3532 return Context->getDependentNameType(Keyword, NNS, Name, Canon); 3533 } 3534 3535 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: { 3536 unsigned Idx = 0; 3537 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++]; 3538 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx); 3539 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx); 3540 unsigned NumArgs = Record[Idx++]; 3541 llvm::SmallVector<TemplateArgument, 8> Args; 3542 Args.reserve(NumArgs); 3543 while (NumArgs--) 3544 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx)); 3545 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name, 3546 Args.size(), Args.data()); 3547 } 3548 3549 case TYPE_DEPENDENT_SIZED_ARRAY: { 3550 unsigned Idx = 0; 3551 3552 // ArrayType 3553 QualType ElementType = GetType(Record[Idx++]); 3554 ArrayType::ArraySizeModifier ASM 3555 = (ArrayType::ArraySizeModifier)Record[Idx++]; 3556 unsigned IndexTypeQuals = Record[Idx++]; 3557 3558 // DependentSizedArrayType 3559 Expr *NumElts = ReadExpr(*Loc.F); 3560 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx); 3561 3562 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM, 3563 IndexTypeQuals, Brackets); 3564 } 3565 3566 case TYPE_TEMPLATE_SPECIALIZATION: { 3567 unsigned Idx = 0; 3568 bool IsDependent = Record[Idx++]; 3569 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx); 3570 llvm::SmallVector<TemplateArgument, 8> Args; 3571 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx); 3572 QualType Underlying = GetType(Record[Idx++]); 3573 QualType T; 3574 if (Underlying.isNull()) 3575 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(), 3576 Args.size()); 3577 else 3578 T = Context->getTemplateSpecializationType(Name, Args.data(), 3579 Args.size(), Underlying); 3580 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent); 3581 return T; 3582 } 3583 } 3584 // Suppress a GCC warning 3585 return QualType(); 3586 } 3587 3588 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> { 3589 ASTReader &Reader; 3590 ASTReader::PerFileData &F; 3591 llvm::BitstreamCursor &DeclsCursor; 3592 const ASTReader::RecordData &Record; 3593 unsigned &Idx; 3594 3595 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R, 3596 unsigned &I) { 3597 return Reader.ReadSourceLocation(F, R, I); 3598 } 3599 3600 public: 3601 TypeLocReader(ASTReader &Reader, ASTReader::PerFileData &F, 3602 const ASTReader::RecordData &Record, unsigned &Idx) 3603 : Reader(Reader), F(F), DeclsCursor(F.DeclsCursor), Record(Record), Idx(Idx) 3604 { } 3605 3606 // We want compile-time assurance that we've enumerated all of 3607 // these, so unfortunately we have to declare them first, then 3608 // define them out-of-line. 3609 #define ABSTRACT_TYPELOC(CLASS, PARENT) 3610 #define TYPELOC(CLASS, PARENT) \ 3611 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc); 3612 #include "clang/AST/TypeLocNodes.def" 3613 3614 void VisitFunctionTypeLoc(FunctionTypeLoc); 3615 void VisitArrayTypeLoc(ArrayTypeLoc); 3616 }; 3617 3618 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 3619 // nothing to do 3620 } 3621 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 3622 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx)); 3623 if (TL.needsExtraLocalData()) { 3624 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++])); 3625 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++])); 3626 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++])); 3627 TL.setModeAttr(Record[Idx++]); 3628 } 3629 } 3630 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) { 3631 TL.setNameLoc(ReadSourceLocation(Record, Idx)); 3632 } 3633 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) { 3634 TL.setStarLoc(ReadSourceLocation(Record, Idx)); 3635 } 3636 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 3637 TL.setCaretLoc(ReadSourceLocation(Record, Idx)); 3638 } 3639 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 3640 TL.setAmpLoc(ReadSourceLocation(Record, Idx)); 3641 } 3642 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 3643 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx)); 3644 } 3645 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 3646 TL.setStarLoc(ReadSourceLocation(Record, Idx)); 3647 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx)); 3648 } 3649 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) { 3650 TL.setLBracketLoc(ReadSourceLocation(Record, Idx)); 3651 TL.setRBracketLoc(ReadSourceLocation(Record, Idx)); 3652 if (Record[Idx++]) 3653 TL.setSizeExpr(Reader.ReadExpr(F)); 3654 else 3655 TL.setSizeExpr(0); 3656 } 3657 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) { 3658 VisitArrayTypeLoc(TL); 3659 } 3660 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) { 3661 VisitArrayTypeLoc(TL); 3662 } 3663 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) { 3664 VisitArrayTypeLoc(TL); 3665 } 3666 void TypeLocReader::VisitDependentSizedArrayTypeLoc( 3667 DependentSizedArrayTypeLoc TL) { 3668 VisitArrayTypeLoc(TL); 3669 } 3670 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc( 3671 DependentSizedExtVectorTypeLoc TL) { 3672 TL.setNameLoc(ReadSourceLocation(Record, Idx)); 3673 } 3674 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) { 3675 TL.setNameLoc(ReadSourceLocation(Record, Idx)); 3676 } 3677 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { 3678 TL.setNameLoc(ReadSourceLocation(Record, Idx)); 3679 } 3680 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) { 3681 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx)); 3682 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx)); 3683 TL.setTrailingReturn(Record[Idx++]); 3684 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) { 3685 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++]))); 3686 } 3687 } 3688 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) { 3689 VisitFunctionTypeLoc(TL); 3690 } 3691 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) { 3692 VisitFunctionTypeLoc(TL); 3693 } 3694 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 3695 TL.setNameLoc(ReadSourceLocation(Record, Idx)); 3696 } 3697 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 3698 TL.setNameLoc(ReadSourceLocation(Record, Idx)); 3699 } 3700 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 3701 TL.setTypeofLoc(ReadSourceLocation(Record, Idx)); 3702 TL.setLParenLoc(ReadSourceLocation(Record, Idx)); 3703 TL.setRParenLoc(ReadSourceLocation(Record, Idx)); 3704 } 3705 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 3706 TL.setTypeofLoc(ReadSourceLocation(Record, Idx)); 3707 TL.setLParenLoc(ReadSourceLocation(Record, Idx)); 3708 TL.setRParenLoc(ReadSourceLocation(Record, Idx)); 3709 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx)); 3710 } 3711 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 3712 TL.setNameLoc(ReadSourceLocation(Record, Idx)); 3713 } 3714 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 3715 TL.setKWLoc(ReadSourceLocation(Record, Idx)); 3716 TL.setLParenLoc(ReadSourceLocation(Record, Idx)); 3717 TL.setRParenLoc(ReadSourceLocation(Record, Idx)); 3718 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx)); 3719 } 3720 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) { 3721 TL.setNameLoc(ReadSourceLocation(Record, Idx)); 3722 } 3723 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) { 3724 TL.setNameLoc(ReadSourceLocation(Record, Idx)); 3725 } 3726 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) { 3727 TL.setNameLoc(ReadSourceLocation(Record, Idx)); 3728 } 3729 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) { 3730 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx)); 3731 if (TL.hasAttrOperand()) { 3732 SourceRange range; 3733 range.setBegin(ReadSourceLocation(Record, Idx)); 3734 range.setEnd(ReadSourceLocation(Record, Idx)); 3735 TL.setAttrOperandParensRange(range); 3736 } 3737 if (TL.hasAttrExprOperand()) { 3738 if (Record[Idx++]) 3739 TL.setAttrExprOperand(Reader.ReadExpr(F)); 3740 else 3741 TL.setAttrExprOperand(0); 3742 } else if (TL.hasAttrEnumOperand()) 3743 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx)); 3744 } 3745 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 3746 TL.setNameLoc(ReadSourceLocation(Record, Idx)); 3747 } 3748 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc( 3749 SubstTemplateTypeParmTypeLoc TL) { 3750 TL.setNameLoc(ReadSourceLocation(Record, Idx)); 3751 } 3752 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc( 3753 SubstTemplateTypeParmPackTypeLoc TL) { 3754 TL.setNameLoc(ReadSourceLocation(Record, Idx)); 3755 } 3756 void TypeLocReader::VisitTemplateSpecializationTypeLoc( 3757 TemplateSpecializationTypeLoc TL) { 3758 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx)); 3759 TL.setLAngleLoc(ReadSourceLocation(Record, Idx)); 3760 TL.setRAngleLoc(ReadSourceLocation(Record, Idx)); 3761 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 3762 TL.setArgLocInfo(i, 3763 Reader.GetTemplateArgumentLocInfo(F, 3764 TL.getTypePtr()->getArg(i).getKind(), 3765 Record, Idx)); 3766 } 3767 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) { 3768 TL.setLParenLoc(ReadSourceLocation(Record, Idx)); 3769 TL.setRParenLoc(ReadSourceLocation(Record, Idx)); 3770 } 3771 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 3772 TL.setKeywordLoc(ReadSourceLocation(Record, Idx)); 3773 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx)); 3774 } 3775 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 3776 TL.setNameLoc(ReadSourceLocation(Record, Idx)); 3777 } 3778 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 3779 TL.setKeywordLoc(ReadSourceLocation(Record, Idx)); 3780 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx)); 3781 TL.setNameLoc(ReadSourceLocation(Record, Idx)); 3782 } 3783 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc( 3784 DependentTemplateSpecializationTypeLoc TL) { 3785 TL.setKeywordLoc(ReadSourceLocation(Record, Idx)); 3786 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx)); 3787 TL.setNameLoc(ReadSourceLocation(Record, Idx)); 3788 TL.setLAngleLoc(ReadSourceLocation(Record, Idx)); 3789 TL.setRAngleLoc(ReadSourceLocation(Record, Idx)); 3790 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) 3791 TL.setArgLocInfo(I, 3792 Reader.GetTemplateArgumentLocInfo(F, 3793 TL.getTypePtr()->getArg(I).getKind(), 3794 Record, Idx)); 3795 } 3796 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { 3797 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx)); 3798 } 3799 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 3800 TL.setNameLoc(ReadSourceLocation(Record, Idx)); 3801 } 3802 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 3803 TL.setHasBaseTypeAsWritten(Record[Idx++]); 3804 TL.setLAngleLoc(ReadSourceLocation(Record, Idx)); 3805 TL.setRAngleLoc(ReadSourceLocation(Record, Idx)); 3806 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 3807 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx)); 3808 } 3809 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 3810 TL.setStarLoc(ReadSourceLocation(Record, Idx)); 3811 } 3812 3813 TypeSourceInfo *ASTReader::GetTypeSourceInfo(PerFileData &F, 3814 const RecordData &Record, 3815 unsigned &Idx) { 3816 QualType InfoTy = GetType(Record[Idx++]); 3817 if (InfoTy.isNull()) 3818 return 0; 3819 3820 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy); 3821 TypeLocReader TLR(*this, F, Record, Idx); 3822 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc()) 3823 TLR.Visit(TL); 3824 return TInfo; 3825 } 3826 3827 QualType ASTReader::GetType(TypeID ID) { 3828 unsigned FastQuals = ID & Qualifiers::FastMask; 3829 unsigned Index = ID >> Qualifiers::FastWidth; 3830 3831 if (Index < NUM_PREDEF_TYPE_IDS) { 3832 QualType T; 3833 switch ((PredefinedTypeIDs)Index) { 3834 case PREDEF_TYPE_NULL_ID: return QualType(); 3835 case PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break; 3836 case PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break; 3837 3838 case PREDEF_TYPE_CHAR_U_ID: 3839 case PREDEF_TYPE_CHAR_S_ID: 3840 // FIXME: Check that the signedness of CharTy is correct! 3841 T = Context->CharTy; 3842 break; 3843 3844 case PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break; 3845 case PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break; 3846 case PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break; 3847 case PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break; 3848 case PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break; 3849 case PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break; 3850 case PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break; 3851 case PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break; 3852 case PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break; 3853 case PREDEF_TYPE_INT_ID: T = Context->IntTy; break; 3854 case PREDEF_TYPE_LONG_ID: T = Context->LongTy; break; 3855 case PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break; 3856 case PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break; 3857 case PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break; 3858 case PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break; 3859 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break; 3860 case PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break; 3861 case PREDEF_TYPE_BOUND_MEMBER: T = Context->BoundMemberTy; break; 3862 case PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break; 3863 case PREDEF_TYPE_UNKNOWN_ANY: T = Context->UnknownAnyTy; break; 3864 case PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break; 3865 case PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break; 3866 case PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break; 3867 case PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break; 3868 case PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break; 3869 case PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break; 3870 } 3871 3872 assert(!T.isNull() && "Unknown predefined type"); 3873 return T.withFastQualifiers(FastQuals); 3874 } 3875 3876 Index -= NUM_PREDEF_TYPE_IDS; 3877 assert(Index < TypesLoaded.size() && "Type index out-of-range"); 3878 if (TypesLoaded[Index].isNull()) { 3879 TypesLoaded[Index] = ReadTypeRecord(Index); 3880 if (TypesLoaded[Index].isNull()) 3881 return QualType(); 3882 3883 TypesLoaded[Index]->setFromAST(); 3884 TypeIdxs[TypesLoaded[Index]] = TypeIdx::fromTypeID(ID); 3885 if (DeserializationListener) 3886 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID), 3887 TypesLoaded[Index]); 3888 } 3889 3890 return TypesLoaded[Index].withFastQualifiers(FastQuals); 3891 } 3892 3893 TypeID ASTReader::GetTypeID(QualType T) const { 3894 return MakeTypeID(T, 3895 std::bind1st(std::mem_fun(&ASTReader::GetTypeIdx), this)); 3896 } 3897 3898 TypeIdx ASTReader::GetTypeIdx(QualType T) const { 3899 if (T.isNull()) 3900 return TypeIdx(); 3901 assert(!T.getLocalFastQualifiers()); 3902 3903 TypeIdxMap::const_iterator I = TypeIdxs.find(T); 3904 // GetTypeIdx is mostly used for computing the hash of DeclarationNames and 3905 // comparing keys of ASTDeclContextNameLookupTable. 3906 // If the type didn't come from the AST file use a specially marked index 3907 // so that any hash/key comparison fail since no such index is stored 3908 // in a AST file. 3909 if (I == TypeIdxs.end()) 3910 return TypeIdx(-1); 3911 return I->second; 3912 } 3913 3914 unsigned ASTReader::getTotalNumCXXBaseSpecifiers() const { 3915 unsigned Result = 0; 3916 for (unsigned I = 0, N = Chain.size(); I != N; ++I) 3917 Result += Chain[I]->LocalNumCXXBaseSpecifiers; 3918 3919 return Result; 3920 } 3921 3922 TemplateArgumentLocInfo 3923 ASTReader::GetTemplateArgumentLocInfo(PerFileData &F, 3924 TemplateArgument::ArgKind Kind, 3925 const RecordData &Record, 3926 unsigned &Index) { 3927 switch (Kind) { 3928 case TemplateArgument::Expression: 3929 return ReadExpr(F); 3930 case TemplateArgument::Type: 3931 return GetTypeSourceInfo(F, Record, Index); 3932 case TemplateArgument::Template: { 3933 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, 3934 Index); 3935 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index); 3936 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc, 3937 SourceLocation()); 3938 } 3939 case TemplateArgument::TemplateExpansion: { 3940 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, 3941 Index); 3942 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index); 3943 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index); 3944 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc, 3945 EllipsisLoc); 3946 } 3947 case TemplateArgument::Null: 3948 case TemplateArgument::Integral: 3949 case TemplateArgument::Declaration: 3950 case TemplateArgument::Pack: 3951 return TemplateArgumentLocInfo(); 3952 } 3953 llvm_unreachable("unexpected template argument loc"); 3954 return TemplateArgumentLocInfo(); 3955 } 3956 3957 TemplateArgumentLoc 3958 ASTReader::ReadTemplateArgumentLoc(PerFileData &F, 3959 const RecordData &Record, unsigned &Index) { 3960 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index); 3961 3962 if (Arg.getKind() == TemplateArgument::Expression) { 3963 if (Record[Index++]) // bool InfoHasSameExpr. 3964 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr())); 3965 } 3966 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(), 3967 Record, Index)); 3968 } 3969 3970 Decl *ASTReader::GetExternalDecl(uint32_t ID) { 3971 return GetDecl(ID); 3972 } 3973 3974 uint64_t 3975 ASTReader::GetCXXBaseSpecifiersOffset(serialization::CXXBaseSpecifiersID ID) { 3976 if (ID == 0) 3977 return 0; 3978 3979 --ID; 3980 uint64_t Offset = 0; 3981 for (unsigned I = 0, N = Chain.size(); I != N; ++I) { 3982 PerFileData &F = *Chain[N - I - 1]; 3983 3984 if (ID < F.LocalNumCXXBaseSpecifiers) 3985 return Offset + F.CXXBaseSpecifiersOffsets[ID]; 3986 3987 ID -= F.LocalNumCXXBaseSpecifiers; 3988 Offset += F.SizeInBits; 3989 } 3990 3991 assert(false && "CXXBaseSpecifiers not found"); 3992 return 0; 3993 } 3994 3995 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) { 3996 // Figure out which AST file contains this offset. 3997 PerFileData *F = 0; 3998 for (unsigned I = 0, N = Chain.size(); I != N; ++I) { 3999 if (Offset < Chain[N - I - 1]->SizeInBits) { 4000 F = Chain[N - I - 1]; 4001 break; 4002 } 4003 4004 Offset -= Chain[N - I - 1]->SizeInBits; 4005 } 4006 4007 if (!F) { 4008 Error("Malformed AST file: C++ base specifiers at impossible offset"); 4009 return 0; 4010 } 4011 4012 llvm::BitstreamCursor &Cursor = F->DeclsCursor; 4013 SavedStreamPosition SavedPosition(Cursor); 4014 Cursor.JumpToBit(Offset); 4015 ReadingKindTracker ReadingKind(Read_Decl, *this); 4016 RecordData Record; 4017 unsigned Code = Cursor.ReadCode(); 4018 unsigned RecCode = Cursor.ReadRecord(Code, Record); 4019 if (RecCode != DECL_CXX_BASE_SPECIFIERS) { 4020 Error("Malformed AST file: missing C++ base specifiers"); 4021 return 0; 4022 } 4023 4024 unsigned Idx = 0; 4025 unsigned NumBases = Record[Idx++]; 4026 void *Mem = Context->Allocate(sizeof(CXXBaseSpecifier) * NumBases); 4027 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases]; 4028 for (unsigned I = 0; I != NumBases; ++I) 4029 Bases[I] = ReadCXXBaseSpecifier(*F, Record, Idx); 4030 return Bases; 4031 } 4032 4033 TranslationUnitDecl *ASTReader::GetTranslationUnitDecl() { 4034 if (!DeclsLoaded[0]) { 4035 ReadDeclRecord(0, 1); 4036 if (DeserializationListener) 4037 DeserializationListener->DeclRead(1, DeclsLoaded[0]); 4038 } 4039 4040 return cast<TranslationUnitDecl>(DeclsLoaded[0]); 4041 } 4042 4043 Decl *ASTReader::GetDecl(DeclID ID) { 4044 if (ID == 0) 4045 return 0; 4046 4047 if (ID > DeclsLoaded.size()) { 4048 Error("declaration ID out-of-range for AST file"); 4049 return 0; 4050 } 4051 4052 unsigned Index = ID - 1; 4053 if (!DeclsLoaded[Index]) { 4054 ReadDeclRecord(Index, ID); 4055 if (DeserializationListener) 4056 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]); 4057 } 4058 4059 return DeclsLoaded[Index]; 4060 } 4061 4062 /// \brief Resolve the offset of a statement into a statement. 4063 /// 4064 /// This operation will read a new statement from the external 4065 /// source each time it is called, and is meant to be used via a 4066 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc). 4067 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) { 4068 // Switch case IDs are per Decl. 4069 ClearSwitchCaseIDs(); 4070 4071 // Offset here is a global offset across the entire chain. 4072 for (unsigned I = 0, N = Chain.size(); I != N; ++I) { 4073 PerFileData &F = *Chain[N - I - 1]; 4074 if (Offset < F.SizeInBits) { 4075 // Since we know that this statement is part of a decl, make sure to use 4076 // the decl cursor to read it. 4077 F.DeclsCursor.JumpToBit(Offset); 4078 return ReadStmtFromStream(F); 4079 } 4080 Offset -= F.SizeInBits; 4081 } 4082 llvm_unreachable("Broken chain"); 4083 } 4084 4085 ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC, 4086 bool (*isKindWeWant)(Decl::Kind), 4087 llvm::SmallVectorImpl<Decl*> &Decls) { 4088 // There might be lexical decls in multiple parts of the chain, for the TU 4089 // at least. 4090 // DeclContextOffsets might reallocate as we load additional decls below, 4091 // so make a copy of the vector. 4092 DeclContextInfos Infos = DeclContextOffsets[DC]; 4093 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end(); 4094 I != E; ++I) { 4095 // IDs can be 0 if this context doesn't contain declarations. 4096 if (!I->LexicalDecls) 4097 continue; 4098 4099 // Load all of the declaration IDs 4100 for (const KindDeclIDPair *ID = I->LexicalDecls, 4101 *IDE = ID + I->NumLexicalDecls; ID != IDE; ++ID) { 4102 if (isKindWeWant && !isKindWeWant((Decl::Kind)ID->first)) 4103 continue; 4104 4105 Decl *D = GetDecl(ID->second); 4106 assert(D && "Null decl in lexical decls"); 4107 Decls.push_back(D); 4108 } 4109 } 4110 4111 ++NumLexicalDeclContextsRead; 4112 return ELR_Success; 4113 } 4114 4115 DeclContext::lookup_result 4116 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC, 4117 DeclarationName Name) { 4118 assert(DC->hasExternalVisibleStorage() && 4119 "DeclContext has no visible decls in storage"); 4120 if (!Name) 4121 return DeclContext::lookup_result(DeclContext::lookup_iterator(0), 4122 DeclContext::lookup_iterator(0)); 4123 4124 llvm::SmallVector<NamedDecl *, 64> Decls; 4125 // There might be visible decls in multiple parts of the chain, for the TU 4126 // and namespaces. For any given name, the last available results replace 4127 // all earlier ones. For this reason, we walk in reverse. 4128 DeclContextInfos &Infos = DeclContextOffsets[DC]; 4129 for (DeclContextInfos::reverse_iterator I = Infos.rbegin(), E = Infos.rend(); 4130 I != E; ++I) { 4131 if (!I->NameLookupTableData) 4132 continue; 4133 4134 ASTDeclContextNameLookupTable *LookupTable = 4135 (ASTDeclContextNameLookupTable*)I->NameLookupTableData; 4136 ASTDeclContextNameLookupTable::iterator Pos = LookupTable->find(Name); 4137 if (Pos == LookupTable->end()) 4138 continue; 4139 4140 ASTDeclContextNameLookupTrait::data_type Data = *Pos; 4141 for (; Data.first != Data.second; ++Data.first) 4142 Decls.push_back(cast<NamedDecl>(GetDecl(*Data.first))); 4143 break; 4144 } 4145 4146 ++NumVisibleDeclContextsRead; 4147 4148 SetExternalVisibleDeclsForName(DC, Name, Decls); 4149 return const_cast<DeclContext*>(DC)->lookup(Name); 4150 } 4151 4152 void ASTReader::MaterializeVisibleDecls(const DeclContext *DC) { 4153 assert(DC->hasExternalVisibleStorage() && 4154 "DeclContext has no visible decls in storage"); 4155 4156 llvm::SmallVector<NamedDecl *, 64> Decls; 4157 // There might be visible decls in multiple parts of the chain, for the TU 4158 // and namespaces. 4159 DeclContextInfos &Infos = DeclContextOffsets[DC]; 4160 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end(); 4161 I != E; ++I) { 4162 if (!I->NameLookupTableData) 4163 continue; 4164 4165 ASTDeclContextNameLookupTable *LookupTable = 4166 (ASTDeclContextNameLookupTable*)I->NameLookupTableData; 4167 for (ASTDeclContextNameLookupTable::item_iterator 4168 ItemI = LookupTable->item_begin(), 4169 ItemEnd = LookupTable->item_end() ; ItemI != ItemEnd; ++ItemI) { 4170 ASTDeclContextNameLookupTable::item_iterator::value_type Val 4171 = *ItemI; 4172 ASTDeclContextNameLookupTrait::data_type Data = Val.second; 4173 Decls.clear(); 4174 for (; Data.first != Data.second; ++Data.first) 4175 Decls.push_back(cast<NamedDecl>(GetDecl(*Data.first))); 4176 MaterializeVisibleDeclsForName(DC, Val.first, Decls); 4177 } 4178 } 4179 } 4180 4181 void ASTReader::PassInterestingDeclsToConsumer() { 4182 assert(Consumer); 4183 while (!InterestingDecls.empty()) { 4184 DeclGroupRef DG(InterestingDecls.front()); 4185 InterestingDecls.pop_front(); 4186 Consumer->HandleInterestingDecl(DG); 4187 } 4188 } 4189 4190 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) { 4191 this->Consumer = Consumer; 4192 4193 if (!Consumer) 4194 return; 4195 4196 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) { 4197 // Force deserialization of this decl, which will cause it to be queued for 4198 // passing to the consumer. 4199 GetDecl(ExternalDefinitions[I]); 4200 } 4201 4202 PassInterestingDeclsToConsumer(); 4203 } 4204 4205 void ASTReader::PrintStats() { 4206 std::fprintf(stderr, "*** AST File Statistics:\n"); 4207 4208 unsigned NumTypesLoaded 4209 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(), 4210 QualType()); 4211 unsigned NumDeclsLoaded 4212 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(), 4213 (Decl *)0); 4214 unsigned NumIdentifiersLoaded 4215 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(), 4216 IdentifiersLoaded.end(), 4217 (IdentifierInfo *)0); 4218 unsigned NumSelectorsLoaded 4219 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(), 4220 SelectorsLoaded.end(), 4221 Selector()); 4222 4223 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits); 4224 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses); 4225 if (TotalNumSLocEntries) 4226 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n", 4227 NumSLocEntriesRead, TotalNumSLocEntries, 4228 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100)); 4229 if (!TypesLoaded.empty()) 4230 std::fprintf(stderr, " %u/%u types read (%f%%)\n", 4231 NumTypesLoaded, (unsigned)TypesLoaded.size(), 4232 ((float)NumTypesLoaded/TypesLoaded.size() * 100)); 4233 if (!DeclsLoaded.empty()) 4234 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n", 4235 NumDeclsLoaded, (unsigned)DeclsLoaded.size(), 4236 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100)); 4237 if (!IdentifiersLoaded.empty()) 4238 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n", 4239 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(), 4240 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100)); 4241 if (!SelectorsLoaded.empty()) 4242 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n", 4243 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(), 4244 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100)); 4245 if (TotalNumStatements) 4246 std::fprintf(stderr, " %u/%u statements read (%f%%)\n", 4247 NumStatementsRead, TotalNumStatements, 4248 ((float)NumStatementsRead/TotalNumStatements * 100)); 4249 if (TotalNumMacros) 4250 std::fprintf(stderr, " %u/%u macros read (%f%%)\n", 4251 NumMacrosRead, TotalNumMacros, 4252 ((float)NumMacrosRead/TotalNumMacros * 100)); 4253 if (TotalLexicalDeclContexts) 4254 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n", 4255 NumLexicalDeclContextsRead, TotalLexicalDeclContexts, 4256 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts 4257 * 100)); 4258 if (TotalVisibleDeclContexts) 4259 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n", 4260 NumVisibleDeclContextsRead, TotalVisibleDeclContexts, 4261 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts 4262 * 100)); 4263 if (TotalNumMethodPoolEntries) { 4264 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n", 4265 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries, 4266 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries 4267 * 100)); 4268 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses); 4269 } 4270 std::fprintf(stderr, "\n"); 4271 } 4272 4273 /// Return the amount of memory used by memory buffers, breaking down 4274 /// by heap-backed versus mmap'ed memory. 4275 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const { 4276 for (unsigned i = 0, e = Chain.size(); i != e; ++i) 4277 if (llvm::MemoryBuffer *buf = Chain[i]->Buffer.get()) { 4278 size_t bytes = buf->getBufferSize(); 4279 switch (buf->getBufferKind()) { 4280 case llvm::MemoryBuffer::MemoryBuffer_Malloc: 4281 sizes.malloc_bytes += bytes; 4282 break; 4283 case llvm::MemoryBuffer::MemoryBuffer_MMap: 4284 sizes.mmap_bytes += bytes; 4285 break; 4286 } 4287 } 4288 } 4289 4290 void ASTReader::InitializeSema(Sema &S) { 4291 SemaObj = &S; 4292 S.ExternalSource = this; 4293 4294 // Makes sure any declarations that were deserialized "too early" 4295 // still get added to the identifier's declaration chains. 4296 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) { 4297 if (SemaObj->TUScope) 4298 SemaObj->TUScope->AddDecl(PreloadedDecls[I]); 4299 4300 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]); 4301 } 4302 PreloadedDecls.clear(); 4303 4304 // If there were any tentative definitions, deserialize them and add 4305 // them to Sema's list of tentative definitions. 4306 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) { 4307 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I])); 4308 SemaObj->TentativeDefinitions.push_back(Var); 4309 } 4310 4311 // If there were any unused file scoped decls, deserialize them and add to 4312 // Sema's list of unused file scoped decls. 4313 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) { 4314 DeclaratorDecl *D = cast<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I])); 4315 SemaObj->UnusedFileScopedDecls.push_back(D); 4316 } 4317 4318 // If there were any delegating constructors, add them to Sema's list 4319 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) { 4320 CXXConstructorDecl *D 4321 = cast<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I])); 4322 SemaObj->DelegatingCtorDecls.push_back(D); 4323 } 4324 4325 // If there were any locally-scoped external declarations, 4326 // deserialize them and add them to Sema's table of locally-scoped 4327 // external declarations. 4328 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) { 4329 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I])); 4330 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D; 4331 } 4332 4333 // If there were any ext_vector type declarations, deserialize them 4334 // and add them to Sema's vector of such declarations. 4335 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) 4336 SemaObj->ExtVectorDecls.push_back( 4337 cast<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]))); 4338 4339 // FIXME: Do VTable uses and dynamic classes deserialize too much ? 4340 // Can we cut them down before writing them ? 4341 4342 // If there were any dynamic classes declarations, deserialize them 4343 // and add them to Sema's vector of such declarations. 4344 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) 4345 SemaObj->DynamicClasses.push_back( 4346 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I]))); 4347 4348 // Load the offsets of the declarations that Sema references. 4349 // They will be lazily deserialized when needed. 4350 if (!SemaDeclRefs.empty()) { 4351 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!"); 4352 SemaObj->StdNamespace = SemaDeclRefs[0]; 4353 SemaObj->StdBadAlloc = SemaDeclRefs[1]; 4354 } 4355 4356 for (PerFileData *F = FirstInSource; F; F = F->NextInSource) { 4357 4358 // If there are @selector references added them to its pool. This is for 4359 // implementation of -Wselector. 4360 if (!F->ReferencedSelectorsData.empty()) { 4361 unsigned int DataSize = F->ReferencedSelectorsData.size()-1; 4362 unsigned I = 0; 4363 while (I < DataSize) { 4364 Selector Sel = DecodeSelector(F->ReferencedSelectorsData[I++]); 4365 SourceLocation SelLoc = ReadSourceLocation( 4366 *F, F->ReferencedSelectorsData, I); 4367 SemaObj->ReferencedSelectors.insert(std::make_pair(Sel, SelLoc)); 4368 } 4369 } 4370 } 4371 4372 // The special data sets below always come from the most recent PCH, 4373 // which is at the front of the chain. 4374 PerFileData &F = *Chain.front(); 4375 4376 // If there were any pending implicit instantiations, deserialize them 4377 // and add them to Sema's queue of such instantiations. 4378 assert(F.PendingInstantiations.size() % 2 == 0 && 4379 "Expected pairs of entries"); 4380 for (unsigned Idx = 0, N = F.PendingInstantiations.size(); Idx < N;) { 4381 ValueDecl *D=cast<ValueDecl>(GetDecl(F.PendingInstantiations[Idx++])); 4382 SourceLocation Loc = ReadSourceLocation(F, F.PendingInstantiations,Idx); 4383 SemaObj->PendingInstantiations.push_back(std::make_pair(D, Loc)); 4384 } 4385 4386 // If there were any weak undeclared identifiers, deserialize them and add to 4387 // Sema's list of weak undeclared identifiers. 4388 if (!WeakUndeclaredIdentifiers.empty()) { 4389 unsigned Idx = 0; 4390 for (unsigned I = 0, N = WeakUndeclaredIdentifiers[Idx++]; I != N; ++I) { 4391 IdentifierInfo *WeakId = GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx); 4392 IdentifierInfo *AliasId= GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx); 4393 SourceLocation Loc = ReadSourceLocation(F, WeakUndeclaredIdentifiers,Idx); 4394 bool Used = WeakUndeclaredIdentifiers[Idx++]; 4395 Sema::WeakInfo WI(AliasId, Loc); 4396 WI.setUsed(Used); 4397 SemaObj->WeakUndeclaredIdentifiers.insert(std::make_pair(WeakId, WI)); 4398 } 4399 } 4400 4401 // If there were any VTable uses, deserialize the information and add it 4402 // to Sema's vector and map of VTable uses. 4403 if (!VTableUses.empty()) { 4404 unsigned Idx = 0; 4405 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) { 4406 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++])); 4407 SourceLocation Loc = ReadSourceLocation(F, VTableUses, Idx); 4408 bool DefinitionRequired = VTableUses[Idx++]; 4409 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc)); 4410 SemaObj->VTablesUsed[Class] = DefinitionRequired; 4411 } 4412 } 4413 4414 if (!FPPragmaOptions.empty()) { 4415 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS"); 4416 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0]; 4417 } 4418 4419 if (!OpenCLExtensions.empty()) { 4420 unsigned I = 0; 4421 #define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++]; 4422 #include "clang/Basic/OpenCLExtensions.def" 4423 4424 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS"); 4425 } 4426 } 4427 4428 IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) { 4429 // Try to find this name within our on-disk hash tables. We start with the 4430 // most recent one, since that one contains the most up-to-date info. 4431 for (unsigned I = 0, N = Chain.size(); I != N; ++I) { 4432 ASTIdentifierLookupTable *IdTable 4433 = (ASTIdentifierLookupTable *)Chain[I]->IdentifierLookupTable; 4434 if (!IdTable) 4435 continue; 4436 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart); 4437 ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key); 4438 if (Pos == IdTable->end()) 4439 continue; 4440 4441 // Dereferencing the iterator has the effect of building the 4442 // IdentifierInfo node and populating it with the various 4443 // declarations it needs. 4444 return *Pos; 4445 } 4446 return 0; 4447 } 4448 4449 namespace clang { 4450 /// \brief An identifier-lookup iterator that enumerates all of the 4451 /// identifiers stored within a set of AST files. 4452 class ASTIdentifierIterator : public IdentifierIterator { 4453 /// \brief The AST reader whose identifiers are being enumerated. 4454 const ASTReader &Reader; 4455 4456 /// \brief The current index into the chain of AST files stored in 4457 /// the AST reader. 4458 unsigned Index; 4459 4460 /// \brief The current position within the identifier lookup table 4461 /// of the current AST file. 4462 ASTIdentifierLookupTable::key_iterator Current; 4463 4464 /// \brief The end position within the identifier lookup table of 4465 /// the current AST file. 4466 ASTIdentifierLookupTable::key_iterator End; 4467 4468 public: 4469 explicit ASTIdentifierIterator(const ASTReader &Reader); 4470 4471 virtual llvm::StringRef Next(); 4472 }; 4473 } 4474 4475 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader) 4476 : Reader(Reader), Index(Reader.Chain.size() - 1) { 4477 ASTIdentifierLookupTable *IdTable 4478 = (ASTIdentifierLookupTable *)Reader.Chain[Index]->IdentifierLookupTable; 4479 Current = IdTable->key_begin(); 4480 End = IdTable->key_end(); 4481 } 4482 4483 llvm::StringRef ASTIdentifierIterator::Next() { 4484 while (Current == End) { 4485 // If we have exhausted all of our AST files, we're done. 4486 if (Index == 0) 4487 return llvm::StringRef(); 4488 4489 --Index; 4490 ASTIdentifierLookupTable *IdTable 4491 = (ASTIdentifierLookupTable *)Reader.Chain[Index]->IdentifierLookupTable; 4492 Current = IdTable->key_begin(); 4493 End = IdTable->key_end(); 4494 } 4495 4496 // We have any identifiers remaining in the current AST file; return 4497 // the next one. 4498 std::pair<const char*, unsigned> Key = *Current; 4499 ++Current; 4500 return llvm::StringRef(Key.first, Key.second); 4501 } 4502 4503 IdentifierIterator *ASTReader::getIdentifiers() const { 4504 return new ASTIdentifierIterator(*this); 4505 } 4506 4507 std::pair<ObjCMethodList, ObjCMethodList> 4508 ASTReader::ReadMethodPool(Selector Sel) { 4509 // Find this selector in a hash table. We want to find the most recent entry. 4510 for (unsigned I = 0, N = Chain.size(); I != N; ++I) { 4511 PerFileData &F = *Chain[I]; 4512 if (!F.SelectorLookupTable) 4513 continue; 4514 4515 ASTSelectorLookupTable *PoolTable 4516 = (ASTSelectorLookupTable*)F.SelectorLookupTable; 4517 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel); 4518 if (Pos != PoolTable->end()) { 4519 ++NumSelectorsRead; 4520 // FIXME: Not quite happy with the statistics here. We probably should 4521 // disable this tracking when called via LoadSelector. 4522 // Also, should entries without methods count as misses? 4523 ++NumMethodPoolEntriesRead; 4524 ASTSelectorLookupTrait::data_type Data = *Pos; 4525 if (DeserializationListener) 4526 DeserializationListener->SelectorRead(Data.ID, Sel); 4527 return std::make_pair(Data.Instance, Data.Factory); 4528 } 4529 } 4530 4531 ++NumMethodPoolMisses; 4532 return std::pair<ObjCMethodList, ObjCMethodList>(); 4533 } 4534 4535 void ASTReader::ReadKnownNamespaces( 4536 llvm::SmallVectorImpl<NamespaceDecl *> &Namespaces) { 4537 Namespaces.clear(); 4538 4539 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) { 4540 if (NamespaceDecl *Namespace 4541 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I]))) 4542 Namespaces.push_back(Namespace); 4543 } 4544 } 4545 4546 void ASTReader::LoadSelector(Selector Sel) { 4547 // It would be complicated to avoid reading the methods anyway. So don't. 4548 ReadMethodPool(Sel); 4549 } 4550 4551 void ASTReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) { 4552 assert(ID && "Non-zero identifier ID required"); 4553 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range"); 4554 IdentifiersLoaded[ID - 1] = II; 4555 if (DeserializationListener) 4556 DeserializationListener->IdentifierRead(ID, II); 4557 } 4558 4559 /// \brief Set the globally-visible declarations associated with the given 4560 /// identifier. 4561 /// 4562 /// If the AST reader is currently in a state where the given declaration IDs 4563 /// cannot safely be resolved, they are queued until it is safe to resolve 4564 /// them. 4565 /// 4566 /// \param II an IdentifierInfo that refers to one or more globally-visible 4567 /// declarations. 4568 /// 4569 /// \param DeclIDs the set of declaration IDs with the name @p II that are 4570 /// visible at global scope. 4571 /// 4572 /// \param Nonrecursive should be true to indicate that the caller knows that 4573 /// this call is non-recursive, and therefore the globally-visible declarations 4574 /// will not be placed onto the pending queue. 4575 void 4576 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II, 4577 const llvm::SmallVectorImpl<uint32_t> &DeclIDs, 4578 bool Nonrecursive) { 4579 if (NumCurrentElementsDeserializing && !Nonrecursive) { 4580 PendingIdentifierInfos.push_back(PendingIdentifierInfo()); 4581 PendingIdentifierInfo &PII = PendingIdentifierInfos.back(); 4582 PII.II = II; 4583 PII.DeclIDs.append(DeclIDs.begin(), DeclIDs.end()); 4584 return; 4585 } 4586 4587 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) { 4588 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I])); 4589 if (SemaObj) { 4590 if (SemaObj->TUScope) { 4591 // Introduce this declaration into the translation-unit scope 4592 // and add it to the declaration chain for this identifier, so 4593 // that (unqualified) name lookup will find it. 4594 SemaObj->TUScope->AddDecl(D); 4595 } 4596 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D); 4597 } else { 4598 // Queue this declaration so that it will be added to the 4599 // translation unit scope and identifier's declaration chain 4600 // once a Sema object is known. 4601 PreloadedDecls.push_back(D); 4602 } 4603 } 4604 } 4605 4606 IdentifierInfo *ASTReader::DecodeIdentifierInfo(unsigned ID) { 4607 if (ID == 0) 4608 return 0; 4609 4610 if (IdentifiersLoaded.empty()) { 4611 Error("no identifier table in AST file"); 4612 return 0; 4613 } 4614 4615 assert(PP && "Forgot to set Preprocessor ?"); 4616 ID -= 1; 4617 if (!IdentifiersLoaded[ID]) { 4618 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1); 4619 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map"); 4620 unsigned Index = ID + I->second.second; 4621 const char *Str = I->second.first->IdentifierTableData 4622 + I->second.first->IdentifierOffsets[Index]; 4623 4624 // All of the strings in the AST file are preceded by a 16-bit length. 4625 // Extract that 16-bit length to avoid having to execute strlen(). 4626 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as 4627 // unsigned integers. This is important to avoid integer overflow when 4628 // we cast them to 'unsigned'. 4629 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2; 4630 unsigned StrLen = (((unsigned) StrLenPtr[0]) 4631 | (((unsigned) StrLenPtr[1]) << 8)) - 1; 4632 IdentifiersLoaded[ID] 4633 = &PP->getIdentifierTable().get(llvm::StringRef(Str, StrLen)); 4634 if (DeserializationListener) 4635 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]); 4636 } 4637 4638 return IdentifiersLoaded[ID]; 4639 } 4640 4641 bool ASTReader::ReadSLocEntry(int ID) { 4642 return ReadSLocEntryRecord(ID) != Success; 4643 } 4644 4645 Selector ASTReader::DecodeSelector(unsigned ID) { 4646 if (ID == 0) 4647 return Selector(); 4648 4649 if (ID > SelectorsLoaded.size()) { 4650 Error("selector ID out of range in AST file"); 4651 return Selector(); 4652 } 4653 4654 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) { 4655 // Load this selector from the selector table. 4656 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID); 4657 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map"); 4658 ASTSelectorLookupTrait Trait(*this); 4659 PerFileData &F = *I->second.first; 4660 unsigned Idx = ID - 1 + I->second.second; 4661 SelectorsLoaded[ID - 1] = 4662 Trait.ReadKey(F.SelectorLookupTableData + F.SelectorOffsets[Idx], 0); 4663 if (DeserializationListener) 4664 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]); 4665 } 4666 4667 return SelectorsLoaded[ID - 1]; 4668 } 4669 4670 Selector ASTReader::GetExternalSelector(uint32_t ID) { 4671 return DecodeSelector(ID); 4672 } 4673 4674 uint32_t ASTReader::GetNumExternalSelectors() { 4675 // ID 0 (the null selector) is considered an external selector. 4676 return getTotalNumSelectors() + 1; 4677 } 4678 4679 DeclarationName 4680 ASTReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) { 4681 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++]; 4682 switch (Kind) { 4683 case DeclarationName::Identifier: 4684 return DeclarationName(GetIdentifierInfo(Record, Idx)); 4685 4686 case DeclarationName::ObjCZeroArgSelector: 4687 case DeclarationName::ObjCOneArgSelector: 4688 case DeclarationName::ObjCMultiArgSelector: 4689 return DeclarationName(GetSelector(Record, Idx)); 4690 4691 case DeclarationName::CXXConstructorName: 4692 return Context->DeclarationNames.getCXXConstructorName( 4693 Context->getCanonicalType(GetType(Record[Idx++]))); 4694 4695 case DeclarationName::CXXDestructorName: 4696 return Context->DeclarationNames.getCXXDestructorName( 4697 Context->getCanonicalType(GetType(Record[Idx++]))); 4698 4699 case DeclarationName::CXXConversionFunctionName: 4700 return Context->DeclarationNames.getCXXConversionFunctionName( 4701 Context->getCanonicalType(GetType(Record[Idx++]))); 4702 4703 case DeclarationName::CXXOperatorName: 4704 return Context->DeclarationNames.getCXXOperatorName( 4705 (OverloadedOperatorKind)Record[Idx++]); 4706 4707 case DeclarationName::CXXLiteralOperatorName: 4708 return Context->DeclarationNames.getCXXLiteralOperatorName( 4709 GetIdentifierInfo(Record, Idx)); 4710 4711 case DeclarationName::CXXUsingDirective: 4712 return DeclarationName::getUsingDirectiveName(); 4713 } 4714 4715 // Required to silence GCC warning 4716 return DeclarationName(); 4717 } 4718 4719 void ASTReader::ReadDeclarationNameLoc(PerFileData &F, 4720 DeclarationNameLoc &DNLoc, 4721 DeclarationName Name, 4722 const RecordData &Record, unsigned &Idx) { 4723 switch (Name.getNameKind()) { 4724 case DeclarationName::CXXConstructorName: 4725 case DeclarationName::CXXDestructorName: 4726 case DeclarationName::CXXConversionFunctionName: 4727 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx); 4728 break; 4729 4730 case DeclarationName::CXXOperatorName: 4731 DNLoc.CXXOperatorName.BeginOpNameLoc 4732 = ReadSourceLocation(F, Record, Idx).getRawEncoding(); 4733 DNLoc.CXXOperatorName.EndOpNameLoc 4734 = ReadSourceLocation(F, Record, Idx).getRawEncoding(); 4735 break; 4736 4737 case DeclarationName::CXXLiteralOperatorName: 4738 DNLoc.CXXLiteralOperatorName.OpNameLoc 4739 = ReadSourceLocation(F, Record, Idx).getRawEncoding(); 4740 break; 4741 4742 case DeclarationName::Identifier: 4743 case DeclarationName::ObjCZeroArgSelector: 4744 case DeclarationName::ObjCOneArgSelector: 4745 case DeclarationName::ObjCMultiArgSelector: 4746 case DeclarationName::CXXUsingDirective: 4747 break; 4748 } 4749 } 4750 4751 void ASTReader::ReadDeclarationNameInfo(PerFileData &F, 4752 DeclarationNameInfo &NameInfo, 4753 const RecordData &Record, unsigned &Idx) { 4754 NameInfo.setName(ReadDeclarationName(Record, Idx)); 4755 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx)); 4756 DeclarationNameLoc DNLoc; 4757 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx); 4758 NameInfo.setInfo(DNLoc); 4759 } 4760 4761 void ASTReader::ReadQualifierInfo(PerFileData &F, QualifierInfo &Info, 4762 const RecordData &Record, unsigned &Idx) { 4763 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx); 4764 unsigned NumTPLists = Record[Idx++]; 4765 Info.NumTemplParamLists = NumTPLists; 4766 if (NumTPLists) { 4767 Info.TemplParamLists = new (*Context) TemplateParameterList*[NumTPLists]; 4768 for (unsigned i=0; i != NumTPLists; ++i) 4769 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx); 4770 } 4771 } 4772 4773 TemplateName 4774 ASTReader::ReadTemplateName(PerFileData &F, const RecordData &Record, 4775 unsigned &Idx) { 4776 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++]; 4777 switch (Kind) { 4778 case TemplateName::Template: 4779 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++]))); 4780 4781 case TemplateName::OverloadedTemplate: { 4782 unsigned size = Record[Idx++]; 4783 UnresolvedSet<8> Decls; 4784 while (size--) 4785 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++]))); 4786 4787 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end()); 4788 } 4789 4790 case TemplateName::QualifiedTemplate: { 4791 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx); 4792 bool hasTemplKeyword = Record[Idx++]; 4793 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++])); 4794 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template); 4795 } 4796 4797 case TemplateName::DependentTemplate: { 4798 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx); 4799 if (Record[Idx++]) // isIdentifier 4800 return Context->getDependentTemplateName(NNS, 4801 GetIdentifierInfo(Record, Idx)); 4802 return Context->getDependentTemplateName(NNS, 4803 (OverloadedOperatorKind)Record[Idx++]); 4804 } 4805 4806 case TemplateName::SubstTemplateTemplateParm: { 4807 TemplateTemplateParmDecl *param 4808 = cast_or_null<TemplateTemplateParmDecl>(GetDecl(Record[Idx++])); 4809 if (!param) return TemplateName(); 4810 TemplateName replacement = ReadTemplateName(F, Record, Idx); 4811 return Context->getSubstTemplateTemplateParm(param, replacement); 4812 } 4813 4814 case TemplateName::SubstTemplateTemplateParmPack: { 4815 TemplateTemplateParmDecl *Param 4816 = cast_or_null<TemplateTemplateParmDecl>(GetDecl(Record[Idx++])); 4817 if (!Param) 4818 return TemplateName(); 4819 4820 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx); 4821 if (ArgPack.getKind() != TemplateArgument::Pack) 4822 return TemplateName(); 4823 4824 return Context->getSubstTemplateTemplateParmPack(Param, ArgPack); 4825 } 4826 } 4827 4828 assert(0 && "Unhandled template name kind!"); 4829 return TemplateName(); 4830 } 4831 4832 TemplateArgument 4833 ASTReader::ReadTemplateArgument(PerFileData &F, 4834 const RecordData &Record, unsigned &Idx) { 4835 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++]; 4836 switch (Kind) { 4837 case TemplateArgument::Null: 4838 return TemplateArgument(); 4839 case TemplateArgument::Type: 4840 return TemplateArgument(GetType(Record[Idx++])); 4841 case TemplateArgument::Declaration: 4842 return TemplateArgument(GetDecl(Record[Idx++])); 4843 case TemplateArgument::Integral: { 4844 llvm::APSInt Value = ReadAPSInt(Record, Idx); 4845 QualType T = GetType(Record[Idx++]); 4846 return TemplateArgument(Value, T); 4847 } 4848 case TemplateArgument::Template: 4849 return TemplateArgument(ReadTemplateName(F, Record, Idx)); 4850 case TemplateArgument::TemplateExpansion: { 4851 TemplateName Name = ReadTemplateName(F, Record, Idx); 4852 llvm::Optional<unsigned> NumTemplateExpansions; 4853 if (unsigned NumExpansions = Record[Idx++]) 4854 NumTemplateExpansions = NumExpansions - 1; 4855 return TemplateArgument(Name, NumTemplateExpansions); 4856 } 4857 case TemplateArgument::Expression: 4858 return TemplateArgument(ReadExpr(F)); 4859 case TemplateArgument::Pack: { 4860 unsigned NumArgs = Record[Idx++]; 4861 TemplateArgument *Args = new (*Context) TemplateArgument[NumArgs]; 4862 for (unsigned I = 0; I != NumArgs; ++I) 4863 Args[I] = ReadTemplateArgument(F, Record, Idx); 4864 return TemplateArgument(Args, NumArgs); 4865 } 4866 } 4867 4868 assert(0 && "Unhandled template argument kind!"); 4869 return TemplateArgument(); 4870 } 4871 4872 TemplateParameterList * 4873 ASTReader::ReadTemplateParameterList(PerFileData &F, 4874 const RecordData &Record, unsigned &Idx) { 4875 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx); 4876 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx); 4877 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx); 4878 4879 unsigned NumParams = Record[Idx++]; 4880 llvm::SmallVector<NamedDecl *, 16> Params; 4881 Params.reserve(NumParams); 4882 while (NumParams--) 4883 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++]))); 4884 4885 TemplateParameterList* TemplateParams = 4886 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc, 4887 Params.data(), Params.size(), RAngleLoc); 4888 return TemplateParams; 4889 } 4890 4891 void 4892 ASTReader:: 4893 ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs, 4894 PerFileData &F, const RecordData &Record, 4895 unsigned &Idx) { 4896 unsigned NumTemplateArgs = Record[Idx++]; 4897 TemplArgs.reserve(NumTemplateArgs); 4898 while (NumTemplateArgs--) 4899 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx)); 4900 } 4901 4902 /// \brief Read a UnresolvedSet structure. 4903 void ASTReader::ReadUnresolvedSet(UnresolvedSetImpl &Set, 4904 const RecordData &Record, unsigned &Idx) { 4905 unsigned NumDecls = Record[Idx++]; 4906 while (NumDecls--) { 4907 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++])); 4908 AccessSpecifier AS = (AccessSpecifier)Record[Idx++]; 4909 Set.addDecl(D, AS); 4910 } 4911 } 4912 4913 CXXBaseSpecifier 4914 ASTReader::ReadCXXBaseSpecifier(PerFileData &F, 4915 const RecordData &Record, unsigned &Idx) { 4916 bool isVirtual = static_cast<bool>(Record[Idx++]); 4917 bool isBaseOfClass = static_cast<bool>(Record[Idx++]); 4918 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]); 4919 bool inheritConstructors = static_cast<bool>(Record[Idx++]); 4920 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx); 4921 SourceRange Range = ReadSourceRange(F, Record, Idx); 4922 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx); 4923 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo, 4924 EllipsisLoc); 4925 Result.setInheritConstructors(inheritConstructors); 4926 return Result; 4927 } 4928 4929 std::pair<CXXCtorInitializer **, unsigned> 4930 ASTReader::ReadCXXCtorInitializers(PerFileData &F, const RecordData &Record, 4931 unsigned &Idx) { 4932 CXXCtorInitializer **CtorInitializers = 0; 4933 unsigned NumInitializers = Record[Idx++]; 4934 if (NumInitializers) { 4935 ASTContext &C = *getContext(); 4936 4937 CtorInitializers 4938 = new (C) CXXCtorInitializer*[NumInitializers]; 4939 for (unsigned i=0; i != NumInitializers; ++i) { 4940 TypeSourceInfo *BaseClassInfo = 0; 4941 bool IsBaseVirtual = false; 4942 FieldDecl *Member = 0; 4943 IndirectFieldDecl *IndirectMember = 0; 4944 CXXConstructorDecl *Target = 0; 4945 4946 CtorInitializerType Type = (CtorInitializerType)Record[Idx++]; 4947 switch (Type) { 4948 case CTOR_INITIALIZER_BASE: 4949 BaseClassInfo = GetTypeSourceInfo(F, Record, Idx); 4950 IsBaseVirtual = Record[Idx++]; 4951 break; 4952 4953 case CTOR_INITIALIZER_DELEGATING: 4954 Target = cast<CXXConstructorDecl>(GetDecl(Record[Idx++])); 4955 break; 4956 4957 case CTOR_INITIALIZER_MEMBER: 4958 Member = cast<FieldDecl>(GetDecl(Record[Idx++])); 4959 break; 4960 4961 case CTOR_INITIALIZER_INDIRECT_MEMBER: 4962 IndirectMember = cast<IndirectFieldDecl>(GetDecl(Record[Idx++])); 4963 break; 4964 } 4965 4966 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx); 4967 Expr *Init = ReadExpr(F); 4968 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx); 4969 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx); 4970 bool IsWritten = Record[Idx++]; 4971 unsigned SourceOrderOrNumArrayIndices; 4972 llvm::SmallVector<VarDecl *, 8> Indices; 4973 if (IsWritten) { 4974 SourceOrderOrNumArrayIndices = Record[Idx++]; 4975 } else { 4976 SourceOrderOrNumArrayIndices = Record[Idx++]; 4977 Indices.reserve(SourceOrderOrNumArrayIndices); 4978 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i) 4979 Indices.push_back(cast<VarDecl>(GetDecl(Record[Idx++]))); 4980 } 4981 4982 CXXCtorInitializer *BOMInit; 4983 if (Type == CTOR_INITIALIZER_BASE) { 4984 BOMInit = new (C) CXXCtorInitializer(C, BaseClassInfo, IsBaseVirtual, 4985 LParenLoc, Init, RParenLoc, 4986 MemberOrEllipsisLoc); 4987 } else if (Type == CTOR_INITIALIZER_DELEGATING) { 4988 BOMInit = new (C) CXXCtorInitializer(C, MemberOrEllipsisLoc, LParenLoc, 4989 Target, Init, RParenLoc); 4990 } else if (IsWritten) { 4991 if (Member) 4992 BOMInit = new (C) CXXCtorInitializer(C, Member, MemberOrEllipsisLoc, 4993 LParenLoc, Init, RParenLoc); 4994 else 4995 BOMInit = new (C) CXXCtorInitializer(C, IndirectMember, 4996 MemberOrEllipsisLoc, LParenLoc, 4997 Init, RParenLoc); 4998 } else { 4999 BOMInit = CXXCtorInitializer::Create(C, Member, MemberOrEllipsisLoc, 5000 LParenLoc, Init, RParenLoc, 5001 Indices.data(), Indices.size()); 5002 } 5003 5004 if (IsWritten) 5005 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices); 5006 CtorInitializers[i] = BOMInit; 5007 } 5008 } 5009 5010 return std::make_pair(CtorInitializers, NumInitializers); 5011 } 5012 5013 NestedNameSpecifier * 5014 ASTReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) { 5015 unsigned N = Record[Idx++]; 5016 NestedNameSpecifier *NNS = 0, *Prev = 0; 5017 for (unsigned I = 0; I != N; ++I) { 5018 NestedNameSpecifier::SpecifierKind Kind 5019 = (NestedNameSpecifier::SpecifierKind)Record[Idx++]; 5020 switch (Kind) { 5021 case NestedNameSpecifier::Identifier: { 5022 IdentifierInfo *II = GetIdentifierInfo(Record, Idx); 5023 NNS = NestedNameSpecifier::Create(*Context, Prev, II); 5024 break; 5025 } 5026 5027 case NestedNameSpecifier::Namespace: { 5028 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++])); 5029 NNS = NestedNameSpecifier::Create(*Context, Prev, NS); 5030 break; 5031 } 5032 5033 case NestedNameSpecifier::NamespaceAlias: { 5034 NamespaceAliasDecl *Alias 5035 = cast<NamespaceAliasDecl>(GetDecl(Record[Idx++])); 5036 NNS = NestedNameSpecifier::Create(*Context, Prev, Alias); 5037 break; 5038 } 5039 5040 case NestedNameSpecifier::TypeSpec: 5041 case NestedNameSpecifier::TypeSpecWithTemplate: { 5042 const Type *T = GetType(Record[Idx++]).getTypePtrOrNull(); 5043 if (!T) 5044 return 0; 5045 5046 bool Template = Record[Idx++]; 5047 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T); 5048 break; 5049 } 5050 5051 case NestedNameSpecifier::Global: { 5052 NNS = NestedNameSpecifier::GlobalSpecifier(*Context); 5053 // No associated value, and there can't be a prefix. 5054 break; 5055 } 5056 } 5057 Prev = NNS; 5058 } 5059 return NNS; 5060 } 5061 5062 NestedNameSpecifierLoc 5063 ASTReader::ReadNestedNameSpecifierLoc(PerFileData &F, const RecordData &Record, 5064 unsigned &Idx) { 5065 unsigned N = Record[Idx++]; 5066 NestedNameSpecifierLocBuilder Builder; 5067 for (unsigned I = 0; I != N; ++I) { 5068 NestedNameSpecifier::SpecifierKind Kind 5069 = (NestedNameSpecifier::SpecifierKind)Record[Idx++]; 5070 switch (Kind) { 5071 case NestedNameSpecifier::Identifier: { 5072 IdentifierInfo *II = GetIdentifierInfo(Record, Idx); 5073 SourceRange Range = ReadSourceRange(F, Record, Idx); 5074 Builder.Extend(*Context, II, Range.getBegin(), Range.getEnd()); 5075 break; 5076 } 5077 5078 case NestedNameSpecifier::Namespace: { 5079 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++])); 5080 SourceRange Range = ReadSourceRange(F, Record, Idx); 5081 Builder.Extend(*Context, NS, Range.getBegin(), Range.getEnd()); 5082 break; 5083 } 5084 5085 case NestedNameSpecifier::NamespaceAlias: { 5086 NamespaceAliasDecl *Alias 5087 = cast<NamespaceAliasDecl>(GetDecl(Record[Idx++])); 5088 SourceRange Range = ReadSourceRange(F, Record, Idx); 5089 Builder.Extend(*Context, Alias, Range.getBegin(), Range.getEnd()); 5090 break; 5091 } 5092 5093 case NestedNameSpecifier::TypeSpec: 5094 case NestedNameSpecifier::TypeSpecWithTemplate: { 5095 bool Template = Record[Idx++]; 5096 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx); 5097 if (!T) 5098 return NestedNameSpecifierLoc(); 5099 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx); 5100 5101 // FIXME: 'template' keyword location not saved anywhere, so we fake it. 5102 Builder.Extend(*Context, 5103 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(), 5104 T->getTypeLoc(), ColonColonLoc); 5105 break; 5106 } 5107 5108 case NestedNameSpecifier::Global: { 5109 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx); 5110 Builder.MakeGlobal(*Context, ColonColonLoc); 5111 break; 5112 } 5113 } 5114 } 5115 5116 return Builder.getWithLocInContext(*Context); 5117 } 5118 5119 SourceRange 5120 ASTReader::ReadSourceRange(PerFileData &F, const RecordData &Record, 5121 unsigned &Idx) { 5122 SourceLocation beg = ReadSourceLocation(F, Record, Idx); 5123 SourceLocation end = ReadSourceLocation(F, Record, Idx); 5124 return SourceRange(beg, end); 5125 } 5126 5127 /// \brief Read an integral value 5128 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) { 5129 unsigned BitWidth = Record[Idx++]; 5130 unsigned NumWords = llvm::APInt::getNumWords(BitWidth); 5131 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]); 5132 Idx += NumWords; 5133 return Result; 5134 } 5135 5136 /// \brief Read a signed integral value 5137 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) { 5138 bool isUnsigned = Record[Idx++]; 5139 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned); 5140 } 5141 5142 /// \brief Read a floating-point value 5143 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) { 5144 return llvm::APFloat(ReadAPInt(Record, Idx)); 5145 } 5146 5147 // \brief Read a string 5148 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) { 5149 unsigned Len = Record[Idx++]; 5150 std::string Result(Record.data() + Idx, Record.data() + Idx + Len); 5151 Idx += Len; 5152 return Result; 5153 } 5154 5155 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record, 5156 unsigned &Idx) { 5157 unsigned Major = Record[Idx++]; 5158 unsigned Minor = Record[Idx++]; 5159 unsigned Subminor = Record[Idx++]; 5160 if (Minor == 0) 5161 return VersionTuple(Major); 5162 if (Subminor == 0) 5163 return VersionTuple(Major, Minor - 1); 5164 return VersionTuple(Major, Minor - 1, Subminor - 1); 5165 } 5166 5167 CXXTemporary *ASTReader::ReadCXXTemporary(const RecordData &Record, 5168 unsigned &Idx) { 5169 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++])); 5170 return CXXTemporary::Create(*Context, Decl); 5171 } 5172 5173 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) { 5174 return Diag(SourceLocation(), DiagID); 5175 } 5176 5177 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) { 5178 return Diags.Report(Loc, DiagID); 5179 } 5180 5181 /// \brief Retrieve the identifier table associated with the 5182 /// preprocessor. 5183 IdentifierTable &ASTReader::getIdentifierTable() { 5184 assert(PP && "Forgot to set Preprocessor ?"); 5185 return PP->getIdentifierTable(); 5186 } 5187 5188 /// \brief Record that the given ID maps to the given switch-case 5189 /// statement. 5190 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) { 5191 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID"); 5192 SwitchCaseStmts[ID] = SC; 5193 } 5194 5195 /// \brief Retrieve the switch-case statement with the given ID. 5196 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) { 5197 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID"); 5198 return SwitchCaseStmts[ID]; 5199 } 5200 5201 void ASTReader::ClearSwitchCaseIDs() { 5202 SwitchCaseStmts.clear(); 5203 } 5204 5205 void ASTReader::FinishedDeserializing() { 5206 assert(NumCurrentElementsDeserializing && 5207 "FinishedDeserializing not paired with StartedDeserializing"); 5208 if (NumCurrentElementsDeserializing == 1) { 5209 // If any identifiers with corresponding top-level declarations have 5210 // been loaded, load those declarations now. 5211 while (!PendingIdentifierInfos.empty()) { 5212 SetGloballyVisibleDecls(PendingIdentifierInfos.front().II, 5213 PendingIdentifierInfos.front().DeclIDs, true); 5214 PendingIdentifierInfos.pop_front(); 5215 } 5216 5217 // Ready to load previous declarations of Decls that were delayed. 5218 while (!PendingPreviousDecls.empty()) { 5219 loadAndAttachPreviousDecl(PendingPreviousDecls.front().first, 5220 PendingPreviousDecls.front().second); 5221 PendingPreviousDecls.pop_front(); 5222 } 5223 5224 // We are not in recursive loading, so it's safe to pass the "interesting" 5225 // decls to the consumer. 5226 if (Consumer) 5227 PassInterestingDeclsToConsumer(); 5228 5229 assert(PendingForwardRefs.size() == 0 && 5230 "Some forward refs did not get linked to the definition!"); 5231 } 5232 --NumCurrentElementsDeserializing; 5233 } 5234 5235 ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context, 5236 const char *isysroot, bool DisableValidation, 5237 bool DisableStatCache) 5238 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0), 5239 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()), 5240 Diags(PP.getDiagnostics()), SemaObj(0), PP(&PP), Context(Context), 5241 Consumer(0), FirstInSource(0), RelocatablePCH(false), isysroot(isysroot), 5242 DisableValidation(DisableValidation), 5243 DisableStatCache(DisableStatCache), NumStatHits(0), NumStatMisses(0), 5244 NumSLocEntriesRead(0), TotalNumSLocEntries(0), 5245 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0), 5246 TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0), 5247 NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0), 5248 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0), 5249 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0), 5250 NumCurrentElementsDeserializing(0) 5251 { 5252 SourceMgr.setExternalSLocEntrySource(this); 5253 } 5254 5255 ASTReader::ASTReader(SourceManager &SourceMgr, FileManager &FileMgr, 5256 Diagnostic &Diags, const char *isysroot, 5257 bool DisableValidation, bool DisableStatCache) 5258 : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr), 5259 Diags(Diags), SemaObj(0), PP(0), Context(0), Consumer(0), FirstInSource(0), 5260 RelocatablePCH(false), isysroot(isysroot), 5261 DisableValidation(DisableValidation), DisableStatCache(DisableStatCache), 5262 NumStatHits(0), NumStatMisses(0), NumSLocEntriesRead(0), 5263 TotalNumSLocEntries(0), NumStatementsRead(0), 5264 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0), 5265 NumSelectorsRead(0), NumMethodPoolEntriesRead(0), NumMethodPoolMisses(0), 5266 TotalNumMethodPoolEntries(0), NumLexicalDeclContextsRead(0), 5267 TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0), 5268 TotalVisibleDeclContexts(0), NumCurrentElementsDeserializing(0) 5269 { 5270 SourceMgr.setExternalSLocEntrySource(this); 5271 } 5272 5273 ASTReader::~ASTReader() { 5274 for (unsigned i = 0, e = Chain.size(); i != e; ++i) 5275 delete Chain[e - i - 1]; 5276 // Delete all visible decl lookup tables 5277 for (DeclContextOffsetsMap::iterator I = DeclContextOffsets.begin(), 5278 E = DeclContextOffsets.end(); 5279 I != E; ++I) { 5280 for (DeclContextInfos::iterator J = I->second.begin(), F = I->second.end(); 5281 J != F; ++J) { 5282 if (J->NameLookupTableData) 5283 delete static_cast<ASTDeclContextNameLookupTable*>( 5284 J->NameLookupTableData); 5285 } 5286 } 5287 for (DeclContextVisibleUpdatesPending::iterator 5288 I = PendingVisibleUpdates.begin(), 5289 E = PendingVisibleUpdates.end(); 5290 I != E; ++I) { 5291 for (DeclContextVisibleUpdates::iterator J = I->second.begin(), 5292 F = I->second.end(); 5293 J != F; ++J) 5294 delete static_cast<ASTDeclContextNameLookupTable*>(*J); 5295 } 5296 } 5297 5298 ASTReader::PerFileData::PerFileData(ASTFileType Ty) 5299 : Type(Ty), SizeInBits(0), LocalNumSLocEntries(0), SLocEntryBaseID(0), 5300 SLocEntryBaseOffset(0), SLocEntryOffsets(0), 5301 SLocFileOffsets(0), LocalNumIdentifiers(0), 5302 IdentifierOffsets(0), IdentifierTableData(0), 5303 IdentifierLookupTable(0), LocalNumMacroDefinitions(0), 5304 MacroDefinitionOffsets(0), LocalNumHeaderFileInfos(0), 5305 HeaderFileInfoTableData(0), HeaderFileInfoTable(0), 5306 LocalNumSelectors(0), SelectorOffsets(0), 5307 SelectorLookupTableData(0), SelectorLookupTable(0), LocalNumDecls(0), 5308 DeclOffsets(0), LocalNumCXXBaseSpecifiers(0), CXXBaseSpecifiersOffsets(0), 5309 LocalNumTypes(0), TypeOffsets(0), StatCache(0), 5310 NumPreallocatedPreprocessingEntities(0), NextInSource(0) 5311 {} 5312 5313 ASTReader::PerFileData::~PerFileData() { 5314 delete static_cast<ASTIdentifierLookupTable *>(IdentifierLookupTable); 5315 delete static_cast<HeaderFileInfoLookupTable *>(HeaderFileInfoTable); 5316 delete static_cast<ASTSelectorLookupTable *>(SelectorLookupTable); 5317 } 5318