1 //===--- ASTReader.cpp - AST File Reader ------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ASTReader class, which reads AST files.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Serialization/ASTReader.h"
15 #include "clang/Serialization/ASTDeserializationListener.h"
16 #include "clang/Serialization/ModuleManager.h"
17 #include "ASTCommon.h"
18 #include "ASTReaderInternals.h"
19 #include "clang/Frontend/FrontendDiagnostic.h"
20 #include "clang/Frontend/Utils.h"
21 #include "clang/Sema/Sema.h"
22 #include "clang/Sema/Scope.h"
23 #include "clang/AST/ASTConsumer.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/NestedNameSpecifier.h"
29 #include "clang/AST/Type.h"
30 #include "clang/AST/TypeLocVisitor.h"
31 #include "clang/Lex/MacroInfo.h"
32 #include "clang/Lex/PreprocessingRecord.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Lex/HeaderSearch.h"
35 #include "clang/Basic/OnDiskHashTable.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/SourceManagerInternals.h"
38 #include "clang/Basic/FileManager.h"
39 #include "clang/Basic/FileSystemStatCache.h"
40 #include "clang/Basic/TargetInfo.h"
41 #include "clang/Basic/Version.h"
42 #include "clang/Basic/VersionTuple.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include "llvm/Bitcode/BitstreamReader.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/FileSystem.h"
48 #include "llvm/Support/Path.h"
49 #include "llvm/Support/system_error.h"
55 using namespace clang;
56 using namespace clang::serialization;
57 using namespace clang::serialization::reader;
59 //===----------------------------------------------------------------------===//
60 // PCH validator implementation
61 //===----------------------------------------------------------------------===//
63 ASTReaderListener::~ASTReaderListener() {}
66 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
67 const LangOptions &PPLangOpts = PP.getLangOptions();
69 #define LANGOPT(Name, Bits, Default, Description) \
70 if (PPLangOpts.Name != LangOpts.Name) { \
71 Reader.Diag(diag::err_pch_langopt_mismatch) \
72 << Description << LangOpts.Name << PPLangOpts.Name; \
76 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
77 if (PPLangOpts.Name != LangOpts.Name) { \
78 Reader.Diag(diag::err_pch_langopt_value_mismatch) \
83 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
84 if (PPLangOpts.get##Name() != LangOpts.get##Name()) { \
85 Reader.Diag(diag::err_pch_langopt_value_mismatch) \
90 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
91 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
92 #include "clang/Basic/LangOptions.def"
97 bool PCHValidator::ReadTargetTriple(StringRef Triple) {
98 if (Triple == PP.getTargetInfo().getTriple().str())
101 Reader.Diag(diag::warn_pch_target_triple)
102 << Triple << PP.getTargetInfo().getTriple().str();
107 struct EmptyStringRef {
108 bool operator ()(StringRef r) const { return r.empty(); }
111 bool operator ()(const PCHPredefinesBlock &r) const {return r.Data.empty();}
115 static bool EqualConcatenations(SmallVector<StringRef, 2> L,
116 PCHPredefinesBlocks R) {
117 // First, sum up the lengths.
118 unsigned LL = 0, RL = 0;
119 for (unsigned I = 0, N = L.size(); I != N; ++I) {
122 for (unsigned I = 0, N = R.size(); I != N; ++I) {
123 RL += R[I].Data.size();
127 if (LL == 0 && RL == 0)
130 // Kick out empty parts, they confuse the algorithm below.
131 L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
132 R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
134 // Do it the hard way. At this point, both vectors must be non-empty.
135 StringRef LR = L[0], RR = R[0].Data;
136 unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
139 // Compare the current pieces.
140 if (LR.size() == RR.size()) {
141 // If they're the same length, it's pretty easy.
144 // Both pieces are done, advance.
147 // If either string is done, they're both done, since they're the same
150 assert(RI == RN && "Strings not the same length after all?");
155 } else if (LR.size() < RR.size()) {
156 // Right piece is longer.
157 if (!RR.startswith(LR))
160 assert(LI != LN && "Strings not the same length after all?");
161 RR = RR.substr(LR.size());
164 // Left piece is longer.
165 if (!LR.startswith(RR))
168 assert(RI != RN && "Strings not the same length after all?");
169 LR = LR.substr(RR.size());
175 static std::pair<FileID, StringRef::size_type>
176 FindMacro(const PCHPredefinesBlocks &Buffers, StringRef MacroDef) {
177 std::pair<FileID, StringRef::size_type> Res;
178 for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
179 Res.second = Buffers[I].Data.find(MacroDef);
180 if (Res.second != StringRef::npos) {
181 Res.first = Buffers[I].BufferID;
188 bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
189 StringRef OriginalFileName,
190 std::string &SuggestedPredefines,
191 FileManager &FileMgr) {
192 // We are in the context of an implicit include, so the predefines buffer will
193 // have a #include entry for the PCH file itself (as normalized by the
194 // preprocessor initialization). Find it and skip over it in the checking
196 llvm::SmallString<256> PCHInclude;
197 PCHInclude += "#include \"";
198 PCHInclude += NormalizeDashIncludePath(OriginalFileName, FileMgr);
199 PCHInclude += "\"\n";
200 std::pair<StringRef,StringRef> Split =
201 StringRef(PP.getPredefines()).split(PCHInclude.str());
202 StringRef Left = Split.first, Right = Split.second;
203 if (Left == PP.getPredefines()) {
204 Error("Missing PCH include entry!");
208 // If the concatenation of all the PCH buffers is equal to the adjusted
209 // command line, we're done.
210 SmallVector<StringRef, 2> CommandLine;
211 CommandLine.push_back(Left);
212 CommandLine.push_back(Right);
213 if (EqualConcatenations(CommandLine, Buffers))
216 SourceManager &SourceMgr = PP.getSourceManager();
218 // The predefines buffers are different. Determine what the differences are,
219 // and whether they require us to reject the PCH file.
220 SmallVector<StringRef, 8> PCHLines;
221 for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
222 Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
224 SmallVector<StringRef, 8> CmdLineLines;
225 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
227 // Pick out implicit #includes after the PCH and don't consider them for
228 // validation; we will insert them into SuggestedPredefines so that the
229 // preprocessor includes them.
230 std::string IncludesAfterPCH;
231 SmallVector<StringRef, 8> AfterPCHLines;
232 Right.split(AfterPCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
233 for (unsigned i = 0, e = AfterPCHLines.size(); i != e; ++i) {
234 if (AfterPCHLines[i].startswith("#include ")) {
235 IncludesAfterPCH += AfterPCHLines[i];
236 IncludesAfterPCH += '\n';
238 CmdLineLines.push_back(AfterPCHLines[i]);
242 // Make sure we add the includes last into SuggestedPredefines before we
243 // exit this function.
244 struct AddIncludesRAII {
245 std::string &SuggestedPredefines;
246 std::string &IncludesAfterPCH;
248 AddIncludesRAII(std::string &SuggestedPredefines,
249 std::string &IncludesAfterPCH)
250 : SuggestedPredefines(SuggestedPredefines),
251 IncludesAfterPCH(IncludesAfterPCH) { }
253 SuggestedPredefines += IncludesAfterPCH;
255 } AddIncludes(SuggestedPredefines, IncludesAfterPCH);
257 // Sort both sets of predefined buffer lines, since we allow some extra
258 // definitions and they may appear at any point in the output.
259 std::sort(CmdLineLines.begin(), CmdLineLines.end());
260 std::sort(PCHLines.begin(), PCHLines.end());
262 // Determine which predefines that were used to build the PCH file are missing
263 // from the command line.
264 std::vector<StringRef> MissingPredefines;
265 std::set_difference(PCHLines.begin(), PCHLines.end(),
266 CmdLineLines.begin(), CmdLineLines.end(),
267 std::back_inserter(MissingPredefines));
269 bool MissingDefines = false;
270 bool ConflictingDefines = false;
271 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
272 StringRef Missing = MissingPredefines[I];
273 if (Missing.startswith("#include ")) {
274 // An -include was specified when generating the PCH; it is included in
275 // the PCH, just ignore it.
278 if (!Missing.startswith("#define ")) {
279 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
283 // This is a macro definition. Determine the name of the macro we're
285 std::string::size_type StartOfMacroName = strlen("#define ");
286 std::string::size_type EndOfMacroName
287 = Missing.find_first_of("( \n\r", StartOfMacroName);
288 assert(EndOfMacroName != std::string::npos &&
289 "Couldn't find the end of the macro name");
290 StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
292 // Determine whether this macro was given a different definition on the
294 std::string MacroDefStart = "#define " + MacroName.str();
295 std::string::size_type MacroDefLen = MacroDefStart.size();
296 SmallVector<StringRef, 8>::iterator ConflictPos
297 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
299 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
300 if (!ConflictPos->startswith(MacroDefStart)) {
301 // Different macro; we're done.
302 ConflictPos = CmdLineLines.end();
306 assert(ConflictPos->size() > MacroDefLen &&
307 "Invalid #define in predefines buffer?");
308 if ((*ConflictPos)[MacroDefLen] != ' ' &&
309 (*ConflictPos)[MacroDefLen] != '(')
310 continue; // Longer macro name; keep trying.
312 // We found a conflicting macro definition.
316 if (ConflictPos != CmdLineLines.end()) {
317 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
320 // Show the definition of this macro within the PCH file.
321 std::pair<FileID, StringRef::size_type> MacroLoc =
322 FindMacro(Buffers, Missing);
323 assert(MacroLoc.second!=StringRef::npos && "Unable to find macro!");
324 SourceLocation PCHMissingLoc =
325 SourceMgr.getLocForStartOfFile(MacroLoc.first)
326 .getLocWithOffset(MacroLoc.second);
327 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
329 ConflictingDefines = true;
333 // If the macro doesn't conflict, then we'll just pick up the macro
334 // definition from the PCH file. Warn the user that they made a mistake.
335 if (ConflictingDefines)
336 continue; // Don't complain if there are already conflicting defs
338 if (!MissingDefines) {
339 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
340 MissingDefines = true;
343 // Show the definition of this macro within the PCH file.
344 std::pair<FileID, StringRef::size_type> MacroLoc =
345 FindMacro(Buffers, Missing);
346 assert(MacroLoc.second!=StringRef::npos && "Unable to find macro!");
347 SourceLocation PCHMissingLoc =
348 SourceMgr.getLocForStartOfFile(MacroLoc.first)
349 .getLocWithOffset(MacroLoc.second);
350 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
353 if (ConflictingDefines)
356 // Determine what predefines were introduced based on command-line
357 // parameters that were not present when building the PCH
358 // file. Extra #defines are okay, so long as the identifiers being
359 // defined were not used within the precompiled header.
360 std::vector<StringRef> ExtraPredefines;
361 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
362 PCHLines.begin(), PCHLines.end(),
363 std::back_inserter(ExtraPredefines));
364 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
365 StringRef &Extra = ExtraPredefines[I];
366 if (!Extra.startswith("#define ")) {
367 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
371 // This is an extra macro definition. Determine the name of the
372 // macro we're defining.
373 std::string::size_type StartOfMacroName = strlen("#define ");
374 std::string::size_type EndOfMacroName
375 = Extra.find_first_of("( \n\r", StartOfMacroName);
376 assert(EndOfMacroName != std::string::npos &&
377 "Couldn't find the end of the macro name");
378 StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
380 // Check whether this name was used somewhere in the PCH file. If
381 // so, defining it as a macro could change behavior, so we reject
383 if (IdentifierInfo *II = Reader.get(MacroName)) {
384 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
388 // Add this definition to the suggested predefines buffer.
389 SuggestedPredefines += Extra;
390 SuggestedPredefines += '\n';
393 // If we get here, it's because the predefines buffer had compatible
394 // contents. Accept the PCH file.
398 void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
400 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
404 void PCHValidator::ReadCounter(unsigned Value) {
405 PP.setCounterValue(Value);
408 //===----------------------------------------------------------------------===//
409 // AST reader implementation
410 //===----------------------------------------------------------------------===//
413 ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
414 DeserializationListener = Listener;
419 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
420 return serialization::ComputeHash(Sel);
424 std::pair<unsigned, unsigned>
425 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
426 using namespace clang::io;
427 unsigned KeyLen = ReadUnalignedLE16(d);
428 unsigned DataLen = ReadUnalignedLE16(d);
429 return std::make_pair(KeyLen, DataLen);
432 ASTSelectorLookupTrait::internal_key_type
433 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
434 using namespace clang::io;
435 SelectorTable &SelTable = Reader.getContext().Selectors;
436 unsigned N = ReadUnalignedLE16(d);
437 IdentifierInfo *FirstII
438 = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
440 return SelTable.getNullarySelector(FirstII);
442 return SelTable.getUnarySelector(FirstII);
444 SmallVector<IdentifierInfo *, 16> Args;
445 Args.push_back(FirstII);
446 for (unsigned I = 1; I != N; ++I)
447 Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
449 return SelTable.getSelector(N, Args.data());
452 ASTSelectorLookupTrait::data_type
453 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
455 using namespace clang::io;
459 Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
460 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
461 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
463 // Load instance methods
464 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
465 if (ObjCMethodDecl *Method
466 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
467 Result.Instance.push_back(Method);
470 // Load factory methods
471 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
472 if (ObjCMethodDecl *Method
473 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
474 Result.Factory.push_back(Method);
480 unsigned ASTIdentifierLookupTrait::ComputeHash(const internal_key_type& a) {
481 return llvm::HashString(StringRef(a.first, a.second));
484 std::pair<unsigned, unsigned>
485 ASTIdentifierLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
486 using namespace clang::io;
487 unsigned DataLen = ReadUnalignedLE16(d);
488 unsigned KeyLen = ReadUnalignedLE16(d);
489 return std::make_pair(KeyLen, DataLen);
492 std::pair<const char*, unsigned>
493 ASTIdentifierLookupTrait::ReadKey(const unsigned char* d, unsigned n) {
494 assert(n >= 2 && d[n-1] == '\0');
495 return std::make_pair((const char*) d, n-1);
498 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
499 const unsigned char* d,
501 using namespace clang::io;
502 unsigned RawID = ReadUnalignedLE32(d);
503 bool IsInteresting = RawID & 0x01;
505 // Wipe out the "is interesting" bit.
508 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
509 if (!IsInteresting) {
510 // For uninteresting identifiers, just build the IdentifierInfo
511 // and associate it with the persistent ID.
512 IdentifierInfo *II = KnownII;
514 II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
515 Reader.SetIdentifierInfo(ID, II);
520 unsigned Bits = ReadUnalignedLE16(d);
521 bool CPlusPlusOperatorKeyword = Bits & 0x01;
523 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
525 bool Poisoned = Bits & 0x01;
527 bool ExtensionToken = Bits & 0x01;
529 bool hasMacroDefinition = Bits & 0x01;
531 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
534 assert(Bits == 0 && "Extra bits in the identifier?");
537 // Build the IdentifierInfo itself and link the identifier ID with
538 // the new IdentifierInfo.
539 IdentifierInfo *II = KnownII;
541 II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
542 Reader.SetIdentifierInfo(ID, II);
544 // Set or check the various bits in the IdentifierInfo structure.
545 // Token IDs are read-only.
546 if (HasRevertedTokenIDToIdentifier)
547 II->RevertTokenIDToIdentifier();
548 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
549 assert(II->isExtensionToken() == ExtensionToken &&
550 "Incorrect extension token flag");
551 (void)ExtensionToken;
553 II->setIsPoisoned(true);
554 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
555 "Incorrect C++ operator keyword flag");
556 (void)CPlusPlusOperatorKeyword;
558 // If this identifier is a macro, deserialize the macro
560 if (hasMacroDefinition) {
561 // FIXME: Check for conflicts?
562 uint32_t Offset = ReadUnalignedLE32(d);
563 Reader.SetIdentifierIsMacro(II, F, Offset);
567 // Read all of the declarations visible at global scope with this
570 SmallVector<uint32_t, 4> DeclIDs;
571 for (; DataLen > 0; DataLen -= 4)
572 DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
573 Reader.SetGloballyVisibleDecls(II, DeclIDs);
581 ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
582 llvm::FoldingSetNodeID ID;
583 ID.AddInteger(Key.Kind);
586 case DeclarationName::Identifier:
587 case DeclarationName::CXXLiteralOperatorName:
588 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
590 case DeclarationName::ObjCZeroArgSelector:
591 case DeclarationName::ObjCOneArgSelector:
592 case DeclarationName::ObjCMultiArgSelector:
593 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
595 case DeclarationName::CXXOperatorName:
596 ID.AddInteger((OverloadedOperatorKind)Key.Data);
598 case DeclarationName::CXXConstructorName:
599 case DeclarationName::CXXDestructorName:
600 case DeclarationName::CXXConversionFunctionName:
601 case DeclarationName::CXXUsingDirective:
605 return ID.ComputeHash();
608 ASTDeclContextNameLookupTrait::internal_key_type
609 ASTDeclContextNameLookupTrait::GetInternalKey(
610 const external_key_type& Name) const {
612 Key.Kind = Name.getNameKind();
613 switch (Name.getNameKind()) {
614 case DeclarationName::Identifier:
615 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
617 case DeclarationName::ObjCZeroArgSelector:
618 case DeclarationName::ObjCOneArgSelector:
619 case DeclarationName::ObjCMultiArgSelector:
620 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
622 case DeclarationName::CXXOperatorName:
623 Key.Data = Name.getCXXOverloadedOperator();
625 case DeclarationName::CXXLiteralOperatorName:
626 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
628 case DeclarationName::CXXConstructorName:
629 case DeclarationName::CXXDestructorName:
630 case DeclarationName::CXXConversionFunctionName:
631 case DeclarationName::CXXUsingDirective:
639 ASTDeclContextNameLookupTrait::external_key_type
640 ASTDeclContextNameLookupTrait::GetExternalKey(
641 const internal_key_type& Key) const {
642 ASTContext &Context = Reader.getContext();
644 case DeclarationName::Identifier:
645 return DeclarationName((IdentifierInfo*)Key.Data);
647 case DeclarationName::ObjCZeroArgSelector:
648 case DeclarationName::ObjCOneArgSelector:
649 case DeclarationName::ObjCMultiArgSelector:
650 return DeclarationName(Selector(Key.Data));
652 case DeclarationName::CXXConstructorName:
653 return Context.DeclarationNames.getCXXConstructorName(
654 Context.getCanonicalType(Reader.getLocalType(F, Key.Data)));
656 case DeclarationName::CXXDestructorName:
657 return Context.DeclarationNames.getCXXDestructorName(
658 Context.getCanonicalType(Reader.getLocalType(F, Key.Data)));
660 case DeclarationName::CXXConversionFunctionName:
661 return Context.DeclarationNames.getCXXConversionFunctionName(
662 Context.getCanonicalType(Reader.getLocalType(F, Key.Data)));
664 case DeclarationName::CXXOperatorName:
665 return Context.DeclarationNames.getCXXOperatorName(
666 (OverloadedOperatorKind)Key.Data);
668 case DeclarationName::CXXLiteralOperatorName:
669 return Context.DeclarationNames.getCXXLiteralOperatorName(
670 (IdentifierInfo*)Key.Data);
672 case DeclarationName::CXXUsingDirective:
673 return DeclarationName::getUsingDirectiveName();
676 llvm_unreachable("Invalid Name Kind ?");
679 std::pair<unsigned, unsigned>
680 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
681 using namespace clang::io;
682 unsigned KeyLen = ReadUnalignedLE16(d);
683 unsigned DataLen = ReadUnalignedLE16(d);
684 return std::make_pair(KeyLen, DataLen);
687 ASTDeclContextNameLookupTrait::internal_key_type
688 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
689 using namespace clang::io;
692 Key.Kind = (DeclarationName::NameKind)*d++;
694 case DeclarationName::Identifier:
695 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
697 case DeclarationName::ObjCZeroArgSelector:
698 case DeclarationName::ObjCOneArgSelector:
699 case DeclarationName::ObjCMultiArgSelector:
701 (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
704 case DeclarationName::CXXOperatorName:
705 Key.Data = *d++; // OverloadedOperatorKind
707 case DeclarationName::CXXLiteralOperatorName:
708 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
710 case DeclarationName::CXXConstructorName:
711 case DeclarationName::CXXDestructorName:
712 case DeclarationName::CXXConversionFunctionName:
713 case DeclarationName::CXXUsingDirective:
721 ASTDeclContextNameLookupTrait::data_type
722 ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
723 const unsigned char* d,
725 using namespace clang::io;
726 unsigned NumDecls = ReadUnalignedLE16(d);
727 DeclID *Start = (DeclID *)d;
728 return std::make_pair(Start, Start + NumDecls);
731 bool ASTReader::ReadDeclContextStorage(Module &M,
732 llvm::BitstreamCursor &Cursor,
733 const std::pair<uint64_t, uint64_t> &Offsets,
734 DeclContextInfo &Info) {
735 SavedStreamPosition SavedPosition(Cursor);
736 // First the lexical decls.
737 if (Offsets.first != 0) {
738 Cursor.JumpToBit(Offsets.first);
743 unsigned Code = Cursor.ReadCode();
744 unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
745 if (RecCode != DECL_CONTEXT_LEXICAL) {
746 Error("Expected lexical block");
750 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob);
751 Info.NumLexicalDecls = BlobLen / sizeof(KindDeclIDPair);
754 // Now the lookup table.
755 if (Offsets.second != 0) {
756 Cursor.JumpToBit(Offsets.second);
761 unsigned Code = Cursor.ReadCode();
762 unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
763 if (RecCode != DECL_CONTEXT_VISIBLE) {
764 Error("Expected visible lookup table block");
767 Info.NameLookupTableData
768 = ASTDeclContextNameLookupTable::Create(
769 (const unsigned char *)Blob + Record[0],
770 (const unsigned char *)Blob,
771 ASTDeclContextNameLookupTrait(*this, M));
777 void ASTReader::Error(StringRef Msg) {
778 Error(diag::err_fe_pch_malformed, Msg);
781 void ASTReader::Error(unsigned DiagID,
782 StringRef Arg1, StringRef Arg2) {
783 if (Diags.isDiagnosticInFlight())
784 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
786 Diag(DiagID) << Arg1 << Arg2;
789 /// \brief Tell the AST listener about the predefines buffers in the chain.
790 bool ASTReader::CheckPredefinesBuffers() {
792 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
793 ActualOriginalFileName,
799 //===----------------------------------------------------------------------===//
800 // Source Manager Deserialization
801 //===----------------------------------------------------------------------===//
803 /// \brief Read the line table in the source manager block.
804 /// \returns true if there was an error.
805 bool ASTReader::ParseLineTable(Module &F,
806 SmallVectorImpl<uint64_t> &Record) {
808 LineTableInfo &LineTable = SourceMgr.getLineTable();
810 // Parse the file names
811 std::map<int, int> FileIDs;
812 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
813 // Extract the file name
814 unsigned FilenameLen = Record[Idx++];
815 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
817 MaybeAddSystemRootToFilename(Filename);
818 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
821 // Parse the line entries
822 std::vector<LineEntry> Entries;
823 while (Idx < Record.size()) {
824 int FID = Record[Idx++];
825 assert(FID >= 0 && "Serialized line entries for non-local file.");
826 // Remap FileID from 1-based old view.
827 FID += F.SLocEntryBaseID - 1;
829 // Extract the line entries
830 unsigned NumEntries = Record[Idx++];
831 assert(NumEntries && "Numentries is 00000");
833 Entries.reserve(NumEntries);
834 for (unsigned I = 0; I != NumEntries; ++I) {
835 unsigned FileOffset = Record[Idx++];
836 unsigned LineNo = Record[Idx++];
837 int FilenameID = FileIDs[Record[Idx++]];
838 SrcMgr::CharacteristicKind FileKind
839 = (SrcMgr::CharacteristicKind)Record[Idx++];
840 unsigned IncludeOffset = Record[Idx++];
841 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
842 FileKind, IncludeOffset));
844 LineTable.AddEntry(FID, Entries);
860 ASTStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
861 : ino(i), dev(d), mode(mo), mtime(m), size(s) {}
864 class ASTStatLookupTrait {
866 typedef const char *external_key_type;
867 typedef const char *internal_key_type;
869 typedef ASTStatData data_type;
871 static unsigned ComputeHash(const char *path) {
872 return llvm::HashString(path);
875 static internal_key_type GetInternalKey(const char *path) { return path; }
877 static bool EqualKey(internal_key_type a, internal_key_type b) {
878 return strcmp(a, b) == 0;
881 static std::pair<unsigned, unsigned>
882 ReadKeyDataLength(const unsigned char*& d) {
883 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
884 unsigned DataLen = (unsigned) *d++;
885 return std::make_pair(KeyLen + 1, DataLen);
888 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
889 return (const char *)d;
892 static data_type ReadData(const internal_key_type, const unsigned char *d,
893 unsigned /*DataLen*/) {
894 using namespace clang::io;
896 ino_t ino = (ino_t) ReadUnalignedLE32(d);
897 dev_t dev = (dev_t) ReadUnalignedLE32(d);
898 mode_t mode = (mode_t) ReadUnalignedLE16(d);
899 time_t mtime = (time_t) ReadUnalignedLE64(d);
900 off_t size = (off_t) ReadUnalignedLE64(d);
901 return data_type(ino, dev, mode, mtime, size);
905 /// \brief stat() cache for precompiled headers.
907 /// This cache is very similar to the stat cache used by pretokenized
909 class ASTStatCache : public FileSystemStatCache {
910 typedef OnDiskChainedHashTable<ASTStatLookupTrait> CacheTy;
913 unsigned &NumStatHits, &NumStatMisses;
915 ASTStatCache(const unsigned char *Buckets, const unsigned char *Base,
916 unsigned &NumStatHits, unsigned &NumStatMisses)
917 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
918 Cache = CacheTy::Create(Buckets, Base);
921 ~ASTStatCache() { delete Cache; }
923 LookupResult getStat(const char *Path, struct stat &StatBuf,
924 int *FileDescriptor) {
925 // Do the lookup for the file's data in the AST file.
926 CacheTy::iterator I = Cache->find(Path);
928 // If we don't get a hit in the AST file just forward to 'stat'.
929 if (I == Cache->end()) {
931 return statChained(Path, StatBuf, FileDescriptor);
935 ASTStatData Data = *I;
937 StatBuf.st_ino = Data.ino;
938 StatBuf.st_dev = Data.dev;
939 StatBuf.st_mtime = Data.mtime;
940 StatBuf.st_mode = Data.mode;
941 StatBuf.st_size = Data.size;
945 } // end anonymous namespace
948 /// \brief Read a source manager block
949 ASTReader::ASTReadResult ASTReader::ReadSourceManagerBlock(Module &F) {
950 using namespace SrcMgr;
952 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
954 // Set the source-location entry cursor to the current position in
955 // the stream. This cursor will be used to read the contents of the
956 // source manager block initially, and then lazily read
957 // source-location entries as needed.
958 SLocEntryCursor = F.Stream;
960 // The stream itself is going to skip over the source manager block.
961 if (F.Stream.SkipBlock()) {
962 Error("malformed block record in AST file");
966 // Enter the source manager block.
967 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
968 Error("malformed source manager block record in AST file");
974 unsigned Code = SLocEntryCursor.ReadCode();
975 if (Code == llvm::bitc::END_BLOCK) {
976 if (SLocEntryCursor.ReadBlockEnd()) {
977 Error("error at end of Source Manager block in AST file");
983 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
984 // No known subblocks, always skip them.
985 SLocEntryCursor.ReadSubBlockID();
986 if (SLocEntryCursor.SkipBlock()) {
987 Error("malformed block record in AST file");
993 if (Code == llvm::bitc::DEFINE_ABBREV) {
994 SLocEntryCursor.ReadAbbrevRecord();
999 const char *BlobStart;
1002 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1003 default: // Default behavior: ignore.
1006 case SM_SLOC_FILE_ENTRY:
1007 case SM_SLOC_BUFFER_ENTRY:
1008 case SM_SLOC_EXPANSION_ENTRY:
1009 // Once we hit one of the source location entries, we're done.
1015 /// \brief If a header file is not found at the path that we expect it to be
1016 /// and the PCH file was moved from its original location, try to resolve the
1017 /// file by assuming that header+PCH were moved together and the header is in
1018 /// the same place relative to the PCH.
1020 resolveFileRelativeToOriginalDir(const std::string &Filename,
1021 const std::string &OriginalDir,
1022 const std::string &CurrDir) {
1023 assert(OriginalDir != CurrDir &&
1024 "No point trying to resolve the file if the PCH dir didn't change");
1025 using namespace llvm::sys;
1026 llvm::SmallString<128> filePath(Filename);
1027 fs::make_absolute(filePath);
1028 assert(path::is_absolute(OriginalDir));
1029 llvm::SmallString<128> currPCHPath(CurrDir);
1031 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1032 fileDirE = path::end(path::parent_path(filePath));
1033 path::const_iterator origDirI = path::begin(OriginalDir),
1034 origDirE = path::end(OriginalDir);
1035 // Skip the common path components from filePath and OriginalDir.
1036 while (fileDirI != fileDirE && origDirI != origDirE &&
1037 *fileDirI == *origDirI) {
1041 for (; origDirI != origDirE; ++origDirI)
1042 path::append(currPCHPath, "..");
1043 path::append(currPCHPath, fileDirI, fileDirE);
1044 path::append(currPCHPath, path::filename(Filename));
1045 return currPCHPath.str();
1048 /// \brief Read in the source location entry with the given ID.
1049 ASTReader::ASTReadResult ASTReader::ReadSLocEntryRecord(int ID) {
1053 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1054 Error("source location entry ID out-of-range for AST file");
1058 Module *F = GlobalSLocEntryMap.find(-ID)->second;
1059 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
1060 llvm::BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1061 unsigned BaseOffset = F->SLocEntryBaseOffset;
1063 ++NumSLocEntriesRead;
1064 unsigned Code = SLocEntryCursor.ReadCode();
1065 if (Code == llvm::bitc::END_BLOCK ||
1066 Code == llvm::bitc::ENTER_SUBBLOCK ||
1067 Code == llvm::bitc::DEFINE_ABBREV) {
1068 Error("incorrectly-formatted source location entry in AST file");
1073 const char *BlobStart;
1075 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1077 Error("incorrectly-formatted source location entry in AST file");
1080 case SM_SLOC_FILE_ENTRY: {
1081 std::string Filename(BlobStart, BlobStart + BlobLen);
1082 MaybeAddSystemRootToFilename(Filename);
1083 const FileEntry *File = FileMgr.getFile(Filename);
1084 if (File == 0 && !OriginalDir.empty() && !CurrentDir.empty() &&
1085 OriginalDir != CurrentDir) {
1086 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1089 if (!resolved.empty())
1090 File = FileMgr.getFile(resolved);
1093 File = FileMgr.getVirtualFile(Filename, (off_t)Record[4],
1096 std::string ErrorStr = "could not find file '";
1097 ErrorStr += Filename;
1098 ErrorStr += "' referenced by AST file";
1099 Error(ErrorStr.c_str());
1103 if (Record.size() < 6) {
1104 Error("source location entry is incorrect");
1108 if (!DisableValidation &&
1109 ((off_t)Record[4] != File->getSize()
1110 #if !defined(LLVM_ON_WIN32)
1111 // In our regression testing, the Windows file system seems to
1112 // have inconsistent modification times that sometimes
1113 // erroneously trigger this error-handling path.
1114 || (time_t)Record[5] != File->getModificationTime()
1117 Error(diag::err_fe_pch_file_modified, Filename);
1121 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1122 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1123 // This is the module's main file.
1124 IncludeLoc = getImportLocation(F);
1126 FileID FID = SourceMgr.createFileID(File, IncludeLoc,
1127 (SrcMgr::CharacteristicKind)Record[2],
1128 ID, BaseOffset + Record[0]);
1129 SrcMgr::FileInfo &FileInfo =
1130 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1131 FileInfo.NumCreatedFIDs = Record[6];
1133 FileInfo.setHasLineDirectives();
1138 case SM_SLOC_BUFFER_ENTRY: {
1139 const char *Name = BlobStart;
1140 unsigned Offset = Record[0];
1141 unsigned Code = SLocEntryCursor.ReadCode();
1144 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
1146 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1147 Error("AST record has invalid code");
1151 llvm::MemoryBuffer *Buffer
1152 = llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - 1),
1154 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID,
1155 BaseOffset + Offset);
1157 if (strcmp(Name, "<built-in>") == 0) {
1158 PCHPredefinesBlock Block = {
1160 StringRef(BlobStart, BlobLen - 1)
1162 PCHPredefinesBuffers.push_back(Block);
1168 case SM_SLOC_EXPANSION_ENTRY: {
1169 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1170 SourceMgr.createExpansionLoc(SpellingLoc,
1171 ReadSourceLocation(*F, Record[2]),
1172 ReadSourceLocation(*F, Record[3]),
1175 BaseOffset + Record[0]);
1183 /// \brief Find the location where the module F is imported.
1184 SourceLocation ASTReader::getImportLocation(Module *F) {
1185 if (F->ImportLoc.isValid())
1186 return F->ImportLoc;
1188 // Otherwise we have a PCH. It's considered to be "imported" at the first
1189 // location of its includer.
1190 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1191 // Main file is the importer. We assume that it is the first entry in the
1192 // entry table. We can't ask the manager, because at the time of PCH loading
1193 // the main file entry doesn't exist yet.
1194 // The very first entry is the invalid instantiation loc, which takes up
1196 return SourceLocation::getFromRawEncoding(2U);
1198 //return F->Loaders[0]->FirstLoc;
1199 return F->ImportedBy[0]->FirstLoc;
1202 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1203 /// specified cursor. Read the abbreviations that are at the top of the block
1204 /// and then leave the cursor pointing into the block.
1205 bool ASTReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1207 if (Cursor.EnterSubBlock(BlockID)) {
1208 Error("malformed block record in AST file");
1213 uint64_t Offset = Cursor.GetCurrentBitNo();
1214 unsigned Code = Cursor.ReadCode();
1216 // We expect all abbrevs to be at the start of the block.
1217 if (Code != llvm::bitc::DEFINE_ABBREV) {
1218 Cursor.JumpToBit(Offset);
1221 Cursor.ReadAbbrevRecord();
1225 void ASTReader::ReadMacroRecord(Module &F, uint64_t Offset) {
1226 llvm::BitstreamCursor &Stream = F.MacroCursor;
1228 // Keep track of where we are in the stream, then jump back there
1229 // after reading this macro.
1230 SavedStreamPosition SavedPosition(Stream);
1232 Stream.JumpToBit(Offset);
1234 SmallVector<IdentifierInfo*, 16> MacroArgs;
1235 MacroInfo *Macro = 0;
1238 unsigned Code = Stream.ReadCode();
1240 case llvm::bitc::END_BLOCK:
1243 case llvm::bitc::ENTER_SUBBLOCK:
1244 // No known subblocks, always skip them.
1245 Stream.ReadSubBlockID();
1246 if (Stream.SkipBlock()) {
1247 Error("malformed block record in AST file");
1252 case llvm::bitc::DEFINE_ABBREV:
1253 Stream.ReadAbbrevRecord();
1259 const char *BlobStart = 0;
1260 unsigned BlobLen = 0;
1262 PreprocessorRecordTypes RecType =
1263 (PreprocessorRecordTypes)Stream.ReadRecord(Code, Record, BlobStart,
1266 case PP_MACRO_OBJECT_LIKE:
1267 case PP_MACRO_FUNCTION_LIKE: {
1268 // If we already have a macro, that means that we've hit the end
1269 // of the definition of the macro we were looking for. We're
1274 IdentifierInfo *II = getLocalIdentifier(F, Record[0]);
1276 Error("macro must have a name in AST file");
1279 SourceLocation Loc = ReadSourceLocation(F, Record[1]);
1280 bool isUsed = Record[2];
1282 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1283 MI->setIsUsed(isUsed);
1286 unsigned NextIndex = 3;
1287 MI->setExportLocation(ReadSourceLocation(F, Record, NextIndex));
1289 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1290 // Decode function-like macro info.
1291 bool isC99VarArgs = Record[NextIndex++];
1292 bool isGNUVarArgs = Record[NextIndex++];
1294 unsigned NumArgs = Record[NextIndex++];
1295 for (unsigned i = 0; i != NumArgs; ++i)
1296 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1298 // Install function-like macro info.
1299 MI->setIsFunctionLike();
1300 if (isC99VarArgs) MI->setIsC99Varargs();
1301 if (isGNUVarArgs) MI->setIsGNUVarargs();
1302 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1303 PP.getPreprocessorAllocator());
1306 // Finally, install the macro.
1307 PP.setMacroInfo(II, MI);
1309 // Remember that we saw this macro last so that we add the tokens that
1310 // form its body to it.
1313 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1314 Record[NextIndex]) {
1315 // We have a macro definition. Register the association
1316 PreprocessedEntityID
1317 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1318 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1319 PPRec.RegisterMacroDefinition(Macro,
1320 PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true));
1328 // If we see a TOKEN before a PP_MACRO_*, then the file is
1329 // erroneous, just pretend we didn't see this.
1330 if (Macro == 0) break;
1334 Tok.setLocation(ReadSourceLocation(F, Record[0]));
1335 Tok.setLength(Record[1]);
1336 if (IdentifierInfo *II = getLocalIdentifier(F, Record[2]))
1337 Tok.setIdentifierInfo(II);
1338 Tok.setKind((tok::TokenKind)Record[3]);
1339 Tok.setFlag((Token::TokenFlags)Record[4]);
1340 Macro->AddTokenToBody(Tok);
1349 PreprocessedEntityID
1350 ASTReader::getGlobalPreprocessedEntityID(Module &M, unsigned LocalID) const {
1351 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1352 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1353 assert(I != M.PreprocessedEntityRemap.end()
1354 && "Invalid index into preprocessed entity index remap");
1356 return LocalID + I->second;
1359 unsigned HeaderFileInfoTrait::ComputeHash(const char *path) {
1360 return llvm::HashString(llvm::sys::path::filename(path));
1363 HeaderFileInfoTrait::internal_key_type
1364 HeaderFileInfoTrait::GetInternalKey(const char *path) { return path; }
1366 bool HeaderFileInfoTrait::EqualKey(internal_key_type a, internal_key_type b) {
1367 if (strcmp(a, b) == 0)
1370 if (llvm::sys::path::filename(a) != llvm::sys::path::filename(b))
1373 // The file names match, but the path names don't. stat() the files to
1374 // see if they are the same.
1375 struct stat StatBufA, StatBufB;
1376 if (StatSimpleCache(a, &StatBufA) || StatSimpleCache(b, &StatBufB))
1379 return StatBufA.st_ino == StatBufB.st_ino;
1382 std::pair<unsigned, unsigned>
1383 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1384 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1385 unsigned DataLen = (unsigned) *d++;
1386 return std::make_pair(KeyLen + 1, DataLen);
1389 HeaderFileInfoTrait::data_type
1390 HeaderFileInfoTrait::ReadData(const internal_key_type, const unsigned char *d,
1392 const unsigned char *End = d + DataLen;
1393 using namespace clang::io;
1395 unsigned Flags = *d++;
1396 HFI.isImport = (Flags >> 5) & 0x01;
1397 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1398 HFI.DirInfo = (Flags >> 2) & 0x03;
1399 HFI.Resolved = (Flags >> 1) & 0x01;
1400 HFI.IndexHeaderMapHeader = Flags & 0x01;
1401 HFI.NumIncludes = ReadUnalignedLE16(d);
1402 HFI.ControllingMacroID = Reader.getGlobalDeclID(M, ReadUnalignedLE32(d));
1403 if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1404 // The framework offset is 1 greater than the actual offset,
1405 // since 0 is used as an indicator for "no framework name".
1406 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1407 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1410 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1413 // This HeaderFileInfo was externally loaded.
1414 HFI.External = true;
1418 void ASTReader::SetIdentifierIsMacro(IdentifierInfo *II, Module &F,
1419 uint64_t LocalOffset) {
1420 // Note that this identifier has a macro definition.
1421 II->setHasMacroDefinition(true);
1423 // Adjust the offset to a global offset.
1424 UnreadMacroRecordOffsets[II] = F.GlobalBitOffset + LocalOffset;
1427 void ASTReader::ReadDefinedMacros() {
1428 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1429 E = ModuleMgr.rend(); I != E; ++I) {
1430 llvm::BitstreamCursor &MacroCursor = (*I)->MacroCursor;
1432 // If there was no preprocessor block, skip this file.
1433 if (!MacroCursor.getBitStreamReader())
1436 llvm::BitstreamCursor Cursor = MacroCursor;
1437 Cursor.JumpToBit((*I)->MacroStartOffset);
1441 unsigned Code = Cursor.ReadCode();
1442 if (Code == llvm::bitc::END_BLOCK)
1445 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1446 // No known subblocks, always skip them.
1447 Cursor.ReadSubBlockID();
1448 if (Cursor.SkipBlock()) {
1449 Error("malformed block record in AST file");
1455 if (Code == llvm::bitc::DEFINE_ABBREV) {
1456 Cursor.ReadAbbrevRecord();
1461 const char *BlobStart;
1464 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1465 default: // Default behavior: ignore.
1468 case PP_MACRO_OBJECT_LIKE:
1469 case PP_MACRO_FUNCTION_LIKE:
1470 getLocalIdentifier(**I, Record[0]);
1480 // Drain the unread macro-record offsets map.
1481 while (!UnreadMacroRecordOffsets.empty())
1482 LoadMacroDefinition(UnreadMacroRecordOffsets.begin());
1485 void ASTReader::LoadMacroDefinition(
1486 llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos) {
1487 assert(Pos != UnreadMacroRecordOffsets.end() && "Unknown macro definition");
1488 uint64_t Offset = Pos->second;
1489 UnreadMacroRecordOffsets.erase(Pos);
1491 RecordLocation Loc = getLocalBitOffset(Offset);
1492 ReadMacroRecord(*Loc.F, Loc.Offset);
1495 void ASTReader::LoadMacroDefinition(IdentifierInfo *II) {
1496 llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos
1497 = UnreadMacroRecordOffsets.find(II);
1498 LoadMacroDefinition(Pos);
1501 const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
1502 std::string Filename = filenameStrRef;
1503 MaybeAddSystemRootToFilename(Filename);
1504 const FileEntry *File = FileMgr.getFile(Filename);
1505 if (File == 0 && !OriginalDir.empty() && !CurrentDir.empty() &&
1506 OriginalDir != CurrentDir) {
1507 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1510 if (!resolved.empty())
1511 File = FileMgr.getFile(resolved);
1517 /// \brief If we are loading a relocatable PCH file, and the filename is
1518 /// not an absolute path, add the system root to the beginning of the file
1520 void ASTReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1521 // If this is not a relocatable PCH file, there's nothing to do.
1522 if (!RelocatablePCH)
1525 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
1528 if (isysroot.empty()) {
1529 // If no system root was given, default to '/'
1530 Filename.insert(Filename.begin(), '/');
1534 unsigned Length = isysroot.size();
1535 if (isysroot[Length - 1] != '/')
1536 Filename.insert(Filename.begin(), '/');
1538 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
1541 ASTReader::ASTReadResult
1542 ASTReader::ReadASTBlock(Module &F) {
1543 llvm::BitstreamCursor &Stream = F.Stream;
1545 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
1546 Error("malformed block record in AST file");
1550 // Read all of the records and blocks for the ASt file.
1552 while (!Stream.AtEndOfStream()) {
1553 unsigned Code = Stream.ReadCode();
1554 if (Code == llvm::bitc::END_BLOCK) {
1555 if (Stream.ReadBlockEnd()) {
1556 Error("error at end of module block in AST file");
1563 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1564 switch (Stream.ReadSubBlockID()) {
1565 case DECLTYPES_BLOCK_ID:
1566 // We lazily load the decls block, but we want to set up the
1567 // DeclsCursor cursor to point into it. Clone our current bitcode
1568 // cursor to it, enter the block and read the abbrevs in that block.
1569 // With the main cursor, we just skip over it.
1570 F.DeclsCursor = Stream;
1571 if (Stream.SkipBlock() || // Skip with the main cursor.
1572 // Read the abbrevs.
1573 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
1574 Error("malformed block record in AST file");
1579 case DECL_UPDATES_BLOCK_ID:
1580 if (Stream.SkipBlock()) {
1581 Error("malformed block record in AST file");
1586 case PREPROCESSOR_BLOCK_ID:
1587 F.MacroCursor = Stream;
1588 if (!PP.getExternalSource())
1589 PP.setExternalSource(this);
1591 if (Stream.SkipBlock() ||
1592 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
1593 Error("malformed block record in AST file");
1596 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
1599 case PREPROCESSOR_DETAIL_BLOCK_ID:
1600 F.PreprocessorDetailCursor = Stream;
1601 if (Stream.SkipBlock() ||
1602 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
1603 PREPROCESSOR_DETAIL_BLOCK_ID)) {
1604 Error("malformed preprocessor detail record in AST file");
1607 F.PreprocessorDetailStartOffset
1608 = F.PreprocessorDetailCursor.GetCurrentBitNo();
1610 if (!PP.getPreprocessingRecord())
1611 PP.createPreprocessingRecord(true);
1612 if (!PP.getPreprocessingRecord()->getExternalSource())
1613 PP.getPreprocessingRecord()->SetExternalSource(*this);
1616 case SOURCE_MANAGER_BLOCK_ID:
1617 switch (ReadSourceManagerBlock(F)) {
1622 Error("malformed source manager block in AST file");
1633 if (Code == llvm::bitc::DEFINE_ABBREV) {
1634 Stream.ReadAbbrevRecord();
1638 // Read and process a record.
1640 const char *BlobStart = 0;
1641 unsigned BlobLen = 0;
1642 switch ((ASTRecordTypes)Stream.ReadRecord(Code, Record,
1643 &BlobStart, &BlobLen)) {
1644 default: // Default behavior: ignore.
1648 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1649 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1650 : diag::warn_pch_version_too_new);
1654 RelocatablePCH = Record[4];
1656 std::string TargetTriple(BlobStart, BlobLen);
1657 if (Listener->ReadTargetTriple(TargetTriple))
1664 // Load each of the imported PCH files.
1665 unsigned Idx = 0, N = Record.size();
1667 // Read information about the AST file.
1668 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
1669 unsigned Length = Record[Idx++];
1670 llvm::SmallString<128> ImportedFile(Record.begin() + Idx,
1671 Record.begin() + Idx + Length);
1674 // Load the AST file.
1675 switch(ReadASTCore(ImportedFile, ImportedKind, &F)) {
1676 case Failure: return Failure;
1677 // If we have to ignore the dependency, we'll have to ignore this too.
1678 case IgnorePCH: return IgnorePCH;
1679 case Success: break;
1686 if (F.LocalNumTypes != 0) {
1687 Error("duplicate TYPE_OFFSET record in AST file");
1690 F.TypeOffsets = (const uint32_t *)BlobStart;
1691 F.LocalNumTypes = Record[0];
1692 unsigned LocalBaseTypeIndex = Record[1];
1693 F.BaseTypeIndex = getTotalNumTypes();
1695 if (F.LocalNumTypes > 0) {
1696 // Introduce the global -> local mapping for types within this module.
1697 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
1699 // Introduce the local -> global mapping for types within this module.
1700 F.TypeRemap.insert(std::make_pair(LocalBaseTypeIndex,
1701 F.BaseTypeIndex - LocalBaseTypeIndex));
1703 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
1709 if (F.LocalNumDecls != 0) {
1710 Error("duplicate DECL_OFFSET record in AST file");
1713 F.DeclOffsets = (const uint32_t *)BlobStart;
1714 F.LocalNumDecls = Record[0];
1715 unsigned LocalBaseDeclID = Record[1];
1716 F.BaseDeclID = getTotalNumDecls();
1718 if (F.LocalNumDecls > 0) {
1719 // Introduce the global -> local mapping for declarations within this
1721 GlobalDeclMap.insert(
1722 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
1724 // Introduce the local -> global mapping for declarations within this
1726 F.DeclRemap.insert(std::make_pair(LocalBaseDeclID,
1727 F.BaseDeclID - LocalBaseDeclID));
1729 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
1734 case TU_UPDATE_LEXICAL: {
1735 DeclContext *TU = Context.getTranslationUnitDecl();
1736 DeclContextInfo &Info = F.DeclContextInfos[TU];
1737 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(BlobStart);
1738 Info.NumLexicalDecls
1739 = static_cast<unsigned int>(BlobLen / sizeof(KindDeclIDPair));
1740 TU->setHasExternalLexicalStorage(true);
1744 case UPDATE_VISIBLE: {
1746 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
1747 void *Table = ASTDeclContextNameLookupTable::Create(
1748 (const unsigned char *)BlobStart + Record[Idx++],
1749 (const unsigned char *)BlobStart,
1750 ASTDeclContextNameLookupTrait(*this, F));
1751 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
1752 DeclContext *TU = Context.getTranslationUnitDecl();
1753 F.DeclContextInfos[TU].NameLookupTableData = Table;
1754 TU->setHasExternalVisibleStorage(true);
1756 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
1760 case REDECLS_UPDATE_LATEST: {
1761 assert(Record.size() % 2 == 0 && "Expected pairs of DeclIDs");
1762 for (unsigned i = 0, e = Record.size(); i < e; /* in loop */) {
1763 DeclID First = ReadDeclID(F, Record, i);
1764 DeclID Latest = ReadDeclID(F, Record, i);
1765 FirstLatestDeclIDs[First] = Latest;
1770 case LANGUAGE_OPTIONS:
1771 if (ParseLanguageOptions(Record) && !DisableValidation)
1775 case IDENTIFIER_TABLE:
1776 F.IdentifierTableData = BlobStart;
1778 F.IdentifierLookupTable
1779 = ASTIdentifierLookupTable::Create(
1780 (const unsigned char *)F.IdentifierTableData + Record[0],
1781 (const unsigned char *)F.IdentifierTableData,
1782 ASTIdentifierLookupTrait(*this, F));
1784 PP.getIdentifierTable().setExternalIdentifierLookup(this);
1788 case IDENTIFIER_OFFSET: {
1789 if (F.LocalNumIdentifiers != 0) {
1790 Error("duplicate IDENTIFIER_OFFSET record in AST file");
1793 F.IdentifierOffsets = (const uint32_t *)BlobStart;
1794 F.LocalNumIdentifiers = Record[0];
1795 unsigned LocalBaseIdentifierID = Record[1];
1796 F.BaseIdentifierID = getTotalNumIdentifiers();
1798 if (F.LocalNumIdentifiers > 0) {
1799 // Introduce the global -> local mapping for identifiers within this
1801 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
1804 // Introduce the local -> global mapping for identifiers within this
1806 F.IdentifierRemap.insert(
1807 std::make_pair(LocalBaseIdentifierID,
1808 F.BaseIdentifierID - LocalBaseIdentifierID));
1810 IdentifiersLoaded.resize(IdentifiersLoaded.size()
1811 + F.LocalNumIdentifiers);
1816 case EXTERNAL_DEFINITIONS:
1817 for (unsigned I = 0, N = Record.size(); I != N; ++I)
1818 ExternalDefinitions.push_back(getGlobalDeclID(F, Record[I]));
1822 for (unsigned I = 0, N = Record.size(); I != N; ++I)
1823 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
1827 TotalNumStatements += Record[0];
1828 TotalNumMacros += Record[1];
1829 TotalLexicalDeclContexts += Record[2];
1830 TotalVisibleDeclContexts += Record[3];
1833 case UNUSED_FILESCOPED_DECLS:
1834 for (unsigned I = 0, N = Record.size(); I != N; ++I)
1835 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
1838 case DELEGATING_CTORS:
1839 for (unsigned I = 0, N = Record.size(); I != N; ++I)
1840 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
1843 case WEAK_UNDECLARED_IDENTIFIERS:
1844 if (Record.size() % 4 != 0) {
1845 Error("invalid weak identifiers record");
1849 // FIXME: Ignore weak undeclared identifiers from non-original PCH
1850 // files. This isn't the way to do it :)
1851 WeakUndeclaredIdentifiers.clear();
1853 // Translate the weak, undeclared identifiers into global IDs.
1854 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
1855 WeakUndeclaredIdentifiers.push_back(
1856 getGlobalIdentifierID(F, Record[I++]));
1857 WeakUndeclaredIdentifiers.push_back(
1858 getGlobalIdentifierID(F, Record[I++]));
1859 WeakUndeclaredIdentifiers.push_back(
1860 ReadSourceLocation(F, Record, I).getRawEncoding());
1861 WeakUndeclaredIdentifiers.push_back(Record[I++]);
1865 case LOCALLY_SCOPED_EXTERNAL_DECLS:
1866 for (unsigned I = 0, N = Record.size(); I != N; ++I)
1867 LocallyScopedExternalDecls.push_back(getGlobalDeclID(F, Record[I]));
1870 case SELECTOR_OFFSETS: {
1871 F.SelectorOffsets = (const uint32_t *)BlobStart;
1872 F.LocalNumSelectors = Record[0];
1873 unsigned LocalBaseSelectorID = Record[1];
1874 F.BaseSelectorID = getTotalNumSelectors();
1876 if (F.LocalNumSelectors > 0) {
1877 // Introduce the global -> local mapping for selectors within this
1879 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
1881 // Introduce the local -> global mapping for selectors within this
1883 F.SelectorRemap.insert(std::make_pair(LocalBaseSelectorID,
1884 F.BaseSelectorID - LocalBaseSelectorID));
1886 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
1892 F.SelectorLookupTableData = (const unsigned char *)BlobStart;
1894 F.SelectorLookupTable
1895 = ASTSelectorLookupTable::Create(
1896 F.SelectorLookupTableData + Record[0],
1897 F.SelectorLookupTableData,
1898 ASTSelectorLookupTrait(*this, F));
1899 TotalNumMethodPoolEntries += Record[1];
1902 case REFERENCED_SELECTOR_POOL:
1903 if (!Record.empty()) {
1904 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
1905 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
1907 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
1913 case PP_COUNTER_VALUE:
1914 if (!Record.empty() && Listener)
1915 Listener->ReadCounter(Record[0]);
1918 case SOURCE_LOCATION_OFFSETS: {
1919 F.SLocEntryOffsets = (const uint32_t *)BlobStart;
1920 F.LocalNumSLocEntries = Record[0];
1921 unsigned SLocSpaceSize = Record[1];
1922 llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
1923 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
1925 // Make our entry in the range map. BaseID is negative and growing, so
1926 // we invert it. Because we invert it, though, we need the other end of
1928 unsigned RangeStart =
1929 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
1930 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
1931 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
1933 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
1934 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
1935 GlobalSLocOffsetMap.insert(
1936 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
1937 - SLocSpaceSize,&F));
1939 // Initialize the remapping table.
1940 // Invalid stays invalid.
1941 F.SLocRemap.insert(std::make_pair(0U, 0));
1942 // This module. Base was 2 when being compiled.
1943 F.SLocRemap.insert(std::make_pair(2U,
1944 static_cast<int>(F.SLocEntryBaseOffset - 2)));
1946 TotalNumSLocEntries += F.LocalNumSLocEntries;
1950 case MODULE_OFFSET_MAP: {
1951 // Additional remapping information.
1952 const unsigned char *Data = (const unsigned char*)BlobStart;
1953 const unsigned char *DataEnd = Data + BlobLen;
1955 // Continuous range maps we may be updating in our module.
1956 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
1957 ContinuousRangeMap<uint32_t, int, 2>::Builder
1958 IdentifierRemap(F.IdentifierRemap);
1959 ContinuousRangeMap<uint32_t, int, 2>::Builder
1960 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
1961 ContinuousRangeMap<uint32_t, int, 2>::Builder
1962 SelectorRemap(F.SelectorRemap);
1963 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
1964 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
1966 while(Data < DataEnd) {
1967 uint16_t Len = io::ReadUnalignedLE16(Data);
1968 StringRef Name = StringRef((const char*)Data, Len);
1970 Module *OM = ModuleMgr.lookup(Name);
1972 Error("SourceLocation remap refers to unknown module");
1976 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
1977 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
1978 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
1979 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
1980 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
1981 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
1983 // Source location offset is mapped to OM->SLocEntryBaseOffset.
1984 SLocRemap.insert(std::make_pair(SLocOffset,
1985 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
1986 IdentifierRemap.insert(
1987 std::make_pair(IdentifierIDOffset,
1988 OM->BaseIdentifierID - IdentifierIDOffset));
1989 PreprocessedEntityRemap.insert(
1990 std::make_pair(PreprocessedEntityIDOffset,
1991 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
1992 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
1993 OM->BaseSelectorID - SelectorIDOffset));
1994 DeclRemap.insert(std::make_pair(DeclIDOffset,
1995 OM->BaseDeclID - DeclIDOffset));
1997 TypeRemap.insert(std::make_pair(TypeIndexOffset,
1998 OM->BaseTypeIndex - TypeIndexOffset));
2003 case SOURCE_MANAGER_LINE_TABLE:
2004 if (ParseLineTable(F, Record))
2008 case FILE_SOURCE_LOCATION_OFFSETS:
2009 F.SLocFileOffsets = (const uint32_t *)BlobStart;
2010 F.LocalNumSLocFileEntries = Record[0];
2013 case SOURCE_LOCATION_PRELOADS: {
2014 // Need to transform from the local view (1-based IDs) to the global view,
2015 // which is based off F.SLocEntryBaseID.
2016 if (!F.PreloadSLocEntries.empty()) {
2017 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2021 F.PreloadSLocEntries.swap(Record);
2026 if (!DisableStatCache) {
2027 ASTStatCache *MyStatCache =
2028 new ASTStatCache((const unsigned char *)BlobStart + Record[0],
2029 (const unsigned char *)BlobStart,
2030 NumStatHits, NumStatMisses);
2031 FileMgr.addStatCache(MyStatCache);
2032 F.StatCache = MyStatCache;
2037 case EXT_VECTOR_DECLS:
2038 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2039 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2043 if (Record.size() % 3 != 0) {
2044 Error("Invalid VTABLE_USES record");
2048 // Later tables overwrite earlier ones.
2049 // FIXME: Modules will have some trouble with this. This is clearly not
2050 // the right way to do this.
2053 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2054 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2055 VTableUses.push_back(
2056 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2057 VTableUses.push_back(Record[Idx++]);
2061 case DYNAMIC_CLASSES:
2062 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2063 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2066 case PENDING_IMPLICIT_INSTANTIATIONS:
2067 if (PendingInstantiations.size() % 2 != 0) {
2068 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2072 // Later lists of pending instantiations overwrite earlier ones.
2073 // FIXME: This is most certainly wrong for modules.
2074 PendingInstantiations.clear();
2075 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2076 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2077 PendingInstantiations.push_back(
2078 ReadSourceLocation(F, Record, I).getRawEncoding());
2082 case SEMA_DECL_REFS:
2083 // Later tables overwrite earlier ones.
2084 // FIXME: Modules will have some trouble with this.
2085 SemaDeclRefs.clear();
2086 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2087 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2090 case ORIGINAL_FILE_NAME:
2091 // The primary AST will be the last to get here, so it will be the one
2093 ActualOriginalFileName.assign(BlobStart, BlobLen);
2094 OriginalFileName = ActualOriginalFileName;
2095 MaybeAddSystemRootToFilename(OriginalFileName);
2098 case ORIGINAL_FILE_ID:
2099 OriginalFileID = FileID::get(Record[0]);
2102 case ORIGINAL_PCH_DIR:
2103 // The primary AST will be the last to get here, so it will be the one
2105 OriginalDir.assign(BlobStart, BlobLen);
2108 case VERSION_CONTROL_BRANCH_REVISION: {
2109 const std::string &CurBranch = getClangFullRepositoryVersion();
2110 StringRef ASTBranch(BlobStart, BlobLen);
2111 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2112 Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
2118 case PPD_ENTITIES_OFFSETS: {
2119 F.PreprocessedEntityOffsets = (const PPEntityOffset *)BlobStart;
2120 assert(BlobLen % sizeof(PPEntityOffset) == 0);
2121 F.NumPreprocessedEntities = BlobLen / sizeof(PPEntityOffset);
2123 unsigned LocalBasePreprocessedEntityID = Record[0];
2125 unsigned StartingID;
2126 if (!PP.getPreprocessingRecord())
2127 PP.createPreprocessingRecord(true);
2128 if (!PP.getPreprocessingRecord()->getExternalSource())
2129 PP.getPreprocessingRecord()->SetExternalSource(*this);
2131 = PP.getPreprocessingRecord()
2132 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2133 F.BasePreprocessedEntityID = StartingID;
2135 if (F.NumPreprocessedEntities > 0) {
2136 // Introduce the global -> local mapping for preprocessed entities in
2138 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2140 // Introduce the local -> global mapping for preprocessed entities in
2142 F.PreprocessedEntityRemap.insert(
2143 std::make_pair(LocalBasePreprocessedEntityID,
2144 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2150 case DECL_UPDATE_OFFSETS: {
2151 if (Record.size() % 2 != 0) {
2152 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2155 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2156 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2157 .push_back(std::make_pair(&F, Record[I+1]));
2161 case DECL_REPLACEMENTS: {
2162 if (Record.size() % 2 != 0) {
2163 Error("invalid DECL_REPLACEMENTS block in AST file");
2166 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2167 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2168 = std::make_pair(&F, Record[I+1]);
2172 case OBJC_CHAINED_CATEGORIES: {
2173 if (Record.size() % 3 != 0) {
2174 Error("invalid OBJC_CHAINED_CATEGORIES block in AST file");
2177 for (unsigned I = 0, N = Record.size(); I != N; I += 3) {
2178 serialization::GlobalDeclID GlobID = getGlobalDeclID(F, Record[I]);
2179 F.ChainedObjCCategories[GlobID] = std::make_pair(Record[I+1],
2181 ObjCChainedCategoriesInterfaces.insert(GlobID);
2186 case CXX_BASE_SPECIFIER_OFFSETS: {
2187 if (F.LocalNumCXXBaseSpecifiers != 0) {
2188 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2192 F.LocalNumCXXBaseSpecifiers = Record[0];
2193 F.CXXBaseSpecifiersOffsets = (const uint32_t *)BlobStart;
2194 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2198 case DIAG_PRAGMA_MAPPINGS:
2199 if (Record.size() % 2 != 0) {
2200 Error("invalid DIAG_USER_MAPPINGS block in AST file");
2204 if (F.PragmaDiagMappings.empty())
2205 F.PragmaDiagMappings.swap(Record);
2207 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2208 Record.begin(), Record.end());
2211 case CUDA_SPECIAL_DECL_REFS:
2212 // Later tables overwrite earlier ones.
2213 // FIXME: Modules will have trouble with this.
2214 CUDASpecialDeclRefs.clear();
2215 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2216 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2219 case HEADER_SEARCH_TABLE: {
2220 F.HeaderFileInfoTableData = BlobStart;
2221 F.LocalNumHeaderFileInfos = Record[1];
2222 F.HeaderFileFrameworkStrings = BlobStart + Record[2];
2224 F.HeaderFileInfoTable
2225 = HeaderFileInfoLookupTable::Create(
2226 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2227 (const unsigned char *)F.HeaderFileInfoTableData,
2228 HeaderFileInfoTrait(*this, F,
2229 &PP.getHeaderSearchInfo(),
2230 BlobStart + Record[2]));
2232 PP.getHeaderSearchInfo().SetExternalSource(this);
2233 if (!PP.getHeaderSearchInfo().getExternalLookup())
2234 PP.getHeaderSearchInfo().SetExternalLookup(this);
2239 case FP_PRAGMA_OPTIONS:
2240 // Later tables overwrite earlier ones.
2241 FPPragmaOptions.swap(Record);
2244 case OPENCL_EXTENSIONS:
2245 // Later tables overwrite earlier ones.
2246 OpenCLExtensions.swap(Record);
2249 case TENTATIVE_DEFINITIONS:
2250 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2251 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2254 case KNOWN_NAMESPACES:
2255 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2256 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2260 Error("premature end of bitstream in AST file");
2264 ASTReader::ASTReadResult ASTReader::validateFileEntries(Module &M) {
2265 llvm::BitstreamCursor &SLocEntryCursor = M.SLocEntryCursor;
2267 for (unsigned i = 0, e = M.LocalNumSLocFileEntries; i != e; ++i) {
2268 SLocEntryCursor.JumpToBit(M.SLocFileOffsets[i]);
2269 unsigned Code = SLocEntryCursor.ReadCode();
2270 if (Code == llvm::bitc::END_BLOCK ||
2271 Code == llvm::bitc::ENTER_SUBBLOCK ||
2272 Code == llvm::bitc::DEFINE_ABBREV) {
2273 Error("incorrectly-formatted source location entry in AST file");
2278 const char *BlobStart;
2280 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
2282 Error("incorrectly-formatted source location entry in AST file");
2285 case SM_SLOC_FILE_ENTRY: {
2286 StringRef Filename(BlobStart, BlobLen);
2287 const FileEntry *File = getFileEntry(Filename);
2290 std::string ErrorStr = "could not find file '";
2291 ErrorStr += Filename;
2292 ErrorStr += "' referenced by AST file";
2293 Error(ErrorStr.c_str());
2297 if (Record.size() < 6) {
2298 Error("source location entry is incorrect");
2302 // The stat info from the FileEntry came from the cached stat
2303 // info of the PCH, so we cannot trust it.
2304 struct stat StatBuf;
2305 if (::stat(File->getName(), &StatBuf) != 0) {
2306 StatBuf.st_size = File->getSize();
2307 StatBuf.st_mtime = File->getModificationTime();
2310 if (((off_t)Record[4] != StatBuf.st_size
2311 #if !defined(LLVM_ON_WIN32)
2312 // In our regression testing, the Windows file system seems to
2313 // have inconsistent modification times that sometimes
2314 // erroneously trigger this error-handling path.
2315 || (time_t)Record[5] != StatBuf.st_mtime
2318 Error(diag::err_fe_pch_file_modified, Filename);
2331 /// \brief Visitor class used to look up identifirs in an AST file.
2332 class IdentifierLookupVisitor {
2334 IdentifierInfo *Found;
2336 explicit IdentifierLookupVisitor(StringRef Name) : Name(Name), Found() { }
2338 static bool visit(Module &M, void *UserData) {
2339 IdentifierLookupVisitor *This
2340 = static_cast<IdentifierLookupVisitor *>(UserData);
2342 ASTIdentifierLookupTable *IdTable
2343 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
2347 std::pair<const char*, unsigned> Key(This->Name.begin(),
2349 ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2350 if (Pos == IdTable->end())
2353 // Dereferencing the iterator has the effect of building the
2354 // IdentifierInfo node and populating it with the various
2355 // declarations it needs.
2360 // \brief Retrieve the identifier info found within the module
2362 IdentifierInfo *getIdentifierInfo() const { return Found; }
2367 ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
2369 switch(ReadASTCore(FileName, Type, /*ImportedBy=*/0)) {
2370 case Failure: return Failure;
2371 case IgnorePCH: return IgnorePCH;
2372 case Success: break;
2375 // Here comes stuff that we only do once the entire chain is loaded.
2377 // Check the predefines buffers.
2378 if (!DisableValidation && Type != MK_Module && Type != MK_Preamble &&
2379 // FIXME: CheckPredefinesBuffers also sets the SuggestedPredefines;
2380 // if DisableValidation is true, defines that were set on command-line
2381 // but not in the PCH file will not be added to SuggestedPredefines.
2382 CheckPredefinesBuffers())
2385 // Initialization of keywords and pragmas occurs before the
2386 // AST file is read, so there may be some identifiers that were
2387 // loaded into the IdentifierTable before we intercepted the
2388 // creation of identifiers. Iterate through the list of known
2389 // identifiers and determine whether we have to establish
2390 // preprocessor definitions or top-level identifier declaration
2391 // chains for those identifiers.
2393 // We copy the IdentifierInfo pointers to a small vector first,
2394 // since de-serializing declarations or macro definitions can add
2395 // new entries into the identifier table, invalidating the
2398 // FIXME: We need a lazier way to load this information, e.g., by marking
2399 // the identifier data as 'dirty', so that it will be looked up in the
2400 // AST file(s) if it is uttered in the source. This could save us some
2401 // module load time.
2402 SmallVector<IdentifierInfo *, 128> Identifiers;
2403 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
2404 IdEnd = PP.getIdentifierTable().end();
2406 Identifiers.push_back(Id->second);
2408 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
2409 IdentifierLookupVisitor Visitor(Identifiers[I]->getName());
2410 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
2413 InitializeContext();
2415 if (DeserializationListener)
2416 DeserializationListener->ReaderInitialized(this);
2418 // If this AST file is a precompiled preamble, then set the preamble file ID
2419 // of the source manager to the file source file from which the preamble was
2421 if (Type == MK_Preamble) {
2422 if (!OriginalFileID.isInvalid()) {
2423 OriginalFileID = FileID::get(ModuleMgr.getPrimaryModule().SLocEntryBaseID
2424 + OriginalFileID.getOpaqueValue() - 1);
2425 SourceMgr.setPreambleFileID(OriginalFileID);
2432 ASTReader::ASTReadResult ASTReader::ReadASTCore(StringRef FileName,
2434 Module *ImportedBy) {
2437 std::string ErrorStr;
2438 llvm::tie(M, NewModule) = ModuleMgr.addModule(FileName, Type, ImportedBy,
2442 // We couldn't load the module.
2443 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
2450 // We've already loaded this module.
2454 // FIXME: This seems rather a hack. Should CurrentDir be part of the
2456 if (FileName != "-") {
2457 CurrentDir = llvm::sys::path::parent_path(FileName);
2458 if (CurrentDir.empty()) CurrentDir = ".";
2462 llvm::BitstreamCursor &Stream = F.Stream;
2463 Stream.init(F.StreamFile);
2464 F.SizeInBits = F.Buffer->getBufferSize() * 8;
2466 // Sniff for the signature.
2467 if (Stream.Read(8) != 'C' ||
2468 Stream.Read(8) != 'P' ||
2469 Stream.Read(8) != 'C' ||
2470 Stream.Read(8) != 'H') {
2471 Diag(diag::err_not_a_pch_file) << FileName;
2475 while (!Stream.AtEndOfStream()) {
2476 unsigned Code = Stream.ReadCode();
2478 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
2479 Error("invalid record at top-level of AST file");
2483 unsigned BlockID = Stream.ReadSubBlockID();
2485 // We only know the AST subblock ID.
2487 case llvm::bitc::BLOCKINFO_BLOCK_ID:
2488 if (Stream.ReadBlockInfoBlock()) {
2489 Error("malformed BlockInfoBlock in AST file");
2494 switch (ReadASTBlock(F)) {
2502 // FIXME: We could consider reading through to the end of this
2503 // AST block, skipping subblocks, to see if there are other
2504 // AST blocks elsewhere.
2506 // FIXME: We can't clear loaded slocentries anymore.
2507 //SourceMgr.ClearPreallocatedSLocEntries();
2509 // Remove the stat cache.
2511 FileMgr.removeStatCache((ASTStatCache*)F.StatCache);
2517 if (Stream.SkipBlock()) {
2518 Error("malformed block record in AST file");
2525 // Once read, set the Module bit base offset and update the size in
2526 // bits of all files we've seen.
2527 F.GlobalBitOffset = TotalModulesSizeInBits;
2528 TotalModulesSizeInBits += F.SizeInBits;
2529 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
2531 // Make sure that the files this module was built against are still available.
2532 if (!DisableValidation) {
2533 switch(validateFileEntries(*M)) {
2534 case Failure: return Failure;
2535 case IgnorePCH: return IgnorePCH;
2536 case Success: break;
2540 // Preload SLocEntries.
2541 for (unsigned I = 0, N = M->PreloadSLocEntries.size(); I != N; ++I) {
2542 int Index = int(M->PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
2543 // Load it through the SourceManager and don't call ReadSLocEntryRecord()
2544 // directly because the entry may have already been loaded in which case
2545 // calling ReadSLocEntryRecord() directly would trigger an assertion in
2547 SourceMgr.getLoadedSLocEntryByID(Index);
2554 void ASTReader::InitializeContext() {
2555 // If there's a listener, notify them that we "read" the translation unit.
2556 if (DeserializationListener)
2557 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
2558 Context.getTranslationUnitDecl());
2560 // Make sure we load the declaration update records for the translation unit,
2561 // if there are any.
2562 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
2563 Context.getTranslationUnitDecl());
2565 // FIXME: Find a better way to deal with collisions between these
2566 // built-in types. Right now, we just ignore the problem.
2568 // Load the special types.
2569 if (SpecialTypes.size() > NumSpecialTypeIDs) {
2570 if (Context.getBuiltinVaListType().isNull()) {
2571 Context.setBuiltinVaListType(
2572 GetType(SpecialTypes[SPECIAL_TYPE_BUILTIN_VA_LIST]));
2575 if (unsigned Proto = SpecialTypes[SPECIAL_TYPE_OBJC_PROTOCOL]) {
2576 if (Context.ObjCProtoType.isNull())
2577 Context.ObjCProtoType = GetType(Proto);
2580 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
2581 if (!Context.CFConstantStringTypeDecl)
2582 Context.setCFConstantStringType(GetType(String));
2585 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
2586 QualType FileType = GetType(File);
2587 if (FileType.isNull()) {
2588 Error("FILE type is NULL");
2592 if (!Context.FILEDecl) {
2593 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
2594 Context.setFILEDecl(Typedef->getDecl());
2596 const TagType *Tag = FileType->getAs<TagType>();
2598 Error("Invalid FILE type in AST file");
2601 Context.setFILEDecl(Tag->getDecl());
2606 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_jmp_buf]) {
2607 QualType Jmp_bufType = GetType(Jmp_buf);
2608 if (Jmp_bufType.isNull()) {
2609 Error("jmp_buf type is NULL");
2613 if (!Context.jmp_bufDecl) {
2614 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
2615 Context.setjmp_bufDecl(Typedef->getDecl());
2617 const TagType *Tag = Jmp_bufType->getAs<TagType>();
2619 Error("Invalid jmp_buf type in AST file");
2622 Context.setjmp_bufDecl(Tag->getDecl());
2627 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_sigjmp_buf]) {
2628 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
2629 if (Sigjmp_bufType.isNull()) {
2630 Error("sigjmp_buf type is NULL");
2634 if (!Context.sigjmp_bufDecl) {
2635 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
2636 Context.setsigjmp_bufDecl(Typedef->getDecl());
2638 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
2639 assert(Tag && "Invalid sigjmp_buf type in AST file");
2640 Context.setsigjmp_bufDecl(Tag->getDecl());
2645 if (unsigned ObjCIdRedef
2646 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
2647 if (Context.ObjCIdRedefinitionType.isNull())
2648 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
2651 if (unsigned ObjCClassRedef
2652 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
2653 if (Context.ObjCClassRedefinitionType.isNull())
2654 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
2657 if (unsigned ObjCSelRedef
2658 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
2659 if (Context.ObjCSelRedefinitionType.isNull())
2660 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2664 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
2666 // If there were any CUDA special declarations, deserialize them.
2667 if (!CUDASpecialDeclRefs.empty()) {
2668 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
2669 Context.setcudaConfigureCallDecl(
2670 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
2674 /// \brief Retrieve the name of the original source file name
2675 /// directly from the AST file, without actually loading the AST
2677 std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
2678 FileManager &FileMgr,
2679 DiagnosticsEngine &Diags) {
2680 // Open the AST file.
2682 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
2683 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
2685 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
2686 return std::string();
2689 // Initialize the stream
2690 llvm::BitstreamReader StreamFile;
2691 llvm::BitstreamCursor Stream;
2692 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
2693 (const unsigned char *)Buffer->getBufferEnd());
2694 Stream.init(StreamFile);
2696 // Sniff for the signature.
2697 if (Stream.Read(8) != 'C' ||
2698 Stream.Read(8) != 'P' ||
2699 Stream.Read(8) != 'C' ||
2700 Stream.Read(8) != 'H') {
2701 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
2702 return std::string();
2706 while (!Stream.AtEndOfStream()) {
2707 unsigned Code = Stream.ReadCode();
2709 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2710 unsigned BlockID = Stream.ReadSubBlockID();
2712 // We only know the AST subblock ID.
2715 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2716 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
2717 return std::string();
2722 if (Stream.SkipBlock()) {
2723 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
2724 return std::string();
2731 if (Code == llvm::bitc::END_BLOCK) {
2732 if (Stream.ReadBlockEnd()) {
2733 Diags.Report(diag::err_fe_pch_error_at_end_block) << ASTFileName;
2734 return std::string();
2739 if (Code == llvm::bitc::DEFINE_ABBREV) {
2740 Stream.ReadAbbrevRecord();
2745 const char *BlobStart = 0;
2746 unsigned BlobLen = 0;
2747 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
2748 == ORIGINAL_FILE_NAME)
2749 return std::string(BlobStart, BlobLen);
2752 return std::string();
2755 /// \brief Parse the record that corresponds to a LangOptions data
2758 /// This routine parses the language options from the AST file and then gives
2759 /// them to the AST listener if one is set.
2761 /// \returns true if the listener deems the file unacceptable, false otherwise.
2762 bool ASTReader::ParseLanguageOptions(
2763 const SmallVectorImpl<uint64_t> &Record) {
2765 LangOptions LangOpts;
2767 #define LANGOPT(Name, Bits, Default, Description) \
2768 LangOpts.Name = Record[Idx++];
2769 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
2770 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
2771 #include "clang/Basic/LangOptions.def"
2773 return Listener->ReadLanguageOptions(LangOpts);
2779 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
2780 PreprocessedEntityID PPID = Index+1;
2781 GlobalPreprocessedEntityMapType::iterator
2782 I = GlobalPreprocessedEntityMap.find(Index);
2783 assert(I != GlobalPreprocessedEntityMap.end() &&
2784 "Corrupted global preprocessed entity map");
2785 Module &M = *I->second;
2786 unsigned LocalIndex = Index - M.BasePreprocessedEntityID;
2787 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
2789 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
2790 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
2792 unsigned Code = M.PreprocessorDetailCursor.ReadCode();
2794 case llvm::bitc::END_BLOCK:
2797 case llvm::bitc::ENTER_SUBBLOCK:
2798 Error("unexpected subblock record in preprocessor detail block");
2801 case llvm::bitc::DEFINE_ABBREV:
2802 Error("unexpected abbrevation record in preprocessor detail block");
2809 if (!PP.getPreprocessingRecord()) {
2810 Error("no preprocessing record");
2815 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
2816 ReadSourceLocation(M, PPOffs.End));
2817 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
2818 const char *BlobStart = 0;
2819 unsigned BlobLen = 0;
2821 PreprocessorDetailRecordTypes RecType =
2822 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.ReadRecord(
2823 Code, Record, BlobStart, BlobLen);
2825 case PPD_MACRO_EXPANSION: {
2826 bool isBuiltin = Record[0];
2827 IdentifierInfo *Name = 0;
2828 MacroDefinition *Def = 0;
2830 Name = getLocalIdentifier(M, Record[1]);
2832 PreprocessedEntityID
2833 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
2834 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
2839 ME = new (PPRec) MacroExpansion(Name, Range);
2841 ME = new (PPRec) MacroExpansion(Def, Range);
2846 case PPD_MACRO_DEFINITION: {
2847 // Decode the identifier info and then check again; if the macro is
2848 // still defined and associated with the identifier,
2849 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
2851 = new (PPRec) MacroDefinition(II, Range);
2853 if (DeserializationListener)
2854 DeserializationListener->MacroDefinitionRead(PPID, MD);
2859 case PPD_INCLUSION_DIRECTIVE: {
2860 const char *FullFileNameStart = BlobStart + Record[0];
2861 const FileEntry *File
2862 = PP.getFileManager().getFile(StringRef(FullFileNameStart,
2863 BlobLen - Record[0]));
2865 // FIXME: Stable encoding
2866 InclusionDirective::InclusionKind Kind
2867 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
2868 InclusionDirective *ID
2869 = new (PPRec) InclusionDirective(PPRec, Kind,
2870 StringRef(BlobStart, Record[0]),
2878 Error("invalid offset in preprocessor detail block");
2882 /// \brief \arg SLocMapI points at a chunk of a module that contains no
2883 /// preprocessed entities or the entities it contains are not the ones we are
2884 /// looking for. Find the next module that contains entities and return the ID
2885 /// of the first entry.
2886 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
2887 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
2889 for (GlobalSLocOffsetMapType::const_iterator
2890 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
2891 Module &M = *SLocMapI->second;
2892 if (M.NumPreprocessedEntities)
2893 return getGlobalPreprocessedEntityID(M, M.BasePreprocessedEntityID);
2896 return getTotalNumPreprocessedEntities();
2901 template <unsigned PPEntityOffset::*PPLoc>
2902 struct PPEntityComp {
2903 const ASTReader &Reader;
2906 PPEntityComp(const ASTReader &Reader, Module &M) : Reader(Reader), M(M) { }
2908 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
2909 SourceLocation LHS = getLoc(L);
2910 SourceLocation RHS = getLoc(R);
2911 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
2914 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
2915 SourceLocation LHS = getLoc(L);
2916 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
2919 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
2920 SourceLocation RHS = getLoc(R);
2921 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
2924 SourceLocation getLoc(const PPEntityOffset &PPE) const {
2925 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
2931 /// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
2932 PreprocessedEntityID
2933 ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
2934 if (SourceMgr.isLocalSourceLocation(BLoc))
2935 return getTotalNumPreprocessedEntities();
2937 GlobalSLocOffsetMapType::const_iterator
2938 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
2940 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
2941 "Corrupted global sloc offset map");
2943 if (SLocMapI->second->NumPreprocessedEntities == 0)
2944 return findNextPreprocessedEntity(SLocMapI);
2946 Module &M = *SLocMapI->second;
2947 typedef const PPEntityOffset *pp_iterator;
2948 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
2949 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
2951 size_t Count = M.NumPreprocessedEntities;
2953 pp_iterator First = pp_begin;
2956 // Do a binary search manually instead of using std::lower_bound because
2957 // The end locations of entities may be unordered (when a macro expansion
2958 // is inside another macro argument), but for this case it is not important
2959 // whether we get the first macro expansion or its containing macro.
2963 std::advance(PPI, Half);
2964 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
2968 Count = Count - Half - 1;
2974 return findNextPreprocessedEntity(SLocMapI);
2976 return getGlobalPreprocessedEntityID(M,
2977 M.BasePreprocessedEntityID + (PPI - pp_begin));
2980 /// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
2981 PreprocessedEntityID
2982 ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
2983 if (SourceMgr.isLocalSourceLocation(ELoc))
2984 return getTotalNumPreprocessedEntities();
2986 GlobalSLocOffsetMapType::const_iterator
2987 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
2989 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
2990 "Corrupted global sloc offset map");
2992 if (SLocMapI->second->NumPreprocessedEntities == 0)
2993 return findNextPreprocessedEntity(SLocMapI);
2995 Module &M = *SLocMapI->second;
2996 typedef const PPEntityOffset *pp_iterator;
2997 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
2998 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
3000 std::upper_bound(pp_begin, pp_end, ELoc,
3001 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
3004 return findNextPreprocessedEntity(SLocMapI);
3006 return getGlobalPreprocessedEntityID(M,
3007 M.BasePreprocessedEntityID + (PPI - pp_begin));
3010 /// \brief Returns a pair of [Begin, End) indices of preallocated
3011 /// preprocessed entities that \arg Range encompasses.
3012 std::pair<unsigned, unsigned>
3013 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
3014 if (Range.isInvalid())
3015 return std::make_pair(0,0);
3016 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
3018 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
3019 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
3020 return std::make_pair(BeginID, EndID);
3024 /// \brief Visitor used to search for information about a header file.
3025 class HeaderFileInfoVisitor {
3027 const FileEntry *FE;
3029 llvm::Optional<HeaderFileInfo> HFI;
3032 HeaderFileInfoVisitor(ASTReader &Reader, const FileEntry *FE)
3033 : Reader(Reader), FE(FE) { }
3035 static bool visit(Module &M, void *UserData) {
3036 HeaderFileInfoVisitor *This
3037 = static_cast<HeaderFileInfoVisitor *>(UserData);
3039 HeaderFileInfoTrait Trait(This->Reader, M,
3040 &This->Reader.getPreprocessor().getHeaderSearchInfo(),
3041 M.HeaderFileFrameworkStrings,
3042 This->FE->getName());
3044 HeaderFileInfoLookupTable *Table
3045 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
3049 // Look in the on-disk hash table for an entry for this file name.
3050 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE->getName(),
3052 if (Pos == Table->end())
3059 llvm::Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
3063 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
3064 HeaderFileInfoVisitor Visitor(*this, FE);
3065 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
3066 if (llvm::Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) {
3068 Listener->ReadHeaderFileInfo(*HFI, FE->getUID());
3072 return HeaderFileInfo();
3075 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
3076 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
3079 while (Idx < F.PragmaDiagMappings.size()) {
3080 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
3082 assert(Idx < F.PragmaDiagMappings.size() &&
3083 "Invalid data, didn't find '-1' marking end of diag/map pairs");
3084 if (Idx >= F.PragmaDiagMappings.size()) {
3085 break; // Something is messed up but at least avoid infinite loop in
3088 unsigned DiagID = F.PragmaDiagMappings[Idx++];
3089 if (DiagID == (unsigned)-1) {
3090 break; // no more diag/map pairs for this location.
3092 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
3093 // The user bit gets set by WritePragmaDiagnosticMappings.
3094 Diag.setDiagnosticMapping(DiagID, Map, Loc);
3100 /// \brief Get the correct cursor and offset for loading a type.
3101 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
3102 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
3103 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
3104 Module *M = I->second;
3105 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
3108 /// \brief Read and return the type with the given index..
3110 /// The index is the type ID, shifted and minus the number of predefs. This
3111 /// routine actually reads the record corresponding to the type at the given
3112 /// location. It is a helper routine for GetType, which deals with reading type
3114 QualType ASTReader::readTypeRecord(unsigned Index) {
3115 RecordLocation Loc = TypeCursorForIndex(Index);
3116 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3118 // Keep track of where we are in the stream, then jump back there
3119 // after reading this type.
3120 SavedStreamPosition SavedPosition(DeclsCursor);
3122 ReadingKindTracker ReadingKind(Read_Type, *this);
3124 // Note that we are loading a type record.
3125 Deserializing AType(this);
3128 DeclsCursor.JumpToBit(Loc.Offset);
3130 unsigned Code = DeclsCursor.ReadCode();
3131 switch ((TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
3132 case TYPE_EXT_QUAL: {
3133 if (Record.size() != 2) {
3134 Error("Incorrect encoding of extended qualifier type");
3137 QualType Base = readType(*Loc.F, Record, Idx);
3138 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
3139 return Context.getQualifiedType(Base, Quals);
3142 case TYPE_COMPLEX: {
3143 if (Record.size() != 1) {
3144 Error("Incorrect encoding of complex type");
3147 QualType ElemType = readType(*Loc.F, Record, Idx);
3148 return Context.getComplexType(ElemType);
3151 case TYPE_POINTER: {
3152 if (Record.size() != 1) {
3153 Error("Incorrect encoding of pointer type");
3156 QualType PointeeType = readType(*Loc.F, Record, Idx);
3157 return Context.getPointerType(PointeeType);
3160 case TYPE_BLOCK_POINTER: {
3161 if (Record.size() != 1) {
3162 Error("Incorrect encoding of block pointer type");
3165 QualType PointeeType = readType(*Loc.F, Record, Idx);
3166 return Context.getBlockPointerType(PointeeType);
3169 case TYPE_LVALUE_REFERENCE: {
3170 if (Record.size() != 2) {
3171 Error("Incorrect encoding of lvalue reference type");
3174 QualType PointeeType = readType(*Loc.F, Record, Idx);
3175 return Context.getLValueReferenceType(PointeeType, Record[1]);
3178 case TYPE_RVALUE_REFERENCE: {
3179 if (Record.size() != 1) {
3180 Error("Incorrect encoding of rvalue reference type");
3183 QualType PointeeType = readType(*Loc.F, Record, Idx);
3184 return Context.getRValueReferenceType(PointeeType);
3187 case TYPE_MEMBER_POINTER: {
3188 if (Record.size() != 2) {
3189 Error("Incorrect encoding of member pointer type");
3192 QualType PointeeType = readType(*Loc.F, Record, Idx);
3193 QualType ClassType = readType(*Loc.F, Record, Idx);
3194 if (PointeeType.isNull() || ClassType.isNull())
3197 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
3200 case TYPE_CONSTANT_ARRAY: {
3201 QualType ElementType = readType(*Loc.F, Record, Idx);
3202 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3203 unsigned IndexTypeQuals = Record[2];
3205 llvm::APInt Size = ReadAPInt(Record, Idx);
3206 return Context.getConstantArrayType(ElementType, Size,
3207 ASM, IndexTypeQuals);
3210 case TYPE_INCOMPLETE_ARRAY: {
3211 QualType ElementType = readType(*Loc.F, Record, Idx);
3212 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3213 unsigned IndexTypeQuals = Record[2];
3214 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
3217 case TYPE_VARIABLE_ARRAY: {
3218 QualType ElementType = readType(*Loc.F, Record, Idx);
3219 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3220 unsigned IndexTypeQuals = Record[2];
3221 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
3222 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
3223 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
3224 ASM, IndexTypeQuals,
3225 SourceRange(LBLoc, RBLoc));
3229 if (Record.size() != 3) {
3230 Error("incorrect encoding of vector type in AST file");
3234 QualType ElementType = readType(*Loc.F, Record, Idx);
3235 unsigned NumElements = Record[1];
3236 unsigned VecKind = Record[2];
3237 return Context.getVectorType(ElementType, NumElements,
3238 (VectorType::VectorKind)VecKind);
3241 case TYPE_EXT_VECTOR: {
3242 if (Record.size() != 3) {
3243 Error("incorrect encoding of extended vector type in AST file");
3247 QualType ElementType = readType(*Loc.F, Record, Idx);
3248 unsigned NumElements = Record[1];
3249 return Context.getExtVectorType(ElementType, NumElements);
3252 case TYPE_FUNCTION_NO_PROTO: {
3253 if (Record.size() != 6) {
3254 Error("incorrect encoding of no-proto function type");
3257 QualType ResultType = readType(*Loc.F, Record, Idx);
3258 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
3259 (CallingConv)Record[4], Record[5]);
3260 return Context.getFunctionNoProtoType(ResultType, Info);
3263 case TYPE_FUNCTION_PROTO: {
3264 QualType ResultType = readType(*Loc.F, Record, Idx);
3266 FunctionProtoType::ExtProtoInfo EPI;
3267 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
3268 /*hasregparm*/ Record[2],
3269 /*regparm*/ Record[3],
3270 static_cast<CallingConv>(Record[4]),
3271 /*produces*/ Record[5]);
3274 unsigned NumParams = Record[Idx++];
3275 SmallVector<QualType, 16> ParamTypes;
3276 for (unsigned I = 0; I != NumParams; ++I)
3277 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
3279 EPI.Variadic = Record[Idx++];
3280 EPI.TypeQuals = Record[Idx++];
3281 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
3282 ExceptionSpecificationType EST =
3283 static_cast<ExceptionSpecificationType>(Record[Idx++]);
3284 EPI.ExceptionSpecType = EST;
3285 if (EST == EST_Dynamic) {
3286 EPI.NumExceptions = Record[Idx++];
3287 SmallVector<QualType, 2> Exceptions;
3288 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
3289 Exceptions.push_back(readType(*Loc.F, Record, Idx));
3290 EPI.Exceptions = Exceptions.data();
3291 } else if (EST == EST_ComputedNoexcept) {
3292 EPI.NoexceptExpr = ReadExpr(*Loc.F);
3294 return Context.getFunctionType(ResultType, ParamTypes.data(), NumParams,
3298 case TYPE_UNRESOLVED_USING: {
3300 return Context.getTypeDeclType(
3301 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
3304 case TYPE_TYPEDEF: {
3305 if (Record.size() != 2) {
3306 Error("incorrect encoding of typedef type");
3310 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
3311 QualType Canonical = readType(*Loc.F, Record, Idx);
3312 if (!Canonical.isNull())
3313 Canonical = Context.getCanonicalType(Canonical);
3314 return Context.getTypedefType(Decl, Canonical);
3317 case TYPE_TYPEOF_EXPR:
3318 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
3321 if (Record.size() != 1) {
3322 Error("incorrect encoding of typeof(type) in AST file");
3325 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
3326 return Context.getTypeOfType(UnderlyingType);
3330 return Context.getDecltypeType(ReadExpr(*Loc.F));
3332 case TYPE_UNARY_TRANSFORM: {
3333 QualType BaseType = readType(*Loc.F, Record, Idx);
3334 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
3335 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
3336 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
3340 return Context.getAutoType(readType(*Loc.F, Record, Idx));
3343 if (Record.size() != 2) {
3344 Error("incorrect encoding of record type");
3348 bool IsDependent = Record[Idx++];
3350 = Context.getRecordType(ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx));
3351 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
3356 if (Record.size() != 2) {
3357 Error("incorrect encoding of enum type");
3361 bool IsDependent = Record[Idx++];
3363 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
3364 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
3368 case TYPE_ATTRIBUTED: {
3369 if (Record.size() != 3) {
3370 Error("incorrect encoding of attributed type");
3373 QualType modifiedType = readType(*Loc.F, Record, Idx);
3374 QualType equivalentType = readType(*Loc.F, Record, Idx);
3375 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
3376 return Context.getAttributedType(kind, modifiedType, equivalentType);
3380 if (Record.size() != 1) {
3381 Error("incorrect encoding of paren type");
3384 QualType InnerType = readType(*Loc.F, Record, Idx);
3385 return Context.getParenType(InnerType);
3388 case TYPE_PACK_EXPANSION: {
3389 if (Record.size() != 2) {
3390 Error("incorrect encoding of pack expansion type");
3393 QualType Pattern = readType(*Loc.F, Record, Idx);
3394 if (Pattern.isNull())
3396 llvm::Optional<unsigned> NumExpansions;
3398 NumExpansions = Record[1] - 1;
3399 return Context.getPackExpansionType(Pattern, NumExpansions);
3402 case TYPE_ELABORATED: {
3404 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
3405 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
3406 QualType NamedType = readType(*Loc.F, Record, Idx);
3407 return Context.getElaboratedType(Keyword, NNS, NamedType);
3410 case TYPE_OBJC_INTERFACE: {
3412 ObjCInterfaceDecl *ItfD
3413 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
3414 return Context.getObjCInterfaceType(ItfD);
3417 case TYPE_OBJC_OBJECT: {
3419 QualType Base = readType(*Loc.F, Record, Idx);
3420 unsigned NumProtos = Record[Idx++];
3421 SmallVector<ObjCProtocolDecl*, 4> Protos;
3422 for (unsigned I = 0; I != NumProtos; ++I)
3423 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
3424 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
3427 case TYPE_OBJC_OBJECT_POINTER: {
3429 QualType Pointee = readType(*Loc.F, Record, Idx);
3430 return Context.getObjCObjectPointerType(Pointee);
3433 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
3435 QualType Parm = readType(*Loc.F, Record, Idx);
3436 QualType Replacement = readType(*Loc.F, Record, Idx);
3438 Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
3442 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
3444 QualType Parm = readType(*Loc.F, Record, Idx);
3445 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
3446 return Context.getSubstTemplateTypeParmPackType(
3447 cast<TemplateTypeParmType>(Parm),
3451 case TYPE_INJECTED_CLASS_NAME: {
3452 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
3453 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
3454 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
3455 // for AST reading, too much interdependencies.
3457 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
3460 case TYPE_TEMPLATE_TYPE_PARM: {
3462 unsigned Depth = Record[Idx++];
3463 unsigned Index = Record[Idx++];
3464 bool Pack = Record[Idx++];
3465 TemplateTypeParmDecl *D
3466 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
3467 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
3470 case TYPE_DEPENDENT_NAME: {
3472 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
3473 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
3474 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
3475 QualType Canon = readType(*Loc.F, Record, Idx);
3476 if (!Canon.isNull())
3477 Canon = Context.getCanonicalType(Canon);
3478 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
3481 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
3483 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
3484 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
3485 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
3486 unsigned NumArgs = Record[Idx++];
3487 SmallVector<TemplateArgument, 8> Args;
3488 Args.reserve(NumArgs);
3490 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
3491 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
3492 Args.size(), Args.data());
3495 case TYPE_DEPENDENT_SIZED_ARRAY: {
3499 QualType ElementType = readType(*Loc.F, Record, Idx);
3500 ArrayType::ArraySizeModifier ASM
3501 = (ArrayType::ArraySizeModifier)Record[Idx++];
3502 unsigned IndexTypeQuals = Record[Idx++];
3504 // DependentSizedArrayType
3505 Expr *NumElts = ReadExpr(*Loc.F);
3506 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
3508 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
3509 IndexTypeQuals, Brackets);
3512 case TYPE_TEMPLATE_SPECIALIZATION: {
3514 bool IsDependent = Record[Idx++];
3515 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
3516 SmallVector<TemplateArgument, 8> Args;
3517 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
3518 QualType Underlying = readType(*Loc.F, Record, Idx);
3520 if (Underlying.isNull())
3521 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
3524 T = Context.getTemplateSpecializationType(Name, Args.data(),
3525 Args.size(), Underlying);
3526 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
3531 if (Record.size() != 1) {
3532 Error("Incorrect encoding of atomic type");
3535 QualType ValueType = readType(*Loc.F, Record, Idx);
3536 return Context.getAtomicType(ValueType);
3539 // Suppress a GCC warning
3543 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
3546 llvm::BitstreamCursor &DeclsCursor;
3547 const ASTReader::RecordData &Record;
3550 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
3552 return Reader.ReadSourceLocation(F, R, I);
3555 template<typename T>
3556 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
3557 return Reader.ReadDeclAs<T>(F, Record, Idx);
3561 TypeLocReader(ASTReader &Reader, Module &F,
3562 const ASTReader::RecordData &Record, unsigned &Idx)
3563 : Reader(Reader), F(F), DeclsCursor(F.DeclsCursor), Record(Record), Idx(Idx)
3566 // We want compile-time assurance that we've enumerated all of
3567 // these, so unfortunately we have to declare them first, then
3568 // define them out-of-line.
3569 #define ABSTRACT_TYPELOC(CLASS, PARENT)
3570 #define TYPELOC(CLASS, PARENT) \
3571 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
3572 #include "clang/AST/TypeLocNodes.def"
3574 void VisitFunctionTypeLoc(FunctionTypeLoc);
3575 void VisitArrayTypeLoc(ArrayTypeLoc);
3578 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3581 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
3582 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
3583 if (TL.needsExtraLocalData()) {
3584 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
3585 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
3586 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
3587 TL.setModeAttr(Record[Idx++]);
3590 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
3591 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3593 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
3594 TL.setStarLoc(ReadSourceLocation(Record, Idx));
3596 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3597 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
3599 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3600 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
3602 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3603 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
3605 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3606 TL.setStarLoc(ReadSourceLocation(Record, Idx));
3607 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
3609 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
3610 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
3611 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
3613 TL.setSizeExpr(Reader.ReadExpr(F));
3617 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
3618 VisitArrayTypeLoc(TL);
3620 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
3621 VisitArrayTypeLoc(TL);
3623 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
3624 VisitArrayTypeLoc(TL);
3626 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
3627 DependentSizedArrayTypeLoc TL) {
3628 VisitArrayTypeLoc(TL);
3630 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
3631 DependentSizedExtVectorTypeLoc TL) {
3632 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3634 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
3635 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3637 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
3638 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3640 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3641 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
3642 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
3643 TL.setTrailingReturn(Record[Idx++]);
3644 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
3645 TL.setArg(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
3648 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
3649 VisitFunctionTypeLoc(TL);
3651 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
3652 VisitFunctionTypeLoc(TL);
3654 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
3655 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3657 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
3658 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3660 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
3661 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
3662 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3663 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3665 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
3666 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
3667 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3668 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3669 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
3671 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
3672 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3674 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
3675 TL.setKWLoc(ReadSourceLocation(Record, Idx));
3676 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3677 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3678 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
3680 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
3681 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3683 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
3684 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3686 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
3687 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3689 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3690 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
3691 if (TL.hasAttrOperand()) {
3693 range.setBegin(ReadSourceLocation(Record, Idx));
3694 range.setEnd(ReadSourceLocation(Record, Idx));
3695 TL.setAttrOperandParensRange(range);
3697 if (TL.hasAttrExprOperand()) {
3699 TL.setAttrExprOperand(Reader.ReadExpr(F));
3701 TL.setAttrExprOperand(0);
3702 } else if (TL.hasAttrEnumOperand())
3703 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
3705 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
3706 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3708 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
3709 SubstTemplateTypeParmTypeLoc TL) {
3710 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3712 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
3713 SubstTemplateTypeParmPackTypeLoc TL) {
3714 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3716 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
3717 TemplateSpecializationTypeLoc TL) {
3718 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
3719 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3720 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
3721 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3723 Reader.GetTemplateArgumentLocInfo(F,
3724 TL.getTypePtr()->getArg(i).getKind(),
3727 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
3728 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3729 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3731 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
3732 TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
3733 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
3735 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
3736 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3738 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
3739 TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
3740 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
3741 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3743 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
3744 DependentTemplateSpecializationTypeLoc TL) {
3745 TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
3746 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
3747 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3748 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3749 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
3750 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
3752 Reader.GetTemplateArgumentLocInfo(F,
3753 TL.getTypePtr()->getArg(I).getKind(),
3756 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
3757 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
3759 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
3760 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3762 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
3763 TL.setHasBaseTypeAsWritten(Record[Idx++]);
3764 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3765 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
3766 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
3767 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
3769 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3770 TL.setStarLoc(ReadSourceLocation(Record, Idx));
3772 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
3773 TL.setKWLoc(ReadSourceLocation(Record, Idx));
3774 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3775 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3778 TypeSourceInfo *ASTReader::GetTypeSourceInfo(Module &F,
3779 const RecordData &Record,
3781 QualType InfoTy = readType(F, Record, Idx);
3782 if (InfoTy.isNull())
3785 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
3786 TypeLocReader TLR(*this, F, Record, Idx);
3787 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
3792 QualType ASTReader::GetType(TypeID ID) {
3793 unsigned FastQuals = ID & Qualifiers::FastMask;
3794 unsigned Index = ID >> Qualifiers::FastWidth;
3796 if (Index < NUM_PREDEF_TYPE_IDS) {
3798 switch ((PredefinedTypeIDs)Index) {
3799 case PREDEF_TYPE_NULL_ID: return QualType();
3800 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
3801 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
3803 case PREDEF_TYPE_CHAR_U_ID:
3804 case PREDEF_TYPE_CHAR_S_ID:
3805 // FIXME: Check that the signedness of CharTy is correct!
3809 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
3810 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
3811 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
3812 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
3813 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
3814 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
3815 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
3816 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
3817 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
3818 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
3819 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
3820 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
3821 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
3822 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
3823 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
3824 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
3825 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
3826 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
3827 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
3828 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
3829 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
3830 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
3831 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
3832 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
3833 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
3834 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
3835 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
3836 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
3838 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
3839 T = Context.getAutoRRefDeductType();
3843 assert(!T.isNull() && "Unknown predefined type");
3844 return T.withFastQualifiers(FastQuals);
3847 Index -= NUM_PREDEF_TYPE_IDS;
3848 assert(Index < TypesLoaded.size() && "Type index out-of-range");
3849 if (TypesLoaded[Index].isNull()) {
3850 TypesLoaded[Index] = readTypeRecord(Index);
3851 if (TypesLoaded[Index].isNull())
3854 TypesLoaded[Index]->setFromAST();
3855 if (DeserializationListener)
3856 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
3857 TypesLoaded[Index]);
3860 return TypesLoaded[Index].withFastQualifiers(FastQuals);
3863 QualType ASTReader::getLocalType(Module &F, unsigned LocalID) {
3864 return GetType(getGlobalTypeID(F, LocalID));
3867 serialization::TypeID
3868 ASTReader::getGlobalTypeID(Module &F, unsigned LocalID) const {
3869 unsigned FastQuals = LocalID & Qualifiers::FastMask;
3870 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
3872 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
3875 ContinuousRangeMap<uint32_t, int, 2>::iterator I
3876 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
3877 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
3879 unsigned GlobalIndex = LocalIndex + I->second;
3880 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
3883 TemplateArgumentLocInfo
3884 ASTReader::GetTemplateArgumentLocInfo(Module &F,
3885 TemplateArgument::ArgKind Kind,
3886 const RecordData &Record,
3889 case TemplateArgument::Expression:
3891 case TemplateArgument::Type:
3892 return GetTypeSourceInfo(F, Record, Index);
3893 case TemplateArgument::Template: {
3894 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
3896 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
3897 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
3900 case TemplateArgument::TemplateExpansion: {
3901 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
3903 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
3904 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
3905 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
3908 case TemplateArgument::Null:
3909 case TemplateArgument::Integral:
3910 case TemplateArgument::Declaration:
3911 case TemplateArgument::Pack:
3912 return TemplateArgumentLocInfo();
3914 llvm_unreachable("unexpected template argument loc");
3915 return TemplateArgumentLocInfo();
3919 ASTReader::ReadTemplateArgumentLoc(Module &F,
3920 const RecordData &Record, unsigned &Index) {
3921 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
3923 if (Arg.getKind() == TemplateArgument::Expression) {
3924 if (Record[Index++]) // bool InfoHasSameExpr.
3925 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
3927 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
3931 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
3935 uint64_t ASTReader::readCXXBaseSpecifiers(Module &M, const RecordData &Record,
3937 if (Idx >= Record.size())
3940 unsigned LocalID = Record[Idx++];
3941 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
3944 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
3945 RecordLocation Loc = getLocalBitOffset(Offset);
3946 llvm::BitstreamCursor &Cursor = Loc.F->DeclsCursor;
3947 SavedStreamPosition SavedPosition(Cursor);
3948 Cursor.JumpToBit(Loc.Offset);
3949 ReadingKindTracker ReadingKind(Read_Decl, *this);
3951 unsigned Code = Cursor.ReadCode();
3952 unsigned RecCode = Cursor.ReadRecord(Code, Record);
3953 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
3954 Error("Malformed AST file: missing C++ base specifiers");
3959 unsigned NumBases = Record[Idx++];
3960 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
3961 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
3962 for (unsigned I = 0; I != NumBases; ++I)
3963 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
3967 serialization::DeclID
3968 ASTReader::getGlobalDeclID(Module &F, unsigned LocalID) const {
3969 if (LocalID < NUM_PREDEF_DECL_IDS)
3972 ContinuousRangeMap<uint32_t, int, 2>::iterator I
3973 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
3974 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
3976 return LocalID + I->second;
3979 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
3981 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
3982 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
3983 return &M == I->second;
3986 Decl *ASTReader::GetDecl(DeclID ID) {
3987 if (ID < NUM_PREDEF_DECL_IDS) {
3988 switch ((PredefinedDeclIDs)ID) {
3989 case PREDEF_DECL_NULL_ID:
3992 case PREDEF_DECL_TRANSLATION_UNIT_ID:
3993 return Context.getTranslationUnitDecl();
3995 case PREDEF_DECL_OBJC_ID_ID:
3996 return Context.getObjCIdDecl();
3998 case PREDEF_DECL_OBJC_SEL_ID:
3999 return Context.getObjCSelDecl();
4001 case PREDEF_DECL_OBJC_CLASS_ID:
4002 return Context.getObjCClassDecl();
4004 case PREDEF_DECL_INT_128_ID:
4005 return Context.getInt128Decl();
4007 case PREDEF_DECL_UNSIGNED_INT_128_ID:
4008 return Context.getUInt128Decl();
4010 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
4011 return Context.getObjCInstanceTypeDecl();
4017 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
4019 if (Index > DeclsLoaded.size()) {
4020 Error("declaration ID out-of-range for AST file");
4024 if (!DeclsLoaded[Index]) {
4026 if (DeserializationListener)
4027 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
4030 return DeclsLoaded[Index];
4033 serialization::DeclID ASTReader::ReadDeclID(Module &F,
4034 const RecordData &Record,
4036 if (Idx >= Record.size()) {
4037 Error("Corrupted AST file");
4041 return getGlobalDeclID(F, Record[Idx++]);
4044 /// \brief Resolve the offset of a statement into a statement.
4046 /// This operation will read a new statement from the external
4047 /// source each time it is called, and is meant to be used via a
4048 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
4049 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
4050 // Switch case IDs are per Decl.
4051 ClearSwitchCaseIDs();
4053 // Offset here is a global offset across the entire chain.
4054 RecordLocation Loc = getLocalBitOffset(Offset);
4055 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
4056 return ReadStmtFromStream(*Loc.F);
4060 class FindExternalLexicalDeclsVisitor {
4062 const DeclContext *DC;
4063 bool (*isKindWeWant)(Decl::Kind);
4065 SmallVectorImpl<Decl*> &Decls;
4066 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
4069 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
4070 bool (*isKindWeWant)(Decl::Kind),
4071 SmallVectorImpl<Decl*> &Decls)
4072 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
4074 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
4075 PredefsVisited[I] = false;
4078 static bool visit(Module &M, bool Preorder, void *UserData) {
4082 FindExternalLexicalDeclsVisitor *This
4083 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
4085 Module::DeclContextInfosMap::iterator Info
4086 = M.DeclContextInfos.find(This->DC);
4087 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
4090 // Load all of the declaration IDs
4091 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
4092 *IDE = ID + Info->second.NumLexicalDecls;
4094 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
4097 // Don't add predefined declarations to the lexical context more
4099 if (ID->second < NUM_PREDEF_DECL_IDS) {
4100 if (This->PredefsVisited[ID->second])
4103 This->PredefsVisited[ID->second] = true;
4106 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
4107 if (!This->DC->isDeclInLexicalTraversal(D))
4108 This->Decls.push_back(D);
4117 ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
4118 bool (*isKindWeWant)(Decl::Kind),
4119 SmallVectorImpl<Decl*> &Decls) {
4120 // There might be lexical decls in multiple modules, for the TU at
4121 // least. Walk all of the modules in the order they were loaded.
4122 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
4123 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
4124 ++NumLexicalDeclContextsRead;
4129 /// \brief Module visitor used to perform name lookup into a
4130 /// declaration context.
4131 class DeclContextNameLookupVisitor {
4133 const DeclContext *DC;
4134 DeclarationName Name;
4135 SmallVectorImpl<NamedDecl *> &Decls;
4138 DeclContextNameLookupVisitor(ASTReader &Reader,
4139 const DeclContext *DC, DeclarationName Name,
4140 SmallVectorImpl<NamedDecl *> &Decls)
4141 : Reader(Reader), DC(DC), Name(Name), Decls(Decls) { }
4143 static bool visit(Module &M, void *UserData) {
4144 DeclContextNameLookupVisitor *This
4145 = static_cast<DeclContextNameLookupVisitor *>(UserData);
4147 // Check whether we have any visible declaration information for
4148 // this context in this module.
4149 Module::DeclContextInfosMap::iterator Info
4150 = M.DeclContextInfos.find(This->DC);
4151 if (Info == M.DeclContextInfos.end() || !Info->second.NameLookupTableData)
4154 // Look for this name within this module.
4155 ASTDeclContextNameLookupTable *LookupTable =
4156 (ASTDeclContextNameLookupTable*)Info->second.NameLookupTableData;
4157 ASTDeclContextNameLookupTable::iterator Pos
4158 = LookupTable->find(This->Name);
4159 if (Pos == LookupTable->end())
4162 bool FoundAnything = false;
4163 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
4164 for (; Data.first != Data.second; ++Data.first) {
4165 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
4169 if (ND->getDeclName() != This->Name) {
4170 assert(!This->Name.getCXXNameType().isNull() &&
4171 "Name mismatch without a type");
4175 // Record this declaration.
4176 FoundAnything = true;
4177 This->Decls.push_back(ND);
4180 return FoundAnything;
4185 DeclContext::lookup_result
4186 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
4187 DeclarationName Name) {
4188 assert(DC->hasExternalVisibleStorage() &&
4189 "DeclContext has no visible decls in storage");
4191 return DeclContext::lookup_result(DeclContext::lookup_iterator(0),
4192 DeclContext::lookup_iterator(0));
4194 SmallVector<NamedDecl *, 64> Decls;
4195 DeclContextNameLookupVisitor Visitor(*this, DC, Name, Decls);
4196 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
4197 ++NumVisibleDeclContextsRead;
4198 SetExternalVisibleDeclsForName(DC, Name, Decls);
4199 return const_cast<DeclContext*>(DC)->lookup(Name);
4202 /// \brief Under non-PCH compilation the consumer receives the objc methods
4203 /// before receiving the implementation, and codegen depends on this.
4204 /// We simulate this by deserializing and passing to consumer the methods of the
4205 /// implementation before passing the deserialized implementation decl.
4206 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
4207 ASTConsumer *Consumer) {
4208 assert(ImplD && Consumer);
4210 for (ObjCImplDecl::method_iterator
4211 I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
4212 Consumer->HandleInterestingDecl(DeclGroupRef(*I));
4214 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
4217 void ASTReader::PassInterestingDeclsToConsumer() {
4219 while (!InterestingDecls.empty()) {
4220 Decl *D = InterestingDecls.front();
4221 InterestingDecls.pop_front();
4223 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4224 PassObjCImplDeclToConsumer(ImplD, Consumer);
4226 Consumer->HandleInterestingDecl(DeclGroupRef(D));
4230 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
4231 this->Consumer = Consumer;
4236 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
4237 // Force deserialization of this decl, which will cause it to be queued for
4238 // passing to the consumer.
4239 GetDecl(ExternalDefinitions[I]);
4241 ExternalDefinitions.clear();
4243 PassInterestingDeclsToConsumer();
4246 void ASTReader::PrintStats() {
4247 std::fprintf(stderr, "*** AST File Statistics:\n");
4249 unsigned NumTypesLoaded
4250 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
4252 unsigned NumDeclsLoaded
4253 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
4255 unsigned NumIdentifiersLoaded
4256 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
4257 IdentifiersLoaded.end(),
4258 (IdentifierInfo *)0);
4259 unsigned NumSelectorsLoaded
4260 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
4261 SelectorsLoaded.end(),
4264 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
4265 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
4266 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
4267 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
4268 NumSLocEntriesRead, TotalNumSLocEntries,
4269 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
4270 if (!TypesLoaded.empty())
4271 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
4272 NumTypesLoaded, (unsigned)TypesLoaded.size(),
4273 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
4274 if (!DeclsLoaded.empty())
4275 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
4276 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
4277 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
4278 if (!IdentifiersLoaded.empty())
4279 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
4280 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
4281 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
4282 if (!SelectorsLoaded.empty())
4283 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
4284 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
4285 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
4286 if (TotalNumStatements)
4287 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
4288 NumStatementsRead, TotalNumStatements,
4289 ((float)NumStatementsRead/TotalNumStatements * 100));
4291 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
4292 NumMacrosRead, TotalNumMacros,
4293 ((float)NumMacrosRead/TotalNumMacros * 100));
4294 if (TotalLexicalDeclContexts)
4295 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
4296 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
4297 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
4299 if (TotalVisibleDeclContexts)
4300 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
4301 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
4302 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
4304 if (TotalNumMethodPoolEntries) {
4305 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
4306 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
4307 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
4309 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
4311 std::fprintf(stderr, "\n");
4313 std::fprintf(stderr, "\n");
4316 template<typename Key, typename Module, unsigned InitialCapacity>
4318 dumpModuleIDMap(StringRef Name,
4319 const ContinuousRangeMap<Key, Module *,
4320 InitialCapacity> &Map) {
4321 if (Map.begin() == Map.end())
4324 typedef ContinuousRangeMap<Key, Module *, InitialCapacity> MapType;
4325 llvm::errs() << Name << ":\n";
4326 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
4328 llvm::errs() << " " << I->first << " -> " << I->second->FileName
4333 void ASTReader::dump() {
4334 llvm::errs() << "*** PCH/Module Remappings:\n";
4335 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
4336 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
4337 dumpModuleIDMap("Global type map", GlobalTypeMap);
4338 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
4339 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
4340 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
4341 dumpModuleIDMap("Global preprocessed entity map",
4342 GlobalPreprocessedEntityMap);
4344 llvm::errs() << "\n*** PCH/Modules Loaded:";
4345 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
4346 MEnd = ModuleMgr.end();
4351 /// Return the amount of memory used by memory buffers, breaking down
4352 /// by heap-backed versus mmap'ed memory.
4353 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
4354 for (ModuleConstIterator I = ModuleMgr.begin(),
4355 E = ModuleMgr.end(); I != E; ++I) {
4356 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
4357 size_t bytes = buf->getBufferSize();
4358 switch (buf->getBufferKind()) {
4359 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
4360 sizes.malloc_bytes += bytes;
4362 case llvm::MemoryBuffer::MemoryBuffer_MMap:
4363 sizes.mmap_bytes += bytes;
4370 void ASTReader::InitializeSema(Sema &S) {
4372 S.ExternalSource = this;
4374 // Makes sure any declarations that were deserialized "too early"
4375 // still get added to the identifier's declaration chains.
4376 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
4377 if (SemaObj->TUScope)
4378 SemaObj->TUScope->AddDecl(PreloadedDecls[I]);
4380 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
4382 PreloadedDecls.clear();
4384 // Load the offsets of the declarations that Sema references.
4385 // They will be lazily deserialized when needed.
4386 if (!SemaDeclRefs.empty()) {
4387 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
4388 if (!SemaObj->StdNamespace)
4389 SemaObj->StdNamespace = SemaDeclRefs[0];
4390 if (!SemaObj->StdBadAlloc)
4391 SemaObj->StdBadAlloc = SemaDeclRefs[1];
4394 if (!FPPragmaOptions.empty()) {
4395 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
4396 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
4399 if (!OpenCLExtensions.empty()) {
4401 #define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
4402 #include "clang/Basic/OpenCLExtensions.def"
4404 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
4408 IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
4409 IdentifierLookupVisitor Visitor(StringRef(NameStart, NameEnd - NameStart));
4410 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
4411 return Visitor.getIdentifierInfo();
4415 /// \brief An identifier-lookup iterator that enumerates all of the
4416 /// identifiers stored within a set of AST files.
4417 class ASTIdentifierIterator : public IdentifierIterator {
4418 /// \brief The AST reader whose identifiers are being enumerated.
4419 const ASTReader &Reader;
4421 /// \brief The current index into the chain of AST files stored in
4425 /// \brief The current position within the identifier lookup table
4426 /// of the current AST file.
4427 ASTIdentifierLookupTable::key_iterator Current;
4429 /// \brief The end position within the identifier lookup table of
4430 /// the current AST file.
4431 ASTIdentifierLookupTable::key_iterator End;
4434 explicit ASTIdentifierIterator(const ASTReader &Reader);
4436 virtual StringRef Next();
4440 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
4441 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
4442 ASTIdentifierLookupTable *IdTable
4443 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
4444 Current = IdTable->key_begin();
4445 End = IdTable->key_end();
4448 StringRef ASTIdentifierIterator::Next() {
4449 while (Current == End) {
4450 // If we have exhausted all of our AST files, we're done.
4455 ASTIdentifierLookupTable *IdTable
4456 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
4457 IdentifierLookupTable;
4458 Current = IdTable->key_begin();
4459 End = IdTable->key_end();
4462 // We have any identifiers remaining in the current AST file; return
4464 std::pair<const char*, unsigned> Key = *Current;
4466 return StringRef(Key.first, Key.second);
4469 IdentifierIterator *ASTReader::getIdentifiers() const {
4470 return new ASTIdentifierIterator(*this);
4473 namespace clang { namespace serialization {
4474 class ReadMethodPoolVisitor {
4477 llvm::SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
4478 llvm::SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
4480 /// \brief Build an ObjCMethodList from a vector of Objective-C method
4483 buildObjCMethodList(const SmallVectorImpl<ObjCMethodDecl *> &Vec) const
4485 ObjCMethodList List;
4486 ObjCMethodList *Prev = 0;
4487 for (unsigned I = 0, N = Vec.size(); I != N; ++I) {
4489 // This is the first method, which is the easy case.
4490 List.Method = Vec[I];
4495 ObjCMethodList *Mem =
4496 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
4497 Prev->Next = new (Mem) ObjCMethodList(Vec[I], 0);
4505 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel)
4506 : Reader(Reader), Sel(Sel) { }
4508 static bool visit(Module &M, void *UserData) {
4509 ReadMethodPoolVisitor *This
4510 = static_cast<ReadMethodPoolVisitor *>(UserData);
4512 if (!M.SelectorLookupTable)
4515 ASTSelectorLookupTable *PoolTable
4516 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
4517 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
4518 if (Pos == PoolTable->end())
4521 ++This->Reader.NumSelectorsRead;
4522 // FIXME: Not quite happy with the statistics here. We probably should
4523 // disable this tracking when called via LoadSelector.
4524 // Also, should entries without methods count as misses?
4525 ++This->Reader.NumMethodPoolEntriesRead;
4526 ASTSelectorLookupTrait::data_type Data = *Pos;
4527 if (This->Reader.DeserializationListener)
4528 This->Reader.DeserializationListener->SelectorRead(Data.ID,
4531 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
4532 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
4536 /// \brief Retrieve the instance methods found by this visitor.
4537 ObjCMethodList getInstanceMethods() const {
4538 return buildObjCMethodList(InstanceMethods);
4541 /// \brief Retrieve the instance methods found by this visitor.
4542 ObjCMethodList getFactoryMethods() const {
4543 return buildObjCMethodList(FactoryMethods);
4546 } } // end namespace clang::serialization
4548 std::pair<ObjCMethodList, ObjCMethodList>
4549 ASTReader::ReadMethodPool(Selector Sel) {
4550 ReadMethodPoolVisitor Visitor(*this, Sel);
4551 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
4552 std::pair<ObjCMethodList, ObjCMethodList> Result;
4553 Result.first = Visitor.getInstanceMethods();
4554 Result.second = Visitor.getFactoryMethods();
4556 if (!Result.first.Method && !Result.second.Method)
4557 ++NumMethodPoolMisses;
4561 void ASTReader::ReadKnownNamespaces(
4562 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
4565 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
4566 if (NamespaceDecl *Namespace
4567 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
4568 Namespaces.push_back(Namespace);
4572 void ASTReader::ReadTentativeDefinitions(
4573 SmallVectorImpl<VarDecl *> &TentativeDefs) {
4574 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
4575 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
4577 TentativeDefs.push_back(Var);
4579 TentativeDefinitions.clear();
4582 void ASTReader::ReadUnusedFileScopedDecls(
4583 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
4584 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
4586 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
4590 UnusedFileScopedDecls.clear();
4593 void ASTReader::ReadDelegatingConstructors(
4594 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
4595 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
4596 CXXConstructorDecl *D
4597 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
4601 DelegatingCtorDecls.clear();
4604 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
4605 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
4607 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
4611 ExtVectorDecls.clear();
4614 void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
4615 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
4617 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
4621 DynamicClasses.clear();
4625 ASTReader::ReadLocallyScopedExternalDecls(SmallVectorImpl<NamedDecl *> &Decls) {
4626 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
4628 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
4632 LocallyScopedExternalDecls.clear();
4635 void ASTReader::ReadReferencedSelectors(
4636 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
4637 if (ReferencedSelectorsData.empty())
4640 // If there are @selector references added them to its pool. This is for
4641 // implementation of -Wselector.
4642 unsigned int DataSize = ReferencedSelectorsData.size()-1;
4644 while (I < DataSize) {
4645 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
4646 SourceLocation SelLoc
4647 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
4648 Sels.push_back(std::make_pair(Sel, SelLoc));
4650 ReferencedSelectorsData.clear();
4653 void ASTReader::ReadWeakUndeclaredIdentifiers(
4654 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
4655 if (WeakUndeclaredIdentifiers.empty())
4658 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
4659 IdentifierInfo *WeakId
4660 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
4661 IdentifierInfo *AliasId
4662 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
4664 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
4665 bool Used = WeakUndeclaredIdentifiers[I++];
4666 WeakInfo WI(AliasId, Loc);
4668 WeakIDs.push_back(std::make_pair(WeakId, WI));
4670 WeakUndeclaredIdentifiers.clear();
4673 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
4674 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
4675 ExternalVTableUse VT;
4676 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
4677 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
4678 VT.DefinitionRequired = VTableUses[Idx++];
4679 VTables.push_back(VT);
4685 void ASTReader::ReadPendingInstantiations(
4686 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
4687 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
4688 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
4690 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
4691 Pending.push_back(std::make_pair(D, Loc));
4693 PendingInstantiations.clear();
4696 void ASTReader::LoadSelector(Selector Sel) {
4697 // It would be complicated to avoid reading the methods anyway. So don't.
4698 ReadMethodPool(Sel);
4701 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
4702 assert(ID && "Non-zero identifier ID required");
4703 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
4704 IdentifiersLoaded[ID - 1] = II;
4705 if (DeserializationListener)
4706 DeserializationListener->IdentifierRead(ID, II);
4709 /// \brief Set the globally-visible declarations associated with the given
4712 /// If the AST reader is currently in a state where the given declaration IDs
4713 /// cannot safely be resolved, they are queued until it is safe to resolve
4716 /// \param II an IdentifierInfo that refers to one or more globally-visible
4719 /// \param DeclIDs the set of declaration IDs with the name @p II that are
4720 /// visible at global scope.
4722 /// \param Nonrecursive should be true to indicate that the caller knows that
4723 /// this call is non-recursive, and therefore the globally-visible declarations
4724 /// will not be placed onto the pending queue.
4726 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
4727 const SmallVectorImpl<uint32_t> &DeclIDs,
4728 bool Nonrecursive) {
4729 if (NumCurrentElementsDeserializing && !Nonrecursive) {
4730 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
4731 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
4733 PII.DeclIDs.append(DeclIDs.begin(), DeclIDs.end());
4737 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
4738 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
4740 if (SemaObj->TUScope) {
4741 // Introduce this declaration into the translation-unit scope
4742 // and add it to the declaration chain for this identifier, so
4743 // that (unqualified) name lookup will find it.
4744 SemaObj->TUScope->AddDecl(D);
4746 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
4748 // Queue this declaration so that it will be added to the
4749 // translation unit scope and identifier's declaration chain
4750 // once a Sema object is known.
4751 PreloadedDecls.push_back(D);
4756 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
4760 if (IdentifiersLoaded.empty()) {
4761 Error("no identifier table in AST file");
4766 if (!IdentifiersLoaded[ID]) {
4767 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
4768 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
4769 Module *M = I->second;
4770 unsigned Index = ID - M->BaseIdentifierID;
4771 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
4773 // All of the strings in the AST file are preceded by a 16-bit length.
4774 // Extract that 16-bit length to avoid having to execute strlen().
4775 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
4776 // unsigned integers. This is important to avoid integer overflow when
4777 // we cast them to 'unsigned'.
4778 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
4779 unsigned StrLen = (((unsigned) StrLenPtr[0])
4780 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
4781 IdentifiersLoaded[ID]
4782 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
4783 if (DeserializationListener)
4784 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
4787 return IdentifiersLoaded[ID];
4790 IdentifierInfo *ASTReader::getLocalIdentifier(Module &M, unsigned LocalID) {
4791 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
4794 IdentifierID ASTReader::getGlobalIdentifierID(Module &M, unsigned LocalID) {
4795 if (LocalID < NUM_PREDEF_IDENT_IDS)
4798 ContinuousRangeMap<uint32_t, int, 2>::iterator I
4799 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
4800 assert(I != M.IdentifierRemap.end()
4801 && "Invalid index into identifier index remap");
4803 return LocalID + I->second;
4806 bool ASTReader::ReadSLocEntry(int ID) {
4807 return ReadSLocEntryRecord(ID) != Success;
4810 Selector ASTReader::getLocalSelector(Module &M, unsigned LocalID) {
4811 return DecodeSelector(getGlobalSelectorID(M, LocalID));
4814 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
4818 if (ID > SelectorsLoaded.size()) {
4819 Error("selector ID out of range in AST file");
4823 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
4824 // Load this selector from the selector table.
4825 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
4826 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
4827 Module &M = *I->second;
4828 ASTSelectorLookupTrait Trait(*this, M);
4829 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
4830 SelectorsLoaded[ID - 1] =
4831 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
4832 if (DeserializationListener)
4833 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
4836 return SelectorsLoaded[ID - 1];
4839 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
4840 return DecodeSelector(ID);
4843 uint32_t ASTReader::GetNumExternalSelectors() {
4844 // ID 0 (the null selector) is considered an external selector.
4845 return getTotalNumSelectors() + 1;
4848 serialization::SelectorID
4849 ASTReader::getGlobalSelectorID(Module &M, unsigned LocalID) const {
4850 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
4853 ContinuousRangeMap<uint32_t, int, 2>::iterator I
4854 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
4855 assert(I != M.SelectorRemap.end()
4856 && "Invalid index into identifier index remap");
4858 return LocalID + I->second;
4862 ASTReader::ReadDeclarationName(Module &F,
4863 const RecordData &Record, unsigned &Idx) {
4864 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
4866 case DeclarationName::Identifier:
4867 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
4869 case DeclarationName::ObjCZeroArgSelector:
4870 case DeclarationName::ObjCOneArgSelector:
4871 case DeclarationName::ObjCMultiArgSelector:
4872 return DeclarationName(ReadSelector(F, Record, Idx));
4874 case DeclarationName::CXXConstructorName:
4875 return Context.DeclarationNames.getCXXConstructorName(
4876 Context.getCanonicalType(readType(F, Record, Idx)));
4878 case DeclarationName::CXXDestructorName:
4879 return Context.DeclarationNames.getCXXDestructorName(
4880 Context.getCanonicalType(readType(F, Record, Idx)));
4882 case DeclarationName::CXXConversionFunctionName:
4883 return Context.DeclarationNames.getCXXConversionFunctionName(
4884 Context.getCanonicalType(readType(F, Record, Idx)));
4886 case DeclarationName::CXXOperatorName:
4887 return Context.DeclarationNames.getCXXOperatorName(
4888 (OverloadedOperatorKind)Record[Idx++]);
4890 case DeclarationName::CXXLiteralOperatorName:
4891 return Context.DeclarationNames.getCXXLiteralOperatorName(
4892 GetIdentifierInfo(F, Record, Idx));
4894 case DeclarationName::CXXUsingDirective:
4895 return DeclarationName::getUsingDirectiveName();
4898 // Required to silence GCC warning
4899 return DeclarationName();
4902 void ASTReader::ReadDeclarationNameLoc(Module &F,
4903 DeclarationNameLoc &DNLoc,
4904 DeclarationName Name,
4905 const RecordData &Record, unsigned &Idx) {
4906 switch (Name.getNameKind()) {
4907 case DeclarationName::CXXConstructorName:
4908 case DeclarationName::CXXDestructorName:
4909 case DeclarationName::CXXConversionFunctionName:
4910 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
4913 case DeclarationName::CXXOperatorName:
4914 DNLoc.CXXOperatorName.BeginOpNameLoc
4915 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
4916 DNLoc.CXXOperatorName.EndOpNameLoc
4917 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
4920 case DeclarationName::CXXLiteralOperatorName:
4921 DNLoc.CXXLiteralOperatorName.OpNameLoc
4922 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
4925 case DeclarationName::Identifier:
4926 case DeclarationName::ObjCZeroArgSelector:
4927 case DeclarationName::ObjCOneArgSelector:
4928 case DeclarationName::ObjCMultiArgSelector:
4929 case DeclarationName::CXXUsingDirective:
4934 void ASTReader::ReadDeclarationNameInfo(Module &F,
4935 DeclarationNameInfo &NameInfo,
4936 const RecordData &Record, unsigned &Idx) {
4937 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
4938 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
4939 DeclarationNameLoc DNLoc;
4940 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
4941 NameInfo.setInfo(DNLoc);
4944 void ASTReader::ReadQualifierInfo(Module &F, QualifierInfo &Info,
4945 const RecordData &Record, unsigned &Idx) {
4946 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
4947 unsigned NumTPLists = Record[Idx++];
4948 Info.NumTemplParamLists = NumTPLists;
4950 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
4951 for (unsigned i=0; i != NumTPLists; ++i)
4952 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
4957 ASTReader::ReadTemplateName(Module &F, const RecordData &Record,
4959 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
4961 case TemplateName::Template:
4962 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
4964 case TemplateName::OverloadedTemplate: {
4965 unsigned size = Record[Idx++];
4966 UnresolvedSet<8> Decls;
4968 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
4970 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
4973 case TemplateName::QualifiedTemplate: {
4974 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
4975 bool hasTemplKeyword = Record[Idx++];
4976 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
4977 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
4980 case TemplateName::DependentTemplate: {
4981 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
4982 if (Record[Idx++]) // isIdentifier
4983 return Context.getDependentTemplateName(NNS,
4984 GetIdentifierInfo(F, Record,
4986 return Context.getDependentTemplateName(NNS,
4987 (OverloadedOperatorKind)Record[Idx++]);
4990 case TemplateName::SubstTemplateTemplateParm: {
4991 TemplateTemplateParmDecl *param
4992 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
4993 if (!param) return TemplateName();
4994 TemplateName replacement = ReadTemplateName(F, Record, Idx);
4995 return Context.getSubstTemplateTemplateParm(param, replacement);
4998 case TemplateName::SubstTemplateTemplateParmPack: {
4999 TemplateTemplateParmDecl *Param
5000 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
5002 return TemplateName();
5004 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
5005 if (ArgPack.getKind() != TemplateArgument::Pack)
5006 return TemplateName();
5008 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
5012 llvm_unreachable("Unhandled template name kind!");
5016 ASTReader::ReadTemplateArgument(Module &F,
5017 const RecordData &Record, unsigned &Idx) {
5018 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
5020 case TemplateArgument::Null:
5021 return TemplateArgument();
5022 case TemplateArgument::Type:
5023 return TemplateArgument(readType(F, Record, Idx));
5024 case TemplateArgument::Declaration:
5025 return TemplateArgument(ReadDecl(F, Record, Idx));
5026 case TemplateArgument::Integral: {
5027 llvm::APSInt Value = ReadAPSInt(Record, Idx);
5028 QualType T = readType(F, Record, Idx);
5029 return TemplateArgument(Value, T);
5031 case TemplateArgument::Template:
5032 return TemplateArgument(ReadTemplateName(F, Record, Idx));
5033 case TemplateArgument::TemplateExpansion: {
5034 TemplateName Name = ReadTemplateName(F, Record, Idx);
5035 llvm::Optional<unsigned> NumTemplateExpansions;
5036 if (unsigned NumExpansions = Record[Idx++])
5037 NumTemplateExpansions = NumExpansions - 1;
5038 return TemplateArgument(Name, NumTemplateExpansions);
5040 case TemplateArgument::Expression:
5041 return TemplateArgument(ReadExpr(F));
5042 case TemplateArgument::Pack: {
5043 unsigned NumArgs = Record[Idx++];
5044 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
5045 for (unsigned I = 0; I != NumArgs; ++I)
5046 Args[I] = ReadTemplateArgument(F, Record, Idx);
5047 return TemplateArgument(Args, NumArgs);
5051 llvm_unreachable("Unhandled template argument kind!");
5054 TemplateParameterList *
5055 ASTReader::ReadTemplateParameterList(Module &F,
5056 const RecordData &Record, unsigned &Idx) {
5057 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
5058 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
5059 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
5061 unsigned NumParams = Record[Idx++];
5062 SmallVector<NamedDecl *, 16> Params;
5063 Params.reserve(NumParams);
5065 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
5067 TemplateParameterList* TemplateParams =
5068 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
5069 Params.data(), Params.size(), RAngleLoc);
5070 return TemplateParams;
5075 ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
5076 Module &F, const RecordData &Record,
5078 unsigned NumTemplateArgs = Record[Idx++];
5079 TemplArgs.reserve(NumTemplateArgs);
5080 while (NumTemplateArgs--)
5081 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
5084 /// \brief Read a UnresolvedSet structure.
5085 void ASTReader::ReadUnresolvedSet(Module &F, UnresolvedSetImpl &Set,
5086 const RecordData &Record, unsigned &Idx) {
5087 unsigned NumDecls = Record[Idx++];
5088 while (NumDecls--) {
5089 NamedDecl *D = ReadDeclAs<NamedDecl>(F, Record, Idx);
5090 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
5096 ASTReader::ReadCXXBaseSpecifier(Module &F,
5097 const RecordData &Record, unsigned &Idx) {
5098 bool isVirtual = static_cast<bool>(Record[Idx++]);
5099 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
5100 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
5101 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
5102 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
5103 SourceRange Range = ReadSourceRange(F, Record, Idx);
5104 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
5105 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
5107 Result.setInheritConstructors(inheritConstructors);
5111 std::pair<CXXCtorInitializer **, unsigned>
5112 ASTReader::ReadCXXCtorInitializers(Module &F, const RecordData &Record,
5114 CXXCtorInitializer **CtorInitializers = 0;
5115 unsigned NumInitializers = Record[Idx++];
5116 if (NumInitializers) {
5118 = new (Context) CXXCtorInitializer*[NumInitializers];
5119 for (unsigned i=0; i != NumInitializers; ++i) {
5120 TypeSourceInfo *BaseClassInfo = 0;
5121 bool IsBaseVirtual = false;
5122 FieldDecl *Member = 0;
5123 IndirectFieldDecl *IndirectMember = 0;
5124 CXXConstructorDecl *Target = 0;
5126 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
5128 case CTOR_INITIALIZER_BASE:
5129 BaseClassInfo = GetTypeSourceInfo(F, Record, Idx);
5130 IsBaseVirtual = Record[Idx++];
5133 case CTOR_INITIALIZER_DELEGATING:
5134 Target = ReadDeclAs<CXXConstructorDecl>(F, Record, Idx);
5137 case CTOR_INITIALIZER_MEMBER:
5138 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
5141 case CTOR_INITIALIZER_INDIRECT_MEMBER:
5142 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
5146 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
5147 Expr *Init = ReadExpr(F);
5148 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
5149 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
5150 bool IsWritten = Record[Idx++];
5151 unsigned SourceOrderOrNumArrayIndices;
5152 SmallVector<VarDecl *, 8> Indices;
5154 SourceOrderOrNumArrayIndices = Record[Idx++];
5156 SourceOrderOrNumArrayIndices = Record[Idx++];
5157 Indices.reserve(SourceOrderOrNumArrayIndices);
5158 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
5159 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
5162 CXXCtorInitializer *BOMInit;
5163 if (Type == CTOR_INITIALIZER_BASE) {
5164 BOMInit = new (Context) CXXCtorInitializer(Context, BaseClassInfo, IsBaseVirtual,
5165 LParenLoc, Init, RParenLoc,
5166 MemberOrEllipsisLoc);
5167 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
5168 BOMInit = new (Context) CXXCtorInitializer(Context, MemberOrEllipsisLoc, LParenLoc,
5169 Target, Init, RParenLoc);
5170 } else if (IsWritten) {
5172 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
5173 LParenLoc, Init, RParenLoc);
5175 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
5176 MemberOrEllipsisLoc, LParenLoc,
5179 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
5180 LParenLoc, Init, RParenLoc,
5181 Indices.data(), Indices.size());
5185 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
5186 CtorInitializers[i] = BOMInit;
5190 return std::make_pair(CtorInitializers, NumInitializers);
5193 NestedNameSpecifier *
5194 ASTReader::ReadNestedNameSpecifier(Module &F,
5195 const RecordData &Record, unsigned &Idx) {
5196 unsigned N = Record[Idx++];
5197 NestedNameSpecifier *NNS = 0, *Prev = 0;
5198 for (unsigned I = 0; I != N; ++I) {
5199 NestedNameSpecifier::SpecifierKind Kind
5200 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
5202 case NestedNameSpecifier::Identifier: {
5203 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
5204 NNS = NestedNameSpecifier::Create(Context, Prev, II);
5208 case NestedNameSpecifier::Namespace: {
5209 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
5210 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
5214 case NestedNameSpecifier::NamespaceAlias: {
5215 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
5216 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
5220 case NestedNameSpecifier::TypeSpec:
5221 case NestedNameSpecifier::TypeSpecWithTemplate: {
5222 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
5226 bool Template = Record[Idx++];
5227 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
5231 case NestedNameSpecifier::Global: {
5232 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
5233 // No associated value, and there can't be a prefix.
5242 NestedNameSpecifierLoc
5243 ASTReader::ReadNestedNameSpecifierLoc(Module &F, const RecordData &Record,
5245 unsigned N = Record[Idx++];
5246 NestedNameSpecifierLocBuilder Builder;
5247 for (unsigned I = 0; I != N; ++I) {
5248 NestedNameSpecifier::SpecifierKind Kind
5249 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
5251 case NestedNameSpecifier::Identifier: {
5252 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
5253 SourceRange Range = ReadSourceRange(F, Record, Idx);
5254 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
5258 case NestedNameSpecifier::Namespace: {
5259 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
5260 SourceRange Range = ReadSourceRange(F, Record, Idx);
5261 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
5265 case NestedNameSpecifier::NamespaceAlias: {
5266 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
5267 SourceRange Range = ReadSourceRange(F, Record, Idx);
5268 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
5272 case NestedNameSpecifier::TypeSpec:
5273 case NestedNameSpecifier::TypeSpecWithTemplate: {
5274 bool Template = Record[Idx++];
5275 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
5277 return NestedNameSpecifierLoc();
5278 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
5280 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
5281 Builder.Extend(Context,
5282 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
5283 T->getTypeLoc(), ColonColonLoc);
5287 case NestedNameSpecifier::Global: {
5288 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
5289 Builder.MakeGlobal(Context, ColonColonLoc);
5295 return Builder.getWithLocInContext(Context);
5299 ASTReader::ReadSourceRange(Module &F, const RecordData &Record,
5301 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
5302 SourceLocation end = ReadSourceLocation(F, Record, Idx);
5303 return SourceRange(beg, end);
5306 /// \brief Read an integral value
5307 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
5308 unsigned BitWidth = Record[Idx++];
5309 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
5310 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
5315 /// \brief Read a signed integral value
5316 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
5317 bool isUnsigned = Record[Idx++];
5318 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
5321 /// \brief Read a floating-point value
5322 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
5323 return llvm::APFloat(ReadAPInt(Record, Idx));
5326 // \brief Read a string
5327 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
5328 unsigned Len = Record[Idx++];
5329 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
5334 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
5336 unsigned Major = Record[Idx++];
5337 unsigned Minor = Record[Idx++];
5338 unsigned Subminor = Record[Idx++];
5340 return VersionTuple(Major);
5342 return VersionTuple(Major, Minor - 1);
5343 return VersionTuple(Major, Minor - 1, Subminor - 1);
5346 CXXTemporary *ASTReader::ReadCXXTemporary(Module &F,
5347 const RecordData &Record,
5349 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
5350 return CXXTemporary::Create(Context, Decl);
5353 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
5354 return Diag(SourceLocation(), DiagID);
5357 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
5358 return Diags.Report(Loc, DiagID);
5361 /// \brief Retrieve the identifier table associated with the
5363 IdentifierTable &ASTReader::getIdentifierTable() {
5364 return PP.getIdentifierTable();
5367 /// \brief Record that the given ID maps to the given switch-case
5369 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
5370 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
5371 SwitchCaseStmts[ID] = SC;
5374 /// \brief Retrieve the switch-case statement with the given ID.
5375 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
5376 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
5377 return SwitchCaseStmts[ID];
5380 void ASTReader::ClearSwitchCaseIDs() {
5381 SwitchCaseStmts.clear();
5384 void ASTReader::FinishedDeserializing() {
5385 assert(NumCurrentElementsDeserializing &&
5386 "FinishedDeserializing not paired with StartedDeserializing");
5387 if (NumCurrentElementsDeserializing == 1) {
5388 // If any identifiers with corresponding top-level declarations have
5389 // been loaded, load those declarations now.
5390 while (!PendingIdentifierInfos.empty()) {
5391 SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
5392 PendingIdentifierInfos.front().DeclIDs, true);
5393 PendingIdentifierInfos.pop_front();
5396 // Ready to load previous declarations of Decls that were delayed.
5397 while (!PendingPreviousDecls.empty()) {
5398 loadAndAttachPreviousDecl(PendingPreviousDecls.front().first,
5399 PendingPreviousDecls.front().second);
5400 PendingPreviousDecls.pop_front();
5403 // We are not in recursive loading, so it's safe to pass the "interesting"
5404 // decls to the consumer.
5406 PassInterestingDeclsToConsumer();
5408 assert(PendingForwardRefs.size() == 0 &&
5409 "Some forward refs did not get linked to the definition!");
5411 --NumCurrentElementsDeserializing;
5414 ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
5415 StringRef isysroot, bool DisableValidation,
5416 bool DisableStatCache)
5417 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
5418 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
5419 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
5420 Consumer(0), ModuleMgr(FileMgr.getFileSystemOptions()),
5421 RelocatablePCH(false), isysroot(isysroot),
5422 DisableValidation(DisableValidation),
5423 DisableStatCache(DisableStatCache), NumStatHits(0), NumStatMisses(0),
5424 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
5425 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
5426 TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
5427 NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0),
5428 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
5429 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
5430 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
5431 NumCXXBaseSpecifiersLoaded(0)
5433 SourceMgr.setExternalSLocEntrySource(this);
5436 ASTReader::~ASTReader() {
5437 for (DeclContextVisibleUpdatesPending::iterator
5438 I = PendingVisibleUpdates.begin(),
5439 E = PendingVisibleUpdates.end();
5441 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
5442 F = I->second.end();
5444 delete static_cast<ASTDeclContextNameLookupTable*>(J->first);