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 "clang/Serialization/SerializationDiagnostic.h"
18 #include "ASTCommon.h"
19 #include "ASTReaderInternals.h"
20 #include "clang/Sema/Sema.h"
21 #include "clang/Sema/Scope.h"
22 #include "clang/AST/ASTConsumer.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/NestedNameSpecifier.h"
28 #include "clang/AST/Type.h"
29 #include "clang/AST/TypeLocVisitor.h"
30 #include "clang/Lex/MacroInfo.h"
31 #include "clang/Lex/PreprocessingRecord.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Lex/PreprocessorOptions.h"
34 #include "clang/Lex/HeaderSearch.h"
35 #include "clang/Lex/HeaderSearchOptions.h"
36 #include "clang/Basic/OnDiskHashTable.h"
37 #include "clang/Basic/SourceManager.h"
38 #include "clang/Basic/SourceManagerInternals.h"
39 #include "clang/Basic/FileManager.h"
40 #include "clang/Basic/FileSystemStatCache.h"
41 #include "clang/Basic/TargetInfo.h"
42 #include "clang/Basic/TargetOptions.h"
43 #include "clang/Basic/Version.h"
44 #include "clang/Basic/VersionTuple.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/Bitcode/BitstreamReader.h"
47 #include "llvm/Support/MemoryBuffer.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/FileSystem.h"
50 #include "llvm/Support/Path.h"
51 #include "llvm/Support/SaveAndRestore.h"
52 #include "llvm/Support/system_error.h"
58 using namespace clang;
59 using namespace clang::serialization;
60 using namespace clang::serialization::reader;
62 //===----------------------------------------------------------------------===//
63 // PCH validator implementation
64 //===----------------------------------------------------------------------===//
66 ASTReaderListener::~ASTReaderListener() {}
68 /// \brief Compare the given set of language options against an existing set of
71 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
73 /// \returns true if the languagae options mis-match, false otherwise.
74 static bool checkLanguageOptions(const LangOptions &LangOpts,
75 const LangOptions &ExistingLangOpts,
76 DiagnosticsEngine *Diags) {
77 #define LANGOPT(Name, Bits, Default, Description) \
78 if (ExistingLangOpts.Name != LangOpts.Name) { \
80 Diags->Report(diag::err_pch_langopt_mismatch) \
81 << Description << LangOpts.Name << ExistingLangOpts.Name; \
85 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
86 if (ExistingLangOpts.Name != LangOpts.Name) { \
88 Diags->Report(diag::err_pch_langopt_value_mismatch) \
93 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
94 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
96 Diags->Report(diag::err_pch_langopt_value_mismatch) \
101 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
102 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
103 #include "clang/Basic/LangOptions.def"
105 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
107 Diags->Report(diag::err_pch_langopt_value_mismatch)
108 << "target Objective-C runtime";
115 /// \brief Compare the given set of target options against an existing set of
118 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
120 /// \returns true if the target options mis-match, false otherwise.
121 static bool checkTargetOptions(const TargetOptions &TargetOpts,
122 const TargetOptions &ExistingTargetOpts,
123 DiagnosticsEngine *Diags) {
124 #define CHECK_TARGET_OPT(Field, Name) \
125 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
127 Diags->Report(diag::err_pch_targetopt_mismatch) \
128 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
132 CHECK_TARGET_OPT(Triple, "target");
133 CHECK_TARGET_OPT(CPU, "target CPU");
134 CHECK_TARGET_OPT(ABI, "target ABI");
135 CHECK_TARGET_OPT(CXXABI, "target C++ ABI");
136 CHECK_TARGET_OPT(LinkerVersion, "target linker version");
137 #undef CHECK_TARGET_OPT
139 // Compare feature sets.
140 SmallVector<StringRef, 4> ExistingFeatures(
141 ExistingTargetOpts.FeaturesAsWritten.begin(),
142 ExistingTargetOpts.FeaturesAsWritten.end());
143 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
144 TargetOpts.FeaturesAsWritten.end());
145 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
146 std::sort(ReadFeatures.begin(), ReadFeatures.end());
148 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
149 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
150 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
151 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
157 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
159 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
160 << false << ReadFeatures[ReadIdx];
165 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
166 << true << ExistingFeatures[ExistingIdx];
170 if (ExistingIdx < ExistingN) {
172 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
173 << true << ExistingFeatures[ExistingIdx];
177 if (ReadIdx < ReadN) {
179 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
180 << false << ReadFeatures[ReadIdx];
188 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
190 const LangOptions &ExistingLangOpts = PP.getLangOpts();
191 return checkLanguageOptions(LangOpts, ExistingLangOpts,
192 Complain? &Reader.Diags : 0);
195 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
197 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
198 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
199 Complain? &Reader.Diags : 0);
203 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
207 /// \brief Collect the macro definitions provided by the given preprocessor
209 static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
210 MacroDefinitionsMap &Macros,
211 SmallVectorImpl<StringRef> *MacroNames = 0){
212 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
213 StringRef Macro = PPOpts.Macros[I].first;
214 bool IsUndef = PPOpts.Macros[I].second;
216 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
217 StringRef MacroName = MacroPair.first;
218 StringRef MacroBody = MacroPair.second;
220 // For an #undef'd macro, we only care about the name.
222 if (MacroNames && !Macros.count(MacroName))
223 MacroNames->push_back(MacroName);
225 Macros[MacroName] = std::make_pair("", true);
229 // For a #define'd macro, figure out the actual definition.
230 if (MacroName.size() == Macro.size())
233 // Note: GCC drops anything following an end-of-line character.
234 StringRef::size_type End = MacroBody.find_first_of("\n\r");
235 MacroBody = MacroBody.substr(0, End);
238 if (MacroNames && !Macros.count(MacroName))
239 MacroNames->push_back(MacroName);
240 Macros[MacroName] = std::make_pair(MacroBody, false);
244 /// \brief Check the preprocessor options deserialized from the control block
245 /// against the preprocessor options in an existing preprocessor.
247 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
248 static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
249 const PreprocessorOptions &ExistingPPOpts,
250 DiagnosticsEngine *Diags,
251 FileManager &FileMgr,
252 std::string &SuggestedPredefines) {
253 // Check macro definitions.
254 MacroDefinitionsMap ASTFileMacros;
255 collectMacroDefinitions(PPOpts, ASTFileMacros);
256 MacroDefinitionsMap ExistingMacros;
257 SmallVector<StringRef, 4> ExistingMacroNames;
258 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
260 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
261 // Dig out the macro definition in the existing preprocessor options.
262 StringRef MacroName = ExistingMacroNames[I];
263 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
265 // Check whether we know anything about this macro name or not.
266 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
267 = ASTFileMacros.find(MacroName);
268 if (Known == ASTFileMacros.end()) {
269 // FIXME: Check whether this identifier was referenced anywhere in the
270 // AST file. If so, we should reject the AST file. Unfortunately, this
271 // information isn't in the control block. What shall we do about it?
273 if (Existing.second) {
274 SuggestedPredefines += "#undef ";
275 SuggestedPredefines += MacroName.str();
276 SuggestedPredefines += '\n';
278 SuggestedPredefines += "#define ";
279 SuggestedPredefines += MacroName.str();
280 SuggestedPredefines += ' ';
281 SuggestedPredefines += Existing.first.str();
282 SuggestedPredefines += '\n';
287 // If the macro was defined in one but undef'd in the other, we have a
289 if (Existing.second != Known->second.second) {
291 Diags->Report(diag::err_pch_macro_def_undef)
292 << MacroName << Known->second.second;
297 // If the macro was #undef'd in both, or if the macro bodies are identical,
299 if (Existing.second || Existing.first == Known->second.first)
302 // The macro bodies differ; complain.
304 Diags->Report(diag::err_pch_macro_def_conflict)
305 << MacroName << Known->second.first << Existing.first;
310 // Check whether we're using predefines.
311 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
313 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
318 // Compute the #include and #include_macros lines we need.
319 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
320 StringRef File = ExistingPPOpts.Includes[I];
321 if (File == ExistingPPOpts.ImplicitPCHInclude)
324 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
325 != PPOpts.Includes.end())
328 SuggestedPredefines += "#include \"";
329 SuggestedPredefines +=
330 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
331 SuggestedPredefines += "\"\n";
334 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
335 StringRef File = ExistingPPOpts.MacroIncludes[I];
336 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
338 != PPOpts.MacroIncludes.end())
341 SuggestedPredefines += "#__include_macros \"";
342 SuggestedPredefines +=
343 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
344 SuggestedPredefines += "\"\n##\n";
350 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
352 std::string &SuggestedPredefines) {
353 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
355 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
356 Complain? &Reader.Diags : 0,
358 SuggestedPredefines);
361 void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
363 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
367 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
368 PP.setCounterValue(Value);
371 //===----------------------------------------------------------------------===//
372 // AST reader implementation
373 //===----------------------------------------------------------------------===//
376 ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
377 DeserializationListener = Listener;
382 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
383 return serialization::ComputeHash(Sel);
387 std::pair<unsigned, unsigned>
388 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
389 using namespace clang::io;
390 unsigned KeyLen = ReadUnalignedLE16(d);
391 unsigned DataLen = ReadUnalignedLE16(d);
392 return std::make_pair(KeyLen, DataLen);
395 ASTSelectorLookupTrait::internal_key_type
396 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
397 using namespace clang::io;
398 SelectorTable &SelTable = Reader.getContext().Selectors;
399 unsigned N = ReadUnalignedLE16(d);
400 IdentifierInfo *FirstII
401 = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
403 return SelTable.getNullarySelector(FirstII);
405 return SelTable.getUnarySelector(FirstII);
407 SmallVector<IdentifierInfo *, 16> Args;
408 Args.push_back(FirstII);
409 for (unsigned I = 1; I != N; ++I)
410 Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
412 return SelTable.getSelector(N, Args.data());
415 ASTSelectorLookupTrait::data_type
416 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
418 using namespace clang::io;
422 Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
423 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
424 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
426 // Load instance methods
427 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
428 if (ObjCMethodDecl *Method
429 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
430 Result.Instance.push_back(Method);
433 // Load factory methods
434 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
435 if (ObjCMethodDecl *Method
436 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
437 Result.Factory.push_back(Method);
443 unsigned ASTIdentifierLookupTrait::ComputeHash(const internal_key_type& a) {
444 return llvm::HashString(StringRef(a.first, a.second));
447 std::pair<unsigned, unsigned>
448 ASTIdentifierLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
449 using namespace clang::io;
450 unsigned DataLen = ReadUnalignedLE16(d);
451 unsigned KeyLen = ReadUnalignedLE16(d);
452 return std::make_pair(KeyLen, DataLen);
455 std::pair<const char*, unsigned>
456 ASTIdentifierLookupTrait::ReadKey(const unsigned char* d, unsigned n) {
457 assert(n >= 2 && d[n-1] == '\0');
458 return std::make_pair((const char*) d, n-1);
461 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
462 const unsigned char* d,
464 using namespace clang::io;
465 unsigned RawID = ReadUnalignedLE32(d);
466 bool IsInteresting = RawID & 0x01;
468 // Wipe out the "is interesting" bit.
471 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
472 if (!IsInteresting) {
473 // For uninteresting identifiers, just build the IdentifierInfo
474 // and associate it with the persistent ID.
475 IdentifierInfo *II = KnownII;
477 II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
480 Reader.SetIdentifierInfo(ID, II);
482 Reader.markIdentifierUpToDate(II);
486 unsigned ObjCOrBuiltinID = ReadUnalignedLE16(d);
487 unsigned Bits = ReadUnalignedLE16(d);
488 bool CPlusPlusOperatorKeyword = Bits & 0x01;
490 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
492 bool Poisoned = Bits & 0x01;
494 bool ExtensionToken = Bits & 0x01;
496 bool hadMacroDefinition = Bits & 0x01;
499 assert(Bits == 0 && "Extra bits in the identifier?");
502 // Build the IdentifierInfo itself and link the identifier ID with
503 // the new IdentifierInfo.
504 IdentifierInfo *II = KnownII;
506 II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
509 Reader.markIdentifierUpToDate(II);
512 // Set or check the various bits in the IdentifierInfo structure.
513 // Token IDs are read-only.
514 if (HasRevertedTokenIDToIdentifier)
515 II->RevertTokenIDToIdentifier();
516 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
517 assert(II->isExtensionToken() == ExtensionToken &&
518 "Incorrect extension token flag");
519 (void)ExtensionToken;
521 II->setIsPoisoned(true);
522 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
523 "Incorrect C++ operator keyword flag");
524 (void)CPlusPlusOperatorKeyword;
526 // If this identifier is a macro, deserialize the macro
528 if (hadMacroDefinition) {
529 SmallVector<MacroID, 4> MacroIDs;
530 while (uint32_t LocalID = ReadUnalignedLE32(d)) {
531 MacroIDs.push_back(Reader.getGlobalMacroID(F, LocalID));
535 Reader.setIdentifierIsMacro(II, MacroIDs);
538 Reader.SetIdentifierInfo(ID, II);
540 // Read all of the declarations visible at global scope with this
543 SmallVector<uint32_t, 4> DeclIDs;
544 for (; DataLen > 0; DataLen -= 4)
545 DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
546 Reader.SetGloballyVisibleDecls(II, DeclIDs);
553 ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
554 llvm::FoldingSetNodeID ID;
555 ID.AddInteger(Key.Kind);
558 case DeclarationName::Identifier:
559 case DeclarationName::CXXLiteralOperatorName:
560 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
562 case DeclarationName::ObjCZeroArgSelector:
563 case DeclarationName::ObjCOneArgSelector:
564 case DeclarationName::ObjCMultiArgSelector:
565 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
567 case DeclarationName::CXXOperatorName:
568 ID.AddInteger((OverloadedOperatorKind)Key.Data);
570 case DeclarationName::CXXConstructorName:
571 case DeclarationName::CXXDestructorName:
572 case DeclarationName::CXXConversionFunctionName:
573 case DeclarationName::CXXUsingDirective:
577 return ID.ComputeHash();
580 ASTDeclContextNameLookupTrait::internal_key_type
581 ASTDeclContextNameLookupTrait::GetInternalKey(
582 const external_key_type& Name) const {
584 Key.Kind = Name.getNameKind();
585 switch (Name.getNameKind()) {
586 case DeclarationName::Identifier:
587 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
589 case DeclarationName::ObjCZeroArgSelector:
590 case DeclarationName::ObjCOneArgSelector:
591 case DeclarationName::ObjCMultiArgSelector:
592 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
594 case DeclarationName::CXXOperatorName:
595 Key.Data = Name.getCXXOverloadedOperator();
597 case DeclarationName::CXXLiteralOperatorName:
598 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
600 case DeclarationName::CXXConstructorName:
601 case DeclarationName::CXXDestructorName:
602 case DeclarationName::CXXConversionFunctionName:
603 case DeclarationName::CXXUsingDirective:
611 std::pair<unsigned, unsigned>
612 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
613 using namespace clang::io;
614 unsigned KeyLen = ReadUnalignedLE16(d);
615 unsigned DataLen = ReadUnalignedLE16(d);
616 return std::make_pair(KeyLen, DataLen);
619 ASTDeclContextNameLookupTrait::internal_key_type
620 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
621 using namespace clang::io;
624 Key.Kind = (DeclarationName::NameKind)*d++;
626 case DeclarationName::Identifier:
627 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
629 case DeclarationName::ObjCZeroArgSelector:
630 case DeclarationName::ObjCOneArgSelector:
631 case DeclarationName::ObjCMultiArgSelector:
633 (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
636 case DeclarationName::CXXOperatorName:
637 Key.Data = *d++; // OverloadedOperatorKind
639 case DeclarationName::CXXLiteralOperatorName:
640 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
642 case DeclarationName::CXXConstructorName:
643 case DeclarationName::CXXDestructorName:
644 case DeclarationName::CXXConversionFunctionName:
645 case DeclarationName::CXXUsingDirective:
653 ASTDeclContextNameLookupTrait::data_type
654 ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
655 const unsigned char* d,
657 using namespace clang::io;
658 unsigned NumDecls = ReadUnalignedLE16(d);
659 LE32DeclID *Start = (LE32DeclID *)d;
660 return std::make_pair(Start, Start + NumDecls);
663 bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
664 llvm::BitstreamCursor &Cursor,
665 const std::pair<uint64_t, uint64_t> &Offsets,
666 DeclContextInfo &Info) {
667 SavedStreamPosition SavedPosition(Cursor);
668 // First the lexical decls.
669 if (Offsets.first != 0) {
670 Cursor.JumpToBit(Offsets.first);
675 unsigned Code = Cursor.ReadCode();
676 unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
677 if (RecCode != DECL_CONTEXT_LEXICAL) {
678 Error("Expected lexical block");
682 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob);
683 Info.NumLexicalDecls = BlobLen / sizeof(KindDeclIDPair);
686 // Now the lookup table.
687 if (Offsets.second != 0) {
688 Cursor.JumpToBit(Offsets.second);
693 unsigned Code = Cursor.ReadCode();
694 unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
695 if (RecCode != DECL_CONTEXT_VISIBLE) {
696 Error("Expected visible lookup table block");
699 Info.NameLookupTableData
700 = ASTDeclContextNameLookupTable::Create(
701 (const unsigned char *)Blob + Record[0],
702 (const unsigned char *)Blob,
703 ASTDeclContextNameLookupTrait(*this, M));
709 void ASTReader::Error(StringRef Msg) {
710 Error(diag::err_fe_pch_malformed, Msg);
713 void ASTReader::Error(unsigned DiagID,
714 StringRef Arg1, StringRef Arg2) {
715 if (Diags.isDiagnosticInFlight())
716 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
718 Diag(DiagID) << Arg1 << Arg2;
721 //===----------------------------------------------------------------------===//
722 // Source Manager Deserialization
723 //===----------------------------------------------------------------------===//
725 /// \brief Read the line table in the source manager block.
726 /// \returns true if there was an error.
727 bool ASTReader::ParseLineTable(ModuleFile &F,
728 SmallVectorImpl<uint64_t> &Record) {
730 LineTableInfo &LineTable = SourceMgr.getLineTable();
732 // Parse the file names
733 std::map<int, int> FileIDs;
734 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
735 // Extract the file name
736 unsigned FilenameLen = Record[Idx++];
737 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
739 MaybeAddSystemRootToFilename(F, Filename);
740 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
743 // Parse the line entries
744 std::vector<LineEntry> Entries;
745 while (Idx < Record.size()) {
746 int FID = Record[Idx++];
747 assert(FID >= 0 && "Serialized line entries for non-local file.");
748 // Remap FileID from 1-based old view.
749 FID += F.SLocEntryBaseID - 1;
751 // Extract the line entries
752 unsigned NumEntries = Record[Idx++];
753 assert(NumEntries && "Numentries is 00000");
755 Entries.reserve(NumEntries);
756 for (unsigned I = 0; I != NumEntries; ++I) {
757 unsigned FileOffset = Record[Idx++];
758 unsigned LineNo = Record[Idx++];
759 int FilenameID = FileIDs[Record[Idx++]];
760 SrcMgr::CharacteristicKind FileKind
761 = (SrcMgr::CharacteristicKind)Record[Idx++];
762 unsigned IncludeOffset = Record[Idx++];
763 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
764 FileKind, IncludeOffset));
766 LineTable.AddEntry(FileID::get(FID), Entries);
772 /// \brief Read a source manager block
773 bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
774 using namespace SrcMgr;
776 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
778 // Set the source-location entry cursor to the current position in
779 // the stream. This cursor will be used to read the contents of the
780 // source manager block initially, and then lazily read
781 // source-location entries as needed.
782 SLocEntryCursor = F.Stream;
784 // The stream itself is going to skip over the source manager block.
785 if (F.Stream.SkipBlock()) {
786 Error("malformed block record in AST file");
790 // Enter the source manager block.
791 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
792 Error("malformed source manager block record in AST file");
798 unsigned Code = SLocEntryCursor.ReadCode();
799 if (Code == llvm::bitc::END_BLOCK) {
800 if (SLocEntryCursor.ReadBlockEnd()) {
801 Error("error at end of Source Manager block in AST file");
807 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
808 // No known subblocks, always skip them.
809 SLocEntryCursor.ReadSubBlockID();
810 if (SLocEntryCursor.SkipBlock()) {
811 Error("malformed block record in AST file");
817 if (Code == llvm::bitc::DEFINE_ABBREV) {
818 SLocEntryCursor.ReadAbbrevRecord();
823 const char *BlobStart;
826 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
827 default: // Default behavior: ignore.
830 case SM_SLOC_FILE_ENTRY:
831 case SM_SLOC_BUFFER_ENTRY:
832 case SM_SLOC_EXPANSION_ENTRY:
833 // Once we hit one of the source location entries, we're done.
839 /// \brief If a header file is not found at the path that we expect it to be
840 /// and the PCH file was moved from its original location, try to resolve the
841 /// file by assuming that header+PCH were moved together and the header is in
842 /// the same place relative to the PCH.
844 resolveFileRelativeToOriginalDir(const std::string &Filename,
845 const std::string &OriginalDir,
846 const std::string &CurrDir) {
847 assert(OriginalDir != CurrDir &&
848 "No point trying to resolve the file if the PCH dir didn't change");
849 using namespace llvm::sys;
850 SmallString<128> filePath(Filename);
851 fs::make_absolute(filePath);
852 assert(path::is_absolute(OriginalDir));
853 SmallString<128> currPCHPath(CurrDir);
855 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
856 fileDirE = path::end(path::parent_path(filePath));
857 path::const_iterator origDirI = path::begin(OriginalDir),
858 origDirE = path::end(OriginalDir);
859 // Skip the common path components from filePath and OriginalDir.
860 while (fileDirI != fileDirE && origDirI != origDirE &&
861 *fileDirI == *origDirI) {
865 for (; origDirI != origDirE; ++origDirI)
866 path::append(currPCHPath, "..");
867 path::append(currPCHPath, fileDirI, fileDirE);
868 path::append(currPCHPath, path::filename(Filename));
869 return currPCHPath.str();
872 bool ASTReader::ReadSLocEntry(int ID) {
876 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
877 Error("source location entry ID out-of-range for AST file");
881 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
882 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
883 llvm::BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
884 unsigned BaseOffset = F->SLocEntryBaseOffset;
886 ++NumSLocEntriesRead;
887 unsigned Code = SLocEntryCursor.ReadCode();
888 if (Code == llvm::bitc::END_BLOCK ||
889 Code == llvm::bitc::ENTER_SUBBLOCK ||
890 Code == llvm::bitc::DEFINE_ABBREV) {
891 Error("incorrectly-formatted source location entry in AST file");
896 const char *BlobStart;
898 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
900 Error("incorrectly-formatted source location entry in AST file");
903 case SM_SLOC_FILE_ENTRY: {
904 // We will detect whether a file changed and return 'Failure' for it, but
905 // we will also try to fail gracefully by setting up the SLocEntry.
906 unsigned InputID = Record[4];
907 InputFile IF = getInputFile(*F, InputID);
908 const FileEntry *File = IF.getPointer();
909 bool OverriddenBuffer = IF.getInt();
911 if (!IF.getPointer())
914 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
915 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
916 // This is the module's main file.
917 IncludeLoc = getImportLocation(F);
919 SrcMgr::CharacteristicKind
920 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
921 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
922 ID, BaseOffset + Record[0]);
923 SrcMgr::FileInfo &FileInfo =
924 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
925 FileInfo.NumCreatedFIDs = Record[5];
927 FileInfo.setHasLineDirectives();
929 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
930 unsigned NumFileDecls = Record[7];
932 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
933 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
937 const SrcMgr::ContentCache *ContentCache
938 = SourceMgr.getOrCreateContentCache(File,
939 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
940 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
941 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
942 unsigned Code = SLocEntryCursor.ReadCode();
945 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
947 if (RecCode != SM_SLOC_BUFFER_BLOB) {
948 Error("AST record has invalid code");
952 llvm::MemoryBuffer *Buffer
953 = llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - 1),
955 SourceMgr.overrideFileContents(File, Buffer);
961 case SM_SLOC_BUFFER_ENTRY: {
962 const char *Name = BlobStart;
963 unsigned Offset = Record[0];
964 SrcMgr::CharacteristicKind
965 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
966 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
967 unsigned Code = SLocEntryCursor.ReadCode();
970 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
972 if (RecCode != SM_SLOC_BUFFER_BLOB) {
973 Error("AST record has invalid code");
977 llvm::MemoryBuffer *Buffer
978 = llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - 1),
980 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
981 BaseOffset + Offset, IncludeLoc);
985 case SM_SLOC_EXPANSION_ENTRY: {
986 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
987 SourceMgr.createExpansionLoc(SpellingLoc,
988 ReadSourceLocation(*F, Record[2]),
989 ReadSourceLocation(*F, Record[3]),
992 BaseOffset + Record[0]);
1000 /// \brief Find the location where the module F is imported.
1001 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1002 if (F->ImportLoc.isValid())
1003 return F->ImportLoc;
1005 // Otherwise we have a PCH. It's considered to be "imported" at the first
1006 // location of its includer.
1007 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1008 // Main file is the importer. We assume that it is the first entry in the
1009 // entry table. We can't ask the manager, because at the time of PCH loading
1010 // the main file entry doesn't exist yet.
1011 // The very first entry is the invalid instantiation loc, which takes up
1013 return SourceLocation::getFromRawEncoding(2U);
1015 //return F->Loaders[0]->FirstLoc;
1016 return F->ImportedBy[0]->FirstLoc;
1019 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1020 /// specified cursor. Read the abbreviations that are at the top of the block
1021 /// and then leave the cursor pointing into the block.
1022 bool ASTReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1024 if (Cursor.EnterSubBlock(BlockID)) {
1025 Error("malformed block record in AST file");
1030 uint64_t Offset = Cursor.GetCurrentBitNo();
1031 unsigned Code = Cursor.ReadCode();
1033 // We expect all abbrevs to be at the start of the block.
1034 if (Code != llvm::bitc::DEFINE_ABBREV) {
1035 Cursor.JumpToBit(Offset);
1038 Cursor.ReadAbbrevRecord();
1042 void ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset,
1044 llvm::BitstreamCursor &Stream = F.MacroCursor;
1046 // Keep track of where we are in the stream, then jump back there
1047 // after reading this macro.
1048 SavedStreamPosition SavedPosition(Stream);
1050 Stream.JumpToBit(Offset);
1052 SmallVector<IdentifierInfo*, 16> MacroArgs;
1053 MacroInfo *Macro = 0;
1055 // RAII object to add the loaded macro information once we're done
1057 struct AddLoadedMacroInfoRAII {
1063 AddLoadedMacroInfoRAII(Preprocessor &PP, MacroInfo *Hint)
1064 : PP(PP), Hint(Hint), MI(), II() { }
1065 ~AddLoadedMacroInfoRAII( ) {
1067 // Finally, install the macro.
1068 PP.addLoadedMacroInfo(II, MI, Hint);
1071 } AddLoadedMacroInfo(PP, Hint);
1074 unsigned Code = Stream.ReadCode();
1076 case llvm::bitc::END_BLOCK:
1079 case llvm::bitc::ENTER_SUBBLOCK:
1080 // No known subblocks, always skip them.
1081 Stream.ReadSubBlockID();
1082 if (Stream.SkipBlock()) {
1083 Error("malformed block record in AST file");
1088 case llvm::bitc::DEFINE_ABBREV:
1089 Stream.ReadAbbrevRecord();
1095 const char *BlobStart = 0;
1096 unsigned BlobLen = 0;
1098 PreprocessorRecordTypes RecType =
1099 (PreprocessorRecordTypes)Stream.ReadRecord(Code, Record, BlobStart,
1102 case PP_MACRO_OBJECT_LIKE:
1103 case PP_MACRO_FUNCTION_LIKE: {
1104 // If we already have a macro, that means that we've hit the end
1105 // of the definition of the macro we were looking for. We're
1110 IdentifierInfo *II = getLocalIdentifier(F, Record[0]);
1112 Error("macro must have a name in AST file");
1116 unsigned GlobalID = getGlobalMacroID(F, Record[1]);
1118 // If this macro has already been loaded, don't do so again.
1119 if (MacrosLoaded[GlobalID - NUM_PREDEF_MACRO_IDS])
1122 SubmoduleID GlobalSubmoduleID = getGlobalSubmoduleID(F, Record[2]);
1123 unsigned NextIndex = 3;
1124 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1125 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1127 // Record this macro.
1128 MacrosLoaded[GlobalID - NUM_PREDEF_MACRO_IDS] = MI;
1130 SourceLocation UndefLoc = ReadSourceLocation(F, Record, NextIndex);
1131 if (UndefLoc.isValid())
1132 MI->setUndefLoc(UndefLoc);
1134 MI->setIsUsed(Record[NextIndex++]);
1137 bool IsPublic = Record[NextIndex++];
1138 MI->setVisibility(IsPublic, ReadSourceLocation(F, Record, NextIndex));
1140 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1141 // Decode function-like macro info.
1142 bool isC99VarArgs = Record[NextIndex++];
1143 bool isGNUVarArgs = Record[NextIndex++];
1145 unsigned NumArgs = Record[NextIndex++];
1146 for (unsigned i = 0; i != NumArgs; ++i)
1147 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1149 // Install function-like macro info.
1150 MI->setIsFunctionLike();
1151 if (isC99VarArgs) MI->setIsC99Varargs();
1152 if (isGNUVarArgs) MI->setIsGNUVarargs();
1153 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1154 PP.getPreprocessorAllocator());
1157 if (DeserializationListener)
1158 DeserializationListener->MacroRead(GlobalID, MI);
1160 // If an update record marked this as undefined, do so now.
1161 // FIXME: Only if the submodule this update came from is visible?
1162 MacroUpdatesMap::iterator Update = MacroUpdates.find(GlobalID);
1163 if (Update != MacroUpdates.end()) {
1164 if (MI->getUndefLoc().isInvalid()) {
1165 for (unsigned I = 0, N = Update->second.size(); I != N; ++I) {
1166 bool Hidden = false;
1167 if (unsigned SubmoduleID = Update->second[I].first) {
1168 if (Module *Owner = getSubmodule(SubmoduleID)) {
1169 if (Owner->NameVisibility == Module::Hidden) {
1170 // Note that this #undef is hidden.
1173 // Record this hiding for later.
1174 HiddenNamesMap[Owner].push_back(
1175 HiddenName(II, MI, Update->second[I].second.UndefLoc));
1181 MI->setUndefLoc(Update->second[I].second.UndefLoc);
1182 if (PPMutationListener *Listener = PP.getPPMutationListener())
1183 Listener->UndefinedMacro(MI);
1188 MacroUpdates.erase(Update);
1191 // Determine whether this macro definition is visible.
1192 bool Hidden = !MI->isPublic();
1193 if (!Hidden && GlobalSubmoduleID) {
1194 if (Module *Owner = getSubmodule(GlobalSubmoduleID)) {
1195 if (Owner->NameVisibility == Module::Hidden) {
1196 // The owning module is not visible, and this macro definition
1197 // should not be, either.
1200 // Note that this macro definition was hidden because its owning
1201 // module is not yet visible.
1202 HiddenNamesMap[Owner].push_back(HiddenName(II, MI));
1206 MI->setHidden(Hidden);
1208 // Make sure we install the macro once we're done.
1209 AddLoadedMacroInfo.MI = MI;
1210 AddLoadedMacroInfo.II = II;
1212 // Remember that we saw this macro last so that we add the tokens that
1213 // form its body to it.
1216 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1217 Record[NextIndex]) {
1218 // We have a macro definition. Register the association
1219 PreprocessedEntityID
1220 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1221 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1222 PPRec.RegisterMacroDefinition(Macro,
1223 PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true));
1231 // If we see a TOKEN before a PP_MACRO_*, then the file is
1232 // erroneous, just pretend we didn't see this.
1233 if (Macro == 0) break;
1237 Tok.setLocation(ReadSourceLocation(F, Record[0]));
1238 Tok.setLength(Record[1]);
1239 if (IdentifierInfo *II = getLocalIdentifier(F, Record[2]))
1240 Tok.setIdentifierInfo(II);
1241 Tok.setKind((tok::TokenKind)Record[3]);
1242 Tok.setFlag((Token::TokenFlags)Record[4]);
1243 Macro->AddTokenToBody(Tok);
1250 PreprocessedEntityID
1251 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1252 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1253 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1254 assert(I != M.PreprocessedEntityRemap.end()
1255 && "Invalid index into preprocessed entity index remap");
1257 return LocalID + I->second;
1260 unsigned HeaderFileInfoTrait::ComputeHash(const char *path) {
1261 return llvm::HashString(llvm::sys::path::filename(path));
1264 HeaderFileInfoTrait::internal_key_type
1265 HeaderFileInfoTrait::GetInternalKey(const char *path) { return path; }
1267 bool HeaderFileInfoTrait::EqualKey(internal_key_type a, internal_key_type b) {
1268 if (strcmp(a, b) == 0)
1271 if (llvm::sys::path::filename(a) != llvm::sys::path::filename(b))
1274 // Determine whether the actual files are equivalent.
1275 bool Result = false;
1276 if (llvm::sys::fs::equivalent(a, b, Result))
1282 std::pair<unsigned, unsigned>
1283 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1284 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1285 unsigned DataLen = (unsigned) *d++;
1286 return std::make_pair(KeyLen + 1, DataLen);
1289 HeaderFileInfoTrait::data_type
1290 HeaderFileInfoTrait::ReadData(const internal_key_type, const unsigned char *d,
1292 const unsigned char *End = d + DataLen;
1293 using namespace clang::io;
1295 unsigned Flags = *d++;
1296 HFI.isImport = (Flags >> 5) & 0x01;
1297 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1298 HFI.DirInfo = (Flags >> 2) & 0x03;
1299 HFI.Resolved = (Flags >> 1) & 0x01;
1300 HFI.IndexHeaderMapHeader = Flags & 0x01;
1301 HFI.NumIncludes = ReadUnalignedLE16(d);
1302 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1303 ReadUnalignedLE32(d));
1304 if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1305 // The framework offset is 1 greater than the actual offset,
1306 // since 0 is used as an indicator for "no framework name".
1307 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1308 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1311 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1314 // This HeaderFileInfo was externally loaded.
1315 HFI.External = true;
1319 void ASTReader::setIdentifierIsMacro(IdentifierInfo *II, ArrayRef<MacroID> IDs){
1320 II->setHadMacroDefinition(true);
1321 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1322 PendingMacroIDs[II].append(IDs.begin(), IDs.end());
1325 void ASTReader::ReadDefinedMacros() {
1326 // Note that we are loading defined macros.
1327 Deserializing Macros(this);
1329 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1330 E = ModuleMgr.rend(); I != E; ++I) {
1331 llvm::BitstreamCursor &MacroCursor = (*I)->MacroCursor;
1333 // If there was no preprocessor block, skip this file.
1334 if (!MacroCursor.getBitStreamReader())
1337 llvm::BitstreamCursor Cursor = MacroCursor;
1338 Cursor.JumpToBit((*I)->MacroStartOffset);
1342 unsigned Code = Cursor.ReadCode();
1343 if (Code == llvm::bitc::END_BLOCK)
1346 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1347 // No known subblocks, always skip them.
1348 Cursor.ReadSubBlockID();
1349 if (Cursor.SkipBlock()) {
1350 Error("malformed block record in AST file");
1356 if (Code == llvm::bitc::DEFINE_ABBREV) {
1357 Cursor.ReadAbbrevRecord();
1362 const char *BlobStart;
1365 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1366 default: // Default behavior: ignore.
1369 case PP_MACRO_OBJECT_LIKE:
1370 case PP_MACRO_FUNCTION_LIKE:
1371 getLocalIdentifier(**I, Record[0]);
1383 /// \brief Visitor class used to look up identifirs in an AST file.
1384 class IdentifierLookupVisitor {
1386 unsigned PriorGeneration;
1387 IdentifierInfo *Found;
1389 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration)
1390 : Name(Name), PriorGeneration(PriorGeneration), Found() { }
1392 static bool visit(ModuleFile &M, void *UserData) {
1393 IdentifierLookupVisitor *This
1394 = static_cast<IdentifierLookupVisitor *>(UserData);
1396 // If we've already searched this module file, skip it now.
1397 if (M.Generation <= This->PriorGeneration)
1400 ASTIdentifierLookupTable *IdTable
1401 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1405 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1408 std::pair<const char*, unsigned> Key(This->Name.begin(),
1410 ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Trait);
1411 if (Pos == IdTable->end())
1414 // Dereferencing the iterator has the effect of building the
1415 // IdentifierInfo node and populating it with the various
1416 // declarations it needs.
1421 // \brief Retrieve the identifier info found within the module
1423 IdentifierInfo *getIdentifierInfo() const { return Found; }
1427 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1428 // Note that we are loading an identifier.
1429 Deserializing AnIdentifier(this);
1431 unsigned PriorGeneration = 0;
1432 if (getContext().getLangOpts().Modules)
1433 PriorGeneration = IdentifierGeneration[&II];
1435 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration);
1436 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
1437 markIdentifierUpToDate(&II);
1440 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1444 II->setOutOfDate(false);
1446 // Update the generation for this identifier.
1447 if (getContext().getLangOpts().Modules)
1448 IdentifierGeneration[II] = CurrentGeneration;
1451 llvm::PointerIntPair<const FileEntry *, 1, bool>
1452 ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
1453 // If this ID is bogus, just return an empty input file.
1454 if (ID == 0 || ID > F.InputFilesLoaded.size())
1457 // If we've already loaded this input file, return it.
1458 if (F.InputFilesLoaded[ID-1].getPointer())
1459 return F.InputFilesLoaded[ID-1];
1461 // Go find this input file.
1462 llvm::BitstreamCursor &Cursor = F.InputFilesCursor;
1463 SavedStreamPosition SavedPosition(Cursor);
1464 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1466 unsigned Code = Cursor.ReadCode();
1468 const char *BlobStart = 0;
1469 unsigned BlobLen = 0;
1470 switch ((InputFileRecordTypes)Cursor.ReadRecord(Code, Record,
1471 &BlobStart, &BlobLen)) {
1473 unsigned StoredID = Record[0];
1474 assert(ID == StoredID && "Bogus stored ID or offset");
1476 off_t StoredSize = (off_t)Record[1];
1477 time_t StoredTime = (time_t)Record[2];
1478 bool Overridden = (bool)Record[3];
1480 // Get the file entry for this input file.
1481 StringRef OrigFilename(BlobStart, BlobLen);
1482 std::string Filename = OrigFilename;
1483 MaybeAddSystemRootToFilename(F, Filename);
1484 const FileEntry *File
1485 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1486 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1488 // If we didn't find the file, resolve it relative to the
1489 // original directory from which this AST file was created.
1490 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1491 F.OriginalDir != CurrentDir) {
1492 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1495 if (!Resolved.empty())
1496 File = FileMgr.getFile(Resolved);
1499 // For an overridden file, create a virtual file with the stored
1501 if (Overridden && File == 0) {
1502 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1507 std::string ErrorStr = "could not find file '";
1508 ErrorStr += Filename;
1509 ErrorStr += "' referenced by AST file";
1510 Error(ErrorStr.c_str());
1515 // Note that we've loaded this input file.
1516 F.InputFilesLoaded[ID-1] = InputFile(File, Overridden);
1518 // Check if there was a request to override the contents of the file
1519 // that was part of the precompiled header. Overridding such a file
1520 // can lead to problems when lexing using the source locations from the
1522 SourceManager &SM = getSourceManager();
1523 if (!Overridden && SM.isFileOverridden(File)) {
1524 Error(diag::err_fe_pch_file_overridden, Filename);
1525 // After emitting the diagnostic, recover by disabling the override so
1526 // that the original file will be used.
1527 SM.disableFileContentsOverride(File);
1528 // The FileEntry is a virtual file entry with the size of the contents
1529 // that would override the original contents. Set it to the original's
1531 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1532 StoredSize, StoredTime);
1535 // For an overridden file, there is nothing to validate.
1537 return InputFile(File, Overridden);
1539 // The stat info from the FileEntry came from the cached stat
1540 // info of the PCH, so we cannot trust it.
1541 struct stat StatBuf;
1542 if (::stat(File->getName(), &StatBuf) != 0) {
1543 StatBuf.st_size = File->getSize();
1544 StatBuf.st_mtime = File->getModificationTime();
1547 if ((StoredSize != StatBuf.st_size
1548 #if !defined(LLVM_ON_WIN32)
1549 // In our regression testing, the Windows file system seems to
1550 // have inconsistent modification times that sometimes
1551 // erroneously trigger this error-handling path.
1552 || StoredTime != StatBuf.st_mtime
1556 Error(diag::err_fe_pch_file_modified, Filename);
1561 return InputFile(File, Overridden);
1568 const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
1569 ModuleFile &M = ModuleMgr.getPrimaryModule();
1570 std::string Filename = filenameStrRef;
1571 MaybeAddSystemRootToFilename(M, Filename);
1572 const FileEntry *File = FileMgr.getFile(Filename);
1573 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
1574 M.OriginalDir != CurrentDir) {
1575 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1578 if (!resolved.empty())
1579 File = FileMgr.getFile(resolved);
1585 /// \brief If we are loading a relocatable PCH file, and the filename is
1586 /// not an absolute path, add the system root to the beginning of the file
1588 void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
1589 std::string &Filename) {
1590 // If this is not a relocatable PCH file, there's nothing to do.
1591 if (!M.RelocatablePCH)
1594 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
1597 if (isysroot.empty()) {
1598 // If no system root was given, default to '/'
1599 Filename.insert(Filename.begin(), '/');
1603 unsigned Length = isysroot.size();
1604 if (isysroot[Length - 1] != '/')
1605 Filename.insert(Filename.begin(), '/');
1607 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
1610 ASTReader::ASTReadResult
1611 ASTReader::ReadControlBlock(ModuleFile &F,
1612 llvm::SmallVectorImpl<ModuleFile *> &Loaded,
1613 unsigned ClientLoadCapabilities) {
1614 llvm::BitstreamCursor &Stream = F.Stream;
1616 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
1617 Error("malformed block record in AST file");
1621 // Read all of the records and blocks in the control block.
1623 while (!Stream.AtEndOfStream()) {
1624 unsigned Code = Stream.ReadCode();
1625 if (Code == llvm::bitc::END_BLOCK) {
1626 if (Stream.ReadBlockEnd()) {
1627 Error("error at end of control block in AST file");
1631 // Validate all of the input files.
1632 if (!DisableValidation) {
1633 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
1634 for (unsigned I = 0, N = Record[0]; I < N; ++I)
1635 if (!getInputFile(F, I+1, Complain).getPointer())
1642 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1643 switch (Stream.ReadSubBlockID()) {
1644 case INPUT_FILES_BLOCK_ID:
1645 F.InputFilesCursor = Stream;
1646 if (Stream.SkipBlock() || // Skip with the main cursor
1647 // Read the abbreviations
1648 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
1649 Error("malformed block record in AST file");
1655 if (!Stream.SkipBlock())
1660 Error("malformed block record in AST file");
1664 if (Code == llvm::bitc::DEFINE_ABBREV) {
1665 Stream.ReadAbbrevRecord();
1669 // Read and process a record.
1671 const char *BlobStart = 0;
1672 unsigned BlobLen = 0;
1673 switch ((ControlRecordTypes)Stream.ReadRecord(Code, Record,
1674 &BlobStart, &BlobLen)) {
1676 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1677 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
1678 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1679 : diag::warn_pch_version_too_new);
1680 return VersionMismatch;
1683 bool hasErrors = Record[5];
1684 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
1685 Diag(diag::err_pch_with_compiler_errors);
1689 F.RelocatablePCH = Record[4];
1691 const std::string &CurBranch = getClangFullRepositoryVersion();
1692 StringRef ASTBranch(BlobStart, BlobLen);
1693 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
1694 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
1695 Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
1696 return VersionMismatch;
1702 // Load each of the imported PCH files.
1703 unsigned Idx = 0, N = Record.size();
1705 // Read information about the AST file.
1706 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
1707 unsigned Length = Record[Idx++];
1708 SmallString<128> ImportedFile(Record.begin() + Idx,
1709 Record.begin() + Idx + Length);
1712 // Load the AST file.
1713 switch(ReadASTCore(ImportedFile, ImportedKind, &F, Loaded,
1714 ClientLoadCapabilities)) {
1715 case Failure: return Failure;
1716 // If we have to ignore the dependency, we'll have to ignore this too.
1717 case OutOfDate: return OutOfDate;
1718 case VersionMismatch: return VersionMismatch;
1719 case ConfigurationMismatch: return ConfigurationMismatch;
1720 case HadErrors: return HadErrors;
1721 case Success: break;
1727 case LANGUAGE_OPTIONS: {
1728 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
1729 if (Listener && &F == *ModuleMgr.begin() &&
1730 ParseLanguageOptions(Record, Complain, *Listener) &&
1732 return ConfigurationMismatch;
1736 case TARGET_OPTIONS: {
1737 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1738 if (Listener && &F == *ModuleMgr.begin() &&
1739 ParseTargetOptions(Record, Complain, *Listener) &&
1741 return ConfigurationMismatch;
1745 case DIAGNOSTIC_OPTIONS: {
1746 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1747 if (Listener && &F == *ModuleMgr.begin() &&
1748 ParseDiagnosticOptions(Record, Complain, *Listener) &&
1750 return ConfigurationMismatch;
1754 case FILE_SYSTEM_OPTIONS: {
1755 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1756 if (Listener && &F == *ModuleMgr.begin() &&
1757 ParseFileSystemOptions(Record, Complain, *Listener) &&
1759 return ConfigurationMismatch;
1763 case HEADER_SEARCH_OPTIONS: {
1764 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1765 if (Listener && &F == *ModuleMgr.begin() &&
1766 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
1768 return ConfigurationMismatch;
1772 case PREPROCESSOR_OPTIONS: {
1773 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1774 if (Listener && &F == *ModuleMgr.begin() &&
1775 ParsePreprocessorOptions(Record, Complain, *Listener,
1776 SuggestedPredefines) &&
1778 return ConfigurationMismatch;
1783 F.OriginalSourceFileID = FileID::get(Record[0]);
1784 F.ActualOriginalSourceFileName.assign(BlobStart, BlobLen);
1785 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
1786 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
1789 case ORIGINAL_PCH_DIR:
1790 F.OriginalDir.assign(BlobStart, BlobLen);
1793 case INPUT_FILE_OFFSETS:
1794 F.InputFileOffsets = (const uint32_t *)BlobStart;
1795 F.InputFilesLoaded.resize(Record[0]);
1800 Error("premature end of bitstream in AST file");
1804 bool ASTReader::ReadASTBlock(ModuleFile &F) {
1805 llvm::BitstreamCursor &Stream = F.Stream;
1807 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
1808 Error("malformed block record in AST file");
1812 // Read all of the records and blocks for the AST file.
1814 while (!Stream.AtEndOfStream()) {
1815 unsigned Code = Stream.ReadCode();
1816 if (Code == llvm::bitc::END_BLOCK) {
1817 if (Stream.ReadBlockEnd()) {
1818 Error("error at end of module block in AST file");
1822 DeclContext *DC = Context.getTranslationUnitDecl();
1823 if (!DC->hasExternalVisibleStorage() && DC->hasExternalLexicalStorage())
1824 DC->setMustBuildLookupTable();
1829 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1830 switch (Stream.ReadSubBlockID()) {
1831 case DECLTYPES_BLOCK_ID:
1832 // We lazily load the decls block, but we want to set up the
1833 // DeclsCursor cursor to point into it. Clone our current bitcode
1834 // cursor to it, enter the block and read the abbrevs in that block.
1835 // With the main cursor, we just skip over it.
1836 F.DeclsCursor = Stream;
1837 if (Stream.SkipBlock() || // Skip with the main cursor.
1838 // Read the abbrevs.
1839 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
1840 Error("malformed block record in AST file");
1845 case DECL_UPDATES_BLOCK_ID:
1846 if (Stream.SkipBlock()) {
1847 Error("malformed block record in AST file");
1852 case PREPROCESSOR_BLOCK_ID:
1853 F.MacroCursor = Stream;
1854 if (!PP.getExternalSource())
1855 PP.setExternalSource(this);
1857 if (Stream.SkipBlock() ||
1858 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
1859 Error("malformed block record in AST file");
1862 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
1865 case PREPROCESSOR_DETAIL_BLOCK_ID:
1866 F.PreprocessorDetailCursor = Stream;
1867 if (Stream.SkipBlock() ||
1868 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
1869 PREPROCESSOR_DETAIL_BLOCK_ID)) {
1870 Error("malformed preprocessor detail record in AST file");
1873 F.PreprocessorDetailStartOffset
1874 = F.PreprocessorDetailCursor.GetCurrentBitNo();
1876 if (!PP.getPreprocessingRecord())
1877 PP.createPreprocessingRecord(/*RecordConditionalDirectives=*/false);
1878 if (!PP.getPreprocessingRecord()->getExternalSource())
1879 PP.getPreprocessingRecord()->SetExternalSource(*this);
1882 case SOURCE_MANAGER_BLOCK_ID:
1883 if (ReadSourceManagerBlock(F))
1887 case SUBMODULE_BLOCK_ID:
1888 if (ReadSubmoduleBlock(F))
1892 case COMMENTS_BLOCK_ID: {
1893 llvm::BitstreamCursor C = Stream;
1894 if (Stream.SkipBlock() ||
1895 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
1896 Error("malformed comments block in AST file");
1899 CommentsCursors.push_back(std::make_pair(C, &F));
1904 if (!Stream.SkipBlock())
1906 Error("malformed block record in AST file");
1912 if (Code == llvm::bitc::DEFINE_ABBREV) {
1913 Stream.ReadAbbrevRecord();
1917 // Read and process a record.
1919 const char *BlobStart = 0;
1920 unsigned BlobLen = 0;
1921 switch ((ASTRecordTypes)Stream.ReadRecord(Code, Record,
1922 &BlobStart, &BlobLen)) {
1923 default: // Default behavior: ignore.
1927 if (F.LocalNumTypes != 0) {
1928 Error("duplicate TYPE_OFFSET record in AST file");
1931 F.TypeOffsets = (const uint32_t *)BlobStart;
1932 F.LocalNumTypes = Record[0];
1933 unsigned LocalBaseTypeIndex = Record[1];
1934 F.BaseTypeIndex = getTotalNumTypes();
1936 if (F.LocalNumTypes > 0) {
1937 // Introduce the global -> local mapping for types within this module.
1938 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
1940 // Introduce the local -> global mapping for types within this module.
1941 F.TypeRemap.insertOrReplace(
1942 std::make_pair(LocalBaseTypeIndex,
1943 F.BaseTypeIndex - LocalBaseTypeIndex));
1945 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
1951 if (F.LocalNumDecls != 0) {
1952 Error("duplicate DECL_OFFSET record in AST file");
1955 F.DeclOffsets = (const DeclOffset *)BlobStart;
1956 F.LocalNumDecls = Record[0];
1957 unsigned LocalBaseDeclID = Record[1];
1958 F.BaseDeclID = getTotalNumDecls();
1960 if (F.LocalNumDecls > 0) {
1961 // Introduce the global -> local mapping for declarations within this
1963 GlobalDeclMap.insert(
1964 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
1966 // Introduce the local -> global mapping for declarations within this
1968 F.DeclRemap.insertOrReplace(
1969 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
1971 // Introduce the global -> local mapping for declarations within this
1973 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
1975 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
1980 case TU_UPDATE_LEXICAL: {
1981 DeclContext *TU = Context.getTranslationUnitDecl();
1982 DeclContextInfo &Info = F.DeclContextInfos[TU];
1983 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(BlobStart);
1984 Info.NumLexicalDecls
1985 = static_cast<unsigned int>(BlobLen / sizeof(KindDeclIDPair));
1986 TU->setHasExternalLexicalStorage(true);
1990 case UPDATE_VISIBLE: {
1992 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
1993 ASTDeclContextNameLookupTable *Table =
1994 ASTDeclContextNameLookupTable::Create(
1995 (const unsigned char *)BlobStart + Record[Idx++],
1996 (const unsigned char *)BlobStart,
1997 ASTDeclContextNameLookupTrait(*this, F));
1998 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
1999 DeclContext *TU = Context.getTranslationUnitDecl();
2000 F.DeclContextInfos[TU].NameLookupTableData = Table;
2001 TU->setHasExternalVisibleStorage(true);
2003 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2007 case IDENTIFIER_TABLE:
2008 F.IdentifierTableData = BlobStart;
2010 F.IdentifierLookupTable
2011 = ASTIdentifierLookupTable::Create(
2012 (const unsigned char *)F.IdentifierTableData + Record[0],
2013 (const unsigned char *)F.IdentifierTableData,
2014 ASTIdentifierLookupTrait(*this, F));
2016 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2020 case IDENTIFIER_OFFSET: {
2021 if (F.LocalNumIdentifiers != 0) {
2022 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2025 F.IdentifierOffsets = (const uint32_t *)BlobStart;
2026 F.LocalNumIdentifiers = Record[0];
2027 unsigned LocalBaseIdentifierID = Record[1];
2028 F.BaseIdentifierID = getTotalNumIdentifiers();
2030 if (F.LocalNumIdentifiers > 0) {
2031 // Introduce the global -> local mapping for identifiers within this
2033 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2036 // Introduce the local -> global mapping for identifiers within this
2038 F.IdentifierRemap.insertOrReplace(
2039 std::make_pair(LocalBaseIdentifierID,
2040 F.BaseIdentifierID - LocalBaseIdentifierID));
2042 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2043 + F.LocalNumIdentifiers);
2048 case EXTERNAL_DEFINITIONS:
2049 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2050 ExternalDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2054 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2055 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2059 TotalNumStatements += Record[0];
2060 TotalNumMacros += Record[1];
2061 TotalLexicalDeclContexts += Record[2];
2062 TotalVisibleDeclContexts += Record[3];
2065 case UNUSED_FILESCOPED_DECLS:
2066 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2067 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2070 case DELEGATING_CTORS:
2071 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2072 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2075 case WEAK_UNDECLARED_IDENTIFIERS:
2076 if (Record.size() % 4 != 0) {
2077 Error("invalid weak identifiers record");
2081 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2082 // files. This isn't the way to do it :)
2083 WeakUndeclaredIdentifiers.clear();
2085 // Translate the weak, undeclared identifiers into global IDs.
2086 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2087 WeakUndeclaredIdentifiers.push_back(
2088 getGlobalIdentifierID(F, Record[I++]));
2089 WeakUndeclaredIdentifiers.push_back(
2090 getGlobalIdentifierID(F, Record[I++]));
2091 WeakUndeclaredIdentifiers.push_back(
2092 ReadSourceLocation(F, Record, I).getRawEncoding());
2093 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2097 case LOCALLY_SCOPED_EXTERNAL_DECLS:
2098 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2099 LocallyScopedExternalDecls.push_back(getGlobalDeclID(F, Record[I]));
2102 case SELECTOR_OFFSETS: {
2103 F.SelectorOffsets = (const uint32_t *)BlobStart;
2104 F.LocalNumSelectors = Record[0];
2105 unsigned LocalBaseSelectorID = Record[1];
2106 F.BaseSelectorID = getTotalNumSelectors();
2108 if (F.LocalNumSelectors > 0) {
2109 // Introduce the global -> local mapping for selectors within this
2111 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2113 // Introduce the local -> global mapping for selectors within this
2115 F.SelectorRemap.insertOrReplace(
2116 std::make_pair(LocalBaseSelectorID,
2117 F.BaseSelectorID - LocalBaseSelectorID));
2119 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2125 F.SelectorLookupTableData = (const unsigned char *)BlobStart;
2127 F.SelectorLookupTable
2128 = ASTSelectorLookupTable::Create(
2129 F.SelectorLookupTableData + Record[0],
2130 F.SelectorLookupTableData,
2131 ASTSelectorLookupTrait(*this, F));
2132 TotalNumMethodPoolEntries += Record[1];
2135 case REFERENCED_SELECTOR_POOL:
2136 if (!Record.empty()) {
2137 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2138 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2140 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2146 case PP_COUNTER_VALUE:
2147 if (!Record.empty() && Listener)
2148 Listener->ReadCounter(F, Record[0]);
2151 case FILE_SORTED_DECLS:
2152 F.FileSortedDecls = (const DeclID *)BlobStart;
2153 F.NumFileSortedDecls = Record[0];
2156 case SOURCE_LOCATION_OFFSETS: {
2157 F.SLocEntryOffsets = (const uint32_t *)BlobStart;
2158 F.LocalNumSLocEntries = Record[0];
2159 unsigned SLocSpaceSize = Record[1];
2160 llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2161 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2163 // Make our entry in the range map. BaseID is negative and growing, so
2164 // we invert it. Because we invert it, though, we need the other end of
2166 unsigned RangeStart =
2167 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2168 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2169 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2171 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2172 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2173 GlobalSLocOffsetMap.insert(
2174 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2175 - SLocSpaceSize,&F));
2177 // Initialize the remapping table.
2178 // Invalid stays invalid.
2179 F.SLocRemap.insert(std::make_pair(0U, 0));
2180 // This module. Base was 2 when being compiled.
2181 F.SLocRemap.insert(std::make_pair(2U,
2182 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2184 TotalNumSLocEntries += F.LocalNumSLocEntries;
2188 case MODULE_OFFSET_MAP: {
2189 // Additional remapping information.
2190 const unsigned char *Data = (const unsigned char*)BlobStart;
2191 const unsigned char *DataEnd = Data + BlobLen;
2193 // Continuous range maps we may be updating in our module.
2194 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2195 ContinuousRangeMap<uint32_t, int, 2>::Builder
2196 IdentifierRemap(F.IdentifierRemap);
2197 ContinuousRangeMap<uint32_t, int, 2>::Builder
2198 MacroRemap(F.MacroRemap);
2199 ContinuousRangeMap<uint32_t, int, 2>::Builder
2200 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2201 ContinuousRangeMap<uint32_t, int, 2>::Builder
2202 SubmoduleRemap(F.SubmoduleRemap);
2203 ContinuousRangeMap<uint32_t, int, 2>::Builder
2204 SelectorRemap(F.SelectorRemap);
2205 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2206 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2208 while(Data < DataEnd) {
2209 uint16_t Len = io::ReadUnalignedLE16(Data);
2210 StringRef Name = StringRef((const char*)Data, Len);
2212 ModuleFile *OM = ModuleMgr.lookup(Name);
2214 Error("SourceLocation remap refers to unknown module");
2218 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2219 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2220 uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
2221 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2222 uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
2223 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2224 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2225 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2227 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2228 SLocRemap.insert(std::make_pair(SLocOffset,
2229 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2230 IdentifierRemap.insert(
2231 std::make_pair(IdentifierIDOffset,
2232 OM->BaseIdentifierID - IdentifierIDOffset));
2233 MacroRemap.insert(std::make_pair(MacroIDOffset,
2234 OM->BaseMacroID - MacroIDOffset));
2235 PreprocessedEntityRemap.insert(
2236 std::make_pair(PreprocessedEntityIDOffset,
2237 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2238 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2239 OM->BaseSubmoduleID - SubmoduleIDOffset));
2240 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2241 OM->BaseSelectorID - SelectorIDOffset));
2242 DeclRemap.insert(std::make_pair(DeclIDOffset,
2243 OM->BaseDeclID - DeclIDOffset));
2245 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2246 OM->BaseTypeIndex - TypeIndexOffset));
2248 // Global -> local mappings.
2249 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2254 case SOURCE_MANAGER_LINE_TABLE:
2255 if (ParseLineTable(F, Record))
2259 case SOURCE_LOCATION_PRELOADS: {
2260 // Need to transform from the local view (1-based IDs) to the global view,
2261 // which is based off F.SLocEntryBaseID.
2262 if (!F.PreloadSLocEntries.empty()) {
2263 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2267 F.PreloadSLocEntries.swap(Record);
2271 case EXT_VECTOR_DECLS:
2272 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2273 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2277 if (Record.size() % 3 != 0) {
2278 Error("Invalid VTABLE_USES record");
2282 // Later tables overwrite earlier ones.
2283 // FIXME: Modules will have some trouble with this. This is clearly not
2284 // the right way to do this.
2287 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2288 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2289 VTableUses.push_back(
2290 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2291 VTableUses.push_back(Record[Idx++]);
2295 case DYNAMIC_CLASSES:
2296 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2297 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2300 case PENDING_IMPLICIT_INSTANTIATIONS:
2301 if (PendingInstantiations.size() % 2 != 0) {
2302 Error("Invalid existing PendingInstantiations");
2306 if (Record.size() % 2 != 0) {
2307 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2311 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2312 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2313 PendingInstantiations.push_back(
2314 ReadSourceLocation(F, Record, I).getRawEncoding());
2318 case SEMA_DECL_REFS:
2319 // Later tables overwrite earlier ones.
2320 // FIXME: Modules will have some trouble with this.
2321 SemaDeclRefs.clear();
2322 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2323 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2326 case PPD_ENTITIES_OFFSETS: {
2327 F.PreprocessedEntityOffsets = (const PPEntityOffset *)BlobStart;
2328 assert(BlobLen % sizeof(PPEntityOffset) == 0);
2329 F.NumPreprocessedEntities = BlobLen / sizeof(PPEntityOffset);
2331 unsigned LocalBasePreprocessedEntityID = Record[0];
2333 unsigned StartingID;
2334 if (!PP.getPreprocessingRecord())
2335 PP.createPreprocessingRecord(/*RecordConditionalDirectives=*/false);
2336 if (!PP.getPreprocessingRecord()->getExternalSource())
2337 PP.getPreprocessingRecord()->SetExternalSource(*this);
2339 = PP.getPreprocessingRecord()
2340 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2341 F.BasePreprocessedEntityID = StartingID;
2343 if (F.NumPreprocessedEntities > 0) {
2344 // Introduce the global -> local mapping for preprocessed entities in
2346 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2348 // Introduce the local -> global mapping for preprocessed entities in
2350 F.PreprocessedEntityRemap.insertOrReplace(
2351 std::make_pair(LocalBasePreprocessedEntityID,
2352 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2358 case DECL_UPDATE_OFFSETS: {
2359 if (Record.size() % 2 != 0) {
2360 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2363 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2364 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2365 .push_back(std::make_pair(&F, Record[I+1]));
2369 case DECL_REPLACEMENTS: {
2370 if (Record.size() % 3 != 0) {
2371 Error("invalid DECL_REPLACEMENTS block in AST file");
2374 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2375 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2376 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2380 case OBJC_CATEGORIES_MAP: {
2381 if (F.LocalNumObjCCategoriesInMap != 0) {
2382 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2386 F.LocalNumObjCCategoriesInMap = Record[0];
2387 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)BlobStart;
2391 case OBJC_CATEGORIES:
2392 F.ObjCCategories.swap(Record);
2395 case CXX_BASE_SPECIFIER_OFFSETS: {
2396 if (F.LocalNumCXXBaseSpecifiers != 0) {
2397 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2401 F.LocalNumCXXBaseSpecifiers = Record[0];
2402 F.CXXBaseSpecifiersOffsets = (const uint32_t *)BlobStart;
2403 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2407 case DIAG_PRAGMA_MAPPINGS:
2408 if (F.PragmaDiagMappings.empty())
2409 F.PragmaDiagMappings.swap(Record);
2411 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2412 Record.begin(), Record.end());
2415 case CUDA_SPECIAL_DECL_REFS:
2416 // Later tables overwrite earlier ones.
2417 // FIXME: Modules will have trouble with this.
2418 CUDASpecialDeclRefs.clear();
2419 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2420 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2423 case HEADER_SEARCH_TABLE: {
2424 F.HeaderFileInfoTableData = BlobStart;
2425 F.LocalNumHeaderFileInfos = Record[1];
2426 F.HeaderFileFrameworkStrings = BlobStart + Record[2];
2428 F.HeaderFileInfoTable
2429 = HeaderFileInfoLookupTable::Create(
2430 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2431 (const unsigned char *)F.HeaderFileInfoTableData,
2432 HeaderFileInfoTrait(*this, F,
2433 &PP.getHeaderSearchInfo(),
2434 BlobStart + Record[2]));
2436 PP.getHeaderSearchInfo().SetExternalSource(this);
2437 if (!PP.getHeaderSearchInfo().getExternalLookup())
2438 PP.getHeaderSearchInfo().SetExternalLookup(this);
2443 case FP_PRAGMA_OPTIONS:
2444 // Later tables overwrite earlier ones.
2445 FPPragmaOptions.swap(Record);
2448 case OPENCL_EXTENSIONS:
2449 // Later tables overwrite earlier ones.
2450 OpenCLExtensions.swap(Record);
2453 case TENTATIVE_DEFINITIONS:
2454 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2455 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2458 case KNOWN_NAMESPACES:
2459 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2460 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2463 case IMPORTED_MODULES: {
2464 if (F.Kind != MK_Module) {
2465 // If we aren't loading a module (which has its own exports), make
2466 // all of the imported modules visible.
2467 // FIXME: Deal with macros-only imports.
2468 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2469 if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
2470 ImportedModules.push_back(GlobalID);
2476 case LOCAL_REDECLARATIONS: {
2477 F.RedeclarationChains.swap(Record);
2481 case LOCAL_REDECLARATIONS_MAP: {
2482 if (F.LocalNumRedeclarationsInMap != 0) {
2483 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
2487 F.LocalNumRedeclarationsInMap = Record[0];
2488 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)BlobStart;
2492 case MERGED_DECLARATIONS: {
2493 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
2494 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
2495 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
2496 for (unsigned N = Record[Idx++]; N > 0; --N)
2497 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
2502 case MACRO_OFFSET: {
2503 if (F.LocalNumMacros != 0) {
2504 Error("duplicate MACRO_OFFSET record in AST file");
2507 F.MacroOffsets = (const uint32_t *)BlobStart;
2508 F.LocalNumMacros = Record[0];
2509 unsigned LocalBaseMacroID = Record[1];
2510 F.BaseMacroID = getTotalNumMacros();
2512 if (F.LocalNumMacros > 0) {
2513 // Introduce the global -> local mapping for macros within this module.
2514 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
2516 // Introduce the local -> global mapping for macros within this module.
2517 F.MacroRemap.insertOrReplace(
2518 std::make_pair(LocalBaseMacroID,
2519 F.BaseMacroID - LocalBaseMacroID));
2521 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
2526 case MACRO_UPDATES: {
2527 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2528 MacroID ID = getGlobalMacroID(F, Record[I++]);
2532 SourceLocation UndefLoc = ReadSourceLocation(F, Record, I);
2533 SubmoduleID SubmoduleID = getGlobalSubmoduleID(F, Record[I++]);;
2535 Update.UndefLoc = UndefLoc;
2536 MacroUpdates[ID].push_back(std::make_pair(SubmoduleID, Update));
2542 Error("premature end of bitstream in AST file");
2546 void ASTReader::makeNamesVisible(const HiddenNames &Names) {
2547 for (unsigned I = 0, N = Names.size(); I != N; ++I) {
2548 switch (Names[I].getKind()) {
2549 case HiddenName::Declaration:
2550 Names[I].getDecl()->Hidden = false;
2553 case HiddenName::MacroVisibility: {
2554 std::pair<IdentifierInfo *, MacroInfo *> Macro = Names[I].getMacro();
2555 Macro.second->setHidden(!Macro.second->isPublic());
2556 if (Macro.second->isDefined()) {
2557 PP.makeLoadedMacroInfoVisible(Macro.first, Macro.second);
2562 case HiddenName::MacroUndef: {
2563 std::pair<IdentifierInfo *, MacroInfo *> Macro = Names[I].getMacro();
2564 if (Macro.second->isDefined()) {
2565 Macro.second->setUndefLoc(Names[I].getMacroUndefLoc());
2566 if (PPMutationListener *Listener = PP.getPPMutationListener())
2567 Listener->UndefinedMacro(Macro.second);
2568 PP.makeLoadedMacroInfoVisible(Macro.first, Macro.second);
2576 void ASTReader::makeModuleVisible(Module *Mod,
2577 Module::NameVisibilityKind NameVisibility) {
2578 llvm::SmallPtrSet<Module *, 4> Visited;
2579 llvm::SmallVector<Module *, 4> Stack;
2580 Stack.push_back(Mod);
2581 while (!Stack.empty()) {
2585 if (NameVisibility <= Mod->NameVisibility) {
2586 // This module already has this level of visibility (or greater), so
2587 // there is nothing more to do.
2591 if (!Mod->isAvailable()) {
2592 // Modules that aren't available cannot be made visible.
2596 // Update the module's name visibility.
2597 Mod->NameVisibility = NameVisibility;
2599 // If we've already deserialized any names from this module,
2600 // mark them as visible.
2601 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
2602 if (Hidden != HiddenNamesMap.end()) {
2603 makeNamesVisible(Hidden->second);
2604 HiddenNamesMap.erase(Hidden);
2607 // Push any non-explicit submodules onto the stack to be marked as
2609 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2610 SubEnd = Mod->submodule_end();
2611 Sub != SubEnd; ++Sub) {
2612 if (!(*Sub)->IsExplicit && Visited.insert(*Sub))
2613 Stack.push_back(*Sub);
2616 // Push any exported modules onto the stack to be marked as visible.
2617 bool AnyWildcard = false;
2618 bool UnrestrictedWildcard = false;
2619 llvm::SmallVector<Module *, 4> WildcardRestrictions;
2620 for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
2621 Module *Exported = Mod->Exports[I].getPointer();
2622 if (!Mod->Exports[I].getInt()) {
2623 // Export a named module directly; no wildcards involved.
2624 if (Visited.insert(Exported))
2625 Stack.push_back(Exported);
2630 // Wildcard export: export all of the imported modules that match
2631 // the given pattern.
2633 if (UnrestrictedWildcard)
2636 if (Module *Restriction = Mod->Exports[I].getPointer())
2637 WildcardRestrictions.push_back(Restriction);
2639 WildcardRestrictions.clear();
2640 UnrestrictedWildcard = true;
2644 // If there were any wildcards, push any imported modules that were
2645 // re-exported by the wildcard restriction.
2649 for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
2650 Module *Imported = Mod->Imports[I];
2651 if (!Visited.insert(Imported))
2654 bool Acceptable = UnrestrictedWildcard;
2656 // Check whether this module meets one of the restrictions.
2657 for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
2658 Module *Restriction = WildcardRestrictions[R];
2659 if (Imported == Restriction || Imported->isSubModuleOf(Restriction)) {
2669 Stack.push_back(Imported);
2674 ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
2676 unsigned ClientLoadCapabilities) {
2677 // Bump the generation number.
2678 unsigned PreviousGeneration = CurrentGeneration++;
2680 unsigned NumModules = ModuleMgr.size();
2681 llvm::SmallVector<ModuleFile *, 4> Loaded;
2682 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type,
2683 /*ImportedBy=*/0, Loaded,
2684 ClientLoadCapabilities)) {
2687 case VersionMismatch:
2688 case ConfigurationMismatch:
2690 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end());
2697 // Here comes stuff that we only do once the entire chain is loaded.
2699 // Load the AST blocks of all of the modules that we loaded.
2700 for (llvm::SmallVectorImpl<ModuleFile *>::iterator M = Loaded.begin(),
2701 MEnd = Loaded.end();
2703 ModuleFile &F = **M;
2705 // Read the AST block.
2706 if (ReadASTBlock(F))
2709 // Once read, set the ModuleFile bit base offset and update the size in
2710 // bits of all files we've seen.
2711 F.GlobalBitOffset = TotalModulesSizeInBits;
2712 TotalModulesSizeInBits += F.SizeInBits;
2713 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
2715 // Preload SLocEntries.
2716 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
2717 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
2718 // Load it through the SourceManager and don't call ReadSLocEntry()
2719 // directly because the entry may have already been loaded in which case
2720 // calling ReadSLocEntry() directly would trigger an assertion in
2722 SourceMgr.getLoadedSLocEntryByID(Index);
2726 // Mark all of the identifiers in the identifier table as being out of date,
2727 // so that various accessors know to check the loaded modules when the
2728 // identifier is used.
2729 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
2730 IdEnd = PP.getIdentifierTable().end();
2732 Id->second->setOutOfDate(true);
2734 // Resolve any unresolved module exports.
2735 for (unsigned I = 0, N = UnresolvedModuleImportExports.size(); I != N; ++I) {
2736 UnresolvedModuleImportExport &Unresolved = UnresolvedModuleImportExports[I];
2737 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
2738 Module *ResolvedMod = getSubmodule(GlobalID);
2740 if (Unresolved.IsImport) {
2742 Unresolved.Mod->Imports.push_back(ResolvedMod);
2746 if (ResolvedMod || Unresolved.IsWildcard)
2747 Unresolved.Mod->Exports.push_back(
2748 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
2750 UnresolvedModuleImportExports.clear();
2752 InitializeContext();
2754 if (DeserializationListener)
2755 DeserializationListener->ReaderInitialized(this);
2757 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
2758 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
2759 PrimaryModule.OriginalSourceFileID
2760 = FileID::get(PrimaryModule.SLocEntryBaseID
2761 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
2763 // If this AST file is a precompiled preamble, then set the
2764 // preamble file ID of the source manager to the file source file
2765 // from which the preamble was built.
2766 if (Type == MK_Preamble) {
2767 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
2768 } else if (Type == MK_MainFile) {
2769 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
2773 // For any Objective-C class definitions we have already loaded, make sure
2774 // that we load any additional categories.
2775 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
2776 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
2777 ObjCClassesLoaded[I],
2778 PreviousGeneration);
2784 ASTReader::ASTReadResult
2785 ASTReader::ReadASTCore(StringRef FileName,
2787 ModuleFile *ImportedBy,
2788 llvm::SmallVectorImpl<ModuleFile *> &Loaded,
2789 unsigned ClientLoadCapabilities) {
2792 std::string ErrorStr;
2793 llvm::tie(M, NewModule) = ModuleMgr.addModule(FileName, Type, ImportedBy,
2794 CurrentGeneration, ErrorStr);
2797 // We couldn't load the module.
2798 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
2805 // We've already loaded this module.
2809 // FIXME: This seems rather a hack. Should CurrentDir be part of the
2811 if (FileName != "-") {
2812 CurrentDir = llvm::sys::path::parent_path(FileName);
2813 if (CurrentDir.empty()) CurrentDir = ".";
2817 llvm::BitstreamCursor &Stream = F.Stream;
2818 Stream.init(F.StreamFile);
2819 F.SizeInBits = F.Buffer->getBufferSize() * 8;
2821 // Sniff for the signature.
2822 if (Stream.Read(8) != 'C' ||
2823 Stream.Read(8) != 'P' ||
2824 Stream.Read(8) != 'C' ||
2825 Stream.Read(8) != 'H') {
2826 Diag(diag::err_not_a_pch_file) << FileName;
2830 while (!Stream.AtEndOfStream()) {
2831 unsigned Code = Stream.ReadCode();
2833 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
2834 Error("invalid record at top-level of AST file");
2838 unsigned BlockID = Stream.ReadSubBlockID();
2840 // We only know the control subblock ID.
2842 case llvm::bitc::BLOCKINFO_BLOCK_ID:
2843 if (Stream.ReadBlockInfoBlock()) {
2844 Error("malformed BlockInfoBlock in AST file");
2848 case CONTROL_BLOCK_ID:
2849 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
2853 case Failure: return Failure;
2854 case OutOfDate: return OutOfDate;
2855 case VersionMismatch: return VersionMismatch;
2856 case ConfigurationMismatch: return ConfigurationMismatch;
2857 case HadErrors: return HadErrors;
2861 // Record that we've loaded this module.
2862 Loaded.push_back(M);
2866 if (Stream.SkipBlock()) {
2867 Error("malformed block record in AST file");
2877 void ASTReader::InitializeContext() {
2878 // If there's a listener, notify them that we "read" the translation unit.
2879 if (DeserializationListener)
2880 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
2881 Context.getTranslationUnitDecl());
2883 // Make sure we load the declaration update records for the translation unit,
2884 // if there are any.
2885 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
2886 Context.getTranslationUnitDecl());
2888 // FIXME: Find a better way to deal with collisions between these
2889 // built-in types. Right now, we just ignore the problem.
2891 // Load the special types.
2892 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
2893 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
2894 if (!Context.CFConstantStringTypeDecl)
2895 Context.setCFConstantStringType(GetType(String));
2898 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
2899 QualType FileType = GetType(File);
2900 if (FileType.isNull()) {
2901 Error("FILE type is NULL");
2905 if (!Context.FILEDecl) {
2906 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
2907 Context.setFILEDecl(Typedef->getDecl());
2909 const TagType *Tag = FileType->getAs<TagType>();
2911 Error("Invalid FILE type in AST file");
2914 Context.setFILEDecl(Tag->getDecl());
2919 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
2920 QualType Jmp_bufType = GetType(Jmp_buf);
2921 if (Jmp_bufType.isNull()) {
2922 Error("jmp_buf type is NULL");
2926 if (!Context.jmp_bufDecl) {
2927 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
2928 Context.setjmp_bufDecl(Typedef->getDecl());
2930 const TagType *Tag = Jmp_bufType->getAs<TagType>();
2932 Error("Invalid jmp_buf type in AST file");
2935 Context.setjmp_bufDecl(Tag->getDecl());
2940 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
2941 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
2942 if (Sigjmp_bufType.isNull()) {
2943 Error("sigjmp_buf type is NULL");
2947 if (!Context.sigjmp_bufDecl) {
2948 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
2949 Context.setsigjmp_bufDecl(Typedef->getDecl());
2951 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
2952 assert(Tag && "Invalid sigjmp_buf type in AST file");
2953 Context.setsigjmp_bufDecl(Tag->getDecl());
2958 if (unsigned ObjCIdRedef
2959 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
2960 if (Context.ObjCIdRedefinitionType.isNull())
2961 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
2964 if (unsigned ObjCClassRedef
2965 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
2966 if (Context.ObjCClassRedefinitionType.isNull())
2967 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
2970 if (unsigned ObjCSelRedef
2971 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
2972 if (Context.ObjCSelRedefinitionType.isNull())
2973 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2976 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
2977 QualType Ucontext_tType = GetType(Ucontext_t);
2978 if (Ucontext_tType.isNull()) {
2979 Error("ucontext_t type is NULL");
2983 if (!Context.ucontext_tDecl) {
2984 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
2985 Context.setucontext_tDecl(Typedef->getDecl());
2987 const TagType *Tag = Ucontext_tType->getAs<TagType>();
2988 assert(Tag && "Invalid ucontext_t type in AST file");
2989 Context.setucontext_tDecl(Tag->getDecl());
2995 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
2997 // If there were any CUDA special declarations, deserialize them.
2998 if (!CUDASpecialDeclRefs.empty()) {
2999 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3000 Context.setcudaConfigureCallDecl(
3001 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3004 // Re-export any modules that were imported by a non-module AST file.
3005 for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3006 if (Module *Imported = getSubmodule(ImportedModules[I]))
3007 makeModuleVisible(Imported, Module::AllVisible);
3009 ImportedModules.clear();
3012 void ASTReader::finalizeForWriting() {
3013 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3014 HiddenEnd = HiddenNamesMap.end();
3015 Hidden != HiddenEnd; ++Hidden) {
3016 makeNamesVisible(Hidden->second);
3018 HiddenNamesMap.clear();
3021 /// \brief Retrieve the name of the original source file name
3022 /// directly from the AST file, without actually loading the AST
3024 std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3025 FileManager &FileMgr,
3026 DiagnosticsEngine &Diags) {
3027 // Open the AST file.
3029 OwningPtr<llvm::MemoryBuffer> Buffer;
3030 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3032 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3033 return std::string();
3036 // Initialize the stream
3037 llvm::BitstreamReader StreamFile;
3038 llvm::BitstreamCursor Stream;
3039 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3040 (const unsigned char *)Buffer->getBufferEnd());
3041 Stream.init(StreamFile);
3043 // Sniff for the signature.
3044 if (Stream.Read(8) != 'C' ||
3045 Stream.Read(8) != 'P' ||
3046 Stream.Read(8) != 'C' ||
3047 Stream.Read(8) != 'H') {
3048 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3049 return std::string();
3053 while (!Stream.AtEndOfStream()) {
3054 unsigned Code = Stream.ReadCode();
3056 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
3057 unsigned BlockID = Stream.ReadSubBlockID();
3059 // We only know the AST subblock ID.
3061 case CONTROL_BLOCK_ID:
3062 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
3063 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3064 return std::string();
3069 if (Stream.SkipBlock()) {
3070 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3071 return std::string();
3078 if (Code == llvm::bitc::END_BLOCK) {
3079 if (Stream.ReadBlockEnd()) {
3080 Diags.Report(diag::err_fe_pch_error_at_end_block) << ASTFileName;
3081 return std::string();
3086 if (Code == llvm::bitc::DEFINE_ABBREV) {
3087 Stream.ReadAbbrevRecord();
3092 const char *BlobStart = 0;
3093 unsigned BlobLen = 0;
3094 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen) == ORIGINAL_FILE)
3095 return std::string(BlobStart, BlobLen);
3098 return std::string();
3102 class SimplePCHValidator : public ASTReaderListener {
3103 const LangOptions &ExistingLangOpts;
3104 const TargetOptions &ExistingTargetOpts;
3105 const PreprocessorOptions &ExistingPPOpts;
3106 FileManager &FileMgr;
3109 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3110 const TargetOptions &ExistingTargetOpts,
3111 const PreprocessorOptions &ExistingPPOpts,
3112 FileManager &FileMgr)
3113 : ExistingLangOpts(ExistingLangOpts),
3114 ExistingTargetOpts(ExistingTargetOpts),
3115 ExistingPPOpts(ExistingPPOpts),
3120 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
3122 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3124 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
3126 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3128 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3130 std::string &SuggestedPredefines) {
3131 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
3132 SuggestedPredefines);
3137 bool ASTReader::readASTFileControlBlock(StringRef Filename,
3138 FileManager &FileMgr,
3139 ASTReaderListener &Listener) {
3140 // Open the AST file.
3142 OwningPtr<llvm::MemoryBuffer> Buffer;
3143 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3148 // Initialize the stream
3149 llvm::BitstreamReader StreamFile;
3150 llvm::BitstreamCursor Stream;
3151 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3152 (const unsigned char *)Buffer->getBufferEnd());
3153 Stream.init(StreamFile);
3155 // Sniff for the signature.
3156 if (Stream.Read(8) != 'C' ||
3157 Stream.Read(8) != 'P' ||
3158 Stream.Read(8) != 'C' ||
3159 Stream.Read(8) != 'H') {
3164 bool InControlBlock = false;
3165 while (!Stream.AtEndOfStream()) {
3166 unsigned Code = Stream.ReadCode();
3168 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
3169 unsigned BlockID = Stream.ReadSubBlockID();
3171 // We only know the control subblock ID.
3173 case CONTROL_BLOCK_ID:
3174 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
3177 InControlBlock = true;
3182 if (Stream.SkipBlock())
3189 if (Code == llvm::bitc::END_BLOCK) {
3190 if (Stream.ReadBlockEnd()) {
3194 InControlBlock = false;
3198 if (Code == llvm::bitc::DEFINE_ABBREV) {
3199 Stream.ReadAbbrevRecord();
3204 const char *BlobStart = 0;
3205 unsigned BlobLen = 0;
3206 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
3207 if (InControlBlock) {
3208 switch ((ControlRecordTypes)RecCode) {
3210 if (Record[0] != VERSION_MAJOR) {
3214 const std::string &CurBranch = getClangFullRepositoryVersion();
3215 StringRef ASTBranch(BlobStart, BlobLen);
3216 if (StringRef(CurBranch) != ASTBranch)
3221 case LANGUAGE_OPTIONS:
3222 if (ParseLanguageOptions(Record, false, Listener))
3226 case TARGET_OPTIONS:
3227 if (ParseTargetOptions(Record, false, Listener))
3231 case DIAGNOSTIC_OPTIONS:
3232 if (ParseDiagnosticOptions(Record, false, Listener))
3236 case FILE_SYSTEM_OPTIONS:
3237 if (ParseFileSystemOptions(Record, false, Listener))
3241 case HEADER_SEARCH_OPTIONS:
3242 if (ParseHeaderSearchOptions(Record, false, Listener))
3246 case PREPROCESSOR_OPTIONS: {
3247 std::string IgnoredSuggestedPredefines;
3248 if (ParsePreprocessorOptions(Record, false, Listener,
3249 IgnoredSuggestedPredefines))
3255 // No other validation to perform.
3265 bool ASTReader::isAcceptableASTFile(StringRef Filename,
3266 FileManager &FileMgr,
3267 const LangOptions &LangOpts,
3268 const TargetOptions &TargetOpts,
3269 const PreprocessorOptions &PPOpts) {
3270 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3271 return !readASTFileControlBlock(Filename, FileMgr, validator);
3274 bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
3275 // Enter the submodule block.
3276 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3277 Error("malformed submodule block record in AST file");
3281 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
3283 Module *CurrentModule = 0;
3286 unsigned Code = F.Stream.ReadCode();
3287 if (Code == llvm::bitc::END_BLOCK) {
3288 if (F.Stream.ReadBlockEnd()) {
3289 Error("error at end of submodule block in AST file");
3295 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
3296 // No known subblocks, always skip them.
3297 F.Stream.ReadSubBlockID();
3298 if (F.Stream.SkipBlock()) {
3299 Error("malformed block record in AST file");
3305 if (Code == llvm::bitc::DEFINE_ABBREV) {
3306 F.Stream.ReadAbbrevRecord();
3311 const char *BlobStart;
3314 switch (F.Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
3315 default: // Default behavior: ignore.
3318 case SUBMODULE_DEFINITION: {
3320 Error("missing submodule metadata record at beginning of block");
3324 if (Record.size() < 7) {
3325 Error("malformed module definition");
3329 StringRef Name(BlobStart, BlobLen);
3330 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
3331 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[1]);
3332 bool IsFramework = Record[2];
3333 bool IsExplicit = Record[3];
3334 bool IsSystem = Record[4];
3335 bool InferSubmodules = Record[5];
3336 bool InferExplicitSubmodules = Record[6];
3337 bool InferExportWildcard = Record[7];
3339 Module *ParentModule = 0;
3341 ParentModule = getSubmodule(Parent);
3343 // Retrieve this (sub)module from the module map, creating it if
3345 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
3348 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
3349 if (GlobalIndex >= SubmodulesLoaded.size() ||
3350 SubmodulesLoaded[GlobalIndex]) {
3351 Error("too many submodules");
3355 CurrentModule->setASTFile(F.File);
3356 CurrentModule->IsFromModuleFile = true;
3357 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
3358 CurrentModule->InferSubmodules = InferSubmodules;
3359 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
3360 CurrentModule->InferExportWildcard = InferExportWildcard;
3361 if (DeserializationListener)
3362 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
3364 SubmodulesLoaded[GlobalIndex] = CurrentModule;
3368 case SUBMODULE_UMBRELLA_HEADER: {
3370 Error("missing submodule metadata record at beginning of block");
3377 StringRef FileName(BlobStart, BlobLen);
3378 if (const FileEntry *Umbrella = PP.getFileManager().getFile(FileName)) {
3379 if (!CurrentModule->getUmbrellaHeader())
3380 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
3381 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
3382 Error("mismatched umbrella headers in submodule");
3389 case SUBMODULE_HEADER: {
3391 Error("missing submodule metadata record at beginning of block");
3398 // FIXME: Be more lazy about this!
3399 StringRef FileName(BlobStart, BlobLen);
3400 if (const FileEntry *File = PP.getFileManager().getFile(FileName)) {
3401 if (std::find(CurrentModule->Headers.begin(),
3402 CurrentModule->Headers.end(),
3403 File) == CurrentModule->Headers.end())
3404 ModMap.addHeader(CurrentModule, File, false);
3409 case SUBMODULE_EXCLUDED_HEADER: {
3411 Error("missing submodule metadata record at beginning of block");
3418 // FIXME: Be more lazy about this!
3419 StringRef FileName(BlobStart, BlobLen);
3420 if (const FileEntry *File = PP.getFileManager().getFile(FileName)) {
3421 if (std::find(CurrentModule->Headers.begin(),
3422 CurrentModule->Headers.end(),
3423 File) == CurrentModule->Headers.end())
3424 ModMap.addHeader(CurrentModule, File, true);
3429 case SUBMODULE_TOPHEADER: {
3431 Error("missing submodule metadata record at beginning of block");
3438 // FIXME: Be more lazy about this!
3439 StringRef FileName(BlobStart, BlobLen);
3440 if (const FileEntry *File = PP.getFileManager().getFile(FileName))
3441 CurrentModule->TopHeaders.insert(File);
3445 case SUBMODULE_UMBRELLA_DIR: {
3447 Error("missing submodule metadata record at beginning of block");
3454 StringRef DirName(BlobStart, BlobLen);
3455 if (const DirectoryEntry *Umbrella
3456 = PP.getFileManager().getDirectory(DirName)) {
3457 if (!CurrentModule->getUmbrellaDir())
3458 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
3459 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
3460 Error("mismatched umbrella directories in submodule");
3467 case SUBMODULE_METADATA: {
3469 Error("submodule metadata record not at beginning of block");
3474 F.BaseSubmoduleID = getTotalNumSubmodules();
3475 F.LocalNumSubmodules = Record[0];
3476 unsigned LocalBaseSubmoduleID = Record[1];
3477 if (F.LocalNumSubmodules > 0) {
3478 // Introduce the global -> local mapping for submodules within this
3480 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
3482 // Introduce the local -> global mapping for submodules within this
3484 F.SubmoduleRemap.insertOrReplace(
3485 std::make_pair(LocalBaseSubmoduleID,
3486 F.BaseSubmoduleID - LocalBaseSubmoduleID));
3488 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
3493 case SUBMODULE_IMPORTS: {
3495 Error("missing submodule metadata record at beginning of block");
3502 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
3503 UnresolvedModuleImportExport Unresolved;
3504 Unresolved.File = &F;
3505 Unresolved.Mod = CurrentModule;
3506 Unresolved.ID = Record[Idx];
3507 Unresolved.IsImport = true;
3508 Unresolved.IsWildcard = false;
3509 UnresolvedModuleImportExports.push_back(Unresolved);
3514 case SUBMODULE_EXPORTS: {
3516 Error("missing submodule metadata record at beginning of block");
3523 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
3524 UnresolvedModuleImportExport Unresolved;
3525 Unresolved.File = &F;
3526 Unresolved.Mod = CurrentModule;
3527 Unresolved.ID = Record[Idx];
3528 Unresolved.IsImport = false;
3529 Unresolved.IsWildcard = Record[Idx + 1];
3530 UnresolvedModuleImportExports.push_back(Unresolved);
3533 // Once we've loaded the set of exports, there's no reason to keep
3534 // the parsed, unresolved exports around.
3535 CurrentModule->UnresolvedExports.clear();
3538 case SUBMODULE_REQUIRES: {
3540 Error("missing submodule metadata record at beginning of block");
3547 CurrentModule->addRequirement(StringRef(BlobStart, BlobLen),
3548 Context.getLangOpts(),
3549 Context.getTargetInfo());
3556 /// \brief Parse the record that corresponds to a LangOptions data
3559 /// This routine parses the language options from the AST file and then gives
3560 /// them to the AST listener if one is set.
3562 /// \returns true if the listener deems the file unacceptable, false otherwise.
3563 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
3565 ASTReaderListener &Listener) {
3566 LangOptions LangOpts;
3568 #define LANGOPT(Name, Bits, Default, Description) \
3569 LangOpts.Name = Record[Idx++];
3570 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
3571 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
3572 #include "clang/Basic/LangOptions.def"
3574 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
3575 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
3576 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
3578 unsigned Length = Record[Idx++];
3579 LangOpts.CurrentModule.assign(Record.begin() + Idx,
3580 Record.begin() + Idx + Length);
3581 return Listener.ReadLanguageOptions(LangOpts, Complain);
3584 bool ASTReader::ParseTargetOptions(const RecordData &Record,
3586 ASTReaderListener &Listener) {
3588 TargetOptions TargetOpts;
3589 TargetOpts.Triple = ReadString(Record, Idx);
3590 TargetOpts.CPU = ReadString(Record, Idx);
3591 TargetOpts.ABI = ReadString(Record, Idx);
3592 TargetOpts.CXXABI = ReadString(Record, Idx);
3593 TargetOpts.LinkerVersion = ReadString(Record, Idx);
3594 for (unsigned N = Record[Idx++]; N; --N) {
3595 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
3597 for (unsigned N = Record[Idx++]; N; --N) {
3598 TargetOpts.Features.push_back(ReadString(Record, Idx));
3601 return Listener.ReadTargetOptions(TargetOpts, Complain);
3604 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
3605 ASTReaderListener &Listener) {
3606 DiagnosticOptions DiagOpts;
3608 #define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
3609 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
3610 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
3611 #include "clang/Basic/DiagnosticOptions.def"
3613 for (unsigned N = Record[Idx++]; N; --N) {
3614 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
3617 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
3620 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
3621 ASTReaderListener &Listener) {
3622 FileSystemOptions FSOpts;
3624 FSOpts.WorkingDir = ReadString(Record, Idx);
3625 return Listener.ReadFileSystemOptions(FSOpts, Complain);
3628 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
3630 ASTReaderListener &Listener) {
3631 HeaderSearchOptions HSOpts;
3633 HSOpts.Sysroot = ReadString(Record, Idx);
3636 for (unsigned N = Record[Idx++]; N; --N) {
3637 std::string Path = ReadString(Record, Idx);
3638 frontend::IncludeDirGroup Group
3639 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
3640 bool IsUserSupplied = Record[Idx++];
3641 bool IsFramework = Record[Idx++];
3642 bool IgnoreSysRoot = Record[Idx++];
3643 bool IsInternal = Record[Idx++];
3644 bool ImplicitExternC = Record[Idx++];
3645 HSOpts.UserEntries.push_back(
3646 HeaderSearchOptions::Entry(Path, Group, IsUserSupplied, IsFramework,
3647 IgnoreSysRoot, IsInternal, ImplicitExternC));
3650 // System header prefixes.
3651 for (unsigned N = Record[Idx++]; N; --N) {
3652 std::string Prefix = ReadString(Record, Idx);
3653 bool IsSystemHeader = Record[Idx++];
3654 HSOpts.SystemHeaderPrefixes.push_back(
3655 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
3658 HSOpts.ResourceDir = ReadString(Record, Idx);
3659 HSOpts.ModuleCachePath = ReadString(Record, Idx);
3660 HSOpts.DisableModuleHash = Record[Idx++];
3661 HSOpts.UseBuiltinIncludes = Record[Idx++];
3662 HSOpts.UseStandardSystemIncludes = Record[Idx++];
3663 HSOpts.UseStandardCXXIncludes = Record[Idx++];
3664 HSOpts.UseLibcxx = Record[Idx++];
3666 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
3669 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
3671 ASTReaderListener &Listener,
3672 std::string &SuggestedPredefines) {
3673 PreprocessorOptions PPOpts;
3676 // Macro definitions/undefs
3677 for (unsigned N = Record[Idx++]; N; --N) {
3678 std::string Macro = ReadString(Record, Idx);
3679 bool IsUndef = Record[Idx++];
3680 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
3684 for (unsigned N = Record[Idx++]; N; --N) {
3685 PPOpts.Includes.push_back(ReadString(Record, Idx));
3689 for (unsigned N = Record[Idx++]; N; --N) {
3690 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
3693 PPOpts.UsePredefines = Record[Idx++];
3694 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
3695 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
3696 PPOpts.ObjCXXARCStandardLibrary =
3697 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
3698 SuggestedPredefines.clear();
3699 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
3700 SuggestedPredefines);
3703 std::pair<ModuleFile *, unsigned>
3704 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
3705 GlobalPreprocessedEntityMapType::iterator
3706 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
3707 assert(I != GlobalPreprocessedEntityMap.end() &&
3708 "Corrupted global preprocessed entity map");
3709 ModuleFile *M = I->second;
3710 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
3711 return std::make_pair(M, LocalIndex);
3714 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
3715 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
3716 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
3717 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
3718 Mod.NumPreprocessedEntities);
3720 return std::make_pair(PreprocessingRecord::iterator(),
3721 PreprocessingRecord::iterator());
3724 std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
3725 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
3726 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
3727 ModuleDeclIterator(this, &Mod,
3728 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
3731 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
3732 PreprocessedEntityID PPID = Index+1;
3733 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
3734 ModuleFile &M = *PPInfo.first;
3735 unsigned LocalIndex = PPInfo.second;
3736 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
3738 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
3739 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
3741 unsigned Code = M.PreprocessorDetailCursor.ReadCode();
3743 case llvm::bitc::END_BLOCK:
3746 case llvm::bitc::ENTER_SUBBLOCK:
3747 Error("unexpected subblock record in preprocessor detail block");
3750 case llvm::bitc::DEFINE_ABBREV:
3751 Error("unexpected abbrevation record in preprocessor detail block");
3758 if (!PP.getPreprocessingRecord()) {
3759 Error("no preprocessing record");
3764 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
3765 ReadSourceLocation(M, PPOffs.End));
3766 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
3767 const char *BlobStart = 0;
3768 unsigned BlobLen = 0;
3770 PreprocessorDetailRecordTypes RecType =
3771 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.ReadRecord(
3772 Code, Record, BlobStart, BlobLen);
3774 case PPD_MACRO_EXPANSION: {
3775 bool isBuiltin = Record[0];
3776 IdentifierInfo *Name = 0;
3777 MacroDefinition *Def = 0;
3779 Name = getLocalIdentifier(M, Record[1]);
3781 PreprocessedEntityID
3782 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
3783 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
3788 ME = new (PPRec) MacroExpansion(Name, Range);
3790 ME = new (PPRec) MacroExpansion(Def, Range);
3795 case PPD_MACRO_DEFINITION: {
3796 // Decode the identifier info and then check again; if the macro is
3797 // still defined and associated with the identifier,
3798 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
3800 = new (PPRec) MacroDefinition(II, Range);
3802 if (DeserializationListener)
3803 DeserializationListener->MacroDefinitionRead(PPID, MD);
3808 case PPD_INCLUSION_DIRECTIVE: {
3809 const char *FullFileNameStart = BlobStart + Record[0];
3810 StringRef FullFileName(FullFileNameStart, BlobLen - Record[0]);
3811 const FileEntry *File = 0;
3812 if (!FullFileName.empty())
3813 File = PP.getFileManager().getFile(FullFileName);
3815 // FIXME: Stable encoding
3816 InclusionDirective::InclusionKind Kind
3817 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
3818 InclusionDirective *ID
3819 = new (PPRec) InclusionDirective(PPRec, Kind,
3820 StringRef(BlobStart, Record[0]),
3821 Record[1], Record[3],
3828 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
3831 /// \brief \arg SLocMapI points at a chunk of a module that contains no
3832 /// preprocessed entities or the entities it contains are not the ones we are
3833 /// looking for. Find the next module that contains entities and return the ID
3834 /// of the first entry.
3835 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
3836 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
3838 for (GlobalSLocOffsetMapType::const_iterator
3839 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
3840 ModuleFile &M = *SLocMapI->second;
3841 if (M.NumPreprocessedEntities)
3842 return M.BasePreprocessedEntityID;
3845 return getTotalNumPreprocessedEntities();
3850 template <unsigned PPEntityOffset::*PPLoc>
3851 struct PPEntityComp {
3852 const ASTReader &Reader;
3855 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
3857 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
3858 SourceLocation LHS = getLoc(L);
3859 SourceLocation RHS = getLoc(R);
3860 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
3863 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
3864 SourceLocation LHS = getLoc(L);
3865 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
3868 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
3869 SourceLocation RHS = getLoc(R);
3870 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
3873 SourceLocation getLoc(const PPEntityOffset &PPE) const {
3874 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
3880 /// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
3881 PreprocessedEntityID
3882 ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
3883 if (SourceMgr.isLocalSourceLocation(BLoc))
3884 return getTotalNumPreprocessedEntities();
3886 GlobalSLocOffsetMapType::const_iterator
3887 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
3889 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
3890 "Corrupted global sloc offset map");
3892 if (SLocMapI->second->NumPreprocessedEntities == 0)
3893 return findNextPreprocessedEntity(SLocMapI);
3895 ModuleFile &M = *SLocMapI->second;
3896 typedef const PPEntityOffset *pp_iterator;
3897 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
3898 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
3900 size_t Count = M.NumPreprocessedEntities;
3902 pp_iterator First = pp_begin;
3905 // Do a binary search manually instead of using std::lower_bound because
3906 // The end locations of entities may be unordered (when a macro expansion
3907 // is inside another macro argument), but for this case it is not important
3908 // whether we get the first macro expansion or its containing macro.
3912 std::advance(PPI, Half);
3913 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
3917 Count = Count - Half - 1;
3923 return findNextPreprocessedEntity(SLocMapI);
3925 return M.BasePreprocessedEntityID + (PPI - pp_begin);
3928 /// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
3929 PreprocessedEntityID
3930 ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
3931 if (SourceMgr.isLocalSourceLocation(ELoc))
3932 return getTotalNumPreprocessedEntities();
3934 GlobalSLocOffsetMapType::const_iterator
3935 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
3937 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
3938 "Corrupted global sloc offset map");
3940 if (SLocMapI->second->NumPreprocessedEntities == 0)
3941 return findNextPreprocessedEntity(SLocMapI);
3943 ModuleFile &M = *SLocMapI->second;
3944 typedef const PPEntityOffset *pp_iterator;
3945 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
3946 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
3948 std::upper_bound(pp_begin, pp_end, ELoc,
3949 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
3952 return findNextPreprocessedEntity(SLocMapI);
3954 return M.BasePreprocessedEntityID + (PPI - pp_begin);
3957 /// \brief Returns a pair of [Begin, End) indices of preallocated
3958 /// preprocessed entities that \arg Range encompasses.
3959 std::pair<unsigned, unsigned>
3960 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
3961 if (Range.isInvalid())
3962 return std::make_pair(0,0);
3963 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
3965 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
3966 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
3967 return std::make_pair(BeginID, EndID);
3970 /// \brief Optionally returns true or false if the preallocated preprocessed
3971 /// entity with index \arg Index came from file \arg FID.
3972 llvm::Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
3974 if (FID.isInvalid())
3977 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
3978 ModuleFile &M = *PPInfo.first;
3979 unsigned LocalIndex = PPInfo.second;
3980 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
3982 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
3983 if (Loc.isInvalid())
3986 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
3993 /// \brief Visitor used to search for information about a header file.
3994 class HeaderFileInfoVisitor {
3996 const FileEntry *FE;
3998 llvm::Optional<HeaderFileInfo> HFI;
4001 HeaderFileInfoVisitor(ASTReader &Reader, const FileEntry *FE)
4002 : Reader(Reader), FE(FE) { }
4004 static bool visit(ModuleFile &M, void *UserData) {
4005 HeaderFileInfoVisitor *This
4006 = static_cast<HeaderFileInfoVisitor *>(UserData);
4008 HeaderFileInfoTrait Trait(This->Reader, M,
4009 &This->Reader.getPreprocessor().getHeaderSearchInfo(),
4010 M.HeaderFileFrameworkStrings,
4011 This->FE->getName());
4013 HeaderFileInfoLookupTable *Table
4014 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4018 // Look in the on-disk hash table for an entry for this file name.
4019 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE->getName(),
4021 if (Pos == Table->end())
4028 llvm::Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
4032 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
4033 HeaderFileInfoVisitor Visitor(*this, FE);
4034 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
4035 if (llvm::Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) {
4037 Listener->ReadHeaderFileInfo(*HFI, FE->getUID());
4041 return HeaderFileInfo();
4044 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4045 // FIXME: Make it work properly with modules.
4046 llvm::SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
4047 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4048 ModuleFile &F = *(*I);
4051 assert(!Diag.DiagStates.empty());
4052 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4053 while (Idx < F.PragmaDiagMappings.size()) {
4054 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4055 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4056 if (DiagStateID != 0) {
4057 Diag.DiagStatePoints.push_back(
4058 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4059 FullSourceLoc(Loc, SourceMgr)));
4063 assert(DiagStateID == 0);
4064 // A new DiagState was created here.
4065 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4066 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4067 DiagStates.push_back(NewState);
4068 Diag.DiagStatePoints.push_back(
4069 DiagnosticsEngine::DiagStatePoint(NewState,
4070 FullSourceLoc(Loc, SourceMgr)));
4072 assert(Idx < F.PragmaDiagMappings.size() &&
4073 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4074 if (Idx >= F.PragmaDiagMappings.size()) {
4075 break; // Something is messed up but at least avoid infinite loop in
4078 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4079 if (DiagID == (unsigned)-1) {
4080 break; // no more diag/map pairs for this location.
4082 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4083 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4084 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4090 /// \brief Get the correct cursor and offset for loading a type.
4091 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4092 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4093 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4094 ModuleFile *M = I->second;
4095 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4098 /// \brief Read and return the type with the given index..
4100 /// The index is the type ID, shifted and minus the number of predefs. This
4101 /// routine actually reads the record corresponding to the type at the given
4102 /// location. It is a helper routine for GetType, which deals with reading type
4104 QualType ASTReader::readTypeRecord(unsigned Index) {
4105 RecordLocation Loc = TypeCursorForIndex(Index);
4106 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
4108 // Keep track of where we are in the stream, then jump back there
4109 // after reading this type.
4110 SavedStreamPosition SavedPosition(DeclsCursor);
4112 ReadingKindTracker ReadingKind(Read_Type, *this);
4114 // Note that we are loading a type record.
4115 Deserializing AType(this);
4118 DeclsCursor.JumpToBit(Loc.Offset);
4120 unsigned Code = DeclsCursor.ReadCode();
4121 switch ((TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
4122 case TYPE_EXT_QUAL: {
4123 if (Record.size() != 2) {
4124 Error("Incorrect encoding of extended qualifier type");
4127 QualType Base = readType(*Loc.F, Record, Idx);
4128 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4129 return Context.getQualifiedType(Base, Quals);
4132 case TYPE_COMPLEX: {
4133 if (Record.size() != 1) {
4134 Error("Incorrect encoding of complex type");
4137 QualType ElemType = readType(*Loc.F, Record, Idx);
4138 return Context.getComplexType(ElemType);
4141 case TYPE_POINTER: {
4142 if (Record.size() != 1) {
4143 Error("Incorrect encoding of pointer type");
4146 QualType PointeeType = readType(*Loc.F, Record, Idx);
4147 return Context.getPointerType(PointeeType);
4150 case TYPE_BLOCK_POINTER: {
4151 if (Record.size() != 1) {
4152 Error("Incorrect encoding of block pointer type");
4155 QualType PointeeType = readType(*Loc.F, Record, Idx);
4156 return Context.getBlockPointerType(PointeeType);
4159 case TYPE_LVALUE_REFERENCE: {
4160 if (Record.size() != 2) {
4161 Error("Incorrect encoding of lvalue reference type");
4164 QualType PointeeType = readType(*Loc.F, Record, Idx);
4165 return Context.getLValueReferenceType(PointeeType, Record[1]);
4168 case TYPE_RVALUE_REFERENCE: {
4169 if (Record.size() != 1) {
4170 Error("Incorrect encoding of rvalue reference type");
4173 QualType PointeeType = readType(*Loc.F, Record, Idx);
4174 return Context.getRValueReferenceType(PointeeType);
4177 case TYPE_MEMBER_POINTER: {
4178 if (Record.size() != 2) {
4179 Error("Incorrect encoding of member pointer type");
4182 QualType PointeeType = readType(*Loc.F, Record, Idx);
4183 QualType ClassType = readType(*Loc.F, Record, Idx);
4184 if (PointeeType.isNull() || ClassType.isNull())
4187 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4190 case TYPE_CONSTANT_ARRAY: {
4191 QualType ElementType = readType(*Loc.F, Record, Idx);
4192 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4193 unsigned IndexTypeQuals = Record[2];
4195 llvm::APInt Size = ReadAPInt(Record, Idx);
4196 return Context.getConstantArrayType(ElementType, Size,
4197 ASM, IndexTypeQuals);
4200 case TYPE_INCOMPLETE_ARRAY: {
4201 QualType ElementType = readType(*Loc.F, Record, Idx);
4202 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4203 unsigned IndexTypeQuals = Record[2];
4204 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4207 case TYPE_VARIABLE_ARRAY: {
4208 QualType ElementType = readType(*Loc.F, Record, Idx);
4209 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4210 unsigned IndexTypeQuals = Record[2];
4211 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4212 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
4213 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
4214 ASM, IndexTypeQuals,
4215 SourceRange(LBLoc, RBLoc));
4219 if (Record.size() != 3) {
4220 Error("incorrect encoding of vector type in AST file");
4224 QualType ElementType = readType(*Loc.F, Record, Idx);
4225 unsigned NumElements = Record[1];
4226 unsigned VecKind = Record[2];
4227 return Context.getVectorType(ElementType, NumElements,
4228 (VectorType::VectorKind)VecKind);
4231 case TYPE_EXT_VECTOR: {
4232 if (Record.size() != 3) {
4233 Error("incorrect encoding of extended vector type in AST file");
4237 QualType ElementType = readType(*Loc.F, Record, Idx);
4238 unsigned NumElements = Record[1];
4239 return Context.getExtVectorType(ElementType, NumElements);
4242 case TYPE_FUNCTION_NO_PROTO: {
4243 if (Record.size() != 6) {
4244 Error("incorrect encoding of no-proto function type");
4247 QualType ResultType = readType(*Loc.F, Record, Idx);
4248 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
4249 (CallingConv)Record[4], Record[5]);
4250 return Context.getFunctionNoProtoType(ResultType, Info);
4253 case TYPE_FUNCTION_PROTO: {
4254 QualType ResultType = readType(*Loc.F, Record, Idx);
4256 FunctionProtoType::ExtProtoInfo EPI;
4257 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
4258 /*hasregparm*/ Record[2],
4259 /*regparm*/ Record[3],
4260 static_cast<CallingConv>(Record[4]),
4261 /*produces*/ Record[5]);
4264 unsigned NumParams = Record[Idx++];
4265 SmallVector<QualType, 16> ParamTypes;
4266 for (unsigned I = 0; I != NumParams; ++I)
4267 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
4269 EPI.Variadic = Record[Idx++];
4270 EPI.HasTrailingReturn = Record[Idx++];
4271 EPI.TypeQuals = Record[Idx++];
4272 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
4273 ExceptionSpecificationType EST =
4274 static_cast<ExceptionSpecificationType>(Record[Idx++]);
4275 EPI.ExceptionSpecType = EST;
4276 SmallVector<QualType, 2> Exceptions;
4277 if (EST == EST_Dynamic) {
4278 EPI.NumExceptions = Record[Idx++];
4279 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
4280 Exceptions.push_back(readType(*Loc.F, Record, Idx));
4281 EPI.Exceptions = Exceptions.data();
4282 } else if (EST == EST_ComputedNoexcept) {
4283 EPI.NoexceptExpr = ReadExpr(*Loc.F);
4284 } else if (EST == EST_Uninstantiated) {
4285 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4286 EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4287 } else if (EST == EST_Unevaluated) {
4288 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4290 return Context.getFunctionType(ResultType, ParamTypes.data(), NumParams,
4294 case TYPE_UNRESOLVED_USING: {
4296 return Context.getTypeDeclType(
4297 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
4300 case TYPE_TYPEDEF: {
4301 if (Record.size() != 2) {
4302 Error("incorrect encoding of typedef type");
4306 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
4307 QualType Canonical = readType(*Loc.F, Record, Idx);
4308 if (!Canonical.isNull())
4309 Canonical = Context.getCanonicalType(Canonical);
4310 return Context.getTypedefType(Decl, Canonical);
4313 case TYPE_TYPEOF_EXPR:
4314 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
4317 if (Record.size() != 1) {
4318 Error("incorrect encoding of typeof(type) in AST file");
4321 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4322 return Context.getTypeOfType(UnderlyingType);
4325 case TYPE_DECLTYPE: {
4326 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4327 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
4330 case TYPE_UNARY_TRANSFORM: {
4331 QualType BaseType = readType(*Loc.F, Record, Idx);
4332 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4333 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
4334 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
4338 return Context.getAutoType(readType(*Loc.F, Record, Idx));
4341 if (Record.size() != 2) {
4342 Error("incorrect encoding of record type");
4346 bool IsDependent = Record[Idx++];
4347 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
4348 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
4349 QualType T = Context.getRecordType(RD);
4350 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4355 if (Record.size() != 2) {
4356 Error("incorrect encoding of enum type");
4360 bool IsDependent = Record[Idx++];
4362 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
4363 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4367 case TYPE_ATTRIBUTED: {
4368 if (Record.size() != 3) {
4369 Error("incorrect encoding of attributed type");
4372 QualType modifiedType = readType(*Loc.F, Record, Idx);
4373 QualType equivalentType = readType(*Loc.F, Record, Idx);
4374 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
4375 return Context.getAttributedType(kind, modifiedType, equivalentType);
4379 if (Record.size() != 1) {
4380 Error("incorrect encoding of paren type");
4383 QualType InnerType = readType(*Loc.F, Record, Idx);
4384 return Context.getParenType(InnerType);
4387 case TYPE_PACK_EXPANSION: {
4388 if (Record.size() != 2) {
4389 Error("incorrect encoding of pack expansion type");
4392 QualType Pattern = readType(*Loc.F, Record, Idx);
4393 if (Pattern.isNull())
4395 llvm::Optional<unsigned> NumExpansions;
4397 NumExpansions = Record[1] - 1;
4398 return Context.getPackExpansionType(Pattern, NumExpansions);
4401 case TYPE_ELABORATED: {
4403 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4404 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4405 QualType NamedType = readType(*Loc.F, Record, Idx);
4406 return Context.getElaboratedType(Keyword, NNS, NamedType);
4409 case TYPE_OBJC_INTERFACE: {
4411 ObjCInterfaceDecl *ItfD
4412 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
4413 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
4416 case TYPE_OBJC_OBJECT: {
4418 QualType Base = readType(*Loc.F, Record, Idx);
4419 unsigned NumProtos = Record[Idx++];
4420 SmallVector<ObjCProtocolDecl*, 4> Protos;
4421 for (unsigned I = 0; I != NumProtos; ++I)
4422 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
4423 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
4426 case TYPE_OBJC_OBJECT_POINTER: {
4428 QualType Pointee = readType(*Loc.F, Record, Idx);
4429 return Context.getObjCObjectPointerType(Pointee);
4432 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
4434 QualType Parm = readType(*Loc.F, Record, Idx);
4435 QualType Replacement = readType(*Loc.F, Record, Idx);
4437 Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
4441 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
4443 QualType Parm = readType(*Loc.F, Record, Idx);
4444 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
4445 return Context.getSubstTemplateTypeParmPackType(
4446 cast<TemplateTypeParmType>(Parm),
4450 case TYPE_INJECTED_CLASS_NAME: {
4451 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
4452 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
4453 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
4454 // for AST reading, too much interdependencies.
4456 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
4459 case TYPE_TEMPLATE_TYPE_PARM: {
4461 unsigned Depth = Record[Idx++];
4462 unsigned Index = Record[Idx++];
4463 bool Pack = Record[Idx++];
4464 TemplateTypeParmDecl *D
4465 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
4466 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
4469 case TYPE_DEPENDENT_NAME: {
4471 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4472 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4473 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4474 QualType Canon = readType(*Loc.F, Record, Idx);
4475 if (!Canon.isNull())
4476 Canon = Context.getCanonicalType(Canon);
4477 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
4480 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
4482 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4483 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4484 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4485 unsigned NumArgs = Record[Idx++];
4486 SmallVector<TemplateArgument, 8> Args;
4487 Args.reserve(NumArgs);
4489 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
4490 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
4491 Args.size(), Args.data());
4494 case TYPE_DEPENDENT_SIZED_ARRAY: {
4498 QualType ElementType = readType(*Loc.F, Record, Idx);
4499 ArrayType::ArraySizeModifier ASM
4500 = (ArrayType::ArraySizeModifier)Record[Idx++];
4501 unsigned IndexTypeQuals = Record[Idx++];
4503 // DependentSizedArrayType
4504 Expr *NumElts = ReadExpr(*Loc.F);
4505 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
4507 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
4508 IndexTypeQuals, Brackets);
4511 case TYPE_TEMPLATE_SPECIALIZATION: {
4513 bool IsDependent = Record[Idx++];
4514 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
4515 SmallVector<TemplateArgument, 8> Args;
4516 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
4517 QualType Underlying = readType(*Loc.F, Record, Idx);
4519 if (Underlying.isNull())
4520 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
4523 T = Context.getTemplateSpecializationType(Name, Args.data(),
4524 Args.size(), Underlying);
4525 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4530 if (Record.size() != 1) {
4531 Error("Incorrect encoding of atomic type");
4534 QualType ValueType = readType(*Loc.F, Record, Idx);
4535 return Context.getAtomicType(ValueType);
4538 llvm_unreachable("Invalid TypeCode!");
4541 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
4544 const ASTReader::RecordData &Record;
4547 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
4549 return Reader.ReadSourceLocation(F, R, I);
4552 template<typename T>
4553 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
4554 return Reader.ReadDeclAs<T>(F, Record, Idx);
4558 TypeLocReader(ASTReader &Reader, ModuleFile &F,
4559 const ASTReader::RecordData &Record, unsigned &Idx)
4560 : Reader(Reader), F(F), Record(Record), Idx(Idx)
4563 // We want compile-time assurance that we've enumerated all of
4564 // these, so unfortunately we have to declare them first, then
4565 // define them out-of-line.
4566 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4567 #define TYPELOC(CLASS, PARENT) \
4568 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
4569 #include "clang/AST/TypeLocNodes.def"
4571 void VisitFunctionTypeLoc(FunctionTypeLoc);
4572 void VisitArrayTypeLoc(ArrayTypeLoc);
4575 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4578 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4579 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
4580 if (TL.needsExtraLocalData()) {
4581 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
4582 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
4583 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
4584 TL.setModeAttr(Record[Idx++]);
4587 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
4588 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4590 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
4591 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4593 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
4594 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
4596 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
4597 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
4599 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
4600 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
4602 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
4603 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4604 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4606 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
4607 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
4608 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
4610 TL.setSizeExpr(Reader.ReadExpr(F));
4614 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
4615 VisitArrayTypeLoc(TL);
4617 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
4618 VisitArrayTypeLoc(TL);
4620 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
4621 VisitArrayTypeLoc(TL);
4623 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
4624 DependentSizedArrayTypeLoc TL) {
4625 VisitArrayTypeLoc(TL);
4627 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
4628 DependentSizedExtVectorTypeLoc TL) {
4629 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4631 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
4632 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4634 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
4635 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4637 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
4638 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
4639 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4640 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4641 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
4642 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
4643 TL.setArg(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
4646 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
4647 VisitFunctionTypeLoc(TL);
4649 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
4650 VisitFunctionTypeLoc(TL);
4652 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
4653 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4655 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
4656 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4658 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
4659 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
4660 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4661 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4663 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
4664 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
4665 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4666 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4667 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4669 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
4670 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4672 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
4673 TL.setKWLoc(ReadSourceLocation(Record, Idx));
4674 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4675 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4676 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4678 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
4679 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4681 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
4682 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4684 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
4685 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4687 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4688 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
4689 if (TL.hasAttrOperand()) {
4691 range.setBegin(ReadSourceLocation(Record, Idx));
4692 range.setEnd(ReadSourceLocation(Record, Idx));
4693 TL.setAttrOperandParensRange(range);
4695 if (TL.hasAttrExprOperand()) {
4697 TL.setAttrExprOperand(Reader.ReadExpr(F));
4699 TL.setAttrExprOperand(0);
4700 } else if (TL.hasAttrEnumOperand())
4701 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
4703 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
4704 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4706 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
4707 SubstTemplateTypeParmTypeLoc TL) {
4708 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4710 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
4711 SubstTemplateTypeParmPackTypeLoc TL) {
4712 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4714 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
4715 TemplateSpecializationTypeLoc TL) {
4716 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
4717 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
4718 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
4719 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
4720 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4722 Reader.GetTemplateArgumentLocInfo(F,
4723 TL.getTypePtr()->getArg(i).getKind(),
4726 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
4727 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4728 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4730 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
4731 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
4732 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
4734 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
4735 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4737 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
4738 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
4739 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
4740 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4742 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
4743 DependentTemplateSpecializationTypeLoc TL) {
4744 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
4745 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
4746 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
4747 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
4748 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
4749 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
4750 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
4752 Reader.GetTemplateArgumentLocInfo(F,
4753 TL.getTypePtr()->getArg(I).getKind(),
4756 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
4757 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
4759 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
4760 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4762 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
4763 TL.setHasBaseTypeAsWritten(Record[Idx++]);
4764 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
4765 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
4766 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
4767 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
4769 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4770 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4772 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
4773 TL.setKWLoc(ReadSourceLocation(Record, Idx));
4774 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4775 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4778 TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
4779 const RecordData &Record,
4781 QualType InfoTy = readType(F, Record, Idx);
4782 if (InfoTy.isNull())
4785 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
4786 TypeLocReader TLR(*this, F, Record, Idx);
4787 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
4792 QualType ASTReader::GetType(TypeID ID) {
4793 unsigned FastQuals = ID & Qualifiers::FastMask;
4794 unsigned Index = ID >> Qualifiers::FastWidth;
4796 if (Index < NUM_PREDEF_TYPE_IDS) {
4798 switch ((PredefinedTypeIDs)Index) {
4799 case PREDEF_TYPE_NULL_ID: return QualType();
4800 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
4801 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
4803 case PREDEF_TYPE_CHAR_U_ID:
4804 case PREDEF_TYPE_CHAR_S_ID:
4805 // FIXME: Check that the signedness of CharTy is correct!
4809 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
4810 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
4811 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
4812 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
4813 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
4814 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
4815 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
4816 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
4817 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
4818 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
4819 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
4820 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
4821 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
4822 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
4823 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
4824 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
4825 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
4826 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
4827 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
4828 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
4829 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
4830 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
4831 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
4832 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
4833 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
4834 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
4835 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
4836 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
4837 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
4839 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
4840 T = Context.getAutoRRefDeductType();
4843 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
4844 T = Context.ARCUnbridgedCastTy;
4847 case PREDEF_TYPE_VA_LIST_TAG:
4848 T = Context.getVaListTagType();
4851 case PREDEF_TYPE_BUILTIN_FN:
4852 T = Context.BuiltinFnTy;
4856 assert(!T.isNull() && "Unknown predefined type");
4857 return T.withFastQualifiers(FastQuals);
4860 Index -= NUM_PREDEF_TYPE_IDS;
4861 assert(Index < TypesLoaded.size() && "Type index out-of-range");
4862 if (TypesLoaded[Index].isNull()) {
4863 TypesLoaded[Index] = readTypeRecord(Index);
4864 if (TypesLoaded[Index].isNull())
4867 TypesLoaded[Index]->setFromAST();
4868 if (DeserializationListener)
4869 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
4870 TypesLoaded[Index]);
4873 return TypesLoaded[Index].withFastQualifiers(FastQuals);
4876 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
4877 return GetType(getGlobalTypeID(F, LocalID));
4880 serialization::TypeID
4881 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
4882 unsigned FastQuals = LocalID & Qualifiers::FastMask;
4883 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
4885 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
4888 ContinuousRangeMap<uint32_t, int, 2>::iterator I
4889 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
4890 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
4892 unsigned GlobalIndex = LocalIndex + I->second;
4893 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
4896 TemplateArgumentLocInfo
4897 ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
4898 TemplateArgument::ArgKind Kind,
4899 const RecordData &Record,
4902 case TemplateArgument::Expression:
4904 case TemplateArgument::Type:
4905 return GetTypeSourceInfo(F, Record, Index);
4906 case TemplateArgument::Template: {
4907 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
4909 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
4910 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
4913 case TemplateArgument::TemplateExpansion: {
4914 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
4916 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
4917 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
4918 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
4921 case TemplateArgument::Null:
4922 case TemplateArgument::Integral:
4923 case TemplateArgument::Declaration:
4924 case TemplateArgument::NullPtr:
4925 case TemplateArgument::Pack:
4926 // FIXME: Is this right?
4927 return TemplateArgumentLocInfo();
4929 llvm_unreachable("unexpected template argument loc");
4933 ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
4934 const RecordData &Record, unsigned &Index) {
4935 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
4937 if (Arg.getKind() == TemplateArgument::Expression) {
4938 if (Record[Index++]) // bool InfoHasSameExpr.
4939 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
4941 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
4945 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
4949 uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
4951 if (Idx >= Record.size())
4954 unsigned LocalID = Record[Idx++];
4955 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
4958 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
4959 RecordLocation Loc = getLocalBitOffset(Offset);
4960 llvm::BitstreamCursor &Cursor = Loc.F->DeclsCursor;
4961 SavedStreamPosition SavedPosition(Cursor);
4962 Cursor.JumpToBit(Loc.Offset);
4963 ReadingKindTracker ReadingKind(Read_Decl, *this);
4965 unsigned Code = Cursor.ReadCode();
4966 unsigned RecCode = Cursor.ReadRecord(Code, Record);
4967 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
4968 Error("Malformed AST file: missing C++ base specifiers");
4973 unsigned NumBases = Record[Idx++];
4974 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
4975 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
4976 for (unsigned I = 0; I != NumBases; ++I)
4977 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
4981 serialization::DeclID
4982 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
4983 if (LocalID < NUM_PREDEF_DECL_IDS)
4986 ContinuousRangeMap<uint32_t, int, 2>::iterator I
4987 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
4988 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
4990 return LocalID + I->second;
4993 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
4994 ModuleFile &M) const {
4995 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
4996 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
4997 return &M == I->second;
5000 ModuleFile *ASTReader::getOwningModuleFile(Decl *D) {
5001 if (!D->isFromASTFile())
5003 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5004 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5008 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5009 if (ID < NUM_PREDEF_DECL_IDS)
5010 return SourceLocation();
5012 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5014 if (Index > DeclsLoaded.size()) {
5015 Error("declaration ID out-of-range for AST file");
5016 return SourceLocation();
5019 if (Decl *D = DeclsLoaded[Index])
5020 return D->getLocation();
5022 unsigned RawLocation = 0;
5023 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5024 return ReadSourceLocation(*Rec.F, RawLocation);
5027 Decl *ASTReader::GetDecl(DeclID ID) {
5028 if (ID < NUM_PREDEF_DECL_IDS) {
5029 switch ((PredefinedDeclIDs)ID) {
5030 case PREDEF_DECL_NULL_ID:
5033 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5034 return Context.getTranslationUnitDecl();
5036 case PREDEF_DECL_OBJC_ID_ID:
5037 return Context.getObjCIdDecl();
5039 case PREDEF_DECL_OBJC_SEL_ID:
5040 return Context.getObjCSelDecl();
5042 case PREDEF_DECL_OBJC_CLASS_ID:
5043 return Context.getObjCClassDecl();
5045 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5046 return Context.getObjCProtocolDecl();
5048 case PREDEF_DECL_INT_128_ID:
5049 return Context.getInt128Decl();
5051 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5052 return Context.getUInt128Decl();
5054 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5055 return Context.getObjCInstanceTypeDecl();
5057 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5058 return Context.getBuiltinVaListDecl();
5062 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5064 if (Index >= DeclsLoaded.size()) {
5065 assert(0 && "declaration ID out-of-range for AST file");
5066 Error("declaration ID out-of-range for AST file");
5070 if (!DeclsLoaded[Index]) {
5072 if (DeserializationListener)
5073 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5076 return DeclsLoaded[Index];
5079 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5081 if (GlobalID < NUM_PREDEF_DECL_IDS)
5084 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5085 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5086 ModuleFile *Owner = I->second;
5088 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5089 = M.GlobalToLocalDeclIDs.find(Owner);
5090 if (Pos == M.GlobalToLocalDeclIDs.end())
5093 return GlobalID - Owner->BaseDeclID + Pos->second;
5096 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5097 const RecordData &Record,
5099 if (Idx >= Record.size()) {
5100 Error("Corrupted AST file");
5104 return getGlobalDeclID(F, Record[Idx++]);
5107 /// \brief Resolve the offset of a statement into a statement.
5109 /// This operation will read a new statement from the external
5110 /// source each time it is called, and is meant to be used via a
5111 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5112 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5113 // Switch case IDs are per Decl.
5114 ClearSwitchCaseIDs();
5116 // Offset here is a global offset across the entire chain.
5117 RecordLocation Loc = getLocalBitOffset(Offset);
5118 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5119 return ReadStmtFromStream(*Loc.F);
5123 class FindExternalLexicalDeclsVisitor {
5125 const DeclContext *DC;
5126 bool (*isKindWeWant)(Decl::Kind);
5128 SmallVectorImpl<Decl*> &Decls;
5129 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5132 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5133 bool (*isKindWeWant)(Decl::Kind),
5134 SmallVectorImpl<Decl*> &Decls)
5135 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5137 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5138 PredefsVisited[I] = false;
5141 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5145 FindExternalLexicalDeclsVisitor *This
5146 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5148 ModuleFile::DeclContextInfosMap::iterator Info
5149 = M.DeclContextInfos.find(This->DC);
5150 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5153 // Load all of the declaration IDs
5154 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5155 *IDE = ID + Info->second.NumLexicalDecls;
5157 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5160 // Don't add predefined declarations to the lexical context more
5162 if (ID->second < NUM_PREDEF_DECL_IDS) {
5163 if (This->PredefsVisited[ID->second])
5166 This->PredefsVisited[ID->second] = true;
5169 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5170 if (!This->DC->isDeclInLexicalTraversal(D))
5171 This->Decls.push_back(D);
5180 ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
5181 bool (*isKindWeWant)(Decl::Kind),
5182 SmallVectorImpl<Decl*> &Decls) {
5183 // There might be lexical decls in multiple modules, for the TU at
5184 // least. Walk all of the modules in the order they were loaded.
5185 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5186 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
5187 ++NumLexicalDeclContextsRead;
5198 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
5200 bool operator()(LocalDeclID L, LocalDeclID R) const {
5201 SourceLocation LHS = getLocation(L);
5202 SourceLocation RHS = getLocation(R);
5203 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5206 bool operator()(SourceLocation LHS, LocalDeclID R) const {
5207 SourceLocation RHS = getLocation(R);
5208 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5211 bool operator()(LocalDeclID L, SourceLocation RHS) const {
5212 SourceLocation LHS = getLocation(L);
5213 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5216 SourceLocation getLocation(LocalDeclID ID) const {
5217 return Reader.getSourceManager().getFileLoc(
5218 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
5224 void ASTReader::FindFileRegionDecls(FileID File,
5225 unsigned Offset, unsigned Length,
5226 SmallVectorImpl<Decl *> &Decls) {
5227 SourceManager &SM = getSourceManager();
5229 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
5230 if (I == FileDeclIDs.end())
5233 FileDeclsInfo &DInfo = I->second;
5234 if (DInfo.Decls.empty())
5238 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
5239 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
5241 DeclIDComp DIDComp(*this, *DInfo.Mod);
5242 ArrayRef<serialization::LocalDeclID>::iterator
5243 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5245 if (BeginIt != DInfo.Decls.begin())
5248 // If we are pointing at a top-level decl inside an objc container, we need
5249 // to backtrack until we find it otherwise we will fail to report that the
5250 // region overlaps with an objc container.
5251 while (BeginIt != DInfo.Decls.begin() &&
5252 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
5253 ->isTopLevelDeclInObjCContainer())
5256 ArrayRef<serialization::LocalDeclID>::iterator
5257 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5259 if (EndIt != DInfo.Decls.end())
5262 for (ArrayRef<serialization::LocalDeclID>::iterator
5263 DIt = BeginIt; DIt != EndIt; ++DIt)
5264 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
5268 /// \brief ModuleFile visitor used to perform name lookup into a
5269 /// declaration context.
5270 class DeclContextNameLookupVisitor {
5272 llvm::SmallVectorImpl<const DeclContext *> &Contexts;
5273 DeclarationName Name;
5274 SmallVectorImpl<NamedDecl *> &Decls;
5277 DeclContextNameLookupVisitor(ASTReader &Reader,
5278 SmallVectorImpl<const DeclContext *> &Contexts,
5279 DeclarationName Name,
5280 SmallVectorImpl<NamedDecl *> &Decls)
5281 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
5283 static bool visit(ModuleFile &M, void *UserData) {
5284 DeclContextNameLookupVisitor *This
5285 = static_cast<DeclContextNameLookupVisitor *>(UserData);
5287 // Check whether we have any visible declaration information for
5288 // this context in this module.
5289 ModuleFile::DeclContextInfosMap::iterator Info;
5290 bool FoundInfo = false;
5291 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5292 Info = M.DeclContextInfos.find(This->Contexts[I]);
5293 if (Info != M.DeclContextInfos.end() &&
5294 Info->second.NameLookupTableData) {
5303 // Look for this name within this module.
5304 ASTDeclContextNameLookupTable *LookupTable =
5305 Info->second.NameLookupTableData;
5306 ASTDeclContextNameLookupTable::iterator Pos
5307 = LookupTable->find(This->Name);
5308 if (Pos == LookupTable->end())
5311 bool FoundAnything = false;
5312 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
5313 for (; Data.first != Data.second; ++Data.first) {
5314 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
5318 if (ND->getDeclName() != This->Name) {
5319 // A name might be null because the decl's redeclarable part is
5320 // currently read before reading its name. The lookup is triggered by
5321 // building that decl (likely indirectly), and so it is later in the
5322 // sense of "already existing" and can be ignored here.
5326 // Record this declaration.
5327 FoundAnything = true;
5328 This->Decls.push_back(ND);
5331 return FoundAnything;
5336 DeclContext::lookup_result
5337 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
5338 DeclarationName Name) {
5339 assert(DC->hasExternalVisibleStorage() &&
5340 "DeclContext has no visible decls in storage");
5342 return DeclContext::lookup_result(DeclContext::lookup_iterator(0),
5343 DeclContext::lookup_iterator(0));
5345 SmallVector<NamedDecl *, 64> Decls;
5347 // Compute the declaration contexts we need to look into. Multiple such
5348 // declaration contexts occur when two declaration contexts from disjoint
5349 // modules get merged, e.g., when two namespaces with the same name are
5350 // independently defined in separate modules.
5351 SmallVector<const DeclContext *, 2> Contexts;
5352 Contexts.push_back(DC);
5354 if (DC->isNamespace()) {
5355 MergedDeclsMap::iterator Merged
5356 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5357 if (Merged != MergedDecls.end()) {
5358 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5359 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5363 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
5364 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
5365 ++NumVisibleDeclContextsRead;
5366 SetExternalVisibleDeclsForName(DC, Name, Decls);
5367 return const_cast<DeclContext*>(DC)->lookup(Name);
5371 /// \brief ModuleFile visitor used to retrieve all visible names in a
5372 /// declaration context.
5373 class DeclContextAllNamesVisitor {
5375 llvm::SmallVectorImpl<const DeclContext *> &Contexts;
5376 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > &Decls;
5379 DeclContextAllNamesVisitor(ASTReader &Reader,
5380 SmallVectorImpl<const DeclContext *> &Contexts,
5381 llvm::DenseMap<DeclarationName,
5382 SmallVector<NamedDecl *, 8> > &Decls)
5383 : Reader(Reader), Contexts(Contexts), Decls(Decls) { }
5385 static bool visit(ModuleFile &M, void *UserData) {
5386 DeclContextAllNamesVisitor *This
5387 = static_cast<DeclContextAllNamesVisitor *>(UserData);
5389 // Check whether we have any visible declaration information for
5390 // this context in this module.
5391 ModuleFile::DeclContextInfosMap::iterator Info;
5392 bool FoundInfo = false;
5393 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5394 Info = M.DeclContextInfos.find(This->Contexts[I]);
5395 if (Info != M.DeclContextInfos.end() &&
5396 Info->second.NameLookupTableData) {
5405 ASTDeclContextNameLookupTable *LookupTable =
5406 Info->second.NameLookupTableData;
5407 bool FoundAnything = false;
5408 for (ASTDeclContextNameLookupTable::data_iterator
5409 I = LookupTable->data_begin(), E = LookupTable->data_end();
5411 ASTDeclContextNameLookupTrait::data_type Data = *I;
5412 for (; Data.first != Data.second; ++Data.first) {
5413 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
5418 // Record this declaration.
5419 FoundAnything = true;
5420 This->Decls[ND->getDeclName()].push_back(ND);
5424 return FoundAnything;
5429 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
5430 if (!DC->hasExternalVisibleStorage())
5432 llvm::DenseMap<DeclarationName, llvm::SmallVector<NamedDecl*, 8> > Decls;
5434 // Compute the declaration contexts we need to look into. Multiple such
5435 // declaration contexts occur when two declaration contexts from disjoint
5436 // modules get merged, e.g., when two namespaces with the same name are
5437 // independently defined in separate modules.
5438 SmallVector<const DeclContext *, 2> Contexts;
5439 Contexts.push_back(DC);
5441 if (DC->isNamespace()) {
5442 MergedDeclsMap::iterator Merged
5443 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5444 if (Merged != MergedDecls.end()) {
5445 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5446 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5450 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls);
5451 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
5452 ++NumVisibleDeclContextsRead;
5454 for (llvm::DenseMap<DeclarationName,
5455 llvm::SmallVector<NamedDecl*, 8> >::iterator
5456 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
5457 SetExternalVisibleDeclsForName(DC, I->first, I->second);
5459 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
5462 /// \brief Under non-PCH compilation the consumer receives the objc methods
5463 /// before receiving the implementation, and codegen depends on this.
5464 /// We simulate this by deserializing and passing to consumer the methods of the
5465 /// implementation before passing the deserialized implementation decl.
5466 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
5467 ASTConsumer *Consumer) {
5468 assert(ImplD && Consumer);
5470 for (ObjCImplDecl::method_iterator
5471 I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
5472 Consumer->HandleInterestingDecl(DeclGroupRef(*I));
5474 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
5477 void ASTReader::PassInterestingDeclsToConsumer() {
5479 while (!InterestingDecls.empty()) {
5480 Decl *D = InterestingDecls.front();
5481 InterestingDecls.pop_front();
5483 PassInterestingDeclToConsumer(D);
5487 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
5488 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5489 PassObjCImplDeclToConsumer(ImplD, Consumer);
5491 Consumer->HandleInterestingDecl(DeclGroupRef(D));
5494 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
5495 this->Consumer = Consumer;
5500 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
5501 // Force deserialization of this decl, which will cause it to be queued for
5502 // passing to the consumer.
5503 GetDecl(ExternalDefinitions[I]);
5505 ExternalDefinitions.clear();
5507 PassInterestingDeclsToConsumer();
5510 void ASTReader::PrintStats() {
5511 std::fprintf(stderr, "*** AST File Statistics:\n");
5513 unsigned NumTypesLoaded
5514 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
5516 unsigned NumDeclsLoaded
5517 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
5519 unsigned NumIdentifiersLoaded
5520 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
5521 IdentifiersLoaded.end(),
5522 (IdentifierInfo *)0);
5523 unsigned NumMacrosLoaded
5524 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
5527 unsigned NumSelectorsLoaded
5528 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
5529 SelectorsLoaded.end(),
5532 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
5533 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
5534 NumSLocEntriesRead, TotalNumSLocEntries,
5535 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
5536 if (!TypesLoaded.empty())
5537 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
5538 NumTypesLoaded, (unsigned)TypesLoaded.size(),
5539 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
5540 if (!DeclsLoaded.empty())
5541 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
5542 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
5543 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
5544 if (!IdentifiersLoaded.empty())
5545 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
5546 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
5547 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
5548 if (!MacrosLoaded.empty())
5549 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5550 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
5551 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
5552 if (!SelectorsLoaded.empty())
5553 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
5554 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
5555 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
5556 if (TotalNumStatements)
5557 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
5558 NumStatementsRead, TotalNumStatements,
5559 ((float)NumStatementsRead/TotalNumStatements * 100));
5561 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5562 NumMacrosRead, TotalNumMacros,
5563 ((float)NumMacrosRead/TotalNumMacros * 100));
5564 if (TotalLexicalDeclContexts)
5565 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
5566 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
5567 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
5569 if (TotalVisibleDeclContexts)
5570 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
5571 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
5572 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
5574 if (TotalNumMethodPoolEntries) {
5575 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
5576 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
5577 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
5579 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
5581 std::fprintf(stderr, "\n");
5583 std::fprintf(stderr, "\n");
5586 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
5588 dumpModuleIDMap(StringRef Name,
5589 const ContinuousRangeMap<Key, ModuleFile *,
5590 InitialCapacity> &Map) {
5591 if (Map.begin() == Map.end())
5594 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
5595 llvm::errs() << Name << ":\n";
5596 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
5598 llvm::errs() << " " << I->first << " -> " << I->second->FileName
5603 void ASTReader::dump() {
5604 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
5605 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
5606 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
5607 dumpModuleIDMap("Global type map", GlobalTypeMap);
5608 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
5609 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
5610 dumpModuleIDMap("Global macro map", GlobalMacroMap);
5611 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
5612 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
5613 dumpModuleIDMap("Global preprocessed entity map",
5614 GlobalPreprocessedEntityMap);
5616 llvm::errs() << "\n*** PCH/Modules Loaded:";
5617 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
5618 MEnd = ModuleMgr.end();
5623 /// Return the amount of memory used by memory buffers, breaking down
5624 /// by heap-backed versus mmap'ed memory.
5625 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
5626 for (ModuleConstIterator I = ModuleMgr.begin(),
5627 E = ModuleMgr.end(); I != E; ++I) {
5628 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
5629 size_t bytes = buf->getBufferSize();
5630 switch (buf->getBufferKind()) {
5631 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
5632 sizes.malloc_bytes += bytes;
5634 case llvm::MemoryBuffer::MemoryBuffer_MMap:
5635 sizes.mmap_bytes += bytes;
5642 void ASTReader::InitializeSema(Sema &S) {
5644 S.addExternalSource(this);
5646 // Makes sure any declarations that were deserialized "too early"
5647 // still get added to the identifier's declaration chains.
5648 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
5649 SemaObj->pushExternalDeclIntoScope(PreloadedDecls[I],
5650 PreloadedDecls[I]->getDeclName());
5652 PreloadedDecls.clear();
5654 // Load the offsets of the declarations that Sema references.
5655 // They will be lazily deserialized when needed.
5656 if (!SemaDeclRefs.empty()) {
5657 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
5658 if (!SemaObj->StdNamespace)
5659 SemaObj->StdNamespace = SemaDeclRefs[0];
5660 if (!SemaObj->StdBadAlloc)
5661 SemaObj->StdBadAlloc = SemaDeclRefs[1];
5664 if (!FPPragmaOptions.empty()) {
5665 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
5666 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
5669 if (!OpenCLExtensions.empty()) {
5671 #define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
5672 #include "clang/Basic/OpenCLExtensions.def"
5674 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
5678 IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
5679 // Note that we are loading an identifier.
5680 Deserializing AnIdentifier(this);
5682 IdentifierLookupVisitor Visitor(StringRef(NameStart, NameEnd - NameStart),
5683 /*PriorGeneration=*/0);
5684 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
5685 IdentifierInfo *II = Visitor.getIdentifierInfo();
5686 markIdentifierUpToDate(II);
5691 /// \brief An identifier-lookup iterator that enumerates all of the
5692 /// identifiers stored within a set of AST files.
5693 class ASTIdentifierIterator : public IdentifierIterator {
5694 /// \brief The AST reader whose identifiers are being enumerated.
5695 const ASTReader &Reader;
5697 /// \brief The current index into the chain of AST files stored in
5701 /// \brief The current position within the identifier lookup table
5702 /// of the current AST file.
5703 ASTIdentifierLookupTable::key_iterator Current;
5705 /// \brief The end position within the identifier lookup table of
5706 /// the current AST file.
5707 ASTIdentifierLookupTable::key_iterator End;
5710 explicit ASTIdentifierIterator(const ASTReader &Reader);
5712 virtual StringRef Next();
5716 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
5717 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
5718 ASTIdentifierLookupTable *IdTable
5719 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
5720 Current = IdTable->key_begin();
5721 End = IdTable->key_end();
5724 StringRef ASTIdentifierIterator::Next() {
5725 while (Current == End) {
5726 // If we have exhausted all of our AST files, we're done.
5731 ASTIdentifierLookupTable *IdTable
5732 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
5733 IdentifierLookupTable;
5734 Current = IdTable->key_begin();
5735 End = IdTable->key_end();
5738 // We have any identifiers remaining in the current AST file; return
5740 std::pair<const char*, unsigned> Key = *Current;
5742 return StringRef(Key.first, Key.second);
5745 IdentifierIterator *ASTReader::getIdentifiers() const {
5746 return new ASTIdentifierIterator(*this);
5749 namespace clang { namespace serialization {
5750 class ReadMethodPoolVisitor {
5753 unsigned PriorGeneration;
5754 llvm::SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
5755 llvm::SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
5758 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
5759 unsigned PriorGeneration)
5760 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) { }
5762 static bool visit(ModuleFile &M, void *UserData) {
5763 ReadMethodPoolVisitor *This
5764 = static_cast<ReadMethodPoolVisitor *>(UserData);
5766 if (!M.SelectorLookupTable)
5769 // If we've already searched this module file, skip it now.
5770 if (M.Generation <= This->PriorGeneration)
5773 ASTSelectorLookupTable *PoolTable
5774 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
5775 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
5776 if (Pos == PoolTable->end())
5779 ++This->Reader.NumSelectorsRead;
5780 // FIXME: Not quite happy with the statistics here. We probably should
5781 // disable this tracking when called via LoadSelector.
5782 // Also, should entries without methods count as misses?
5783 ++This->Reader.NumMethodPoolEntriesRead;
5784 ASTSelectorLookupTrait::data_type Data = *Pos;
5785 if (This->Reader.DeserializationListener)
5786 This->Reader.DeserializationListener->SelectorRead(Data.ID,
5789 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
5790 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
5794 /// \brief Retrieve the instance methods found by this visitor.
5795 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
5796 return InstanceMethods;
5799 /// \brief Retrieve the instance methods found by this visitor.
5800 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
5801 return FactoryMethods;
5804 } } // end namespace clang::serialization
5806 /// \brief Add the given set of methods to the method list.
5807 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
5808 ObjCMethodList &List) {
5809 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
5810 S.addMethodToGlobalList(&List, Methods[I]);
5814 void ASTReader::ReadMethodPool(Selector Sel) {
5815 // Get the selector generation and update it to the current generation.
5816 unsigned &Generation = SelectorGeneration[Sel];
5817 unsigned PriorGeneration = Generation;
5818 Generation = CurrentGeneration;
5820 // Search for methods defined with this selector.
5821 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
5822 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
5824 if (Visitor.getInstanceMethods().empty() &&
5825 Visitor.getFactoryMethods().empty()) {
5826 ++NumMethodPoolMisses;
5833 Sema &S = *getSema();
5834 Sema::GlobalMethodPool::iterator Pos
5835 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
5837 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
5838 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
5841 void ASTReader::ReadKnownNamespaces(
5842 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
5845 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
5846 if (NamespaceDecl *Namespace
5847 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
5848 Namespaces.push_back(Namespace);
5852 void ASTReader::ReadTentativeDefinitions(
5853 SmallVectorImpl<VarDecl *> &TentativeDefs) {
5854 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
5855 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
5857 TentativeDefs.push_back(Var);
5859 TentativeDefinitions.clear();
5862 void ASTReader::ReadUnusedFileScopedDecls(
5863 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
5864 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
5866 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
5870 UnusedFileScopedDecls.clear();
5873 void ASTReader::ReadDelegatingConstructors(
5874 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
5875 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
5876 CXXConstructorDecl *D
5877 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
5881 DelegatingCtorDecls.clear();
5884 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
5885 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
5887 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
5891 ExtVectorDecls.clear();
5894 void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
5895 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
5897 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
5901 DynamicClasses.clear();
5905 ASTReader::ReadLocallyScopedExternalDecls(SmallVectorImpl<NamedDecl *> &Decls) {
5906 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
5908 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
5912 LocallyScopedExternalDecls.clear();
5915 void ASTReader::ReadReferencedSelectors(
5916 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
5917 if (ReferencedSelectorsData.empty())
5920 // If there are @selector references added them to its pool. This is for
5921 // implementation of -Wselector.
5922 unsigned int DataSize = ReferencedSelectorsData.size()-1;
5924 while (I < DataSize) {
5925 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
5926 SourceLocation SelLoc
5927 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
5928 Sels.push_back(std::make_pair(Sel, SelLoc));
5930 ReferencedSelectorsData.clear();
5933 void ASTReader::ReadWeakUndeclaredIdentifiers(
5934 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
5935 if (WeakUndeclaredIdentifiers.empty())
5938 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
5939 IdentifierInfo *WeakId
5940 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
5941 IdentifierInfo *AliasId
5942 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
5944 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
5945 bool Used = WeakUndeclaredIdentifiers[I++];
5946 WeakInfo WI(AliasId, Loc);
5948 WeakIDs.push_back(std::make_pair(WeakId, WI));
5950 WeakUndeclaredIdentifiers.clear();
5953 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
5954 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
5955 ExternalVTableUse VT;
5956 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
5957 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
5958 VT.DefinitionRequired = VTableUses[Idx++];
5959 VTables.push_back(VT);
5965 void ASTReader::ReadPendingInstantiations(
5966 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
5967 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
5968 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
5970 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
5972 Pending.push_back(std::make_pair(D, Loc));
5974 PendingInstantiations.clear();
5977 void ASTReader::LoadSelector(Selector Sel) {
5978 // It would be complicated to avoid reading the methods anyway. So don't.
5979 ReadMethodPool(Sel);
5982 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
5983 assert(ID && "Non-zero identifier ID required");
5984 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
5985 IdentifiersLoaded[ID - 1] = II;
5986 if (DeserializationListener)
5987 DeserializationListener->IdentifierRead(ID, II);
5990 /// \brief Set the globally-visible declarations associated with the given
5993 /// If the AST reader is currently in a state where the given declaration IDs
5994 /// cannot safely be resolved, they are queued until it is safe to resolve
5997 /// \param II an IdentifierInfo that refers to one or more globally-visible
6000 /// \param DeclIDs the set of declaration IDs with the name @p II that are
6001 /// visible at global scope.
6003 /// \param Nonrecursive should be true to indicate that the caller knows that
6004 /// this call is non-recursive, and therefore the globally-visible declarations
6005 /// will not be placed onto the pending queue.
6007 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6008 const SmallVectorImpl<uint32_t> &DeclIDs,
6009 bool Nonrecursive) {
6010 if (NumCurrentElementsDeserializing && !Nonrecursive) {
6011 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
6012 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
6014 PII.DeclIDs.append(DeclIDs.begin(), DeclIDs.end());
6018 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6019 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6021 // Introduce this declaration into the translation-unit scope
6022 // and add it to the declaration chain for this identifier, so
6023 // that (unqualified) name lookup will find it.
6024 SemaObj->pushExternalDeclIntoScope(D, II);
6026 // Queue this declaration so that it will be added to the
6027 // translation unit scope and identifier's declaration chain
6028 // once a Sema object is known.
6029 PreloadedDecls.push_back(D);
6034 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
6038 if (IdentifiersLoaded.empty()) {
6039 Error("no identifier table in AST file");
6044 if (!IdentifiersLoaded[ID]) {
6045 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6046 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
6047 ModuleFile *M = I->second;
6048 unsigned Index = ID - M->BaseIdentifierID;
6049 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
6051 // All of the strings in the AST file are preceded by a 16-bit length.
6052 // Extract that 16-bit length to avoid having to execute strlen().
6053 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6054 // unsigned integers. This is important to avoid integer overflow when
6055 // we cast them to 'unsigned'.
6056 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
6057 unsigned StrLen = (((unsigned) StrLenPtr[0])
6058 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
6059 IdentifiersLoaded[ID]
6060 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
6061 if (DeserializationListener)
6062 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
6065 return IdentifiersLoaded[ID];
6068 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
6069 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
6072 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
6073 if (LocalID < NUM_PREDEF_IDENT_IDS)
6076 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6077 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6078 assert(I != M.IdentifierRemap.end()
6079 && "Invalid index into identifier index remap");
6081 return LocalID + I->second;
6084 MacroInfo *ASTReader::getMacro(MacroID ID, MacroInfo *Hint) {
6088 if (MacrosLoaded.empty()) {
6089 Error("no macro table in AST file");
6093 ID -= NUM_PREDEF_MACRO_IDS;
6094 if (!MacrosLoaded[ID]) {
6095 GlobalMacroMapType::iterator I
6096 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
6097 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
6098 ModuleFile *M = I->second;
6099 unsigned Index = ID - M->BaseMacroID;
6100 ReadMacroRecord(*M, M->MacroOffsets[Index], Hint);
6103 return MacrosLoaded[ID];
6106 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
6107 if (LocalID < NUM_PREDEF_MACRO_IDS)
6110 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6111 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
6112 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
6114 return LocalID + I->second;
6117 serialization::SubmoduleID
6118 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
6119 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
6122 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6123 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
6124 assert(I != M.SubmoduleRemap.end()
6125 && "Invalid index into submodule index remap");
6127 return LocalID + I->second;
6130 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
6131 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6132 assert(GlobalID == 0 && "Unhandled global submodule ID");
6136 if (GlobalID > SubmodulesLoaded.size()) {
6137 Error("submodule ID out of range in AST file");
6141 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
6144 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
6145 return DecodeSelector(getGlobalSelectorID(M, LocalID));
6148 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
6152 if (ID > SelectorsLoaded.size()) {
6153 Error("selector ID out of range in AST file");
6157 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
6158 // Load this selector from the selector table.
6159 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
6160 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
6161 ModuleFile &M = *I->second;
6162 ASTSelectorLookupTrait Trait(*this, M);
6163 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
6164 SelectorsLoaded[ID - 1] =
6165 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
6166 if (DeserializationListener)
6167 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
6170 return SelectorsLoaded[ID - 1];
6173 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
6174 return DecodeSelector(ID);
6177 uint32_t ASTReader::GetNumExternalSelectors() {
6178 // ID 0 (the null selector) is considered an external selector.
6179 return getTotalNumSelectors() + 1;
6182 serialization::SelectorID
6183 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
6184 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
6187 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6188 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
6189 assert(I != M.SelectorRemap.end()
6190 && "Invalid index into selector index remap");
6192 return LocalID + I->second;
6196 ASTReader::ReadDeclarationName(ModuleFile &F,
6197 const RecordData &Record, unsigned &Idx) {
6198 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
6200 case DeclarationName::Identifier:
6201 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
6203 case DeclarationName::ObjCZeroArgSelector:
6204 case DeclarationName::ObjCOneArgSelector:
6205 case DeclarationName::ObjCMultiArgSelector:
6206 return DeclarationName(ReadSelector(F, Record, Idx));
6208 case DeclarationName::CXXConstructorName:
6209 return Context.DeclarationNames.getCXXConstructorName(
6210 Context.getCanonicalType(readType(F, Record, Idx)));
6212 case DeclarationName::CXXDestructorName:
6213 return Context.DeclarationNames.getCXXDestructorName(
6214 Context.getCanonicalType(readType(F, Record, Idx)));
6216 case DeclarationName::CXXConversionFunctionName:
6217 return Context.DeclarationNames.getCXXConversionFunctionName(
6218 Context.getCanonicalType(readType(F, Record, Idx)));
6220 case DeclarationName::CXXOperatorName:
6221 return Context.DeclarationNames.getCXXOperatorName(
6222 (OverloadedOperatorKind)Record[Idx++]);
6224 case DeclarationName::CXXLiteralOperatorName:
6225 return Context.DeclarationNames.getCXXLiteralOperatorName(
6226 GetIdentifierInfo(F, Record, Idx));
6228 case DeclarationName::CXXUsingDirective:
6229 return DeclarationName::getUsingDirectiveName();
6232 llvm_unreachable("Invalid NameKind!");
6235 void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
6236 DeclarationNameLoc &DNLoc,
6237 DeclarationName Name,
6238 const RecordData &Record, unsigned &Idx) {
6239 switch (Name.getNameKind()) {
6240 case DeclarationName::CXXConstructorName:
6241 case DeclarationName::CXXDestructorName:
6242 case DeclarationName::CXXConversionFunctionName:
6243 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
6246 case DeclarationName::CXXOperatorName:
6247 DNLoc.CXXOperatorName.BeginOpNameLoc
6248 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6249 DNLoc.CXXOperatorName.EndOpNameLoc
6250 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6253 case DeclarationName::CXXLiteralOperatorName:
6254 DNLoc.CXXLiteralOperatorName.OpNameLoc
6255 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6258 case DeclarationName::Identifier:
6259 case DeclarationName::ObjCZeroArgSelector:
6260 case DeclarationName::ObjCOneArgSelector:
6261 case DeclarationName::ObjCMultiArgSelector:
6262 case DeclarationName::CXXUsingDirective:
6267 void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
6268 DeclarationNameInfo &NameInfo,
6269 const RecordData &Record, unsigned &Idx) {
6270 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
6271 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
6272 DeclarationNameLoc DNLoc;
6273 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
6274 NameInfo.setInfo(DNLoc);
6277 void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
6278 const RecordData &Record, unsigned &Idx) {
6279 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
6280 unsigned NumTPLists = Record[Idx++];
6281 Info.NumTemplParamLists = NumTPLists;
6283 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
6284 for (unsigned i=0; i != NumTPLists; ++i)
6285 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
6290 ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
6292 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
6294 case TemplateName::Template:
6295 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
6297 case TemplateName::OverloadedTemplate: {
6298 unsigned size = Record[Idx++];
6299 UnresolvedSet<8> Decls;
6301 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
6303 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
6306 case TemplateName::QualifiedTemplate: {
6307 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6308 bool hasTemplKeyword = Record[Idx++];
6309 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
6310 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
6313 case TemplateName::DependentTemplate: {
6314 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6315 if (Record[Idx++]) // isIdentifier
6316 return Context.getDependentTemplateName(NNS,
6317 GetIdentifierInfo(F, Record,
6319 return Context.getDependentTemplateName(NNS,
6320 (OverloadedOperatorKind)Record[Idx++]);
6323 case TemplateName::SubstTemplateTemplateParm: {
6324 TemplateTemplateParmDecl *param
6325 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6326 if (!param) return TemplateName();
6327 TemplateName replacement = ReadTemplateName(F, Record, Idx);
6328 return Context.getSubstTemplateTemplateParm(param, replacement);
6331 case TemplateName::SubstTemplateTemplateParmPack: {
6332 TemplateTemplateParmDecl *Param
6333 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6335 return TemplateName();
6337 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
6338 if (ArgPack.getKind() != TemplateArgument::Pack)
6339 return TemplateName();
6341 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
6345 llvm_unreachable("Unhandled template name kind!");
6349 ASTReader::ReadTemplateArgument(ModuleFile &F,
6350 const RecordData &Record, unsigned &Idx) {
6351 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
6353 case TemplateArgument::Null:
6354 return TemplateArgument();
6355 case TemplateArgument::Type:
6356 return TemplateArgument(readType(F, Record, Idx));
6357 case TemplateArgument::Declaration: {
6358 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
6359 bool ForReferenceParam = Record[Idx++];
6360 return TemplateArgument(D, ForReferenceParam);
6362 case TemplateArgument::NullPtr:
6363 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
6364 case TemplateArgument::Integral: {
6365 llvm::APSInt Value = ReadAPSInt(Record, Idx);
6366 QualType T = readType(F, Record, Idx);
6367 return TemplateArgument(Context, Value, T);
6369 case TemplateArgument::Template:
6370 return TemplateArgument(ReadTemplateName(F, Record, Idx));
6371 case TemplateArgument::TemplateExpansion: {
6372 TemplateName Name = ReadTemplateName(F, Record, Idx);
6373 llvm::Optional<unsigned> NumTemplateExpansions;
6374 if (unsigned NumExpansions = Record[Idx++])
6375 NumTemplateExpansions = NumExpansions - 1;
6376 return TemplateArgument(Name, NumTemplateExpansions);
6378 case TemplateArgument::Expression:
6379 return TemplateArgument(ReadExpr(F));
6380 case TemplateArgument::Pack: {
6381 unsigned NumArgs = Record[Idx++];
6382 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
6383 for (unsigned I = 0; I != NumArgs; ++I)
6384 Args[I] = ReadTemplateArgument(F, Record, Idx);
6385 return TemplateArgument(Args, NumArgs);
6389 llvm_unreachable("Unhandled template argument kind!");
6392 TemplateParameterList *
6393 ASTReader::ReadTemplateParameterList(ModuleFile &F,
6394 const RecordData &Record, unsigned &Idx) {
6395 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
6396 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
6397 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
6399 unsigned NumParams = Record[Idx++];
6400 SmallVector<NamedDecl *, 16> Params;
6401 Params.reserve(NumParams);
6403 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
6405 TemplateParameterList* TemplateParams =
6406 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
6407 Params.data(), Params.size(), RAngleLoc);
6408 return TemplateParams;
6413 ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
6414 ModuleFile &F, const RecordData &Record,
6416 unsigned NumTemplateArgs = Record[Idx++];
6417 TemplArgs.reserve(NumTemplateArgs);
6418 while (NumTemplateArgs--)
6419 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
6422 /// \brief Read a UnresolvedSet structure.
6423 void ASTReader::ReadUnresolvedSet(ModuleFile &F, UnresolvedSetImpl &Set,
6424 const RecordData &Record, unsigned &Idx) {
6425 unsigned NumDecls = Record[Idx++];
6426 while (NumDecls--) {
6427 NamedDecl *D = ReadDeclAs<NamedDecl>(F, Record, Idx);
6428 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
6434 ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
6435 const RecordData &Record, unsigned &Idx) {
6436 bool isVirtual = static_cast<bool>(Record[Idx++]);
6437 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
6438 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
6439 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
6440 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
6441 SourceRange Range = ReadSourceRange(F, Record, Idx);
6442 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
6443 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
6445 Result.setInheritConstructors(inheritConstructors);
6449 std::pair<CXXCtorInitializer **, unsigned>
6450 ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
6452 CXXCtorInitializer **CtorInitializers = 0;
6453 unsigned NumInitializers = Record[Idx++];
6454 if (NumInitializers) {
6456 = new (Context) CXXCtorInitializer*[NumInitializers];
6457 for (unsigned i=0; i != NumInitializers; ++i) {
6458 TypeSourceInfo *TInfo = 0;
6459 bool IsBaseVirtual = false;
6460 FieldDecl *Member = 0;
6461 IndirectFieldDecl *IndirectMember = 0;
6463 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
6465 case CTOR_INITIALIZER_BASE:
6466 TInfo = GetTypeSourceInfo(F, Record, Idx);
6467 IsBaseVirtual = Record[Idx++];
6470 case CTOR_INITIALIZER_DELEGATING:
6471 TInfo = GetTypeSourceInfo(F, Record, Idx);
6474 case CTOR_INITIALIZER_MEMBER:
6475 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
6478 case CTOR_INITIALIZER_INDIRECT_MEMBER:
6479 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
6483 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
6484 Expr *Init = ReadExpr(F);
6485 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
6486 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
6487 bool IsWritten = Record[Idx++];
6488 unsigned SourceOrderOrNumArrayIndices;
6489 SmallVector<VarDecl *, 8> Indices;
6491 SourceOrderOrNumArrayIndices = Record[Idx++];
6493 SourceOrderOrNumArrayIndices = Record[Idx++];
6494 Indices.reserve(SourceOrderOrNumArrayIndices);
6495 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
6496 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
6499 CXXCtorInitializer *BOMInit;
6500 if (Type == CTOR_INITIALIZER_BASE) {
6501 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
6502 LParenLoc, Init, RParenLoc,
6503 MemberOrEllipsisLoc);
6504 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
6505 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
6507 } else if (IsWritten) {
6509 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
6510 LParenLoc, Init, RParenLoc);
6512 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
6513 MemberOrEllipsisLoc, LParenLoc,
6516 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
6517 LParenLoc, Init, RParenLoc,
6518 Indices.data(), Indices.size());
6522 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
6523 CtorInitializers[i] = BOMInit;
6527 return std::make_pair(CtorInitializers, NumInitializers);
6530 NestedNameSpecifier *
6531 ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
6532 const RecordData &Record, unsigned &Idx) {
6533 unsigned N = Record[Idx++];
6534 NestedNameSpecifier *NNS = 0, *Prev = 0;
6535 for (unsigned I = 0; I != N; ++I) {
6536 NestedNameSpecifier::SpecifierKind Kind
6537 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6539 case NestedNameSpecifier::Identifier: {
6540 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
6541 NNS = NestedNameSpecifier::Create(Context, Prev, II);
6545 case NestedNameSpecifier::Namespace: {
6546 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
6547 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
6551 case NestedNameSpecifier::NamespaceAlias: {
6552 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
6553 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
6557 case NestedNameSpecifier::TypeSpec:
6558 case NestedNameSpecifier::TypeSpecWithTemplate: {
6559 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
6563 bool Template = Record[Idx++];
6564 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
6568 case NestedNameSpecifier::Global: {
6569 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
6570 // No associated value, and there can't be a prefix.
6579 NestedNameSpecifierLoc
6580 ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
6582 unsigned N = Record[Idx++];
6583 NestedNameSpecifierLocBuilder Builder;
6584 for (unsigned I = 0; I != N; ++I) {
6585 NestedNameSpecifier::SpecifierKind Kind
6586 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6588 case NestedNameSpecifier::Identifier: {
6589 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
6590 SourceRange Range = ReadSourceRange(F, Record, Idx);
6591 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
6595 case NestedNameSpecifier::Namespace: {
6596 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
6597 SourceRange Range = ReadSourceRange(F, Record, Idx);
6598 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
6602 case NestedNameSpecifier::NamespaceAlias: {
6603 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
6604 SourceRange Range = ReadSourceRange(F, Record, Idx);
6605 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
6609 case NestedNameSpecifier::TypeSpec:
6610 case NestedNameSpecifier::TypeSpecWithTemplate: {
6611 bool Template = Record[Idx++];
6612 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
6614 return NestedNameSpecifierLoc();
6615 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
6617 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
6618 Builder.Extend(Context,
6619 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
6620 T->getTypeLoc(), ColonColonLoc);
6624 case NestedNameSpecifier::Global: {
6625 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
6626 Builder.MakeGlobal(Context, ColonColonLoc);
6632 return Builder.getWithLocInContext(Context);
6636 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
6638 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
6639 SourceLocation end = ReadSourceLocation(F, Record, Idx);
6640 return SourceRange(beg, end);
6643 /// \brief Read an integral value
6644 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
6645 unsigned BitWidth = Record[Idx++];
6646 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
6647 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
6652 /// \brief Read a signed integral value
6653 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
6654 bool isUnsigned = Record[Idx++];
6655 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
6658 /// \brief Read a floating-point value
6659 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
6660 return llvm::APFloat(ReadAPInt(Record, Idx));
6663 // \brief Read a string
6664 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
6665 unsigned Len = Record[Idx++];
6666 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
6671 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
6673 unsigned Major = Record[Idx++];
6674 unsigned Minor = Record[Idx++];
6675 unsigned Subminor = Record[Idx++];
6677 return VersionTuple(Major);
6679 return VersionTuple(Major, Minor - 1);
6680 return VersionTuple(Major, Minor - 1, Subminor - 1);
6683 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
6684 const RecordData &Record,
6686 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
6687 return CXXTemporary::Create(Context, Decl);
6690 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
6691 return Diag(SourceLocation(), DiagID);
6694 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
6695 return Diags.Report(Loc, DiagID);
6698 /// \brief Retrieve the identifier table associated with the
6700 IdentifierTable &ASTReader::getIdentifierTable() {
6701 return PP.getIdentifierTable();
6704 /// \brief Record that the given ID maps to the given switch-case
6706 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
6707 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
6708 "Already have a SwitchCase with this ID");
6709 (*CurrSwitchCaseStmts)[ID] = SC;
6712 /// \brief Retrieve the switch-case statement with the given ID.
6713 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
6714 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
6715 return (*CurrSwitchCaseStmts)[ID];
6718 void ASTReader::ClearSwitchCaseIDs() {
6719 CurrSwitchCaseStmts->clear();
6722 void ASTReader::ReadComments() {
6723 std::vector<RawComment *> Comments;
6724 for (SmallVectorImpl<std::pair<llvm::BitstreamCursor,
6725 serialization::ModuleFile *> >::iterator
6726 I = CommentsCursors.begin(),
6727 E = CommentsCursors.end();
6729 llvm::BitstreamCursor &Cursor = I->first;
6730 serialization::ModuleFile &F = *I->second;
6731 SavedStreamPosition SavedPosition(Cursor);
6735 unsigned Code = Cursor.ReadCode();
6736 if (Code == llvm::bitc::END_BLOCK)
6739 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
6740 // No known subblocks, always skip them.
6741 Cursor.ReadSubBlockID();
6742 if (Cursor.SkipBlock()) {
6743 Error("malformed block record in AST file");
6749 if (Code == llvm::bitc::DEFINE_ABBREV) {
6750 Cursor.ReadAbbrevRecord();
6756 switch ((CommentRecordTypes) Cursor.ReadRecord(Code, Record)) {
6757 case COMMENTS_RAW_COMMENT: {
6759 SourceRange SR = ReadSourceRange(F, Record, Idx);
6760 RawComment::CommentKind Kind =
6761 (RawComment::CommentKind) Record[Idx++];
6762 bool IsTrailingComment = Record[Idx++];
6763 bool IsAlmostTrailingComment = Record[Idx++];
6764 Comments.push_back(new (Context) RawComment(SR, Kind,
6766 IsAlmostTrailingComment));
6772 Context.Comments.addCommentsToFront(Comments);
6775 void ASTReader::finishPendingActions() {
6776 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
6777 !PendingMacroIDs.empty()) {
6778 // If any identifiers with corresponding top-level declarations have
6779 // been loaded, load those declarations now.
6780 while (!PendingIdentifierInfos.empty()) {
6781 SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
6782 PendingIdentifierInfos.front().DeclIDs, true);
6783 PendingIdentifierInfos.pop_front();
6786 // Load pending declaration chains.
6787 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
6788 loadPendingDeclChain(PendingDeclChains[I]);
6789 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
6791 PendingDeclChains.clear();
6793 // Load any pending macro definitions.
6794 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
6795 // FIXME: std::move here
6796 SmallVector<MacroID, 2> GlobalIDs = PendingMacroIDs.begin()[I].second;
6797 MacroInfo *Hint = 0;
6798 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
6800 Hint = getMacro(GlobalIDs[IDIdx], Hint);
6803 PendingMacroIDs.clear();
6806 // If we deserialized any C++ or Objective-C class definitions, any
6807 // Objective-C protocol definitions, or any redeclarable templates, make sure
6808 // that all redeclarations point to the definitions. Note that this can only
6809 // happen now, after the redeclaration chains have been fully wired.
6810 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
6811 DEnd = PendingDefinitions.end();
6813 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
6814 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
6815 // Make sure that the TagType points at the definition.
6816 const_cast<TagType*>(TagT)->decl = TD;
6819 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(*D)) {
6820 for (CXXRecordDecl::redecl_iterator R = RD->redecls_begin(),
6821 REnd = RD->redecls_end();
6823 cast<CXXRecordDecl>(*R)->DefinitionData = RD->DefinitionData;
6830 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
6831 // Make sure that the ObjCInterfaceType points at the definition.
6832 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
6835 for (ObjCInterfaceDecl::redecl_iterator R = ID->redecls_begin(),
6836 REnd = ID->redecls_end();
6843 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(*D)) {
6844 for (ObjCProtocolDecl::redecl_iterator R = PD->redecls_begin(),
6845 REnd = PD->redecls_end();
6852 RedeclarableTemplateDecl *RTD
6853 = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
6854 for (RedeclarableTemplateDecl::redecl_iterator R = RTD->redecls_begin(),
6855 REnd = RTD->redecls_end();
6857 R->Common = RTD->Common;
6859 PendingDefinitions.clear();
6861 // Load the bodies of any functions or methods we've encountered. We do
6862 // this now (delayed) so that we can be sure that the declaration chains
6863 // have been fully wired up.
6864 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
6865 PBEnd = PendingBodies.end();
6866 PB != PBEnd; ++PB) {
6867 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
6868 // FIXME: Check for =delete/=default?
6869 // FIXME: Complain about ODR violations here?
6870 if (!getContext().getLangOpts().Modules || !FD->hasBody())
6871 FD->setLazyBody(PB->second);
6875 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
6876 if (!getContext().getLangOpts().Modules || !MD->hasBody())
6877 MD->setLazyBody(PB->second);
6879 PendingBodies.clear();
6882 void ASTReader::FinishedDeserializing() {
6883 assert(NumCurrentElementsDeserializing &&
6884 "FinishedDeserializing not paired with StartedDeserializing");
6885 if (NumCurrentElementsDeserializing == 1) {
6886 // We decrease NumCurrentElementsDeserializing only after pending actions
6887 // are finished, to avoid recursively re-calling finishPendingActions().
6888 finishPendingActions();
6890 --NumCurrentElementsDeserializing;
6892 if (NumCurrentElementsDeserializing == 0 &&
6893 Consumer && !PassingDeclsToConsumer) {
6894 // Guard variable to avoid recursively redoing the process of passing
6895 // decls to consumer.
6896 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6899 while (!InterestingDecls.empty()) {
6900 // We are not in recursive loading, so it's safe to pass the "interesting"
6901 // decls to the consumer.
6902 Decl *D = InterestingDecls.front();
6903 InterestingDecls.pop_front();
6904 PassInterestingDeclToConsumer(D);
6909 ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
6910 StringRef isysroot, bool DisableValidation,
6911 bool AllowASTWithCompilerErrors)
6912 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
6913 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
6914 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
6915 Consumer(0), ModuleMgr(PP.getFileManager()),
6916 isysroot(isysroot), DisableValidation(DisableValidation),
6917 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
6918 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
6919 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
6920 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
6921 TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
6922 NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0),
6923 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
6924 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
6925 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
6926 PassingDeclsToConsumer(false),
6927 NumCXXBaseSpecifiersLoaded(0)
6929 SourceMgr.setExternalSLocEntrySource(this);
6932 ASTReader::~ASTReader() {
6933 for (DeclContextVisibleUpdatesPending::iterator
6934 I = PendingVisibleUpdates.begin(),
6935 E = PendingVisibleUpdates.end();
6937 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
6938 F = I->second.end();