1*67e74705SXin Li //===-- ASTReader.cpp - AST File Reader ----------------------------------===//
2*67e74705SXin Li //
3*67e74705SXin Li // The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // This file defines the ASTReader class, which reads AST files.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li
14*67e74705SXin Li #include "clang/Serialization/ASTReader.h"
15*67e74705SXin Li #include "ASTCommon.h"
16*67e74705SXin Li #include "ASTReaderInternals.h"
17*67e74705SXin Li #include "clang/AST/ASTConsumer.h"
18*67e74705SXin Li #include "clang/AST/ASTContext.h"
19*67e74705SXin Li #include "clang/AST/DeclTemplate.h"
20*67e74705SXin Li #include "clang/AST/Expr.h"
21*67e74705SXin Li #include "clang/AST/ExprCXX.h"
22*67e74705SXin Li #include "clang/Frontend/PCHContainerOperations.h"
23*67e74705SXin Li #include "clang/AST/ASTMutationListener.h"
24*67e74705SXin Li #include "clang/AST/NestedNameSpecifier.h"
25*67e74705SXin Li #include "clang/AST/Type.h"
26*67e74705SXin Li #include "clang/AST/TypeLocVisitor.h"
27*67e74705SXin Li #include "clang/Basic/DiagnosticOptions.h"
28*67e74705SXin Li #include "clang/Basic/FileManager.h"
29*67e74705SXin Li #include "clang/Basic/SourceManager.h"
30*67e74705SXin Li #include "clang/Basic/SourceManagerInternals.h"
31*67e74705SXin Li #include "clang/Basic/TargetInfo.h"
32*67e74705SXin Li #include "clang/Basic/TargetOptions.h"
33*67e74705SXin Li #include "clang/Basic/Version.h"
34*67e74705SXin Li #include "clang/Basic/VersionTuple.h"
35*67e74705SXin Li #include "clang/Frontend/Utils.h"
36*67e74705SXin Li #include "clang/Lex/HeaderSearch.h"
37*67e74705SXin Li #include "clang/Lex/HeaderSearchOptions.h"
38*67e74705SXin Li #include "clang/Lex/MacroInfo.h"
39*67e74705SXin Li #include "clang/Lex/PreprocessingRecord.h"
40*67e74705SXin Li #include "clang/Lex/Preprocessor.h"
41*67e74705SXin Li #include "clang/Lex/PreprocessorOptions.h"
42*67e74705SXin Li #include "clang/Sema/Scope.h"
43*67e74705SXin Li #include "clang/Sema/Sema.h"
44*67e74705SXin Li #include "clang/Serialization/ASTDeserializationListener.h"
45*67e74705SXin Li #include "clang/Serialization/GlobalModuleIndex.h"
46*67e74705SXin Li #include "clang/Serialization/ModuleManager.h"
47*67e74705SXin Li #include "clang/Serialization/SerializationDiagnostic.h"
48*67e74705SXin Li #include "llvm/ADT/Hashing.h"
49*67e74705SXin Li #include "llvm/ADT/StringExtras.h"
50*67e74705SXin Li #include "llvm/Bitcode/BitstreamReader.h"
51*67e74705SXin Li #include "llvm/Support/Compression.h"
52*67e74705SXin Li #include "llvm/Support/ErrorHandling.h"
53*67e74705SXin Li #include "llvm/Support/FileSystem.h"
54*67e74705SXin Li #include "llvm/Support/MemoryBuffer.h"
55*67e74705SXin Li #include "llvm/Support/Path.h"
56*67e74705SXin Li #include "llvm/Support/SaveAndRestore.h"
57*67e74705SXin Li #include "llvm/Support/raw_ostream.h"
58*67e74705SXin Li #include <algorithm>
59*67e74705SXin Li #include <cstdio>
60*67e74705SXin Li #include <iterator>
61*67e74705SXin Li #include <system_error>
62*67e74705SXin Li
63*67e74705SXin Li using namespace clang;
64*67e74705SXin Li using namespace clang::serialization;
65*67e74705SXin Li using namespace clang::serialization::reader;
66*67e74705SXin Li using llvm::BitstreamCursor;
67*67e74705SXin Li
68*67e74705SXin Li
69*67e74705SXin Li //===----------------------------------------------------------------------===//
70*67e74705SXin Li // ChainedASTReaderListener implementation
71*67e74705SXin Li //===----------------------------------------------------------------------===//
72*67e74705SXin Li
73*67e74705SXin Li bool
ReadFullVersionInformation(StringRef FullVersion)74*67e74705SXin Li ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
75*67e74705SXin Li return First->ReadFullVersionInformation(FullVersion) ||
76*67e74705SXin Li Second->ReadFullVersionInformation(FullVersion);
77*67e74705SXin Li }
ReadModuleName(StringRef ModuleName)78*67e74705SXin Li void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
79*67e74705SXin Li First->ReadModuleName(ModuleName);
80*67e74705SXin Li Second->ReadModuleName(ModuleName);
81*67e74705SXin Li }
ReadModuleMapFile(StringRef ModuleMapPath)82*67e74705SXin Li void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
83*67e74705SXin Li First->ReadModuleMapFile(ModuleMapPath);
84*67e74705SXin Li Second->ReadModuleMapFile(ModuleMapPath);
85*67e74705SXin Li }
86*67e74705SXin Li bool
ReadLanguageOptions(const LangOptions & LangOpts,bool Complain,bool AllowCompatibleDifferences)87*67e74705SXin Li ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
88*67e74705SXin Li bool Complain,
89*67e74705SXin Li bool AllowCompatibleDifferences) {
90*67e74705SXin Li return First->ReadLanguageOptions(LangOpts, Complain,
91*67e74705SXin Li AllowCompatibleDifferences) ||
92*67e74705SXin Li Second->ReadLanguageOptions(LangOpts, Complain,
93*67e74705SXin Li AllowCompatibleDifferences);
94*67e74705SXin Li }
ReadTargetOptions(const TargetOptions & TargetOpts,bool Complain,bool AllowCompatibleDifferences)95*67e74705SXin Li bool ChainedASTReaderListener::ReadTargetOptions(
96*67e74705SXin Li const TargetOptions &TargetOpts, bool Complain,
97*67e74705SXin Li bool AllowCompatibleDifferences) {
98*67e74705SXin Li return First->ReadTargetOptions(TargetOpts, Complain,
99*67e74705SXin Li AllowCompatibleDifferences) ||
100*67e74705SXin Li Second->ReadTargetOptions(TargetOpts, Complain,
101*67e74705SXin Li AllowCompatibleDifferences);
102*67e74705SXin Li }
ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,bool Complain)103*67e74705SXin Li bool ChainedASTReaderListener::ReadDiagnosticOptions(
104*67e74705SXin Li IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
105*67e74705SXin Li return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
106*67e74705SXin Li Second->ReadDiagnosticOptions(DiagOpts, Complain);
107*67e74705SXin Li }
108*67e74705SXin Li bool
ReadFileSystemOptions(const FileSystemOptions & FSOpts,bool Complain)109*67e74705SXin Li ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
110*67e74705SXin Li bool Complain) {
111*67e74705SXin Li return First->ReadFileSystemOptions(FSOpts, Complain) ||
112*67e74705SXin Li Second->ReadFileSystemOptions(FSOpts, Complain);
113*67e74705SXin Li }
114*67e74705SXin Li
ReadHeaderSearchOptions(const HeaderSearchOptions & HSOpts,StringRef SpecificModuleCachePath,bool Complain)115*67e74705SXin Li bool ChainedASTReaderListener::ReadHeaderSearchOptions(
116*67e74705SXin Li const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
117*67e74705SXin Li bool Complain) {
118*67e74705SXin Li return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
119*67e74705SXin Li Complain) ||
120*67e74705SXin Li Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
121*67e74705SXin Li Complain);
122*67e74705SXin Li }
ReadPreprocessorOptions(const PreprocessorOptions & PPOpts,bool Complain,std::string & SuggestedPredefines)123*67e74705SXin Li bool ChainedASTReaderListener::ReadPreprocessorOptions(
124*67e74705SXin Li const PreprocessorOptions &PPOpts, bool Complain,
125*67e74705SXin Li std::string &SuggestedPredefines) {
126*67e74705SXin Li return First->ReadPreprocessorOptions(PPOpts, Complain,
127*67e74705SXin Li SuggestedPredefines) ||
128*67e74705SXin Li Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
129*67e74705SXin Li }
ReadCounter(const serialization::ModuleFile & M,unsigned Value)130*67e74705SXin Li void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
131*67e74705SXin Li unsigned Value) {
132*67e74705SXin Li First->ReadCounter(M, Value);
133*67e74705SXin Li Second->ReadCounter(M, Value);
134*67e74705SXin Li }
needsInputFileVisitation()135*67e74705SXin Li bool ChainedASTReaderListener::needsInputFileVisitation() {
136*67e74705SXin Li return First->needsInputFileVisitation() ||
137*67e74705SXin Li Second->needsInputFileVisitation();
138*67e74705SXin Li }
needsSystemInputFileVisitation()139*67e74705SXin Li bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
140*67e74705SXin Li return First->needsSystemInputFileVisitation() ||
141*67e74705SXin Li Second->needsSystemInputFileVisitation();
142*67e74705SXin Li }
visitModuleFile(StringRef Filename,ModuleKind Kind)143*67e74705SXin Li void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
144*67e74705SXin Li ModuleKind Kind) {
145*67e74705SXin Li First->visitModuleFile(Filename, Kind);
146*67e74705SXin Li Second->visitModuleFile(Filename, Kind);
147*67e74705SXin Li }
visitInputFile(StringRef Filename,bool isSystem,bool isOverridden,bool isExplicitModule)148*67e74705SXin Li bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
149*67e74705SXin Li bool isSystem,
150*67e74705SXin Li bool isOverridden,
151*67e74705SXin Li bool isExplicitModule) {
152*67e74705SXin Li bool Continue = false;
153*67e74705SXin Li if (First->needsInputFileVisitation() &&
154*67e74705SXin Li (!isSystem || First->needsSystemInputFileVisitation()))
155*67e74705SXin Li Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
156*67e74705SXin Li isExplicitModule);
157*67e74705SXin Li if (Second->needsInputFileVisitation() &&
158*67e74705SXin Li (!isSystem || Second->needsSystemInputFileVisitation()))
159*67e74705SXin Li Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
160*67e74705SXin Li isExplicitModule);
161*67e74705SXin Li return Continue;
162*67e74705SXin Li }
163*67e74705SXin Li
readModuleFileExtension(const ModuleFileExtensionMetadata & Metadata)164*67e74705SXin Li void ChainedASTReaderListener::readModuleFileExtension(
165*67e74705SXin Li const ModuleFileExtensionMetadata &Metadata) {
166*67e74705SXin Li First->readModuleFileExtension(Metadata);
167*67e74705SXin Li Second->readModuleFileExtension(Metadata);
168*67e74705SXin Li }
169*67e74705SXin Li
170*67e74705SXin Li //===----------------------------------------------------------------------===//
171*67e74705SXin Li // PCH validator implementation
172*67e74705SXin Li //===----------------------------------------------------------------------===//
173*67e74705SXin Li
~ASTReaderListener()174*67e74705SXin Li ASTReaderListener::~ASTReaderListener() {}
175*67e74705SXin Li
176*67e74705SXin Li /// \brief Compare the given set of language options against an existing set of
177*67e74705SXin Li /// language options.
178*67e74705SXin Li ///
179*67e74705SXin Li /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
180*67e74705SXin Li /// \param AllowCompatibleDifferences If true, differences between compatible
181*67e74705SXin Li /// language options will be permitted.
182*67e74705SXin Li ///
183*67e74705SXin Li /// \returns true if the languagae options mis-match, false otherwise.
checkLanguageOptions(const LangOptions & LangOpts,const LangOptions & ExistingLangOpts,DiagnosticsEngine * Diags,bool AllowCompatibleDifferences=true)184*67e74705SXin Li static bool checkLanguageOptions(const LangOptions &LangOpts,
185*67e74705SXin Li const LangOptions &ExistingLangOpts,
186*67e74705SXin Li DiagnosticsEngine *Diags,
187*67e74705SXin Li bool AllowCompatibleDifferences = true) {
188*67e74705SXin Li #define LANGOPT(Name, Bits, Default, Description) \
189*67e74705SXin Li if (ExistingLangOpts.Name != LangOpts.Name) { \
190*67e74705SXin Li if (Diags) \
191*67e74705SXin Li Diags->Report(diag::err_pch_langopt_mismatch) \
192*67e74705SXin Li << Description << LangOpts.Name << ExistingLangOpts.Name; \
193*67e74705SXin Li return true; \
194*67e74705SXin Li }
195*67e74705SXin Li
196*67e74705SXin Li #define VALUE_LANGOPT(Name, Bits, Default, Description) \
197*67e74705SXin Li if (ExistingLangOpts.Name != LangOpts.Name) { \
198*67e74705SXin Li if (Diags) \
199*67e74705SXin Li Diags->Report(diag::err_pch_langopt_value_mismatch) \
200*67e74705SXin Li << Description; \
201*67e74705SXin Li return true; \
202*67e74705SXin Li }
203*67e74705SXin Li
204*67e74705SXin Li #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
205*67e74705SXin Li if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
206*67e74705SXin Li if (Diags) \
207*67e74705SXin Li Diags->Report(diag::err_pch_langopt_value_mismatch) \
208*67e74705SXin Li << Description; \
209*67e74705SXin Li return true; \
210*67e74705SXin Li }
211*67e74705SXin Li
212*67e74705SXin Li #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
213*67e74705SXin Li if (!AllowCompatibleDifferences) \
214*67e74705SXin Li LANGOPT(Name, Bits, Default, Description)
215*67e74705SXin Li
216*67e74705SXin Li #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
217*67e74705SXin Li if (!AllowCompatibleDifferences) \
218*67e74705SXin Li ENUM_LANGOPT(Name, Bits, Default, Description)
219*67e74705SXin Li
220*67e74705SXin Li #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
221*67e74705SXin Li if (!AllowCompatibleDifferences) \
222*67e74705SXin Li VALUE_LANGOPT(Name, Bits, Default, Description)
223*67e74705SXin Li
224*67e74705SXin Li #define BENIGN_LANGOPT(Name, Bits, Default, Description)
225*67e74705SXin Li #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
226*67e74705SXin Li #define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
227*67e74705SXin Li #include "clang/Basic/LangOptions.def"
228*67e74705SXin Li
229*67e74705SXin Li if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
230*67e74705SXin Li if (Diags)
231*67e74705SXin Li Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
232*67e74705SXin Li return true;
233*67e74705SXin Li }
234*67e74705SXin Li
235*67e74705SXin Li if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
236*67e74705SXin Li if (Diags)
237*67e74705SXin Li Diags->Report(diag::err_pch_langopt_value_mismatch)
238*67e74705SXin Li << "target Objective-C runtime";
239*67e74705SXin Li return true;
240*67e74705SXin Li }
241*67e74705SXin Li
242*67e74705SXin Li if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
243*67e74705SXin Li LangOpts.CommentOpts.BlockCommandNames) {
244*67e74705SXin Li if (Diags)
245*67e74705SXin Li Diags->Report(diag::err_pch_langopt_value_mismatch)
246*67e74705SXin Li << "block command names";
247*67e74705SXin Li return true;
248*67e74705SXin Li }
249*67e74705SXin Li
250*67e74705SXin Li return false;
251*67e74705SXin Li }
252*67e74705SXin Li
253*67e74705SXin Li /// \brief Compare the given set of target options against an existing set of
254*67e74705SXin Li /// target options.
255*67e74705SXin Li ///
256*67e74705SXin Li /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
257*67e74705SXin Li ///
258*67e74705SXin Li /// \returns true if the target options mis-match, false otherwise.
checkTargetOptions(const TargetOptions & TargetOpts,const TargetOptions & ExistingTargetOpts,DiagnosticsEngine * Diags,bool AllowCompatibleDifferences=true)259*67e74705SXin Li static bool checkTargetOptions(const TargetOptions &TargetOpts,
260*67e74705SXin Li const TargetOptions &ExistingTargetOpts,
261*67e74705SXin Li DiagnosticsEngine *Diags,
262*67e74705SXin Li bool AllowCompatibleDifferences = true) {
263*67e74705SXin Li #define CHECK_TARGET_OPT(Field, Name) \
264*67e74705SXin Li if (TargetOpts.Field != ExistingTargetOpts.Field) { \
265*67e74705SXin Li if (Diags) \
266*67e74705SXin Li Diags->Report(diag::err_pch_targetopt_mismatch) \
267*67e74705SXin Li << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
268*67e74705SXin Li return true; \
269*67e74705SXin Li }
270*67e74705SXin Li
271*67e74705SXin Li // The triple and ABI must match exactly.
272*67e74705SXin Li CHECK_TARGET_OPT(Triple, "target");
273*67e74705SXin Li CHECK_TARGET_OPT(ABI, "target ABI");
274*67e74705SXin Li
275*67e74705SXin Li // We can tolerate different CPUs in many cases, notably when one CPU
276*67e74705SXin Li // supports a strict superset of another. When allowing compatible
277*67e74705SXin Li // differences skip this check.
278*67e74705SXin Li if (!AllowCompatibleDifferences)
279*67e74705SXin Li CHECK_TARGET_OPT(CPU, "target CPU");
280*67e74705SXin Li
281*67e74705SXin Li #undef CHECK_TARGET_OPT
282*67e74705SXin Li
283*67e74705SXin Li // Compare feature sets.
284*67e74705SXin Li SmallVector<StringRef, 4> ExistingFeatures(
285*67e74705SXin Li ExistingTargetOpts.FeaturesAsWritten.begin(),
286*67e74705SXin Li ExistingTargetOpts.FeaturesAsWritten.end());
287*67e74705SXin Li SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
288*67e74705SXin Li TargetOpts.FeaturesAsWritten.end());
289*67e74705SXin Li std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
290*67e74705SXin Li std::sort(ReadFeatures.begin(), ReadFeatures.end());
291*67e74705SXin Li
292*67e74705SXin Li // We compute the set difference in both directions explicitly so that we can
293*67e74705SXin Li // diagnose the differences differently.
294*67e74705SXin Li SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
295*67e74705SXin Li std::set_difference(
296*67e74705SXin Li ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
297*67e74705SXin Li ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
298*67e74705SXin Li std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
299*67e74705SXin Li ExistingFeatures.begin(), ExistingFeatures.end(),
300*67e74705SXin Li std::back_inserter(UnmatchedReadFeatures));
301*67e74705SXin Li
302*67e74705SXin Li // If we are allowing compatible differences and the read feature set is
303*67e74705SXin Li // a strict subset of the existing feature set, there is nothing to diagnose.
304*67e74705SXin Li if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
305*67e74705SXin Li return false;
306*67e74705SXin Li
307*67e74705SXin Li if (Diags) {
308*67e74705SXin Li for (StringRef Feature : UnmatchedReadFeatures)
309*67e74705SXin Li Diags->Report(diag::err_pch_targetopt_feature_mismatch)
310*67e74705SXin Li << /* is-existing-feature */ false << Feature;
311*67e74705SXin Li for (StringRef Feature : UnmatchedExistingFeatures)
312*67e74705SXin Li Diags->Report(diag::err_pch_targetopt_feature_mismatch)
313*67e74705SXin Li << /* is-existing-feature */ true << Feature;
314*67e74705SXin Li }
315*67e74705SXin Li
316*67e74705SXin Li return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
317*67e74705SXin Li }
318*67e74705SXin Li
319*67e74705SXin Li bool
ReadLanguageOptions(const LangOptions & LangOpts,bool Complain,bool AllowCompatibleDifferences)320*67e74705SXin Li PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
321*67e74705SXin Li bool Complain,
322*67e74705SXin Li bool AllowCompatibleDifferences) {
323*67e74705SXin Li const LangOptions &ExistingLangOpts = PP.getLangOpts();
324*67e74705SXin Li return checkLanguageOptions(LangOpts, ExistingLangOpts,
325*67e74705SXin Li Complain ? &Reader.Diags : nullptr,
326*67e74705SXin Li AllowCompatibleDifferences);
327*67e74705SXin Li }
328*67e74705SXin Li
ReadTargetOptions(const TargetOptions & TargetOpts,bool Complain,bool AllowCompatibleDifferences)329*67e74705SXin Li bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
330*67e74705SXin Li bool Complain,
331*67e74705SXin Li bool AllowCompatibleDifferences) {
332*67e74705SXin Li const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
333*67e74705SXin Li return checkTargetOptions(TargetOpts, ExistingTargetOpts,
334*67e74705SXin Li Complain ? &Reader.Diags : nullptr,
335*67e74705SXin Li AllowCompatibleDifferences);
336*67e74705SXin Li }
337*67e74705SXin Li
338*67e74705SXin Li namespace {
339*67e74705SXin Li typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
340*67e74705SXin Li MacroDefinitionsMap;
341*67e74705SXin Li typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
342*67e74705SXin Li DeclsMap;
343*67e74705SXin Li }
344*67e74705SXin Li
checkDiagnosticGroupMappings(DiagnosticsEngine & StoredDiags,DiagnosticsEngine & Diags,bool Complain)345*67e74705SXin Li static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
346*67e74705SXin Li DiagnosticsEngine &Diags,
347*67e74705SXin Li bool Complain) {
348*67e74705SXin Li typedef DiagnosticsEngine::Level Level;
349*67e74705SXin Li
350*67e74705SXin Li // Check current mappings for new -Werror mappings, and the stored mappings
351*67e74705SXin Li // for cases that were explicitly mapped to *not* be errors that are now
352*67e74705SXin Li // errors because of options like -Werror.
353*67e74705SXin Li DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
354*67e74705SXin Li
355*67e74705SXin Li for (DiagnosticsEngine *MappingSource : MappingSources) {
356*67e74705SXin Li for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
357*67e74705SXin Li diag::kind DiagID = DiagIDMappingPair.first;
358*67e74705SXin Li Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
359*67e74705SXin Li if (CurLevel < DiagnosticsEngine::Error)
360*67e74705SXin Li continue; // not significant
361*67e74705SXin Li Level StoredLevel =
362*67e74705SXin Li StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
363*67e74705SXin Li if (StoredLevel < DiagnosticsEngine::Error) {
364*67e74705SXin Li if (Complain)
365*67e74705SXin Li Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
366*67e74705SXin Li Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
367*67e74705SXin Li return true;
368*67e74705SXin Li }
369*67e74705SXin Li }
370*67e74705SXin Li }
371*67e74705SXin Li
372*67e74705SXin Li return false;
373*67e74705SXin Li }
374*67e74705SXin Li
isExtHandlingFromDiagsError(DiagnosticsEngine & Diags)375*67e74705SXin Li static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
376*67e74705SXin Li diag::Severity Ext = Diags.getExtensionHandlingBehavior();
377*67e74705SXin Li if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
378*67e74705SXin Li return true;
379*67e74705SXin Li return Ext >= diag::Severity::Error;
380*67e74705SXin Li }
381*67e74705SXin Li
checkDiagnosticMappings(DiagnosticsEngine & StoredDiags,DiagnosticsEngine & Diags,bool IsSystem,bool Complain)382*67e74705SXin Li static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
383*67e74705SXin Li DiagnosticsEngine &Diags,
384*67e74705SXin Li bool IsSystem, bool Complain) {
385*67e74705SXin Li // Top-level options
386*67e74705SXin Li if (IsSystem) {
387*67e74705SXin Li if (Diags.getSuppressSystemWarnings())
388*67e74705SXin Li return false;
389*67e74705SXin Li // If -Wsystem-headers was not enabled before, be conservative
390*67e74705SXin Li if (StoredDiags.getSuppressSystemWarnings()) {
391*67e74705SXin Li if (Complain)
392*67e74705SXin Li Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
393*67e74705SXin Li return true;
394*67e74705SXin Li }
395*67e74705SXin Li }
396*67e74705SXin Li
397*67e74705SXin Li if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
398*67e74705SXin Li if (Complain)
399*67e74705SXin Li Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
400*67e74705SXin Li return true;
401*67e74705SXin Li }
402*67e74705SXin Li
403*67e74705SXin Li if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
404*67e74705SXin Li !StoredDiags.getEnableAllWarnings()) {
405*67e74705SXin Li if (Complain)
406*67e74705SXin Li Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
407*67e74705SXin Li return true;
408*67e74705SXin Li }
409*67e74705SXin Li
410*67e74705SXin Li if (isExtHandlingFromDiagsError(Diags) &&
411*67e74705SXin Li !isExtHandlingFromDiagsError(StoredDiags)) {
412*67e74705SXin Li if (Complain)
413*67e74705SXin Li Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
414*67e74705SXin Li return true;
415*67e74705SXin Li }
416*67e74705SXin Li
417*67e74705SXin Li return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
418*67e74705SXin Li }
419*67e74705SXin Li
ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,bool Complain)420*67e74705SXin Li bool PCHValidator::ReadDiagnosticOptions(
421*67e74705SXin Li IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
422*67e74705SXin Li DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
423*67e74705SXin Li IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
424*67e74705SXin Li IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
425*67e74705SXin Li new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
426*67e74705SXin Li // This should never fail, because we would have processed these options
427*67e74705SXin Li // before writing them to an ASTFile.
428*67e74705SXin Li ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
429*67e74705SXin Li
430*67e74705SXin Li ModuleManager &ModuleMgr = Reader.getModuleManager();
431*67e74705SXin Li assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
432*67e74705SXin Li
433*67e74705SXin Li // If the original import came from a file explicitly generated by the user,
434*67e74705SXin Li // don't check the diagnostic mappings.
435*67e74705SXin Li // FIXME: currently this is approximated by checking whether this is not a
436*67e74705SXin Li // module import of an implicitly-loaded module file.
437*67e74705SXin Li // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
438*67e74705SXin Li // the transitive closure of its imports, since unrelated modules cannot be
439*67e74705SXin Li // imported until after this module finishes validation.
440*67e74705SXin Li ModuleFile *TopImport = *ModuleMgr.rbegin();
441*67e74705SXin Li while (!TopImport->ImportedBy.empty())
442*67e74705SXin Li TopImport = TopImport->ImportedBy[0];
443*67e74705SXin Li if (TopImport->Kind != MK_ImplicitModule)
444*67e74705SXin Li return false;
445*67e74705SXin Li
446*67e74705SXin Li StringRef ModuleName = TopImport->ModuleName;
447*67e74705SXin Li assert(!ModuleName.empty() && "diagnostic options read before module name");
448*67e74705SXin Li
449*67e74705SXin Li Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
450*67e74705SXin Li assert(M && "missing module");
451*67e74705SXin Li
452*67e74705SXin Li // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
453*67e74705SXin Li // contains the union of their flags.
454*67e74705SXin Li return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
455*67e74705SXin Li }
456*67e74705SXin Li
457*67e74705SXin Li /// \brief Collect the macro definitions provided by the given preprocessor
458*67e74705SXin Li /// options.
459*67e74705SXin Li static void
collectMacroDefinitions(const PreprocessorOptions & PPOpts,MacroDefinitionsMap & Macros,SmallVectorImpl<StringRef> * MacroNames=nullptr)460*67e74705SXin Li collectMacroDefinitions(const PreprocessorOptions &PPOpts,
461*67e74705SXin Li MacroDefinitionsMap &Macros,
462*67e74705SXin Li SmallVectorImpl<StringRef> *MacroNames = nullptr) {
463*67e74705SXin Li for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
464*67e74705SXin Li StringRef Macro = PPOpts.Macros[I].first;
465*67e74705SXin Li bool IsUndef = PPOpts.Macros[I].second;
466*67e74705SXin Li
467*67e74705SXin Li std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
468*67e74705SXin Li StringRef MacroName = MacroPair.first;
469*67e74705SXin Li StringRef MacroBody = MacroPair.second;
470*67e74705SXin Li
471*67e74705SXin Li // For an #undef'd macro, we only care about the name.
472*67e74705SXin Li if (IsUndef) {
473*67e74705SXin Li if (MacroNames && !Macros.count(MacroName))
474*67e74705SXin Li MacroNames->push_back(MacroName);
475*67e74705SXin Li
476*67e74705SXin Li Macros[MacroName] = std::make_pair("", true);
477*67e74705SXin Li continue;
478*67e74705SXin Li }
479*67e74705SXin Li
480*67e74705SXin Li // For a #define'd macro, figure out the actual definition.
481*67e74705SXin Li if (MacroName.size() == Macro.size())
482*67e74705SXin Li MacroBody = "1";
483*67e74705SXin Li else {
484*67e74705SXin Li // Note: GCC drops anything following an end-of-line character.
485*67e74705SXin Li StringRef::size_type End = MacroBody.find_first_of("\n\r");
486*67e74705SXin Li MacroBody = MacroBody.substr(0, End);
487*67e74705SXin Li }
488*67e74705SXin Li
489*67e74705SXin Li if (MacroNames && !Macros.count(MacroName))
490*67e74705SXin Li MacroNames->push_back(MacroName);
491*67e74705SXin Li Macros[MacroName] = std::make_pair(MacroBody, false);
492*67e74705SXin Li }
493*67e74705SXin Li }
494*67e74705SXin Li
495*67e74705SXin Li /// \brief Check the preprocessor options deserialized from the control block
496*67e74705SXin Li /// against the preprocessor options in an existing preprocessor.
497*67e74705SXin Li ///
498*67e74705SXin Li /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
checkPreprocessorOptions(const PreprocessorOptions & PPOpts,const PreprocessorOptions & ExistingPPOpts,DiagnosticsEngine * Diags,FileManager & FileMgr,std::string & SuggestedPredefines,const LangOptions & LangOpts)499*67e74705SXin Li static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
500*67e74705SXin Li const PreprocessorOptions &ExistingPPOpts,
501*67e74705SXin Li DiagnosticsEngine *Diags,
502*67e74705SXin Li FileManager &FileMgr,
503*67e74705SXin Li std::string &SuggestedPredefines,
504*67e74705SXin Li const LangOptions &LangOpts) {
505*67e74705SXin Li // Check macro definitions.
506*67e74705SXin Li MacroDefinitionsMap ASTFileMacros;
507*67e74705SXin Li collectMacroDefinitions(PPOpts, ASTFileMacros);
508*67e74705SXin Li MacroDefinitionsMap ExistingMacros;
509*67e74705SXin Li SmallVector<StringRef, 4> ExistingMacroNames;
510*67e74705SXin Li collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
511*67e74705SXin Li
512*67e74705SXin Li for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
513*67e74705SXin Li // Dig out the macro definition in the existing preprocessor options.
514*67e74705SXin Li StringRef MacroName = ExistingMacroNames[I];
515*67e74705SXin Li std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
516*67e74705SXin Li
517*67e74705SXin Li // Check whether we know anything about this macro name or not.
518*67e74705SXin Li llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
519*67e74705SXin Li = ASTFileMacros.find(MacroName);
520*67e74705SXin Li if (Known == ASTFileMacros.end()) {
521*67e74705SXin Li // FIXME: Check whether this identifier was referenced anywhere in the
522*67e74705SXin Li // AST file. If so, we should reject the AST file. Unfortunately, this
523*67e74705SXin Li // information isn't in the control block. What shall we do about it?
524*67e74705SXin Li
525*67e74705SXin Li if (Existing.second) {
526*67e74705SXin Li SuggestedPredefines += "#undef ";
527*67e74705SXin Li SuggestedPredefines += MacroName.str();
528*67e74705SXin Li SuggestedPredefines += '\n';
529*67e74705SXin Li } else {
530*67e74705SXin Li SuggestedPredefines += "#define ";
531*67e74705SXin Li SuggestedPredefines += MacroName.str();
532*67e74705SXin Li SuggestedPredefines += ' ';
533*67e74705SXin Li SuggestedPredefines += Existing.first.str();
534*67e74705SXin Li SuggestedPredefines += '\n';
535*67e74705SXin Li }
536*67e74705SXin Li continue;
537*67e74705SXin Li }
538*67e74705SXin Li
539*67e74705SXin Li // If the macro was defined in one but undef'd in the other, we have a
540*67e74705SXin Li // conflict.
541*67e74705SXin Li if (Existing.second != Known->second.second) {
542*67e74705SXin Li if (Diags) {
543*67e74705SXin Li Diags->Report(diag::err_pch_macro_def_undef)
544*67e74705SXin Li << MacroName << Known->second.second;
545*67e74705SXin Li }
546*67e74705SXin Li return true;
547*67e74705SXin Li }
548*67e74705SXin Li
549*67e74705SXin Li // If the macro was #undef'd in both, or if the macro bodies are identical,
550*67e74705SXin Li // it's fine.
551*67e74705SXin Li if (Existing.second || Existing.first == Known->second.first)
552*67e74705SXin Li continue;
553*67e74705SXin Li
554*67e74705SXin Li // The macro bodies differ; complain.
555*67e74705SXin Li if (Diags) {
556*67e74705SXin Li Diags->Report(diag::err_pch_macro_def_conflict)
557*67e74705SXin Li << MacroName << Known->second.first << Existing.first;
558*67e74705SXin Li }
559*67e74705SXin Li return true;
560*67e74705SXin Li }
561*67e74705SXin Li
562*67e74705SXin Li // Check whether we're using predefines.
563*67e74705SXin Li if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
564*67e74705SXin Li if (Diags) {
565*67e74705SXin Li Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
566*67e74705SXin Li }
567*67e74705SXin Li return true;
568*67e74705SXin Li }
569*67e74705SXin Li
570*67e74705SXin Li // Detailed record is important since it is used for the module cache hash.
571*67e74705SXin Li if (LangOpts.Modules &&
572*67e74705SXin Li PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
573*67e74705SXin Li if (Diags) {
574*67e74705SXin Li Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
575*67e74705SXin Li }
576*67e74705SXin Li return true;
577*67e74705SXin Li }
578*67e74705SXin Li
579*67e74705SXin Li // Compute the #include and #include_macros lines we need.
580*67e74705SXin Li for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
581*67e74705SXin Li StringRef File = ExistingPPOpts.Includes[I];
582*67e74705SXin Li if (File == ExistingPPOpts.ImplicitPCHInclude)
583*67e74705SXin Li continue;
584*67e74705SXin Li
585*67e74705SXin Li if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
586*67e74705SXin Li != PPOpts.Includes.end())
587*67e74705SXin Li continue;
588*67e74705SXin Li
589*67e74705SXin Li SuggestedPredefines += "#include \"";
590*67e74705SXin Li SuggestedPredefines += File;
591*67e74705SXin Li SuggestedPredefines += "\"\n";
592*67e74705SXin Li }
593*67e74705SXin Li
594*67e74705SXin Li for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
595*67e74705SXin Li StringRef File = ExistingPPOpts.MacroIncludes[I];
596*67e74705SXin Li if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
597*67e74705SXin Li File)
598*67e74705SXin Li != PPOpts.MacroIncludes.end())
599*67e74705SXin Li continue;
600*67e74705SXin Li
601*67e74705SXin Li SuggestedPredefines += "#__include_macros \"";
602*67e74705SXin Li SuggestedPredefines += File;
603*67e74705SXin Li SuggestedPredefines += "\"\n##\n";
604*67e74705SXin Li }
605*67e74705SXin Li
606*67e74705SXin Li return false;
607*67e74705SXin Li }
608*67e74705SXin Li
ReadPreprocessorOptions(const PreprocessorOptions & PPOpts,bool Complain,std::string & SuggestedPredefines)609*67e74705SXin Li bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
610*67e74705SXin Li bool Complain,
611*67e74705SXin Li std::string &SuggestedPredefines) {
612*67e74705SXin Li const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
613*67e74705SXin Li
614*67e74705SXin Li return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
615*67e74705SXin Li Complain? &Reader.Diags : nullptr,
616*67e74705SXin Li PP.getFileManager(),
617*67e74705SXin Li SuggestedPredefines,
618*67e74705SXin Li PP.getLangOpts());
619*67e74705SXin Li }
620*67e74705SXin Li
621*67e74705SXin Li /// Check the header search options deserialized from the control block
622*67e74705SXin Li /// against the header search options in an existing preprocessor.
623*67e74705SXin Li ///
624*67e74705SXin Li /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
checkHeaderSearchOptions(const HeaderSearchOptions & HSOpts,StringRef SpecificModuleCachePath,StringRef ExistingModuleCachePath,DiagnosticsEngine * Diags,const LangOptions & LangOpts)625*67e74705SXin Li static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
626*67e74705SXin Li StringRef SpecificModuleCachePath,
627*67e74705SXin Li StringRef ExistingModuleCachePath,
628*67e74705SXin Li DiagnosticsEngine *Diags,
629*67e74705SXin Li const LangOptions &LangOpts) {
630*67e74705SXin Li if (LangOpts.Modules) {
631*67e74705SXin Li if (SpecificModuleCachePath != ExistingModuleCachePath) {
632*67e74705SXin Li if (Diags)
633*67e74705SXin Li Diags->Report(diag::err_pch_modulecache_mismatch)
634*67e74705SXin Li << SpecificModuleCachePath << ExistingModuleCachePath;
635*67e74705SXin Li return true;
636*67e74705SXin Li }
637*67e74705SXin Li }
638*67e74705SXin Li
639*67e74705SXin Li return false;
640*67e74705SXin Li }
641*67e74705SXin Li
ReadHeaderSearchOptions(const HeaderSearchOptions & HSOpts,StringRef SpecificModuleCachePath,bool Complain)642*67e74705SXin Li bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
643*67e74705SXin Li StringRef SpecificModuleCachePath,
644*67e74705SXin Li bool Complain) {
645*67e74705SXin Li return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
646*67e74705SXin Li PP.getHeaderSearchInfo().getModuleCachePath(),
647*67e74705SXin Li Complain ? &Reader.Diags : nullptr,
648*67e74705SXin Li PP.getLangOpts());
649*67e74705SXin Li }
650*67e74705SXin Li
ReadCounter(const ModuleFile & M,unsigned Value)651*67e74705SXin Li void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
652*67e74705SXin Li PP.setCounterValue(Value);
653*67e74705SXin Li }
654*67e74705SXin Li
655*67e74705SXin Li //===----------------------------------------------------------------------===//
656*67e74705SXin Li // AST reader implementation
657*67e74705SXin Li //===----------------------------------------------------------------------===//
658*67e74705SXin Li
setDeserializationListener(ASTDeserializationListener * Listener,bool TakeOwnership)659*67e74705SXin Li void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
660*67e74705SXin Li bool TakeOwnership) {
661*67e74705SXin Li DeserializationListener = Listener;
662*67e74705SXin Li OwnsDeserializationListener = TakeOwnership;
663*67e74705SXin Li }
664*67e74705SXin Li
665*67e74705SXin Li
666*67e74705SXin Li
ComputeHash(Selector Sel)667*67e74705SXin Li unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
668*67e74705SXin Li return serialization::ComputeHash(Sel);
669*67e74705SXin Li }
670*67e74705SXin Li
671*67e74705SXin Li
672*67e74705SXin Li std::pair<unsigned, unsigned>
ReadKeyDataLength(const unsigned char * & d)673*67e74705SXin Li ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
674*67e74705SXin Li using namespace llvm::support;
675*67e74705SXin Li unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
676*67e74705SXin Li unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
677*67e74705SXin Li return std::make_pair(KeyLen, DataLen);
678*67e74705SXin Li }
679*67e74705SXin Li
680*67e74705SXin Li ASTSelectorLookupTrait::internal_key_type
ReadKey(const unsigned char * d,unsigned)681*67e74705SXin Li ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
682*67e74705SXin Li using namespace llvm::support;
683*67e74705SXin Li SelectorTable &SelTable = Reader.getContext().Selectors;
684*67e74705SXin Li unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
685*67e74705SXin Li IdentifierInfo *FirstII = Reader.getLocalIdentifier(
686*67e74705SXin Li F, endian::readNext<uint32_t, little, unaligned>(d));
687*67e74705SXin Li if (N == 0)
688*67e74705SXin Li return SelTable.getNullarySelector(FirstII);
689*67e74705SXin Li else if (N == 1)
690*67e74705SXin Li return SelTable.getUnarySelector(FirstII);
691*67e74705SXin Li
692*67e74705SXin Li SmallVector<IdentifierInfo *, 16> Args;
693*67e74705SXin Li Args.push_back(FirstII);
694*67e74705SXin Li for (unsigned I = 1; I != N; ++I)
695*67e74705SXin Li Args.push_back(Reader.getLocalIdentifier(
696*67e74705SXin Li F, endian::readNext<uint32_t, little, unaligned>(d)));
697*67e74705SXin Li
698*67e74705SXin Li return SelTable.getSelector(N, Args.data());
699*67e74705SXin Li }
700*67e74705SXin Li
701*67e74705SXin Li ASTSelectorLookupTrait::data_type
ReadData(Selector,const unsigned char * d,unsigned DataLen)702*67e74705SXin Li ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
703*67e74705SXin Li unsigned DataLen) {
704*67e74705SXin Li using namespace llvm::support;
705*67e74705SXin Li
706*67e74705SXin Li data_type Result;
707*67e74705SXin Li
708*67e74705SXin Li Result.ID = Reader.getGlobalSelectorID(
709*67e74705SXin Li F, endian::readNext<uint32_t, little, unaligned>(d));
710*67e74705SXin Li unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
711*67e74705SXin Li unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
712*67e74705SXin Li Result.InstanceBits = FullInstanceBits & 0x3;
713*67e74705SXin Li Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
714*67e74705SXin Li Result.FactoryBits = FullFactoryBits & 0x3;
715*67e74705SXin Li Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
716*67e74705SXin Li unsigned NumInstanceMethods = FullInstanceBits >> 3;
717*67e74705SXin Li unsigned NumFactoryMethods = FullFactoryBits >> 3;
718*67e74705SXin Li
719*67e74705SXin Li // Load instance methods
720*67e74705SXin Li for (unsigned I = 0; I != NumInstanceMethods; ++I) {
721*67e74705SXin Li if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
722*67e74705SXin Li F, endian::readNext<uint32_t, little, unaligned>(d)))
723*67e74705SXin Li Result.Instance.push_back(Method);
724*67e74705SXin Li }
725*67e74705SXin Li
726*67e74705SXin Li // Load factory methods
727*67e74705SXin Li for (unsigned I = 0; I != NumFactoryMethods; ++I) {
728*67e74705SXin Li if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
729*67e74705SXin Li F, endian::readNext<uint32_t, little, unaligned>(d)))
730*67e74705SXin Li Result.Factory.push_back(Method);
731*67e74705SXin Li }
732*67e74705SXin Li
733*67e74705SXin Li return Result;
734*67e74705SXin Li }
735*67e74705SXin Li
ComputeHash(const internal_key_type & a)736*67e74705SXin Li unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
737*67e74705SXin Li return llvm::HashString(a);
738*67e74705SXin Li }
739*67e74705SXin Li
740*67e74705SXin Li std::pair<unsigned, unsigned>
ReadKeyDataLength(const unsigned char * & d)741*67e74705SXin Li ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
742*67e74705SXin Li using namespace llvm::support;
743*67e74705SXin Li unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
744*67e74705SXin Li unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
745*67e74705SXin Li return std::make_pair(KeyLen, DataLen);
746*67e74705SXin Li }
747*67e74705SXin Li
748*67e74705SXin Li ASTIdentifierLookupTraitBase::internal_key_type
ReadKey(const unsigned char * d,unsigned n)749*67e74705SXin Li ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
750*67e74705SXin Li assert(n >= 2 && d[n-1] == '\0');
751*67e74705SXin Li return StringRef((const char*) d, n-1);
752*67e74705SXin Li }
753*67e74705SXin Li
754*67e74705SXin Li /// \brief Whether the given identifier is "interesting".
isInterestingIdentifier(ASTReader & Reader,IdentifierInfo & II,bool IsModule)755*67e74705SXin Li static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
756*67e74705SXin Li bool IsModule) {
757*67e74705SXin Li return II.hadMacroDefinition() ||
758*67e74705SXin Li II.isPoisoned() ||
759*67e74705SXin Li (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
760*67e74705SXin Li II.hasRevertedTokenIDToIdentifier() ||
761*67e74705SXin Li (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
762*67e74705SXin Li II.getFETokenInfo<void>());
763*67e74705SXin Li }
764*67e74705SXin Li
readBit(unsigned & Bits)765*67e74705SXin Li static bool readBit(unsigned &Bits) {
766*67e74705SXin Li bool Value = Bits & 0x1;
767*67e74705SXin Li Bits >>= 1;
768*67e74705SXin Li return Value;
769*67e74705SXin Li }
770*67e74705SXin Li
ReadIdentifierID(const unsigned char * d)771*67e74705SXin Li IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
772*67e74705SXin Li using namespace llvm::support;
773*67e74705SXin Li unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
774*67e74705SXin Li return Reader.getGlobalIdentifierID(F, RawID >> 1);
775*67e74705SXin Li }
776*67e74705SXin Li
markIdentifierFromAST(ASTReader & Reader,IdentifierInfo & II)777*67e74705SXin Li static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
778*67e74705SXin Li if (!II.isFromAST()) {
779*67e74705SXin Li II.setIsFromAST();
780*67e74705SXin Li bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
781*67e74705SXin Li if (isInterestingIdentifier(Reader, II, IsModule))
782*67e74705SXin Li II.setChangedSinceDeserialization();
783*67e74705SXin Li }
784*67e74705SXin Li }
785*67e74705SXin Li
ReadData(const internal_key_type & k,const unsigned char * d,unsigned DataLen)786*67e74705SXin Li IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
787*67e74705SXin Li const unsigned char* d,
788*67e74705SXin Li unsigned DataLen) {
789*67e74705SXin Li using namespace llvm::support;
790*67e74705SXin Li unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
791*67e74705SXin Li bool IsInteresting = RawID & 0x01;
792*67e74705SXin Li
793*67e74705SXin Li // Wipe out the "is interesting" bit.
794*67e74705SXin Li RawID = RawID >> 1;
795*67e74705SXin Li
796*67e74705SXin Li // Build the IdentifierInfo and link the identifier ID with it.
797*67e74705SXin Li IdentifierInfo *II = KnownII;
798*67e74705SXin Li if (!II) {
799*67e74705SXin Li II = &Reader.getIdentifierTable().getOwn(k);
800*67e74705SXin Li KnownII = II;
801*67e74705SXin Li }
802*67e74705SXin Li markIdentifierFromAST(Reader, *II);
803*67e74705SXin Li Reader.markIdentifierUpToDate(II);
804*67e74705SXin Li
805*67e74705SXin Li IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
806*67e74705SXin Li if (!IsInteresting) {
807*67e74705SXin Li // For uninteresting identifiers, there's nothing else to do. Just notify
808*67e74705SXin Li // the reader that we've finished loading this identifier.
809*67e74705SXin Li Reader.SetIdentifierInfo(ID, II);
810*67e74705SXin Li return II;
811*67e74705SXin Li }
812*67e74705SXin Li
813*67e74705SXin Li unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
814*67e74705SXin Li unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
815*67e74705SXin Li bool CPlusPlusOperatorKeyword = readBit(Bits);
816*67e74705SXin Li bool HasRevertedTokenIDToIdentifier = readBit(Bits);
817*67e74705SXin Li bool HasRevertedBuiltin = readBit(Bits);
818*67e74705SXin Li bool Poisoned = readBit(Bits);
819*67e74705SXin Li bool ExtensionToken = readBit(Bits);
820*67e74705SXin Li bool HadMacroDefinition = readBit(Bits);
821*67e74705SXin Li
822*67e74705SXin Li assert(Bits == 0 && "Extra bits in the identifier?");
823*67e74705SXin Li DataLen -= 8;
824*67e74705SXin Li
825*67e74705SXin Li // Set or check the various bits in the IdentifierInfo structure.
826*67e74705SXin Li // Token IDs are read-only.
827*67e74705SXin Li if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
828*67e74705SXin Li II->revertTokenIDToIdentifier();
829*67e74705SXin Li if (!F.isModule())
830*67e74705SXin Li II->setObjCOrBuiltinID(ObjCOrBuiltinID);
831*67e74705SXin Li else if (HasRevertedBuiltin && II->getBuiltinID()) {
832*67e74705SXin Li II->revertBuiltin();
833*67e74705SXin Li assert((II->hasRevertedBuiltin() ||
834*67e74705SXin Li II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
835*67e74705SXin Li "Incorrect ObjC keyword or builtin ID");
836*67e74705SXin Li }
837*67e74705SXin Li assert(II->isExtensionToken() == ExtensionToken &&
838*67e74705SXin Li "Incorrect extension token flag");
839*67e74705SXin Li (void)ExtensionToken;
840*67e74705SXin Li if (Poisoned)
841*67e74705SXin Li II->setIsPoisoned(true);
842*67e74705SXin Li assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
843*67e74705SXin Li "Incorrect C++ operator keyword flag");
844*67e74705SXin Li (void)CPlusPlusOperatorKeyword;
845*67e74705SXin Li
846*67e74705SXin Li // If this identifier is a macro, deserialize the macro
847*67e74705SXin Li // definition.
848*67e74705SXin Li if (HadMacroDefinition) {
849*67e74705SXin Li uint32_t MacroDirectivesOffset =
850*67e74705SXin Li endian::readNext<uint32_t, little, unaligned>(d);
851*67e74705SXin Li DataLen -= 4;
852*67e74705SXin Li
853*67e74705SXin Li Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
854*67e74705SXin Li }
855*67e74705SXin Li
856*67e74705SXin Li Reader.SetIdentifierInfo(ID, II);
857*67e74705SXin Li
858*67e74705SXin Li // Read all of the declarations visible at global scope with this
859*67e74705SXin Li // name.
860*67e74705SXin Li if (DataLen > 0) {
861*67e74705SXin Li SmallVector<uint32_t, 4> DeclIDs;
862*67e74705SXin Li for (; DataLen > 0; DataLen -= 4)
863*67e74705SXin Li DeclIDs.push_back(Reader.getGlobalDeclID(
864*67e74705SXin Li F, endian::readNext<uint32_t, little, unaligned>(d)));
865*67e74705SXin Li Reader.SetGloballyVisibleDecls(II, DeclIDs);
866*67e74705SXin Li }
867*67e74705SXin Li
868*67e74705SXin Li return II;
869*67e74705SXin Li }
870*67e74705SXin Li
DeclarationNameKey(DeclarationName Name)871*67e74705SXin Li DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
872*67e74705SXin Li : Kind(Name.getNameKind()) {
873*67e74705SXin Li switch (Kind) {
874*67e74705SXin Li case DeclarationName::Identifier:
875*67e74705SXin Li Data = (uint64_t)Name.getAsIdentifierInfo();
876*67e74705SXin Li break;
877*67e74705SXin Li case DeclarationName::ObjCZeroArgSelector:
878*67e74705SXin Li case DeclarationName::ObjCOneArgSelector:
879*67e74705SXin Li case DeclarationName::ObjCMultiArgSelector:
880*67e74705SXin Li Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
881*67e74705SXin Li break;
882*67e74705SXin Li case DeclarationName::CXXOperatorName:
883*67e74705SXin Li Data = Name.getCXXOverloadedOperator();
884*67e74705SXin Li break;
885*67e74705SXin Li case DeclarationName::CXXLiteralOperatorName:
886*67e74705SXin Li Data = (uint64_t)Name.getCXXLiteralIdentifier();
887*67e74705SXin Li break;
888*67e74705SXin Li case DeclarationName::CXXConstructorName:
889*67e74705SXin Li case DeclarationName::CXXDestructorName:
890*67e74705SXin Li case DeclarationName::CXXConversionFunctionName:
891*67e74705SXin Li case DeclarationName::CXXUsingDirective:
892*67e74705SXin Li Data = 0;
893*67e74705SXin Li break;
894*67e74705SXin Li }
895*67e74705SXin Li }
896*67e74705SXin Li
getHash() const897*67e74705SXin Li unsigned DeclarationNameKey::getHash() const {
898*67e74705SXin Li llvm::FoldingSetNodeID ID;
899*67e74705SXin Li ID.AddInteger(Kind);
900*67e74705SXin Li
901*67e74705SXin Li switch (Kind) {
902*67e74705SXin Li case DeclarationName::Identifier:
903*67e74705SXin Li case DeclarationName::CXXLiteralOperatorName:
904*67e74705SXin Li ID.AddString(((IdentifierInfo*)Data)->getName());
905*67e74705SXin Li break;
906*67e74705SXin Li case DeclarationName::ObjCZeroArgSelector:
907*67e74705SXin Li case DeclarationName::ObjCOneArgSelector:
908*67e74705SXin Li case DeclarationName::ObjCMultiArgSelector:
909*67e74705SXin Li ID.AddInteger(serialization::ComputeHash(Selector(Data)));
910*67e74705SXin Li break;
911*67e74705SXin Li case DeclarationName::CXXOperatorName:
912*67e74705SXin Li ID.AddInteger((OverloadedOperatorKind)Data);
913*67e74705SXin Li break;
914*67e74705SXin Li case DeclarationName::CXXConstructorName:
915*67e74705SXin Li case DeclarationName::CXXDestructorName:
916*67e74705SXin Li case DeclarationName::CXXConversionFunctionName:
917*67e74705SXin Li case DeclarationName::CXXUsingDirective:
918*67e74705SXin Li break;
919*67e74705SXin Li }
920*67e74705SXin Li
921*67e74705SXin Li return ID.ComputeHash();
922*67e74705SXin Li }
923*67e74705SXin Li
924*67e74705SXin Li ModuleFile *
ReadFileRef(const unsigned char * & d)925*67e74705SXin Li ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
926*67e74705SXin Li using namespace llvm::support;
927*67e74705SXin Li uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
928*67e74705SXin Li return Reader.getLocalModuleFile(F, ModuleFileID);
929*67e74705SXin Li }
930*67e74705SXin Li
931*67e74705SXin Li std::pair<unsigned, unsigned>
ReadKeyDataLength(const unsigned char * & d)932*67e74705SXin Li ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
933*67e74705SXin Li using namespace llvm::support;
934*67e74705SXin Li unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
935*67e74705SXin Li unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
936*67e74705SXin Li return std::make_pair(KeyLen, DataLen);
937*67e74705SXin Li }
938*67e74705SXin Li
939*67e74705SXin Li ASTDeclContextNameLookupTrait::internal_key_type
ReadKey(const unsigned char * d,unsigned)940*67e74705SXin Li ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
941*67e74705SXin Li using namespace llvm::support;
942*67e74705SXin Li
943*67e74705SXin Li auto Kind = (DeclarationName::NameKind)*d++;
944*67e74705SXin Li uint64_t Data;
945*67e74705SXin Li switch (Kind) {
946*67e74705SXin Li case DeclarationName::Identifier:
947*67e74705SXin Li Data = (uint64_t)Reader.getLocalIdentifier(
948*67e74705SXin Li F, endian::readNext<uint32_t, little, unaligned>(d));
949*67e74705SXin Li break;
950*67e74705SXin Li case DeclarationName::ObjCZeroArgSelector:
951*67e74705SXin Li case DeclarationName::ObjCOneArgSelector:
952*67e74705SXin Li case DeclarationName::ObjCMultiArgSelector:
953*67e74705SXin Li Data =
954*67e74705SXin Li (uint64_t)Reader.getLocalSelector(
955*67e74705SXin Li F, endian::readNext<uint32_t, little, unaligned>(
956*67e74705SXin Li d)).getAsOpaquePtr();
957*67e74705SXin Li break;
958*67e74705SXin Li case DeclarationName::CXXOperatorName:
959*67e74705SXin Li Data = *d++; // OverloadedOperatorKind
960*67e74705SXin Li break;
961*67e74705SXin Li case DeclarationName::CXXLiteralOperatorName:
962*67e74705SXin Li Data = (uint64_t)Reader.getLocalIdentifier(
963*67e74705SXin Li F, endian::readNext<uint32_t, little, unaligned>(d));
964*67e74705SXin Li break;
965*67e74705SXin Li case DeclarationName::CXXConstructorName:
966*67e74705SXin Li case DeclarationName::CXXDestructorName:
967*67e74705SXin Li case DeclarationName::CXXConversionFunctionName:
968*67e74705SXin Li case DeclarationName::CXXUsingDirective:
969*67e74705SXin Li Data = 0;
970*67e74705SXin Li break;
971*67e74705SXin Li }
972*67e74705SXin Li
973*67e74705SXin Li return DeclarationNameKey(Kind, Data);
974*67e74705SXin Li }
975*67e74705SXin Li
ReadDataInto(internal_key_type,const unsigned char * d,unsigned DataLen,data_type_builder & Val)976*67e74705SXin Li void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
977*67e74705SXin Li const unsigned char *d,
978*67e74705SXin Li unsigned DataLen,
979*67e74705SXin Li data_type_builder &Val) {
980*67e74705SXin Li using namespace llvm::support;
981*67e74705SXin Li for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
982*67e74705SXin Li uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
983*67e74705SXin Li Val.insert(Reader.getGlobalDeclID(F, LocalID));
984*67e74705SXin Li }
985*67e74705SXin Li }
986*67e74705SXin Li
ReadLexicalDeclContextStorage(ModuleFile & M,BitstreamCursor & Cursor,uint64_t Offset,DeclContext * DC)987*67e74705SXin Li bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
988*67e74705SXin Li BitstreamCursor &Cursor,
989*67e74705SXin Li uint64_t Offset,
990*67e74705SXin Li DeclContext *DC) {
991*67e74705SXin Li assert(Offset != 0);
992*67e74705SXin Li
993*67e74705SXin Li SavedStreamPosition SavedPosition(Cursor);
994*67e74705SXin Li Cursor.JumpToBit(Offset);
995*67e74705SXin Li
996*67e74705SXin Li RecordData Record;
997*67e74705SXin Li StringRef Blob;
998*67e74705SXin Li unsigned Code = Cursor.ReadCode();
999*67e74705SXin Li unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1000*67e74705SXin Li if (RecCode != DECL_CONTEXT_LEXICAL) {
1001*67e74705SXin Li Error("Expected lexical block");
1002*67e74705SXin Li return true;
1003*67e74705SXin Li }
1004*67e74705SXin Li
1005*67e74705SXin Li assert(!isa<TranslationUnitDecl>(DC) &&
1006*67e74705SXin Li "expected a TU_UPDATE_LEXICAL record for TU");
1007*67e74705SXin Li // If we are handling a C++ class template instantiation, we can see multiple
1008*67e74705SXin Li // lexical updates for the same record. It's important that we select only one
1009*67e74705SXin Li // of them, so that field numbering works properly. Just pick the first one we
1010*67e74705SXin Li // see.
1011*67e74705SXin Li auto &Lex = LexicalDecls[DC];
1012*67e74705SXin Li if (!Lex.first) {
1013*67e74705SXin Li Lex = std::make_pair(
1014*67e74705SXin Li &M, llvm::makeArrayRef(
1015*67e74705SXin Li reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1016*67e74705SXin Li Blob.data()),
1017*67e74705SXin Li Blob.size() / 4));
1018*67e74705SXin Li }
1019*67e74705SXin Li DC->setHasExternalLexicalStorage(true);
1020*67e74705SXin Li return false;
1021*67e74705SXin Li }
1022*67e74705SXin Li
ReadVisibleDeclContextStorage(ModuleFile & M,BitstreamCursor & Cursor,uint64_t Offset,DeclID ID)1023*67e74705SXin Li bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1024*67e74705SXin Li BitstreamCursor &Cursor,
1025*67e74705SXin Li uint64_t Offset,
1026*67e74705SXin Li DeclID ID) {
1027*67e74705SXin Li assert(Offset != 0);
1028*67e74705SXin Li
1029*67e74705SXin Li SavedStreamPosition SavedPosition(Cursor);
1030*67e74705SXin Li Cursor.JumpToBit(Offset);
1031*67e74705SXin Li
1032*67e74705SXin Li RecordData Record;
1033*67e74705SXin Li StringRef Blob;
1034*67e74705SXin Li unsigned Code = Cursor.ReadCode();
1035*67e74705SXin Li unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1036*67e74705SXin Li if (RecCode != DECL_CONTEXT_VISIBLE) {
1037*67e74705SXin Li Error("Expected visible lookup table block");
1038*67e74705SXin Li return true;
1039*67e74705SXin Li }
1040*67e74705SXin Li
1041*67e74705SXin Li // We can't safely determine the primary context yet, so delay attaching the
1042*67e74705SXin Li // lookup table until we're done with recursive deserialization.
1043*67e74705SXin Li auto *Data = (const unsigned char*)Blob.data();
1044*67e74705SXin Li PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1045*67e74705SXin Li return false;
1046*67e74705SXin Li }
1047*67e74705SXin Li
Error(StringRef Msg)1048*67e74705SXin Li void ASTReader::Error(StringRef Msg) {
1049*67e74705SXin Li Error(diag::err_fe_pch_malformed, Msg);
1050*67e74705SXin Li if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1051*67e74705SXin Li !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1052*67e74705SXin Li Diag(diag::note_module_cache_path)
1053*67e74705SXin Li << PP.getHeaderSearchInfo().getModuleCachePath();
1054*67e74705SXin Li }
1055*67e74705SXin Li }
1056*67e74705SXin Li
Error(unsigned DiagID,StringRef Arg1,StringRef Arg2)1057*67e74705SXin Li void ASTReader::Error(unsigned DiagID,
1058*67e74705SXin Li StringRef Arg1, StringRef Arg2) {
1059*67e74705SXin Li if (Diags.isDiagnosticInFlight())
1060*67e74705SXin Li Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1061*67e74705SXin Li else
1062*67e74705SXin Li Diag(DiagID) << Arg1 << Arg2;
1063*67e74705SXin Li }
1064*67e74705SXin Li
1065*67e74705SXin Li //===----------------------------------------------------------------------===//
1066*67e74705SXin Li // Source Manager Deserialization
1067*67e74705SXin Li //===----------------------------------------------------------------------===//
1068*67e74705SXin Li
1069*67e74705SXin Li /// \brief Read the line table in the source manager block.
1070*67e74705SXin Li /// \returns true if there was an error.
ParseLineTable(ModuleFile & F,const RecordData & Record)1071*67e74705SXin Li bool ASTReader::ParseLineTable(ModuleFile &F,
1072*67e74705SXin Li const RecordData &Record) {
1073*67e74705SXin Li unsigned Idx = 0;
1074*67e74705SXin Li LineTableInfo &LineTable = SourceMgr.getLineTable();
1075*67e74705SXin Li
1076*67e74705SXin Li // Parse the file names
1077*67e74705SXin Li std::map<int, int> FileIDs;
1078*67e74705SXin Li for (unsigned I = 0; Record[Idx]; ++I) {
1079*67e74705SXin Li // Extract the file name
1080*67e74705SXin Li auto Filename = ReadPath(F, Record, Idx);
1081*67e74705SXin Li FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1082*67e74705SXin Li }
1083*67e74705SXin Li ++Idx;
1084*67e74705SXin Li
1085*67e74705SXin Li // Parse the line entries
1086*67e74705SXin Li std::vector<LineEntry> Entries;
1087*67e74705SXin Li while (Idx < Record.size()) {
1088*67e74705SXin Li int FID = Record[Idx++];
1089*67e74705SXin Li assert(FID >= 0 && "Serialized line entries for non-local file.");
1090*67e74705SXin Li // Remap FileID from 1-based old view.
1091*67e74705SXin Li FID += F.SLocEntryBaseID - 1;
1092*67e74705SXin Li
1093*67e74705SXin Li // Extract the line entries
1094*67e74705SXin Li unsigned NumEntries = Record[Idx++];
1095*67e74705SXin Li assert(NumEntries && "no line entries for file ID");
1096*67e74705SXin Li Entries.clear();
1097*67e74705SXin Li Entries.reserve(NumEntries);
1098*67e74705SXin Li for (unsigned I = 0; I != NumEntries; ++I) {
1099*67e74705SXin Li unsigned FileOffset = Record[Idx++];
1100*67e74705SXin Li unsigned LineNo = Record[Idx++];
1101*67e74705SXin Li int FilenameID = FileIDs[Record[Idx++]];
1102*67e74705SXin Li SrcMgr::CharacteristicKind FileKind
1103*67e74705SXin Li = (SrcMgr::CharacteristicKind)Record[Idx++];
1104*67e74705SXin Li unsigned IncludeOffset = Record[Idx++];
1105*67e74705SXin Li Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1106*67e74705SXin Li FileKind, IncludeOffset));
1107*67e74705SXin Li }
1108*67e74705SXin Li LineTable.AddEntry(FileID::get(FID), Entries);
1109*67e74705SXin Li }
1110*67e74705SXin Li
1111*67e74705SXin Li return false;
1112*67e74705SXin Li }
1113*67e74705SXin Li
1114*67e74705SXin Li /// \brief Read a source manager block
ReadSourceManagerBlock(ModuleFile & F)1115*67e74705SXin Li bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1116*67e74705SXin Li using namespace SrcMgr;
1117*67e74705SXin Li
1118*67e74705SXin Li BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1119*67e74705SXin Li
1120*67e74705SXin Li // Set the source-location entry cursor to the current position in
1121*67e74705SXin Li // the stream. This cursor will be used to read the contents of the
1122*67e74705SXin Li // source manager block initially, and then lazily read
1123*67e74705SXin Li // source-location entries as needed.
1124*67e74705SXin Li SLocEntryCursor = F.Stream;
1125*67e74705SXin Li
1126*67e74705SXin Li // The stream itself is going to skip over the source manager block.
1127*67e74705SXin Li if (F.Stream.SkipBlock()) {
1128*67e74705SXin Li Error("malformed block record in AST file");
1129*67e74705SXin Li return true;
1130*67e74705SXin Li }
1131*67e74705SXin Li
1132*67e74705SXin Li // Enter the source manager block.
1133*67e74705SXin Li if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1134*67e74705SXin Li Error("malformed source manager block record in AST file");
1135*67e74705SXin Li return true;
1136*67e74705SXin Li }
1137*67e74705SXin Li
1138*67e74705SXin Li RecordData Record;
1139*67e74705SXin Li while (true) {
1140*67e74705SXin Li llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1141*67e74705SXin Li
1142*67e74705SXin Li switch (E.Kind) {
1143*67e74705SXin Li case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1144*67e74705SXin Li case llvm::BitstreamEntry::Error:
1145*67e74705SXin Li Error("malformed block record in AST file");
1146*67e74705SXin Li return true;
1147*67e74705SXin Li case llvm::BitstreamEntry::EndBlock:
1148*67e74705SXin Li return false;
1149*67e74705SXin Li case llvm::BitstreamEntry::Record:
1150*67e74705SXin Li // The interesting case.
1151*67e74705SXin Li break;
1152*67e74705SXin Li }
1153*67e74705SXin Li
1154*67e74705SXin Li // Read a record.
1155*67e74705SXin Li Record.clear();
1156*67e74705SXin Li StringRef Blob;
1157*67e74705SXin Li switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
1158*67e74705SXin Li default: // Default behavior: ignore.
1159*67e74705SXin Li break;
1160*67e74705SXin Li
1161*67e74705SXin Li case SM_SLOC_FILE_ENTRY:
1162*67e74705SXin Li case SM_SLOC_BUFFER_ENTRY:
1163*67e74705SXin Li case SM_SLOC_EXPANSION_ENTRY:
1164*67e74705SXin Li // Once we hit one of the source location entries, we're done.
1165*67e74705SXin Li return false;
1166*67e74705SXin Li }
1167*67e74705SXin Li }
1168*67e74705SXin Li }
1169*67e74705SXin Li
1170*67e74705SXin Li /// \brief If a header file is not found at the path that we expect it to be
1171*67e74705SXin Li /// and the PCH file was moved from its original location, try to resolve the
1172*67e74705SXin Li /// file by assuming that header+PCH were moved together and the header is in
1173*67e74705SXin Li /// the same place relative to the PCH.
1174*67e74705SXin Li static std::string
resolveFileRelativeToOriginalDir(const std::string & Filename,const std::string & OriginalDir,const std::string & CurrDir)1175*67e74705SXin Li resolveFileRelativeToOriginalDir(const std::string &Filename,
1176*67e74705SXin Li const std::string &OriginalDir,
1177*67e74705SXin Li const std::string &CurrDir) {
1178*67e74705SXin Li assert(OriginalDir != CurrDir &&
1179*67e74705SXin Li "No point trying to resolve the file if the PCH dir didn't change");
1180*67e74705SXin Li using namespace llvm::sys;
1181*67e74705SXin Li SmallString<128> filePath(Filename);
1182*67e74705SXin Li fs::make_absolute(filePath);
1183*67e74705SXin Li assert(path::is_absolute(OriginalDir));
1184*67e74705SXin Li SmallString<128> currPCHPath(CurrDir);
1185*67e74705SXin Li
1186*67e74705SXin Li path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1187*67e74705SXin Li fileDirE = path::end(path::parent_path(filePath));
1188*67e74705SXin Li path::const_iterator origDirI = path::begin(OriginalDir),
1189*67e74705SXin Li origDirE = path::end(OriginalDir);
1190*67e74705SXin Li // Skip the common path components from filePath and OriginalDir.
1191*67e74705SXin Li while (fileDirI != fileDirE && origDirI != origDirE &&
1192*67e74705SXin Li *fileDirI == *origDirI) {
1193*67e74705SXin Li ++fileDirI;
1194*67e74705SXin Li ++origDirI;
1195*67e74705SXin Li }
1196*67e74705SXin Li for (; origDirI != origDirE; ++origDirI)
1197*67e74705SXin Li path::append(currPCHPath, "..");
1198*67e74705SXin Li path::append(currPCHPath, fileDirI, fileDirE);
1199*67e74705SXin Li path::append(currPCHPath, path::filename(Filename));
1200*67e74705SXin Li return currPCHPath.str();
1201*67e74705SXin Li }
1202*67e74705SXin Li
ReadSLocEntry(int ID)1203*67e74705SXin Li bool ASTReader::ReadSLocEntry(int ID) {
1204*67e74705SXin Li if (ID == 0)
1205*67e74705SXin Li return false;
1206*67e74705SXin Li
1207*67e74705SXin Li if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1208*67e74705SXin Li Error("source location entry ID out-of-range for AST file");
1209*67e74705SXin Li return true;
1210*67e74705SXin Li }
1211*67e74705SXin Li
1212*67e74705SXin Li // Local helper to read the (possibly-compressed) buffer data following the
1213*67e74705SXin Li // entry record.
1214*67e74705SXin Li auto ReadBuffer = [this](
1215*67e74705SXin Li BitstreamCursor &SLocEntryCursor,
1216*67e74705SXin Li StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1217*67e74705SXin Li RecordData Record;
1218*67e74705SXin Li StringRef Blob;
1219*67e74705SXin Li unsigned Code = SLocEntryCursor.ReadCode();
1220*67e74705SXin Li unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1221*67e74705SXin Li
1222*67e74705SXin Li if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1223*67e74705SXin Li SmallString<0> Uncompressed;
1224*67e74705SXin Li if (llvm::zlib::uncompress(Blob, Uncompressed, Record[0]) !=
1225*67e74705SXin Li llvm::zlib::StatusOK) {
1226*67e74705SXin Li Error("could not decompress embedded file contents");
1227*67e74705SXin Li return nullptr;
1228*67e74705SXin Li }
1229*67e74705SXin Li return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1230*67e74705SXin Li } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1231*67e74705SXin Li return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1232*67e74705SXin Li } else {
1233*67e74705SXin Li Error("AST record has invalid code");
1234*67e74705SXin Li return nullptr;
1235*67e74705SXin Li }
1236*67e74705SXin Li };
1237*67e74705SXin Li
1238*67e74705SXin Li ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1239*67e74705SXin Li F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
1240*67e74705SXin Li BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1241*67e74705SXin Li unsigned BaseOffset = F->SLocEntryBaseOffset;
1242*67e74705SXin Li
1243*67e74705SXin Li ++NumSLocEntriesRead;
1244*67e74705SXin Li llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1245*67e74705SXin Li if (Entry.Kind != llvm::BitstreamEntry::Record) {
1246*67e74705SXin Li Error("incorrectly-formatted source location entry in AST file");
1247*67e74705SXin Li return true;
1248*67e74705SXin Li }
1249*67e74705SXin Li
1250*67e74705SXin Li RecordData Record;
1251*67e74705SXin Li StringRef Blob;
1252*67e74705SXin Li switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
1253*67e74705SXin Li default:
1254*67e74705SXin Li Error("incorrectly-formatted source location entry in AST file");
1255*67e74705SXin Li return true;
1256*67e74705SXin Li
1257*67e74705SXin Li case SM_SLOC_FILE_ENTRY: {
1258*67e74705SXin Li // We will detect whether a file changed and return 'Failure' for it, but
1259*67e74705SXin Li // we will also try to fail gracefully by setting up the SLocEntry.
1260*67e74705SXin Li unsigned InputID = Record[4];
1261*67e74705SXin Li InputFile IF = getInputFile(*F, InputID);
1262*67e74705SXin Li const FileEntry *File = IF.getFile();
1263*67e74705SXin Li bool OverriddenBuffer = IF.isOverridden();
1264*67e74705SXin Li
1265*67e74705SXin Li // Note that we only check if a File was returned. If it was out-of-date
1266*67e74705SXin Li // we have complained but we will continue creating a FileID to recover
1267*67e74705SXin Li // gracefully.
1268*67e74705SXin Li if (!File)
1269*67e74705SXin Li return true;
1270*67e74705SXin Li
1271*67e74705SXin Li SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1272*67e74705SXin Li if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1273*67e74705SXin Li // This is the module's main file.
1274*67e74705SXin Li IncludeLoc = getImportLocation(F);
1275*67e74705SXin Li }
1276*67e74705SXin Li SrcMgr::CharacteristicKind
1277*67e74705SXin Li FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1278*67e74705SXin Li FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1279*67e74705SXin Li ID, BaseOffset + Record[0]);
1280*67e74705SXin Li SrcMgr::FileInfo &FileInfo =
1281*67e74705SXin Li const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1282*67e74705SXin Li FileInfo.NumCreatedFIDs = Record[5];
1283*67e74705SXin Li if (Record[3])
1284*67e74705SXin Li FileInfo.setHasLineDirectives();
1285*67e74705SXin Li
1286*67e74705SXin Li const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1287*67e74705SXin Li unsigned NumFileDecls = Record[7];
1288*67e74705SXin Li if (NumFileDecls) {
1289*67e74705SXin Li assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1290*67e74705SXin Li FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1291*67e74705SXin Li NumFileDecls));
1292*67e74705SXin Li }
1293*67e74705SXin Li
1294*67e74705SXin Li const SrcMgr::ContentCache *ContentCache
1295*67e74705SXin Li = SourceMgr.getOrCreateContentCache(File,
1296*67e74705SXin Li /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1297*67e74705SXin Li if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1298*67e74705SXin Li ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1299*67e74705SXin Li !ContentCache->getRawBuffer()) {
1300*67e74705SXin Li auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1301*67e74705SXin Li if (!Buffer)
1302*67e74705SXin Li return true;
1303*67e74705SXin Li SourceMgr.overrideFileContents(File, std::move(Buffer));
1304*67e74705SXin Li }
1305*67e74705SXin Li
1306*67e74705SXin Li break;
1307*67e74705SXin Li }
1308*67e74705SXin Li
1309*67e74705SXin Li case SM_SLOC_BUFFER_ENTRY: {
1310*67e74705SXin Li const char *Name = Blob.data();
1311*67e74705SXin Li unsigned Offset = Record[0];
1312*67e74705SXin Li SrcMgr::CharacteristicKind
1313*67e74705SXin Li FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1314*67e74705SXin Li SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1315*67e74705SXin Li if (IncludeLoc.isInvalid() &&
1316*67e74705SXin Li (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
1317*67e74705SXin Li IncludeLoc = getImportLocation(F);
1318*67e74705SXin Li }
1319*67e74705SXin Li
1320*67e74705SXin Li auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1321*67e74705SXin Li if (!Buffer)
1322*67e74705SXin Li return true;
1323*67e74705SXin Li SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1324*67e74705SXin Li BaseOffset + Offset, IncludeLoc);
1325*67e74705SXin Li break;
1326*67e74705SXin Li }
1327*67e74705SXin Li
1328*67e74705SXin Li case SM_SLOC_EXPANSION_ENTRY: {
1329*67e74705SXin Li SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1330*67e74705SXin Li SourceMgr.createExpansionLoc(SpellingLoc,
1331*67e74705SXin Li ReadSourceLocation(*F, Record[2]),
1332*67e74705SXin Li ReadSourceLocation(*F, Record[3]),
1333*67e74705SXin Li Record[4],
1334*67e74705SXin Li ID,
1335*67e74705SXin Li BaseOffset + Record[0]);
1336*67e74705SXin Li break;
1337*67e74705SXin Li }
1338*67e74705SXin Li }
1339*67e74705SXin Li
1340*67e74705SXin Li return false;
1341*67e74705SXin Li }
1342*67e74705SXin Li
getModuleImportLoc(int ID)1343*67e74705SXin Li std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1344*67e74705SXin Li if (ID == 0)
1345*67e74705SXin Li return std::make_pair(SourceLocation(), "");
1346*67e74705SXin Li
1347*67e74705SXin Li if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1348*67e74705SXin Li Error("source location entry ID out-of-range for AST file");
1349*67e74705SXin Li return std::make_pair(SourceLocation(), "");
1350*67e74705SXin Li }
1351*67e74705SXin Li
1352*67e74705SXin Li // Find which module file this entry lands in.
1353*67e74705SXin Li ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1354*67e74705SXin Li if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
1355*67e74705SXin Li return std::make_pair(SourceLocation(), "");
1356*67e74705SXin Li
1357*67e74705SXin Li // FIXME: Can we map this down to a particular submodule? That would be
1358*67e74705SXin Li // ideal.
1359*67e74705SXin Li return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1360*67e74705SXin Li }
1361*67e74705SXin Li
1362*67e74705SXin Li /// \brief Find the location where the module F is imported.
getImportLocation(ModuleFile * F)1363*67e74705SXin Li SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1364*67e74705SXin Li if (F->ImportLoc.isValid())
1365*67e74705SXin Li return F->ImportLoc;
1366*67e74705SXin Li
1367*67e74705SXin Li // Otherwise we have a PCH. It's considered to be "imported" at the first
1368*67e74705SXin Li // location of its includer.
1369*67e74705SXin Li if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1370*67e74705SXin Li // Main file is the importer.
1371*67e74705SXin Li assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1372*67e74705SXin Li return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1373*67e74705SXin Li }
1374*67e74705SXin Li return F->ImportedBy[0]->FirstLoc;
1375*67e74705SXin Li }
1376*67e74705SXin Li
1377*67e74705SXin Li /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1378*67e74705SXin Li /// specified cursor. Read the abbreviations that are at the top of the block
1379*67e74705SXin Li /// and then leave the cursor pointing into the block.
ReadBlockAbbrevs(BitstreamCursor & Cursor,unsigned BlockID)1380*67e74705SXin Li bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
1381*67e74705SXin Li if (Cursor.EnterSubBlock(BlockID))
1382*67e74705SXin Li return true;
1383*67e74705SXin Li
1384*67e74705SXin Li while (true) {
1385*67e74705SXin Li uint64_t Offset = Cursor.GetCurrentBitNo();
1386*67e74705SXin Li unsigned Code = Cursor.ReadCode();
1387*67e74705SXin Li
1388*67e74705SXin Li // We expect all abbrevs to be at the start of the block.
1389*67e74705SXin Li if (Code != llvm::bitc::DEFINE_ABBREV) {
1390*67e74705SXin Li Cursor.JumpToBit(Offset);
1391*67e74705SXin Li return false;
1392*67e74705SXin Li }
1393*67e74705SXin Li Cursor.ReadAbbrevRecord();
1394*67e74705SXin Li }
1395*67e74705SXin Li }
1396*67e74705SXin Li
ReadToken(ModuleFile & F,const RecordDataImpl & Record,unsigned & Idx)1397*67e74705SXin Li Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
1398*67e74705SXin Li unsigned &Idx) {
1399*67e74705SXin Li Token Tok;
1400*67e74705SXin Li Tok.startToken();
1401*67e74705SXin Li Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1402*67e74705SXin Li Tok.setLength(Record[Idx++]);
1403*67e74705SXin Li if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1404*67e74705SXin Li Tok.setIdentifierInfo(II);
1405*67e74705SXin Li Tok.setKind((tok::TokenKind)Record[Idx++]);
1406*67e74705SXin Li Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1407*67e74705SXin Li return Tok;
1408*67e74705SXin Li }
1409*67e74705SXin Li
ReadMacroRecord(ModuleFile & F,uint64_t Offset)1410*67e74705SXin Li MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
1411*67e74705SXin Li BitstreamCursor &Stream = F.MacroCursor;
1412*67e74705SXin Li
1413*67e74705SXin Li // Keep track of where we are in the stream, then jump back there
1414*67e74705SXin Li // after reading this macro.
1415*67e74705SXin Li SavedStreamPosition SavedPosition(Stream);
1416*67e74705SXin Li
1417*67e74705SXin Li Stream.JumpToBit(Offset);
1418*67e74705SXin Li RecordData Record;
1419*67e74705SXin Li SmallVector<IdentifierInfo*, 16> MacroArgs;
1420*67e74705SXin Li MacroInfo *Macro = nullptr;
1421*67e74705SXin Li
1422*67e74705SXin Li while (true) {
1423*67e74705SXin Li // Advance to the next record, but if we get to the end of the block, don't
1424*67e74705SXin Li // pop it (removing all the abbreviations from the cursor) since we want to
1425*67e74705SXin Li // be able to reseek within the block and read entries.
1426*67e74705SXin Li unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1427*67e74705SXin Li llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1428*67e74705SXin Li
1429*67e74705SXin Li switch (Entry.Kind) {
1430*67e74705SXin Li case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1431*67e74705SXin Li case llvm::BitstreamEntry::Error:
1432*67e74705SXin Li Error("malformed block record in AST file");
1433*67e74705SXin Li return Macro;
1434*67e74705SXin Li case llvm::BitstreamEntry::EndBlock:
1435*67e74705SXin Li return Macro;
1436*67e74705SXin Li case llvm::BitstreamEntry::Record:
1437*67e74705SXin Li // The interesting case.
1438*67e74705SXin Li break;
1439*67e74705SXin Li }
1440*67e74705SXin Li
1441*67e74705SXin Li // Read a record.
1442*67e74705SXin Li Record.clear();
1443*67e74705SXin Li PreprocessorRecordTypes RecType =
1444*67e74705SXin Li (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
1445*67e74705SXin Li switch (RecType) {
1446*67e74705SXin Li case PP_MODULE_MACRO:
1447*67e74705SXin Li case PP_MACRO_DIRECTIVE_HISTORY:
1448*67e74705SXin Li return Macro;
1449*67e74705SXin Li
1450*67e74705SXin Li case PP_MACRO_OBJECT_LIKE:
1451*67e74705SXin Li case PP_MACRO_FUNCTION_LIKE: {
1452*67e74705SXin Li // If we already have a macro, that means that we've hit the end
1453*67e74705SXin Li // of the definition of the macro we were looking for. We're
1454*67e74705SXin Li // done.
1455*67e74705SXin Li if (Macro)
1456*67e74705SXin Li return Macro;
1457*67e74705SXin Li
1458*67e74705SXin Li unsigned NextIndex = 1; // Skip identifier ID.
1459*67e74705SXin Li SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
1460*67e74705SXin Li SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1461*67e74705SXin Li MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
1462*67e74705SXin Li MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1463*67e74705SXin Li MI->setIsUsed(Record[NextIndex++]);
1464*67e74705SXin Li MI->setUsedForHeaderGuard(Record[NextIndex++]);
1465*67e74705SXin Li
1466*67e74705SXin Li if (RecType == PP_MACRO_FUNCTION_LIKE) {
1467*67e74705SXin Li // Decode function-like macro info.
1468*67e74705SXin Li bool isC99VarArgs = Record[NextIndex++];
1469*67e74705SXin Li bool isGNUVarArgs = Record[NextIndex++];
1470*67e74705SXin Li bool hasCommaPasting = Record[NextIndex++];
1471*67e74705SXin Li MacroArgs.clear();
1472*67e74705SXin Li unsigned NumArgs = Record[NextIndex++];
1473*67e74705SXin Li for (unsigned i = 0; i != NumArgs; ++i)
1474*67e74705SXin Li MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1475*67e74705SXin Li
1476*67e74705SXin Li // Install function-like macro info.
1477*67e74705SXin Li MI->setIsFunctionLike();
1478*67e74705SXin Li if (isC99VarArgs) MI->setIsC99Varargs();
1479*67e74705SXin Li if (isGNUVarArgs) MI->setIsGNUVarargs();
1480*67e74705SXin Li if (hasCommaPasting) MI->setHasCommaPasting();
1481*67e74705SXin Li MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
1482*67e74705SXin Li }
1483*67e74705SXin Li
1484*67e74705SXin Li // Remember that we saw this macro last so that we add the tokens that
1485*67e74705SXin Li // form its body to it.
1486*67e74705SXin Li Macro = MI;
1487*67e74705SXin Li
1488*67e74705SXin Li if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1489*67e74705SXin Li Record[NextIndex]) {
1490*67e74705SXin Li // We have a macro definition. Register the association
1491*67e74705SXin Li PreprocessedEntityID
1492*67e74705SXin Li GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1493*67e74705SXin Li PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1494*67e74705SXin Li PreprocessingRecord::PPEntityID PPID =
1495*67e74705SXin Li PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1496*67e74705SXin Li MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1497*67e74705SXin Li PPRec.getPreprocessedEntity(PPID));
1498*67e74705SXin Li if (PPDef)
1499*67e74705SXin Li PPRec.RegisterMacroDefinition(Macro, PPDef);
1500*67e74705SXin Li }
1501*67e74705SXin Li
1502*67e74705SXin Li ++NumMacrosRead;
1503*67e74705SXin Li break;
1504*67e74705SXin Li }
1505*67e74705SXin Li
1506*67e74705SXin Li case PP_TOKEN: {
1507*67e74705SXin Li // If we see a TOKEN before a PP_MACRO_*, then the file is
1508*67e74705SXin Li // erroneous, just pretend we didn't see this.
1509*67e74705SXin Li if (!Macro) break;
1510*67e74705SXin Li
1511*67e74705SXin Li unsigned Idx = 0;
1512*67e74705SXin Li Token Tok = ReadToken(F, Record, Idx);
1513*67e74705SXin Li Macro->AddTokenToBody(Tok);
1514*67e74705SXin Li break;
1515*67e74705SXin Li }
1516*67e74705SXin Li }
1517*67e74705SXin Li }
1518*67e74705SXin Li }
1519*67e74705SXin Li
1520*67e74705SXin Li PreprocessedEntityID
getGlobalPreprocessedEntityID(ModuleFile & M,unsigned LocalID) const1521*67e74705SXin Li ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1522*67e74705SXin Li ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1523*67e74705SXin Li I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1524*67e74705SXin Li assert(I != M.PreprocessedEntityRemap.end()
1525*67e74705SXin Li && "Invalid index into preprocessed entity index remap");
1526*67e74705SXin Li
1527*67e74705SXin Li return LocalID + I->second;
1528*67e74705SXin Li }
1529*67e74705SXin Li
ComputeHash(internal_key_ref ikey)1530*67e74705SXin Li unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1531*67e74705SXin Li return llvm::hash_combine(ikey.Size, ikey.ModTime);
1532*67e74705SXin Li }
1533*67e74705SXin Li
1534*67e74705SXin Li HeaderFileInfoTrait::internal_key_type
GetInternalKey(const FileEntry * FE)1535*67e74705SXin Li HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1536*67e74705SXin Li internal_key_type ikey = {FE->getSize(),
1537*67e74705SXin Li M.HasTimestamps ? FE->getModificationTime() : 0,
1538*67e74705SXin Li FE->getName(), /*Imported*/ false};
1539*67e74705SXin Li return ikey;
1540*67e74705SXin Li }
1541*67e74705SXin Li
EqualKey(internal_key_ref a,internal_key_ref b)1542*67e74705SXin Li bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1543*67e74705SXin Li if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
1544*67e74705SXin Li return false;
1545*67e74705SXin Li
1546*67e74705SXin Li if (llvm::sys::path::is_absolute(a.Filename) &&
1547*67e74705SXin Li strcmp(a.Filename, b.Filename) == 0)
1548*67e74705SXin Li return true;
1549*67e74705SXin Li
1550*67e74705SXin Li // Determine whether the actual files are equivalent.
1551*67e74705SXin Li FileManager &FileMgr = Reader.getFileManager();
1552*67e74705SXin Li auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1553*67e74705SXin Li if (!Key.Imported)
1554*67e74705SXin Li return FileMgr.getFile(Key.Filename);
1555*67e74705SXin Li
1556*67e74705SXin Li std::string Resolved = Key.Filename;
1557*67e74705SXin Li Reader.ResolveImportedPath(M, Resolved);
1558*67e74705SXin Li return FileMgr.getFile(Resolved);
1559*67e74705SXin Li };
1560*67e74705SXin Li
1561*67e74705SXin Li const FileEntry *FEA = GetFile(a);
1562*67e74705SXin Li const FileEntry *FEB = GetFile(b);
1563*67e74705SXin Li return FEA && FEA == FEB;
1564*67e74705SXin Li }
1565*67e74705SXin Li
1566*67e74705SXin Li std::pair<unsigned, unsigned>
ReadKeyDataLength(const unsigned char * & d)1567*67e74705SXin Li HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1568*67e74705SXin Li using namespace llvm::support;
1569*67e74705SXin Li unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1570*67e74705SXin Li unsigned DataLen = (unsigned) *d++;
1571*67e74705SXin Li return std::make_pair(KeyLen, DataLen);
1572*67e74705SXin Li }
1573*67e74705SXin Li
1574*67e74705SXin Li HeaderFileInfoTrait::internal_key_type
ReadKey(const unsigned char * d,unsigned)1575*67e74705SXin Li HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1576*67e74705SXin Li using namespace llvm::support;
1577*67e74705SXin Li internal_key_type ikey;
1578*67e74705SXin Li ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1579*67e74705SXin Li ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
1580*67e74705SXin Li ikey.Filename = (const char *)d;
1581*67e74705SXin Li ikey.Imported = true;
1582*67e74705SXin Li return ikey;
1583*67e74705SXin Li }
1584*67e74705SXin Li
1585*67e74705SXin Li HeaderFileInfoTrait::data_type
ReadData(internal_key_ref key,const unsigned char * d,unsigned DataLen)1586*67e74705SXin Li HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
1587*67e74705SXin Li unsigned DataLen) {
1588*67e74705SXin Li const unsigned char *End = d + DataLen;
1589*67e74705SXin Li using namespace llvm::support;
1590*67e74705SXin Li HeaderFileInfo HFI;
1591*67e74705SXin Li unsigned Flags = *d++;
1592*67e74705SXin Li // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1593*67e74705SXin Li HFI.isImport |= (Flags >> 4) & 0x01;
1594*67e74705SXin Li HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1595*67e74705SXin Li HFI.DirInfo = (Flags >> 1) & 0x03;
1596*67e74705SXin Li HFI.IndexHeaderMapHeader = Flags & 0x01;
1597*67e74705SXin Li // FIXME: Find a better way to handle this. Maybe just store a
1598*67e74705SXin Li // "has been included" flag?
1599*67e74705SXin Li HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1600*67e74705SXin Li HFI.NumIncludes);
1601*67e74705SXin Li HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1602*67e74705SXin Li M, endian::readNext<uint32_t, little, unaligned>(d));
1603*67e74705SXin Li if (unsigned FrameworkOffset =
1604*67e74705SXin Li endian::readNext<uint32_t, little, unaligned>(d)) {
1605*67e74705SXin Li // The framework offset is 1 greater than the actual offset,
1606*67e74705SXin Li // since 0 is used as an indicator for "no framework name".
1607*67e74705SXin Li StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1608*67e74705SXin Li HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1609*67e74705SXin Li }
1610*67e74705SXin Li
1611*67e74705SXin Li assert((End - d) % 4 == 0 &&
1612*67e74705SXin Li "Wrong data length in HeaderFileInfo deserialization");
1613*67e74705SXin Li while (d != End) {
1614*67e74705SXin Li uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1615*67e74705SXin Li auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1616*67e74705SXin Li LocalSMID >>= 2;
1617*67e74705SXin Li
1618*67e74705SXin Li // This header is part of a module. Associate it with the module to enable
1619*67e74705SXin Li // implicit module import.
1620*67e74705SXin Li SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1621*67e74705SXin Li Module *Mod = Reader.getSubmodule(GlobalSMID);
1622*67e74705SXin Li FileManager &FileMgr = Reader.getFileManager();
1623*67e74705SXin Li ModuleMap &ModMap =
1624*67e74705SXin Li Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1625*67e74705SXin Li
1626*67e74705SXin Li std::string Filename = key.Filename;
1627*67e74705SXin Li if (key.Imported)
1628*67e74705SXin Li Reader.ResolveImportedPath(M, Filename);
1629*67e74705SXin Li // FIXME: This is not always the right filename-as-written, but we're not
1630*67e74705SXin Li // going to use this information to rebuild the module, so it doesn't make
1631*67e74705SXin Li // a lot of difference.
1632*67e74705SXin Li Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
1633*67e74705SXin Li ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1634*67e74705SXin Li HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
1635*67e74705SXin Li }
1636*67e74705SXin Li
1637*67e74705SXin Li // This HeaderFileInfo was externally loaded.
1638*67e74705SXin Li HFI.External = true;
1639*67e74705SXin Li HFI.IsValid = true;
1640*67e74705SXin Li return HFI;
1641*67e74705SXin Li }
1642*67e74705SXin Li
addPendingMacro(IdentifierInfo * II,ModuleFile * M,uint64_t MacroDirectivesOffset)1643*67e74705SXin Li void ASTReader::addPendingMacro(IdentifierInfo *II,
1644*67e74705SXin Li ModuleFile *M,
1645*67e74705SXin Li uint64_t MacroDirectivesOffset) {
1646*67e74705SXin Li assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1647*67e74705SXin Li PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1648*67e74705SXin Li }
1649*67e74705SXin Li
ReadDefinedMacros()1650*67e74705SXin Li void ASTReader::ReadDefinedMacros() {
1651*67e74705SXin Li // Note that we are loading defined macros.
1652*67e74705SXin Li Deserializing Macros(this);
1653*67e74705SXin Li
1654*67e74705SXin Li for (auto &I : llvm::reverse(ModuleMgr)) {
1655*67e74705SXin Li BitstreamCursor &MacroCursor = I->MacroCursor;
1656*67e74705SXin Li
1657*67e74705SXin Li // If there was no preprocessor block, skip this file.
1658*67e74705SXin Li if (!MacroCursor.getBitStreamReader())
1659*67e74705SXin Li continue;
1660*67e74705SXin Li
1661*67e74705SXin Li BitstreamCursor Cursor = MacroCursor;
1662*67e74705SXin Li Cursor.JumpToBit(I->MacroStartOffset);
1663*67e74705SXin Li
1664*67e74705SXin Li RecordData Record;
1665*67e74705SXin Li while (true) {
1666*67e74705SXin Li llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1667*67e74705SXin Li
1668*67e74705SXin Li switch (E.Kind) {
1669*67e74705SXin Li case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1670*67e74705SXin Li case llvm::BitstreamEntry::Error:
1671*67e74705SXin Li Error("malformed block record in AST file");
1672*67e74705SXin Li return;
1673*67e74705SXin Li case llvm::BitstreamEntry::EndBlock:
1674*67e74705SXin Li goto NextCursor;
1675*67e74705SXin Li
1676*67e74705SXin Li case llvm::BitstreamEntry::Record:
1677*67e74705SXin Li Record.clear();
1678*67e74705SXin Li switch (Cursor.readRecord(E.ID, Record)) {
1679*67e74705SXin Li default: // Default behavior: ignore.
1680*67e74705SXin Li break;
1681*67e74705SXin Li
1682*67e74705SXin Li case PP_MACRO_OBJECT_LIKE:
1683*67e74705SXin Li case PP_MACRO_FUNCTION_LIKE: {
1684*67e74705SXin Li IdentifierInfo *II = getLocalIdentifier(*I, Record[0]);
1685*67e74705SXin Li if (II->isOutOfDate())
1686*67e74705SXin Li updateOutOfDateIdentifier(*II);
1687*67e74705SXin Li break;
1688*67e74705SXin Li }
1689*67e74705SXin Li
1690*67e74705SXin Li case PP_TOKEN:
1691*67e74705SXin Li // Ignore tokens.
1692*67e74705SXin Li break;
1693*67e74705SXin Li }
1694*67e74705SXin Li break;
1695*67e74705SXin Li }
1696*67e74705SXin Li }
1697*67e74705SXin Li NextCursor: ;
1698*67e74705SXin Li }
1699*67e74705SXin Li }
1700*67e74705SXin Li
1701*67e74705SXin Li namespace {
1702*67e74705SXin Li /// \brief Visitor class used to look up identifirs in an AST file.
1703*67e74705SXin Li class IdentifierLookupVisitor {
1704*67e74705SXin Li StringRef Name;
1705*67e74705SXin Li unsigned NameHash;
1706*67e74705SXin Li unsigned PriorGeneration;
1707*67e74705SXin Li unsigned &NumIdentifierLookups;
1708*67e74705SXin Li unsigned &NumIdentifierLookupHits;
1709*67e74705SXin Li IdentifierInfo *Found;
1710*67e74705SXin Li
1711*67e74705SXin Li public:
IdentifierLookupVisitor(StringRef Name,unsigned PriorGeneration,unsigned & NumIdentifierLookups,unsigned & NumIdentifierLookupHits)1712*67e74705SXin Li IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1713*67e74705SXin Li unsigned &NumIdentifierLookups,
1714*67e74705SXin Li unsigned &NumIdentifierLookupHits)
1715*67e74705SXin Li : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1716*67e74705SXin Li PriorGeneration(PriorGeneration),
1717*67e74705SXin Li NumIdentifierLookups(NumIdentifierLookups),
1718*67e74705SXin Li NumIdentifierLookupHits(NumIdentifierLookupHits),
1719*67e74705SXin Li Found()
1720*67e74705SXin Li {
1721*67e74705SXin Li }
1722*67e74705SXin Li
operator ()(ModuleFile & M)1723*67e74705SXin Li bool operator()(ModuleFile &M) {
1724*67e74705SXin Li // If we've already searched this module file, skip it now.
1725*67e74705SXin Li if (M.Generation <= PriorGeneration)
1726*67e74705SXin Li return true;
1727*67e74705SXin Li
1728*67e74705SXin Li ASTIdentifierLookupTable *IdTable
1729*67e74705SXin Li = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1730*67e74705SXin Li if (!IdTable)
1731*67e74705SXin Li return false;
1732*67e74705SXin Li
1733*67e74705SXin Li ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
1734*67e74705SXin Li Found);
1735*67e74705SXin Li ++NumIdentifierLookups;
1736*67e74705SXin Li ASTIdentifierLookupTable::iterator Pos =
1737*67e74705SXin Li IdTable->find_hashed(Name, NameHash, &Trait);
1738*67e74705SXin Li if (Pos == IdTable->end())
1739*67e74705SXin Li return false;
1740*67e74705SXin Li
1741*67e74705SXin Li // Dereferencing the iterator has the effect of building the
1742*67e74705SXin Li // IdentifierInfo node and populating it with the various
1743*67e74705SXin Li // declarations it needs.
1744*67e74705SXin Li ++NumIdentifierLookupHits;
1745*67e74705SXin Li Found = *Pos;
1746*67e74705SXin Li return true;
1747*67e74705SXin Li }
1748*67e74705SXin Li
1749*67e74705SXin Li // \brief Retrieve the identifier info found within the module
1750*67e74705SXin Li // files.
getIdentifierInfo() const1751*67e74705SXin Li IdentifierInfo *getIdentifierInfo() const { return Found; }
1752*67e74705SXin Li };
1753*67e74705SXin Li }
1754*67e74705SXin Li
updateOutOfDateIdentifier(IdentifierInfo & II)1755*67e74705SXin Li void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1756*67e74705SXin Li // Note that we are loading an identifier.
1757*67e74705SXin Li Deserializing AnIdentifier(this);
1758*67e74705SXin Li
1759*67e74705SXin Li unsigned PriorGeneration = 0;
1760*67e74705SXin Li if (getContext().getLangOpts().Modules)
1761*67e74705SXin Li PriorGeneration = IdentifierGeneration[&II];
1762*67e74705SXin Li
1763*67e74705SXin Li // If there is a global index, look there first to determine which modules
1764*67e74705SXin Li // provably do not have any results for this identifier.
1765*67e74705SXin Li GlobalModuleIndex::HitSet Hits;
1766*67e74705SXin Li GlobalModuleIndex::HitSet *HitsPtr = nullptr;
1767*67e74705SXin Li if (!loadGlobalIndex()) {
1768*67e74705SXin Li if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1769*67e74705SXin Li HitsPtr = &Hits;
1770*67e74705SXin Li }
1771*67e74705SXin Li }
1772*67e74705SXin Li
1773*67e74705SXin Li IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
1774*67e74705SXin Li NumIdentifierLookups,
1775*67e74705SXin Li NumIdentifierLookupHits);
1776*67e74705SXin Li ModuleMgr.visit(Visitor, HitsPtr);
1777*67e74705SXin Li markIdentifierUpToDate(&II);
1778*67e74705SXin Li }
1779*67e74705SXin Li
markIdentifierUpToDate(IdentifierInfo * II)1780*67e74705SXin Li void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1781*67e74705SXin Li if (!II)
1782*67e74705SXin Li return;
1783*67e74705SXin Li
1784*67e74705SXin Li II->setOutOfDate(false);
1785*67e74705SXin Li
1786*67e74705SXin Li // Update the generation for this identifier.
1787*67e74705SXin Li if (getContext().getLangOpts().Modules)
1788*67e74705SXin Li IdentifierGeneration[II] = getGeneration();
1789*67e74705SXin Li }
1790*67e74705SXin Li
resolvePendingMacro(IdentifierInfo * II,const PendingMacroInfo & PMInfo)1791*67e74705SXin Li void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1792*67e74705SXin Li const PendingMacroInfo &PMInfo) {
1793*67e74705SXin Li ModuleFile &M = *PMInfo.M;
1794*67e74705SXin Li
1795*67e74705SXin Li BitstreamCursor &Cursor = M.MacroCursor;
1796*67e74705SXin Li SavedStreamPosition SavedPosition(Cursor);
1797*67e74705SXin Li Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
1798*67e74705SXin Li
1799*67e74705SXin Li struct ModuleMacroRecord {
1800*67e74705SXin Li SubmoduleID SubModID;
1801*67e74705SXin Li MacroInfo *MI;
1802*67e74705SXin Li SmallVector<SubmoduleID, 8> Overrides;
1803*67e74705SXin Li };
1804*67e74705SXin Li llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
1805*67e74705SXin Li
1806*67e74705SXin Li // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1807*67e74705SXin Li // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1808*67e74705SXin Li // macro histroy.
1809*67e74705SXin Li RecordData Record;
1810*67e74705SXin Li while (true) {
1811*67e74705SXin Li llvm::BitstreamEntry Entry =
1812*67e74705SXin Li Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1813*67e74705SXin Li if (Entry.Kind != llvm::BitstreamEntry::Record) {
1814*67e74705SXin Li Error("malformed block record in AST file");
1815*67e74705SXin Li return;
1816*67e74705SXin Li }
1817*67e74705SXin Li
1818*67e74705SXin Li Record.clear();
1819*67e74705SXin Li switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
1820*67e74705SXin Li case PP_MACRO_DIRECTIVE_HISTORY:
1821*67e74705SXin Li break;
1822*67e74705SXin Li
1823*67e74705SXin Li case PP_MODULE_MACRO: {
1824*67e74705SXin Li ModuleMacros.push_back(ModuleMacroRecord());
1825*67e74705SXin Li auto &Info = ModuleMacros.back();
1826*67e74705SXin Li Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1827*67e74705SXin Li Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
1828*67e74705SXin Li for (int I = 2, N = Record.size(); I != N; ++I)
1829*67e74705SXin Li Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
1830*67e74705SXin Li continue;
1831*67e74705SXin Li }
1832*67e74705SXin Li
1833*67e74705SXin Li default:
1834*67e74705SXin Li Error("malformed block record in AST file");
1835*67e74705SXin Li return;
1836*67e74705SXin Li }
1837*67e74705SXin Li
1838*67e74705SXin Li // We found the macro directive history; that's the last record
1839*67e74705SXin Li // for this macro.
1840*67e74705SXin Li break;
1841*67e74705SXin Li }
1842*67e74705SXin Li
1843*67e74705SXin Li // Module macros are listed in reverse dependency order.
1844*67e74705SXin Li {
1845*67e74705SXin Li std::reverse(ModuleMacros.begin(), ModuleMacros.end());
1846*67e74705SXin Li llvm::SmallVector<ModuleMacro*, 8> Overrides;
1847*67e74705SXin Li for (auto &MMR : ModuleMacros) {
1848*67e74705SXin Li Overrides.clear();
1849*67e74705SXin Li for (unsigned ModID : MMR.Overrides) {
1850*67e74705SXin Li Module *Mod = getSubmodule(ModID);
1851*67e74705SXin Li auto *Macro = PP.getModuleMacro(Mod, II);
1852*67e74705SXin Li assert(Macro && "missing definition for overridden macro");
1853*67e74705SXin Li Overrides.push_back(Macro);
1854*67e74705SXin Li }
1855*67e74705SXin Li
1856*67e74705SXin Li bool Inserted = false;
1857*67e74705SXin Li Module *Owner = getSubmodule(MMR.SubModID);
1858*67e74705SXin Li PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
1859*67e74705SXin Li }
1860*67e74705SXin Li }
1861*67e74705SXin Li
1862*67e74705SXin Li // Don't read the directive history for a module; we don't have anywhere
1863*67e74705SXin Li // to put it.
1864*67e74705SXin Li if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1865*67e74705SXin Li return;
1866*67e74705SXin Li
1867*67e74705SXin Li // Deserialize the macro directives history in reverse source-order.
1868*67e74705SXin Li MacroDirective *Latest = nullptr, *Earliest = nullptr;
1869*67e74705SXin Li unsigned Idx = 0, N = Record.size();
1870*67e74705SXin Li while (Idx < N) {
1871*67e74705SXin Li MacroDirective *MD = nullptr;
1872*67e74705SXin Li SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
1873*67e74705SXin Li MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1874*67e74705SXin Li switch (K) {
1875*67e74705SXin Li case MacroDirective::MD_Define: {
1876*67e74705SXin Li MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
1877*67e74705SXin Li MD = PP.AllocateDefMacroDirective(MI, Loc);
1878*67e74705SXin Li break;
1879*67e74705SXin Li }
1880*67e74705SXin Li case MacroDirective::MD_Undefine: {
1881*67e74705SXin Li MD = PP.AllocateUndefMacroDirective(Loc);
1882*67e74705SXin Li break;
1883*67e74705SXin Li }
1884*67e74705SXin Li case MacroDirective::MD_Visibility:
1885*67e74705SXin Li bool isPublic = Record[Idx++];
1886*67e74705SXin Li MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1887*67e74705SXin Li break;
1888*67e74705SXin Li }
1889*67e74705SXin Li
1890*67e74705SXin Li if (!Latest)
1891*67e74705SXin Li Latest = MD;
1892*67e74705SXin Li if (Earliest)
1893*67e74705SXin Li Earliest->setPrevious(MD);
1894*67e74705SXin Li Earliest = MD;
1895*67e74705SXin Li }
1896*67e74705SXin Li
1897*67e74705SXin Li if (Latest)
1898*67e74705SXin Li PP.setLoadedMacroDirective(II, Latest);
1899*67e74705SXin Li }
1900*67e74705SXin Li
1901*67e74705SXin Li ASTReader::InputFileInfo
readInputFileInfo(ModuleFile & F,unsigned ID)1902*67e74705SXin Li ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
1903*67e74705SXin Li // Go find this input file.
1904*67e74705SXin Li BitstreamCursor &Cursor = F.InputFilesCursor;
1905*67e74705SXin Li SavedStreamPosition SavedPosition(Cursor);
1906*67e74705SXin Li Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1907*67e74705SXin Li
1908*67e74705SXin Li unsigned Code = Cursor.ReadCode();
1909*67e74705SXin Li RecordData Record;
1910*67e74705SXin Li StringRef Blob;
1911*67e74705SXin Li
1912*67e74705SXin Li unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1913*67e74705SXin Li assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1914*67e74705SXin Li "invalid record type for input file");
1915*67e74705SXin Li (void)Result;
1916*67e74705SXin Li
1917*67e74705SXin Li assert(Record[0] == ID && "Bogus stored ID or offset");
1918*67e74705SXin Li InputFileInfo R;
1919*67e74705SXin Li R.StoredSize = static_cast<off_t>(Record[1]);
1920*67e74705SXin Li R.StoredTime = static_cast<time_t>(Record[2]);
1921*67e74705SXin Li R.Overridden = static_cast<bool>(Record[3]);
1922*67e74705SXin Li R.Transient = static_cast<bool>(Record[4]);
1923*67e74705SXin Li R.Filename = Blob;
1924*67e74705SXin Li ResolveImportedPath(F, R.Filename);
1925*67e74705SXin Li return R;
1926*67e74705SXin Li }
1927*67e74705SXin Li
getInputFile(ModuleFile & F,unsigned ID,bool Complain)1928*67e74705SXin Li InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
1929*67e74705SXin Li // If this ID is bogus, just return an empty input file.
1930*67e74705SXin Li if (ID == 0 || ID > F.InputFilesLoaded.size())
1931*67e74705SXin Li return InputFile();
1932*67e74705SXin Li
1933*67e74705SXin Li // If we've already loaded this input file, return it.
1934*67e74705SXin Li if (F.InputFilesLoaded[ID-1].getFile())
1935*67e74705SXin Li return F.InputFilesLoaded[ID-1];
1936*67e74705SXin Li
1937*67e74705SXin Li if (F.InputFilesLoaded[ID-1].isNotFound())
1938*67e74705SXin Li return InputFile();
1939*67e74705SXin Li
1940*67e74705SXin Li // Go find this input file.
1941*67e74705SXin Li BitstreamCursor &Cursor = F.InputFilesCursor;
1942*67e74705SXin Li SavedStreamPosition SavedPosition(Cursor);
1943*67e74705SXin Li Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1944*67e74705SXin Li
1945*67e74705SXin Li InputFileInfo FI = readInputFileInfo(F, ID);
1946*67e74705SXin Li off_t StoredSize = FI.StoredSize;
1947*67e74705SXin Li time_t StoredTime = FI.StoredTime;
1948*67e74705SXin Li bool Overridden = FI.Overridden;
1949*67e74705SXin Li bool Transient = FI.Transient;
1950*67e74705SXin Li StringRef Filename = FI.Filename;
1951*67e74705SXin Li
1952*67e74705SXin Li const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
1953*67e74705SXin Li
1954*67e74705SXin Li // If we didn't find the file, resolve it relative to the
1955*67e74705SXin Li // original directory from which this AST file was created.
1956*67e74705SXin Li if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1957*67e74705SXin Li F.OriginalDir != CurrentDir) {
1958*67e74705SXin Li std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1959*67e74705SXin Li F.OriginalDir,
1960*67e74705SXin Li CurrentDir);
1961*67e74705SXin Li if (!Resolved.empty())
1962*67e74705SXin Li File = FileMgr.getFile(Resolved);
1963*67e74705SXin Li }
1964*67e74705SXin Li
1965*67e74705SXin Li // For an overridden file, create a virtual file with the stored
1966*67e74705SXin Li // size/timestamp.
1967*67e74705SXin Li if ((Overridden || Transient) && File == nullptr)
1968*67e74705SXin Li File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1969*67e74705SXin Li
1970*67e74705SXin Li if (File == nullptr) {
1971*67e74705SXin Li if (Complain) {
1972*67e74705SXin Li std::string ErrorStr = "could not find file '";
1973*67e74705SXin Li ErrorStr += Filename;
1974*67e74705SXin Li ErrorStr += "' referenced by AST file '";
1975*67e74705SXin Li ErrorStr += F.FileName;
1976*67e74705SXin Li ErrorStr += "'";
1977*67e74705SXin Li Error(ErrorStr.c_str());
1978*67e74705SXin Li }
1979*67e74705SXin Li // Record that we didn't find the file.
1980*67e74705SXin Li F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1981*67e74705SXin Li return InputFile();
1982*67e74705SXin Li }
1983*67e74705SXin Li
1984*67e74705SXin Li // Check if there was a request to override the contents of the file
1985*67e74705SXin Li // that was part of the precompiled header. Overridding such a file
1986*67e74705SXin Li // can lead to problems when lexing using the source locations from the
1987*67e74705SXin Li // PCH.
1988*67e74705SXin Li SourceManager &SM = getSourceManager();
1989*67e74705SXin Li // FIXME: Reject if the overrides are different.
1990*67e74705SXin Li if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
1991*67e74705SXin Li if (Complain)
1992*67e74705SXin Li Error(diag::err_fe_pch_file_overridden, Filename);
1993*67e74705SXin Li // After emitting the diagnostic, recover by disabling the override so
1994*67e74705SXin Li // that the original file will be used.
1995*67e74705SXin Li //
1996*67e74705SXin Li // FIXME: This recovery is just as broken as the original state; there may
1997*67e74705SXin Li // be another precompiled module that's using the overridden contents, or
1998*67e74705SXin Li // we might be half way through parsing it. Instead, we should treat the
1999*67e74705SXin Li // overridden contents as belonging to a separate FileEntry.
2000*67e74705SXin Li SM.disableFileContentsOverride(File);
2001*67e74705SXin Li // The FileEntry is a virtual file entry with the size of the contents
2002*67e74705SXin Li // that would override the original contents. Set it to the original's
2003*67e74705SXin Li // size/time.
2004*67e74705SXin Li FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2005*67e74705SXin Li StoredSize, StoredTime);
2006*67e74705SXin Li }
2007*67e74705SXin Li
2008*67e74705SXin Li bool IsOutOfDate = false;
2009*67e74705SXin Li
2010*67e74705SXin Li // For an overridden file, there is nothing to validate.
2011*67e74705SXin Li if (!Overridden && //
2012*67e74705SXin Li (StoredSize != File->getSize() ||
2013*67e74705SXin Li (StoredTime && StoredTime != File->getModificationTime() &&
2014*67e74705SXin Li !DisableValidation)
2015*67e74705SXin Li )) {
2016*67e74705SXin Li if (Complain) {
2017*67e74705SXin Li // Build a list of the PCH imports that got us here (in reverse).
2018*67e74705SXin Li SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2019*67e74705SXin Li while (ImportStack.back()->ImportedBy.size() > 0)
2020*67e74705SXin Li ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2021*67e74705SXin Li
2022*67e74705SXin Li // The top-level PCH is stale.
2023*67e74705SXin Li StringRef TopLevelPCHName(ImportStack.back()->FileName);
2024*67e74705SXin Li Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2025*67e74705SXin Li
2026*67e74705SXin Li // Print the import stack.
2027*67e74705SXin Li if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2028*67e74705SXin Li Diag(diag::note_pch_required_by)
2029*67e74705SXin Li << Filename << ImportStack[0]->FileName;
2030*67e74705SXin Li for (unsigned I = 1; I < ImportStack.size(); ++I)
2031*67e74705SXin Li Diag(diag::note_pch_required_by)
2032*67e74705SXin Li << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2033*67e74705SXin Li }
2034*67e74705SXin Li
2035*67e74705SXin Li if (!Diags.isDiagnosticInFlight())
2036*67e74705SXin Li Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2037*67e74705SXin Li }
2038*67e74705SXin Li
2039*67e74705SXin Li IsOutOfDate = true;
2040*67e74705SXin Li }
2041*67e74705SXin Li // FIXME: If the file is overridden and we've already opened it,
2042*67e74705SXin Li // issue an error (or split it into a separate FileEntry).
2043*67e74705SXin Li
2044*67e74705SXin Li InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
2045*67e74705SXin Li
2046*67e74705SXin Li // Note that we've loaded this input file.
2047*67e74705SXin Li F.InputFilesLoaded[ID-1] = IF;
2048*67e74705SXin Li return IF;
2049*67e74705SXin Li }
2050*67e74705SXin Li
2051*67e74705SXin Li /// \brief If we are loading a relocatable PCH or module file, and the filename
2052*67e74705SXin Li /// is not an absolute path, add the system or module root to the beginning of
2053*67e74705SXin Li /// the file name.
ResolveImportedPath(ModuleFile & M,std::string & Filename)2054*67e74705SXin Li void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2055*67e74705SXin Li // Resolve relative to the base directory, if we have one.
2056*67e74705SXin Li if (!M.BaseDirectory.empty())
2057*67e74705SXin Li return ResolveImportedPath(Filename, M.BaseDirectory);
2058*67e74705SXin Li }
2059*67e74705SXin Li
ResolveImportedPath(std::string & Filename,StringRef Prefix)2060*67e74705SXin Li void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2061*67e74705SXin Li if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2062*67e74705SXin Li return;
2063*67e74705SXin Li
2064*67e74705SXin Li SmallString<128> Buffer;
2065*67e74705SXin Li llvm::sys::path::append(Buffer, Prefix, Filename);
2066*67e74705SXin Li Filename.assign(Buffer.begin(), Buffer.end());
2067*67e74705SXin Li }
2068*67e74705SXin Li
isDiagnosedResult(ASTReader::ASTReadResult ARR,unsigned Caps)2069*67e74705SXin Li static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2070*67e74705SXin Li switch (ARR) {
2071*67e74705SXin Li case ASTReader::Failure: return true;
2072*67e74705SXin Li case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2073*67e74705SXin Li case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2074*67e74705SXin Li case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2075*67e74705SXin Li case ASTReader::ConfigurationMismatch:
2076*67e74705SXin Li return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2077*67e74705SXin Li case ASTReader::HadErrors: return true;
2078*67e74705SXin Li case ASTReader::Success: return false;
2079*67e74705SXin Li }
2080*67e74705SXin Li
2081*67e74705SXin Li llvm_unreachable("unknown ASTReadResult");
2082*67e74705SXin Li }
2083*67e74705SXin Li
ReadOptionsBlock(BitstreamCursor & Stream,unsigned ClientLoadCapabilities,bool AllowCompatibleConfigurationMismatch,ASTReaderListener & Listener,std::string & SuggestedPredefines)2084*67e74705SXin Li ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2085*67e74705SXin Li BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2086*67e74705SXin Li bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2087*67e74705SXin Li std::string &SuggestedPredefines) {
2088*67e74705SXin Li if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2089*67e74705SXin Li return Failure;
2090*67e74705SXin Li
2091*67e74705SXin Li // Read all of the records in the options block.
2092*67e74705SXin Li RecordData Record;
2093*67e74705SXin Li ASTReadResult Result = Success;
2094*67e74705SXin Li while (1) {
2095*67e74705SXin Li llvm::BitstreamEntry Entry = Stream.advance();
2096*67e74705SXin Li
2097*67e74705SXin Li switch (Entry.Kind) {
2098*67e74705SXin Li case llvm::BitstreamEntry::Error:
2099*67e74705SXin Li case llvm::BitstreamEntry::SubBlock:
2100*67e74705SXin Li return Failure;
2101*67e74705SXin Li
2102*67e74705SXin Li case llvm::BitstreamEntry::EndBlock:
2103*67e74705SXin Li return Result;
2104*67e74705SXin Li
2105*67e74705SXin Li case llvm::BitstreamEntry::Record:
2106*67e74705SXin Li // The interesting case.
2107*67e74705SXin Li break;
2108*67e74705SXin Li }
2109*67e74705SXin Li
2110*67e74705SXin Li // Read and process a record.
2111*67e74705SXin Li Record.clear();
2112*67e74705SXin Li switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2113*67e74705SXin Li case LANGUAGE_OPTIONS: {
2114*67e74705SXin Li bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2115*67e74705SXin Li if (ParseLanguageOptions(Record, Complain, Listener,
2116*67e74705SXin Li AllowCompatibleConfigurationMismatch))
2117*67e74705SXin Li Result = ConfigurationMismatch;
2118*67e74705SXin Li break;
2119*67e74705SXin Li }
2120*67e74705SXin Li
2121*67e74705SXin Li case TARGET_OPTIONS: {
2122*67e74705SXin Li bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2123*67e74705SXin Li if (ParseTargetOptions(Record, Complain, Listener,
2124*67e74705SXin Li AllowCompatibleConfigurationMismatch))
2125*67e74705SXin Li Result = ConfigurationMismatch;
2126*67e74705SXin Li break;
2127*67e74705SXin Li }
2128*67e74705SXin Li
2129*67e74705SXin Li case DIAGNOSTIC_OPTIONS: {
2130*67e74705SXin Li bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2131*67e74705SXin Li if (!AllowCompatibleConfigurationMismatch &&
2132*67e74705SXin Li ParseDiagnosticOptions(Record, Complain, Listener))
2133*67e74705SXin Li return OutOfDate;
2134*67e74705SXin Li break;
2135*67e74705SXin Li }
2136*67e74705SXin Li
2137*67e74705SXin Li case FILE_SYSTEM_OPTIONS: {
2138*67e74705SXin Li bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2139*67e74705SXin Li if (!AllowCompatibleConfigurationMismatch &&
2140*67e74705SXin Li ParseFileSystemOptions(Record, Complain, Listener))
2141*67e74705SXin Li Result = ConfigurationMismatch;
2142*67e74705SXin Li break;
2143*67e74705SXin Li }
2144*67e74705SXin Li
2145*67e74705SXin Li case HEADER_SEARCH_OPTIONS: {
2146*67e74705SXin Li bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2147*67e74705SXin Li if (!AllowCompatibleConfigurationMismatch &&
2148*67e74705SXin Li ParseHeaderSearchOptions(Record, Complain, Listener))
2149*67e74705SXin Li Result = ConfigurationMismatch;
2150*67e74705SXin Li break;
2151*67e74705SXin Li }
2152*67e74705SXin Li
2153*67e74705SXin Li case PREPROCESSOR_OPTIONS:
2154*67e74705SXin Li bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2155*67e74705SXin Li if (!AllowCompatibleConfigurationMismatch &&
2156*67e74705SXin Li ParsePreprocessorOptions(Record, Complain, Listener,
2157*67e74705SXin Li SuggestedPredefines))
2158*67e74705SXin Li Result = ConfigurationMismatch;
2159*67e74705SXin Li break;
2160*67e74705SXin Li }
2161*67e74705SXin Li }
2162*67e74705SXin Li }
2163*67e74705SXin Li
2164*67e74705SXin Li ASTReader::ASTReadResult
ReadControlBlock(ModuleFile & F,SmallVectorImpl<ImportedModule> & Loaded,const ModuleFile * ImportedBy,unsigned ClientLoadCapabilities)2165*67e74705SXin Li ASTReader::ReadControlBlock(ModuleFile &F,
2166*67e74705SXin Li SmallVectorImpl<ImportedModule> &Loaded,
2167*67e74705SXin Li const ModuleFile *ImportedBy,
2168*67e74705SXin Li unsigned ClientLoadCapabilities) {
2169*67e74705SXin Li BitstreamCursor &Stream = F.Stream;
2170*67e74705SXin Li ASTReadResult Result = Success;
2171*67e74705SXin Li
2172*67e74705SXin Li if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2173*67e74705SXin Li Error("malformed block record in AST file");
2174*67e74705SXin Li return Failure;
2175*67e74705SXin Li }
2176*67e74705SXin Li
2177*67e74705SXin Li // Read all of the records and blocks in the control block.
2178*67e74705SXin Li RecordData Record;
2179*67e74705SXin Li unsigned NumInputs = 0;
2180*67e74705SXin Li unsigned NumUserInputs = 0;
2181*67e74705SXin Li while (1) {
2182*67e74705SXin Li llvm::BitstreamEntry Entry = Stream.advance();
2183*67e74705SXin Li
2184*67e74705SXin Li switch (Entry.Kind) {
2185*67e74705SXin Li case llvm::BitstreamEntry::Error:
2186*67e74705SXin Li Error("malformed block record in AST file");
2187*67e74705SXin Li return Failure;
2188*67e74705SXin Li case llvm::BitstreamEntry::EndBlock: {
2189*67e74705SXin Li // Validate input files.
2190*67e74705SXin Li const HeaderSearchOptions &HSOpts =
2191*67e74705SXin Li PP.getHeaderSearchInfo().getHeaderSearchOpts();
2192*67e74705SXin Li
2193*67e74705SXin Li // All user input files reside at the index range [0, NumUserInputs), and
2194*67e74705SXin Li // system input files reside at [NumUserInputs, NumInputs). For explicitly
2195*67e74705SXin Li // loaded module files, ignore missing inputs.
2196*67e74705SXin Li if (!DisableValidation && F.Kind != MK_ExplicitModule) {
2197*67e74705SXin Li bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2198*67e74705SXin Li
2199*67e74705SXin Li // If we are reading a module, we will create a verification timestamp,
2200*67e74705SXin Li // so we verify all input files. Otherwise, verify only user input
2201*67e74705SXin Li // files.
2202*67e74705SXin Li
2203*67e74705SXin Li unsigned N = NumUserInputs;
2204*67e74705SXin Li if (ValidateSystemInputs ||
2205*67e74705SXin Li (HSOpts.ModulesValidateOncePerBuildSession &&
2206*67e74705SXin Li F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
2207*67e74705SXin Li F.Kind == MK_ImplicitModule))
2208*67e74705SXin Li N = NumInputs;
2209*67e74705SXin Li
2210*67e74705SXin Li for (unsigned I = 0; I < N; ++I) {
2211*67e74705SXin Li InputFile IF = getInputFile(F, I+1, Complain);
2212*67e74705SXin Li if (!IF.getFile() || IF.isOutOfDate())
2213*67e74705SXin Li return OutOfDate;
2214*67e74705SXin Li }
2215*67e74705SXin Li }
2216*67e74705SXin Li
2217*67e74705SXin Li if (Listener)
2218*67e74705SXin Li Listener->visitModuleFile(F.FileName, F.Kind);
2219*67e74705SXin Li
2220*67e74705SXin Li if (Listener && Listener->needsInputFileVisitation()) {
2221*67e74705SXin Li unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2222*67e74705SXin Li : NumUserInputs;
2223*67e74705SXin Li for (unsigned I = 0; I < N; ++I) {
2224*67e74705SXin Li bool IsSystem = I >= NumUserInputs;
2225*67e74705SXin Li InputFileInfo FI = readInputFileInfo(F, I+1);
2226*67e74705SXin Li Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2227*67e74705SXin Li F.Kind == MK_ExplicitModule);
2228*67e74705SXin Li }
2229*67e74705SXin Li }
2230*67e74705SXin Li
2231*67e74705SXin Li return Result;
2232*67e74705SXin Li }
2233*67e74705SXin Li
2234*67e74705SXin Li case llvm::BitstreamEntry::SubBlock:
2235*67e74705SXin Li switch (Entry.ID) {
2236*67e74705SXin Li case INPUT_FILES_BLOCK_ID:
2237*67e74705SXin Li F.InputFilesCursor = Stream;
2238*67e74705SXin Li if (Stream.SkipBlock() || // Skip with the main cursor
2239*67e74705SXin Li // Read the abbreviations
2240*67e74705SXin Li ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2241*67e74705SXin Li Error("malformed block record in AST file");
2242*67e74705SXin Li return Failure;
2243*67e74705SXin Li }
2244*67e74705SXin Li continue;
2245*67e74705SXin Li
2246*67e74705SXin Li case OPTIONS_BLOCK_ID:
2247*67e74705SXin Li // If we're reading the first module for this group, check its options
2248*67e74705SXin Li // are compatible with ours. For modules it imports, no further checking
2249*67e74705SXin Li // is required, because we checked them when we built it.
2250*67e74705SXin Li if (Listener && !ImportedBy) {
2251*67e74705SXin Li // Should we allow the configuration of the module file to differ from
2252*67e74705SXin Li // the configuration of the current translation unit in a compatible
2253*67e74705SXin Li // way?
2254*67e74705SXin Li //
2255*67e74705SXin Li // FIXME: Allow this for files explicitly specified with -include-pch.
2256*67e74705SXin Li bool AllowCompatibleConfigurationMismatch =
2257*67e74705SXin Li F.Kind == MK_ExplicitModule;
2258*67e74705SXin Li
2259*67e74705SXin Li Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2260*67e74705SXin Li AllowCompatibleConfigurationMismatch,
2261*67e74705SXin Li *Listener, SuggestedPredefines);
2262*67e74705SXin Li if (Result == Failure) {
2263*67e74705SXin Li Error("malformed block record in AST file");
2264*67e74705SXin Li return Result;
2265*67e74705SXin Li }
2266*67e74705SXin Li
2267*67e74705SXin Li if (DisableValidation ||
2268*67e74705SXin Li (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2269*67e74705SXin Li Result = Success;
2270*67e74705SXin Li
2271*67e74705SXin Li // If we can't load the module, exit early since we likely
2272*67e74705SXin Li // will rebuild the module anyway. The stream may be in the
2273*67e74705SXin Li // middle of a block.
2274*67e74705SXin Li if (Result != Success)
2275*67e74705SXin Li return Result;
2276*67e74705SXin Li } else if (Stream.SkipBlock()) {
2277*67e74705SXin Li Error("malformed block record in AST file");
2278*67e74705SXin Li return Failure;
2279*67e74705SXin Li }
2280*67e74705SXin Li continue;
2281*67e74705SXin Li
2282*67e74705SXin Li default:
2283*67e74705SXin Li if (Stream.SkipBlock()) {
2284*67e74705SXin Li Error("malformed block record in AST file");
2285*67e74705SXin Li return Failure;
2286*67e74705SXin Li }
2287*67e74705SXin Li continue;
2288*67e74705SXin Li }
2289*67e74705SXin Li
2290*67e74705SXin Li case llvm::BitstreamEntry::Record:
2291*67e74705SXin Li // The interesting case.
2292*67e74705SXin Li break;
2293*67e74705SXin Li }
2294*67e74705SXin Li
2295*67e74705SXin Li // Read and process a record.
2296*67e74705SXin Li Record.clear();
2297*67e74705SXin Li StringRef Blob;
2298*67e74705SXin Li switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2299*67e74705SXin Li case METADATA: {
2300*67e74705SXin Li if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2301*67e74705SXin Li if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2302*67e74705SXin Li Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2303*67e74705SXin Li : diag::err_pch_version_too_new);
2304*67e74705SXin Li return VersionMismatch;
2305*67e74705SXin Li }
2306*67e74705SXin Li
2307*67e74705SXin Li bool hasErrors = Record[6];
2308*67e74705SXin Li if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2309*67e74705SXin Li Diag(diag::err_pch_with_compiler_errors);
2310*67e74705SXin Li return HadErrors;
2311*67e74705SXin Li }
2312*67e74705SXin Li if (hasErrors) {
2313*67e74705SXin Li Diags.ErrorOccurred = true;
2314*67e74705SXin Li Diags.UncompilableErrorOccurred = true;
2315*67e74705SXin Li Diags.UnrecoverableErrorOccurred = true;
2316*67e74705SXin Li }
2317*67e74705SXin Li
2318*67e74705SXin Li F.RelocatablePCH = Record[4];
2319*67e74705SXin Li // Relative paths in a relocatable PCH are relative to our sysroot.
2320*67e74705SXin Li if (F.RelocatablePCH)
2321*67e74705SXin Li F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
2322*67e74705SXin Li
2323*67e74705SXin Li F.HasTimestamps = Record[5];
2324*67e74705SXin Li
2325*67e74705SXin Li const std::string &CurBranch = getClangFullRepositoryVersion();
2326*67e74705SXin Li StringRef ASTBranch = Blob;
2327*67e74705SXin Li if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2328*67e74705SXin Li if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2329*67e74705SXin Li Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2330*67e74705SXin Li return VersionMismatch;
2331*67e74705SXin Li }
2332*67e74705SXin Li break;
2333*67e74705SXin Li }
2334*67e74705SXin Li
2335*67e74705SXin Li case SIGNATURE:
2336*67e74705SXin Li assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2337*67e74705SXin Li F.Signature = Record[0];
2338*67e74705SXin Li break;
2339*67e74705SXin Li
2340*67e74705SXin Li case IMPORTS: {
2341*67e74705SXin Li // Load each of the imported PCH files.
2342*67e74705SXin Li unsigned Idx = 0, N = Record.size();
2343*67e74705SXin Li while (Idx < N) {
2344*67e74705SXin Li // Read information about the AST file.
2345*67e74705SXin Li ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2346*67e74705SXin Li // The import location will be the local one for now; we will adjust
2347*67e74705SXin Li // all import locations of module imports after the global source
2348*67e74705SXin Li // location info are setup, in ReadAST.
2349*67e74705SXin Li SourceLocation ImportLoc =
2350*67e74705SXin Li ReadUntranslatedSourceLocation(Record[Idx++]);
2351*67e74705SXin Li off_t StoredSize = (off_t)Record[Idx++];
2352*67e74705SXin Li time_t StoredModTime = (time_t)Record[Idx++];
2353*67e74705SXin Li ASTFileSignature StoredSignature = Record[Idx++];
2354*67e74705SXin Li auto ImportedFile = ReadPath(F, Record, Idx);
2355*67e74705SXin Li
2356*67e74705SXin Li // If our client can't cope with us being out of date, we can't cope with
2357*67e74705SXin Li // our dependency being missing.
2358*67e74705SXin Li unsigned Capabilities = ClientLoadCapabilities;
2359*67e74705SXin Li if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2360*67e74705SXin Li Capabilities &= ~ARR_Missing;
2361*67e74705SXin Li
2362*67e74705SXin Li // Load the AST file.
2363*67e74705SXin Li auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2364*67e74705SXin Li Loaded, StoredSize, StoredModTime,
2365*67e74705SXin Li StoredSignature, Capabilities);
2366*67e74705SXin Li
2367*67e74705SXin Li // If we diagnosed a problem, produce a backtrace.
2368*67e74705SXin Li if (isDiagnosedResult(Result, Capabilities))
2369*67e74705SXin Li Diag(diag::note_module_file_imported_by)
2370*67e74705SXin Li << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2371*67e74705SXin Li
2372*67e74705SXin Li switch (Result) {
2373*67e74705SXin Li case Failure: return Failure;
2374*67e74705SXin Li // If we have to ignore the dependency, we'll have to ignore this too.
2375*67e74705SXin Li case Missing:
2376*67e74705SXin Li case OutOfDate: return OutOfDate;
2377*67e74705SXin Li case VersionMismatch: return VersionMismatch;
2378*67e74705SXin Li case ConfigurationMismatch: return ConfigurationMismatch;
2379*67e74705SXin Li case HadErrors: return HadErrors;
2380*67e74705SXin Li case Success: break;
2381*67e74705SXin Li }
2382*67e74705SXin Li }
2383*67e74705SXin Li break;
2384*67e74705SXin Li }
2385*67e74705SXin Li
2386*67e74705SXin Li case ORIGINAL_FILE:
2387*67e74705SXin Li F.OriginalSourceFileID = FileID::get(Record[0]);
2388*67e74705SXin Li F.ActualOriginalSourceFileName = Blob;
2389*67e74705SXin Li F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2390*67e74705SXin Li ResolveImportedPath(F, F.OriginalSourceFileName);
2391*67e74705SXin Li break;
2392*67e74705SXin Li
2393*67e74705SXin Li case ORIGINAL_FILE_ID:
2394*67e74705SXin Li F.OriginalSourceFileID = FileID::get(Record[0]);
2395*67e74705SXin Li break;
2396*67e74705SXin Li
2397*67e74705SXin Li case ORIGINAL_PCH_DIR:
2398*67e74705SXin Li F.OriginalDir = Blob;
2399*67e74705SXin Li break;
2400*67e74705SXin Li
2401*67e74705SXin Li case MODULE_NAME:
2402*67e74705SXin Li F.ModuleName = Blob;
2403*67e74705SXin Li if (Listener)
2404*67e74705SXin Li Listener->ReadModuleName(F.ModuleName);
2405*67e74705SXin Li break;
2406*67e74705SXin Li
2407*67e74705SXin Li case MODULE_DIRECTORY: {
2408*67e74705SXin Li assert(!F.ModuleName.empty() &&
2409*67e74705SXin Li "MODULE_DIRECTORY found before MODULE_NAME");
2410*67e74705SXin Li // If we've already loaded a module map file covering this module, we may
2411*67e74705SXin Li // have a better path for it (relative to the current build).
2412*67e74705SXin Li Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2413*67e74705SXin Li if (M && M->Directory) {
2414*67e74705SXin Li // If we're implicitly loading a module, the base directory can't
2415*67e74705SXin Li // change between the build and use.
2416*67e74705SXin Li if (F.Kind != MK_ExplicitModule) {
2417*67e74705SXin Li const DirectoryEntry *BuildDir =
2418*67e74705SXin Li PP.getFileManager().getDirectory(Blob);
2419*67e74705SXin Li if (!BuildDir || BuildDir != M->Directory) {
2420*67e74705SXin Li if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2421*67e74705SXin Li Diag(diag::err_imported_module_relocated)
2422*67e74705SXin Li << F.ModuleName << Blob << M->Directory->getName();
2423*67e74705SXin Li return OutOfDate;
2424*67e74705SXin Li }
2425*67e74705SXin Li }
2426*67e74705SXin Li F.BaseDirectory = M->Directory->getName();
2427*67e74705SXin Li } else {
2428*67e74705SXin Li F.BaseDirectory = Blob;
2429*67e74705SXin Li }
2430*67e74705SXin Li break;
2431*67e74705SXin Li }
2432*67e74705SXin Li
2433*67e74705SXin Li case MODULE_MAP_FILE:
2434*67e74705SXin Li if (ASTReadResult Result =
2435*67e74705SXin Li ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2436*67e74705SXin Li return Result;
2437*67e74705SXin Li break;
2438*67e74705SXin Li
2439*67e74705SXin Li case INPUT_FILE_OFFSETS:
2440*67e74705SXin Li NumInputs = Record[0];
2441*67e74705SXin Li NumUserInputs = Record[1];
2442*67e74705SXin Li F.InputFileOffsets =
2443*67e74705SXin Li (const llvm::support::unaligned_uint64_t *)Blob.data();
2444*67e74705SXin Li F.InputFilesLoaded.resize(NumInputs);
2445*67e74705SXin Li break;
2446*67e74705SXin Li }
2447*67e74705SXin Li }
2448*67e74705SXin Li }
2449*67e74705SXin Li
2450*67e74705SXin Li ASTReader::ASTReadResult
ReadASTBlock(ModuleFile & F,unsigned ClientLoadCapabilities)2451*67e74705SXin Li ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
2452*67e74705SXin Li BitstreamCursor &Stream = F.Stream;
2453*67e74705SXin Li
2454*67e74705SXin Li if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2455*67e74705SXin Li Error("malformed block record in AST file");
2456*67e74705SXin Li return Failure;
2457*67e74705SXin Li }
2458*67e74705SXin Li
2459*67e74705SXin Li // Read all of the records and blocks for the AST file.
2460*67e74705SXin Li RecordData Record;
2461*67e74705SXin Li while (1) {
2462*67e74705SXin Li llvm::BitstreamEntry Entry = Stream.advance();
2463*67e74705SXin Li
2464*67e74705SXin Li switch (Entry.Kind) {
2465*67e74705SXin Li case llvm::BitstreamEntry::Error:
2466*67e74705SXin Li Error("error at end of module block in AST file");
2467*67e74705SXin Li return Failure;
2468*67e74705SXin Li case llvm::BitstreamEntry::EndBlock: {
2469*67e74705SXin Li // Outside of C++, we do not store a lookup map for the translation unit.
2470*67e74705SXin Li // Instead, mark it as needing a lookup map to be built if this module
2471*67e74705SXin Li // contains any declarations lexically within it (which it always does!).
2472*67e74705SXin Li // This usually has no cost, since we very rarely need the lookup map for
2473*67e74705SXin Li // the translation unit outside C++.
2474*67e74705SXin Li DeclContext *DC = Context.getTranslationUnitDecl();
2475*67e74705SXin Li if (DC->hasExternalLexicalStorage() &&
2476*67e74705SXin Li !getContext().getLangOpts().CPlusPlus)
2477*67e74705SXin Li DC->setMustBuildLookupTable();
2478*67e74705SXin Li
2479*67e74705SXin Li return Success;
2480*67e74705SXin Li }
2481*67e74705SXin Li case llvm::BitstreamEntry::SubBlock:
2482*67e74705SXin Li switch (Entry.ID) {
2483*67e74705SXin Li case DECLTYPES_BLOCK_ID:
2484*67e74705SXin Li // We lazily load the decls block, but we want to set up the
2485*67e74705SXin Li // DeclsCursor cursor to point into it. Clone our current bitcode
2486*67e74705SXin Li // cursor to it, enter the block and read the abbrevs in that block.
2487*67e74705SXin Li // With the main cursor, we just skip over it.
2488*67e74705SXin Li F.DeclsCursor = Stream;
2489*67e74705SXin Li if (Stream.SkipBlock() || // Skip with the main cursor.
2490*67e74705SXin Li // Read the abbrevs.
2491*67e74705SXin Li ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2492*67e74705SXin Li Error("malformed block record in AST file");
2493*67e74705SXin Li return Failure;
2494*67e74705SXin Li }
2495*67e74705SXin Li break;
2496*67e74705SXin Li
2497*67e74705SXin Li case PREPROCESSOR_BLOCK_ID:
2498*67e74705SXin Li F.MacroCursor = Stream;
2499*67e74705SXin Li if (!PP.getExternalSource())
2500*67e74705SXin Li PP.setExternalSource(this);
2501*67e74705SXin Li
2502*67e74705SXin Li if (Stream.SkipBlock() ||
2503*67e74705SXin Li ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2504*67e74705SXin Li Error("malformed block record in AST file");
2505*67e74705SXin Li return Failure;
2506*67e74705SXin Li }
2507*67e74705SXin Li F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2508*67e74705SXin Li break;
2509*67e74705SXin Li
2510*67e74705SXin Li case PREPROCESSOR_DETAIL_BLOCK_ID:
2511*67e74705SXin Li F.PreprocessorDetailCursor = Stream;
2512*67e74705SXin Li if (Stream.SkipBlock() ||
2513*67e74705SXin Li ReadBlockAbbrevs(F.PreprocessorDetailCursor,
2514*67e74705SXin Li PREPROCESSOR_DETAIL_BLOCK_ID)) {
2515*67e74705SXin Li Error("malformed preprocessor detail record in AST file");
2516*67e74705SXin Li return Failure;
2517*67e74705SXin Li }
2518*67e74705SXin Li F.PreprocessorDetailStartOffset
2519*67e74705SXin Li = F.PreprocessorDetailCursor.GetCurrentBitNo();
2520*67e74705SXin Li
2521*67e74705SXin Li if (!PP.getPreprocessingRecord())
2522*67e74705SXin Li PP.createPreprocessingRecord();
2523*67e74705SXin Li if (!PP.getPreprocessingRecord()->getExternalSource())
2524*67e74705SXin Li PP.getPreprocessingRecord()->SetExternalSource(*this);
2525*67e74705SXin Li break;
2526*67e74705SXin Li
2527*67e74705SXin Li case SOURCE_MANAGER_BLOCK_ID:
2528*67e74705SXin Li if (ReadSourceManagerBlock(F))
2529*67e74705SXin Li return Failure;
2530*67e74705SXin Li break;
2531*67e74705SXin Li
2532*67e74705SXin Li case SUBMODULE_BLOCK_ID:
2533*67e74705SXin Li if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2534*67e74705SXin Li return Result;
2535*67e74705SXin Li break;
2536*67e74705SXin Li
2537*67e74705SXin Li case COMMENTS_BLOCK_ID: {
2538*67e74705SXin Li BitstreamCursor C = Stream;
2539*67e74705SXin Li if (Stream.SkipBlock() ||
2540*67e74705SXin Li ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2541*67e74705SXin Li Error("malformed comments block in AST file");
2542*67e74705SXin Li return Failure;
2543*67e74705SXin Li }
2544*67e74705SXin Li CommentsCursors.push_back(std::make_pair(C, &F));
2545*67e74705SXin Li break;
2546*67e74705SXin Li }
2547*67e74705SXin Li
2548*67e74705SXin Li default:
2549*67e74705SXin Li if (Stream.SkipBlock()) {
2550*67e74705SXin Li Error("malformed block record in AST file");
2551*67e74705SXin Li return Failure;
2552*67e74705SXin Li }
2553*67e74705SXin Li break;
2554*67e74705SXin Li }
2555*67e74705SXin Li continue;
2556*67e74705SXin Li
2557*67e74705SXin Li case llvm::BitstreamEntry::Record:
2558*67e74705SXin Li // The interesting case.
2559*67e74705SXin Li break;
2560*67e74705SXin Li }
2561*67e74705SXin Li
2562*67e74705SXin Li // Read and process a record.
2563*67e74705SXin Li Record.clear();
2564*67e74705SXin Li StringRef Blob;
2565*67e74705SXin Li switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2566*67e74705SXin Li default: // Default behavior: ignore.
2567*67e74705SXin Li break;
2568*67e74705SXin Li
2569*67e74705SXin Li case TYPE_OFFSET: {
2570*67e74705SXin Li if (F.LocalNumTypes != 0) {
2571*67e74705SXin Li Error("duplicate TYPE_OFFSET record in AST file");
2572*67e74705SXin Li return Failure;
2573*67e74705SXin Li }
2574*67e74705SXin Li F.TypeOffsets = (const uint32_t *)Blob.data();
2575*67e74705SXin Li F.LocalNumTypes = Record[0];
2576*67e74705SXin Li unsigned LocalBaseTypeIndex = Record[1];
2577*67e74705SXin Li F.BaseTypeIndex = getTotalNumTypes();
2578*67e74705SXin Li
2579*67e74705SXin Li if (F.LocalNumTypes > 0) {
2580*67e74705SXin Li // Introduce the global -> local mapping for types within this module.
2581*67e74705SXin Li GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2582*67e74705SXin Li
2583*67e74705SXin Li // Introduce the local -> global mapping for types within this module.
2584*67e74705SXin Li F.TypeRemap.insertOrReplace(
2585*67e74705SXin Li std::make_pair(LocalBaseTypeIndex,
2586*67e74705SXin Li F.BaseTypeIndex - LocalBaseTypeIndex));
2587*67e74705SXin Li
2588*67e74705SXin Li TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2589*67e74705SXin Li }
2590*67e74705SXin Li break;
2591*67e74705SXin Li }
2592*67e74705SXin Li
2593*67e74705SXin Li case DECL_OFFSET: {
2594*67e74705SXin Li if (F.LocalNumDecls != 0) {
2595*67e74705SXin Li Error("duplicate DECL_OFFSET record in AST file");
2596*67e74705SXin Li return Failure;
2597*67e74705SXin Li }
2598*67e74705SXin Li F.DeclOffsets = (const DeclOffset *)Blob.data();
2599*67e74705SXin Li F.LocalNumDecls = Record[0];
2600*67e74705SXin Li unsigned LocalBaseDeclID = Record[1];
2601*67e74705SXin Li F.BaseDeclID = getTotalNumDecls();
2602*67e74705SXin Li
2603*67e74705SXin Li if (F.LocalNumDecls > 0) {
2604*67e74705SXin Li // Introduce the global -> local mapping for declarations within this
2605*67e74705SXin Li // module.
2606*67e74705SXin Li GlobalDeclMap.insert(
2607*67e74705SXin Li std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2608*67e74705SXin Li
2609*67e74705SXin Li // Introduce the local -> global mapping for declarations within this
2610*67e74705SXin Li // module.
2611*67e74705SXin Li F.DeclRemap.insertOrReplace(
2612*67e74705SXin Li std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2613*67e74705SXin Li
2614*67e74705SXin Li // Introduce the global -> local mapping for declarations within this
2615*67e74705SXin Li // module.
2616*67e74705SXin Li F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2617*67e74705SXin Li
2618*67e74705SXin Li DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2619*67e74705SXin Li }
2620*67e74705SXin Li break;
2621*67e74705SXin Li }
2622*67e74705SXin Li
2623*67e74705SXin Li case TU_UPDATE_LEXICAL: {
2624*67e74705SXin Li DeclContext *TU = Context.getTranslationUnitDecl();
2625*67e74705SXin Li LexicalContents Contents(
2626*67e74705SXin Li reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2627*67e74705SXin Li Blob.data()),
2628*67e74705SXin Li static_cast<unsigned int>(Blob.size() / 4));
2629*67e74705SXin Li TULexicalDecls.push_back(std::make_pair(&F, Contents));
2630*67e74705SXin Li TU->setHasExternalLexicalStorage(true);
2631*67e74705SXin Li break;
2632*67e74705SXin Li }
2633*67e74705SXin Li
2634*67e74705SXin Li case UPDATE_VISIBLE: {
2635*67e74705SXin Li unsigned Idx = 0;
2636*67e74705SXin Li serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2637*67e74705SXin Li auto *Data = (const unsigned char*)Blob.data();
2638*67e74705SXin Li PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
2639*67e74705SXin Li // If we've already loaded the decl, perform the updates when we finish
2640*67e74705SXin Li // loading this block.
2641*67e74705SXin Li if (Decl *D = GetExistingDecl(ID))
2642*67e74705SXin Li PendingUpdateRecords.push_back(std::make_pair(ID, D));
2643*67e74705SXin Li break;
2644*67e74705SXin Li }
2645*67e74705SXin Li
2646*67e74705SXin Li case IDENTIFIER_TABLE:
2647*67e74705SXin Li F.IdentifierTableData = Blob.data();
2648*67e74705SXin Li if (Record[0]) {
2649*67e74705SXin Li F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2650*67e74705SXin Li (const unsigned char *)F.IdentifierTableData + Record[0],
2651*67e74705SXin Li (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2652*67e74705SXin Li (const unsigned char *)F.IdentifierTableData,
2653*67e74705SXin Li ASTIdentifierLookupTrait(*this, F));
2654*67e74705SXin Li
2655*67e74705SXin Li PP.getIdentifierTable().setExternalIdentifierLookup(this);
2656*67e74705SXin Li }
2657*67e74705SXin Li break;
2658*67e74705SXin Li
2659*67e74705SXin Li case IDENTIFIER_OFFSET: {
2660*67e74705SXin Li if (F.LocalNumIdentifiers != 0) {
2661*67e74705SXin Li Error("duplicate IDENTIFIER_OFFSET record in AST file");
2662*67e74705SXin Li return Failure;
2663*67e74705SXin Li }
2664*67e74705SXin Li F.IdentifierOffsets = (const uint32_t *)Blob.data();
2665*67e74705SXin Li F.LocalNumIdentifiers = Record[0];
2666*67e74705SXin Li unsigned LocalBaseIdentifierID = Record[1];
2667*67e74705SXin Li F.BaseIdentifierID = getTotalNumIdentifiers();
2668*67e74705SXin Li
2669*67e74705SXin Li if (F.LocalNumIdentifiers > 0) {
2670*67e74705SXin Li // Introduce the global -> local mapping for identifiers within this
2671*67e74705SXin Li // module.
2672*67e74705SXin Li GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2673*67e74705SXin Li &F));
2674*67e74705SXin Li
2675*67e74705SXin Li // Introduce the local -> global mapping for identifiers within this
2676*67e74705SXin Li // module.
2677*67e74705SXin Li F.IdentifierRemap.insertOrReplace(
2678*67e74705SXin Li std::make_pair(LocalBaseIdentifierID,
2679*67e74705SXin Li F.BaseIdentifierID - LocalBaseIdentifierID));
2680*67e74705SXin Li
2681*67e74705SXin Li IdentifiersLoaded.resize(IdentifiersLoaded.size()
2682*67e74705SXin Li + F.LocalNumIdentifiers);
2683*67e74705SXin Li }
2684*67e74705SXin Li break;
2685*67e74705SXin Li }
2686*67e74705SXin Li
2687*67e74705SXin Li case INTERESTING_IDENTIFIERS:
2688*67e74705SXin Li F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2689*67e74705SXin Li break;
2690*67e74705SXin Li
2691*67e74705SXin Li case EAGERLY_DESERIALIZED_DECLS:
2692*67e74705SXin Li // FIXME: Skip reading this record if our ASTConsumer doesn't care
2693*67e74705SXin Li // about "interesting" decls (for instance, if we're building a module).
2694*67e74705SXin Li for (unsigned I = 0, N = Record.size(); I != N; ++I)
2695*67e74705SXin Li EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2696*67e74705SXin Li break;
2697*67e74705SXin Li
2698*67e74705SXin Li case SPECIAL_TYPES:
2699*67e74705SXin Li if (SpecialTypes.empty()) {
2700*67e74705SXin Li for (unsigned I = 0, N = Record.size(); I != N; ++I)
2701*67e74705SXin Li SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2702*67e74705SXin Li break;
2703*67e74705SXin Li }
2704*67e74705SXin Li
2705*67e74705SXin Li if (SpecialTypes.size() != Record.size()) {
2706*67e74705SXin Li Error("invalid special-types record");
2707*67e74705SXin Li return Failure;
2708*67e74705SXin Li }
2709*67e74705SXin Li
2710*67e74705SXin Li for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2711*67e74705SXin Li serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2712*67e74705SXin Li if (!SpecialTypes[I])
2713*67e74705SXin Li SpecialTypes[I] = ID;
2714*67e74705SXin Li // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2715*67e74705SXin Li // merge step?
2716*67e74705SXin Li }
2717*67e74705SXin Li break;
2718*67e74705SXin Li
2719*67e74705SXin Li case STATISTICS:
2720*67e74705SXin Li TotalNumStatements += Record[0];
2721*67e74705SXin Li TotalNumMacros += Record[1];
2722*67e74705SXin Li TotalLexicalDeclContexts += Record[2];
2723*67e74705SXin Li TotalVisibleDeclContexts += Record[3];
2724*67e74705SXin Li break;
2725*67e74705SXin Li
2726*67e74705SXin Li case UNUSED_FILESCOPED_DECLS:
2727*67e74705SXin Li for (unsigned I = 0, N = Record.size(); I != N; ++I)
2728*67e74705SXin Li UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2729*67e74705SXin Li break;
2730*67e74705SXin Li
2731*67e74705SXin Li case DELEGATING_CTORS:
2732*67e74705SXin Li for (unsigned I = 0, N = Record.size(); I != N; ++I)
2733*67e74705SXin Li DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2734*67e74705SXin Li break;
2735*67e74705SXin Li
2736*67e74705SXin Li case WEAK_UNDECLARED_IDENTIFIERS:
2737*67e74705SXin Li if (Record.size() % 4 != 0) {
2738*67e74705SXin Li Error("invalid weak identifiers record");
2739*67e74705SXin Li return Failure;
2740*67e74705SXin Li }
2741*67e74705SXin Li
2742*67e74705SXin Li // FIXME: Ignore weak undeclared identifiers from non-original PCH
2743*67e74705SXin Li // files. This isn't the way to do it :)
2744*67e74705SXin Li WeakUndeclaredIdentifiers.clear();
2745*67e74705SXin Li
2746*67e74705SXin Li // Translate the weak, undeclared identifiers into global IDs.
2747*67e74705SXin Li for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2748*67e74705SXin Li WeakUndeclaredIdentifiers.push_back(
2749*67e74705SXin Li getGlobalIdentifierID(F, Record[I++]));
2750*67e74705SXin Li WeakUndeclaredIdentifiers.push_back(
2751*67e74705SXin Li getGlobalIdentifierID(F, Record[I++]));
2752*67e74705SXin Li WeakUndeclaredIdentifiers.push_back(
2753*67e74705SXin Li ReadSourceLocation(F, Record, I).getRawEncoding());
2754*67e74705SXin Li WeakUndeclaredIdentifiers.push_back(Record[I++]);
2755*67e74705SXin Li }
2756*67e74705SXin Li break;
2757*67e74705SXin Li
2758*67e74705SXin Li case SELECTOR_OFFSETS: {
2759*67e74705SXin Li F.SelectorOffsets = (const uint32_t *)Blob.data();
2760*67e74705SXin Li F.LocalNumSelectors = Record[0];
2761*67e74705SXin Li unsigned LocalBaseSelectorID = Record[1];
2762*67e74705SXin Li F.BaseSelectorID = getTotalNumSelectors();
2763*67e74705SXin Li
2764*67e74705SXin Li if (F.LocalNumSelectors > 0) {
2765*67e74705SXin Li // Introduce the global -> local mapping for selectors within this
2766*67e74705SXin Li // module.
2767*67e74705SXin Li GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2768*67e74705SXin Li
2769*67e74705SXin Li // Introduce the local -> global mapping for selectors within this
2770*67e74705SXin Li // module.
2771*67e74705SXin Li F.SelectorRemap.insertOrReplace(
2772*67e74705SXin Li std::make_pair(LocalBaseSelectorID,
2773*67e74705SXin Li F.BaseSelectorID - LocalBaseSelectorID));
2774*67e74705SXin Li
2775*67e74705SXin Li SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2776*67e74705SXin Li }
2777*67e74705SXin Li break;
2778*67e74705SXin Li }
2779*67e74705SXin Li
2780*67e74705SXin Li case METHOD_POOL:
2781*67e74705SXin Li F.SelectorLookupTableData = (const unsigned char *)Blob.data();
2782*67e74705SXin Li if (Record[0])
2783*67e74705SXin Li F.SelectorLookupTable
2784*67e74705SXin Li = ASTSelectorLookupTable::Create(
2785*67e74705SXin Li F.SelectorLookupTableData + Record[0],
2786*67e74705SXin Li F.SelectorLookupTableData,
2787*67e74705SXin Li ASTSelectorLookupTrait(*this, F));
2788*67e74705SXin Li TotalNumMethodPoolEntries += Record[1];
2789*67e74705SXin Li break;
2790*67e74705SXin Li
2791*67e74705SXin Li case REFERENCED_SELECTOR_POOL:
2792*67e74705SXin Li if (!Record.empty()) {
2793*67e74705SXin Li for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2794*67e74705SXin Li ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2795*67e74705SXin Li Record[Idx++]));
2796*67e74705SXin Li ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2797*67e74705SXin Li getRawEncoding());
2798*67e74705SXin Li }
2799*67e74705SXin Li }
2800*67e74705SXin Li break;
2801*67e74705SXin Li
2802*67e74705SXin Li case PP_COUNTER_VALUE:
2803*67e74705SXin Li if (!Record.empty() && Listener)
2804*67e74705SXin Li Listener->ReadCounter(F, Record[0]);
2805*67e74705SXin Li break;
2806*67e74705SXin Li
2807*67e74705SXin Li case FILE_SORTED_DECLS:
2808*67e74705SXin Li F.FileSortedDecls = (const DeclID *)Blob.data();
2809*67e74705SXin Li F.NumFileSortedDecls = Record[0];
2810*67e74705SXin Li break;
2811*67e74705SXin Li
2812*67e74705SXin Li case SOURCE_LOCATION_OFFSETS: {
2813*67e74705SXin Li F.SLocEntryOffsets = (const uint32_t *)Blob.data();
2814*67e74705SXin Li F.LocalNumSLocEntries = Record[0];
2815*67e74705SXin Li unsigned SLocSpaceSize = Record[1];
2816*67e74705SXin Li std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2817*67e74705SXin Li SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2818*67e74705SXin Li SLocSpaceSize);
2819*67e74705SXin Li if (!F.SLocEntryBaseID) {
2820*67e74705SXin Li Error("ran out of source locations");
2821*67e74705SXin Li break;
2822*67e74705SXin Li }
2823*67e74705SXin Li // Make our entry in the range map. BaseID is negative and growing, so
2824*67e74705SXin Li // we invert it. Because we invert it, though, we need the other end of
2825*67e74705SXin Li // the range.
2826*67e74705SXin Li unsigned RangeStart =
2827*67e74705SXin Li unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2828*67e74705SXin Li GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2829*67e74705SXin Li F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2830*67e74705SXin Li
2831*67e74705SXin Li // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2832*67e74705SXin Li assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2833*67e74705SXin Li GlobalSLocOffsetMap.insert(
2834*67e74705SXin Li std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2835*67e74705SXin Li - SLocSpaceSize,&F));
2836*67e74705SXin Li
2837*67e74705SXin Li // Initialize the remapping table.
2838*67e74705SXin Li // Invalid stays invalid.
2839*67e74705SXin Li F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
2840*67e74705SXin Li // This module. Base was 2 when being compiled.
2841*67e74705SXin Li F.SLocRemap.insertOrReplace(std::make_pair(2U,
2842*67e74705SXin Li static_cast<int>(F.SLocEntryBaseOffset - 2)));
2843*67e74705SXin Li
2844*67e74705SXin Li TotalNumSLocEntries += F.LocalNumSLocEntries;
2845*67e74705SXin Li break;
2846*67e74705SXin Li }
2847*67e74705SXin Li
2848*67e74705SXin Li case MODULE_OFFSET_MAP: {
2849*67e74705SXin Li // Additional remapping information.
2850*67e74705SXin Li const unsigned char *Data = (const unsigned char*)Blob.data();
2851*67e74705SXin Li const unsigned char *DataEnd = Data + Blob.size();
2852*67e74705SXin Li
2853*67e74705SXin Li // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2854*67e74705SXin Li if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2855*67e74705SXin Li F.SLocRemap.insert(std::make_pair(0U, 0));
2856*67e74705SXin Li F.SLocRemap.insert(std::make_pair(2U, 1));
2857*67e74705SXin Li }
2858*67e74705SXin Li
2859*67e74705SXin Li // Continuous range maps we may be updating in our module.
2860*67e74705SXin Li typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2861*67e74705SXin Li RemapBuilder;
2862*67e74705SXin Li RemapBuilder SLocRemap(F.SLocRemap);
2863*67e74705SXin Li RemapBuilder IdentifierRemap(F.IdentifierRemap);
2864*67e74705SXin Li RemapBuilder MacroRemap(F.MacroRemap);
2865*67e74705SXin Li RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2866*67e74705SXin Li RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2867*67e74705SXin Li RemapBuilder SelectorRemap(F.SelectorRemap);
2868*67e74705SXin Li RemapBuilder DeclRemap(F.DeclRemap);
2869*67e74705SXin Li RemapBuilder TypeRemap(F.TypeRemap);
2870*67e74705SXin Li
2871*67e74705SXin Li while (Data < DataEnd) {
2872*67e74705SXin Li using namespace llvm::support;
2873*67e74705SXin Li uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
2874*67e74705SXin Li StringRef Name = StringRef((const char*)Data, Len);
2875*67e74705SXin Li Data += Len;
2876*67e74705SXin Li ModuleFile *OM = ModuleMgr.lookup(Name);
2877*67e74705SXin Li if (!OM) {
2878*67e74705SXin Li Error("SourceLocation remap refers to unknown module");
2879*67e74705SXin Li return Failure;
2880*67e74705SXin Li }
2881*67e74705SXin Li
2882*67e74705SXin Li uint32_t SLocOffset =
2883*67e74705SXin Li endian::readNext<uint32_t, little, unaligned>(Data);
2884*67e74705SXin Li uint32_t IdentifierIDOffset =
2885*67e74705SXin Li endian::readNext<uint32_t, little, unaligned>(Data);
2886*67e74705SXin Li uint32_t MacroIDOffset =
2887*67e74705SXin Li endian::readNext<uint32_t, little, unaligned>(Data);
2888*67e74705SXin Li uint32_t PreprocessedEntityIDOffset =
2889*67e74705SXin Li endian::readNext<uint32_t, little, unaligned>(Data);
2890*67e74705SXin Li uint32_t SubmoduleIDOffset =
2891*67e74705SXin Li endian::readNext<uint32_t, little, unaligned>(Data);
2892*67e74705SXin Li uint32_t SelectorIDOffset =
2893*67e74705SXin Li endian::readNext<uint32_t, little, unaligned>(Data);
2894*67e74705SXin Li uint32_t DeclIDOffset =
2895*67e74705SXin Li endian::readNext<uint32_t, little, unaligned>(Data);
2896*67e74705SXin Li uint32_t TypeIndexOffset =
2897*67e74705SXin Li endian::readNext<uint32_t, little, unaligned>(Data);
2898*67e74705SXin Li
2899*67e74705SXin Li uint32_t None = std::numeric_limits<uint32_t>::max();
2900*67e74705SXin Li
2901*67e74705SXin Li auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2902*67e74705SXin Li RemapBuilder &Remap) {
2903*67e74705SXin Li if (Offset != None)
2904*67e74705SXin Li Remap.insert(std::make_pair(Offset,
2905*67e74705SXin Li static_cast<int>(BaseOffset - Offset)));
2906*67e74705SXin Li };
2907*67e74705SXin Li mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2908*67e74705SXin Li mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2909*67e74705SXin Li mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2910*67e74705SXin Li mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2911*67e74705SXin Li PreprocessedEntityRemap);
2912*67e74705SXin Li mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2913*67e74705SXin Li mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2914*67e74705SXin Li mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2915*67e74705SXin Li mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
2916*67e74705SXin Li
2917*67e74705SXin Li // Global -> local mappings.
2918*67e74705SXin Li F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2919*67e74705SXin Li }
2920*67e74705SXin Li break;
2921*67e74705SXin Li }
2922*67e74705SXin Li
2923*67e74705SXin Li case SOURCE_MANAGER_LINE_TABLE:
2924*67e74705SXin Li if (ParseLineTable(F, Record))
2925*67e74705SXin Li return Failure;
2926*67e74705SXin Li break;
2927*67e74705SXin Li
2928*67e74705SXin Li case SOURCE_LOCATION_PRELOADS: {
2929*67e74705SXin Li // Need to transform from the local view (1-based IDs) to the global view,
2930*67e74705SXin Li // which is based off F.SLocEntryBaseID.
2931*67e74705SXin Li if (!F.PreloadSLocEntries.empty()) {
2932*67e74705SXin Li Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2933*67e74705SXin Li return Failure;
2934*67e74705SXin Li }
2935*67e74705SXin Li
2936*67e74705SXin Li F.PreloadSLocEntries.swap(Record);
2937*67e74705SXin Li break;
2938*67e74705SXin Li }
2939*67e74705SXin Li
2940*67e74705SXin Li case EXT_VECTOR_DECLS:
2941*67e74705SXin Li for (unsigned I = 0, N = Record.size(); I != N; ++I)
2942*67e74705SXin Li ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2943*67e74705SXin Li break;
2944*67e74705SXin Li
2945*67e74705SXin Li case VTABLE_USES:
2946*67e74705SXin Li if (Record.size() % 3 != 0) {
2947*67e74705SXin Li Error("Invalid VTABLE_USES record");
2948*67e74705SXin Li return Failure;
2949*67e74705SXin Li }
2950*67e74705SXin Li
2951*67e74705SXin Li // Later tables overwrite earlier ones.
2952*67e74705SXin Li // FIXME: Modules will have some trouble with this. This is clearly not
2953*67e74705SXin Li // the right way to do this.
2954*67e74705SXin Li VTableUses.clear();
2955*67e74705SXin Li
2956*67e74705SXin Li for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2957*67e74705SXin Li VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2958*67e74705SXin Li VTableUses.push_back(
2959*67e74705SXin Li ReadSourceLocation(F, Record, Idx).getRawEncoding());
2960*67e74705SXin Li VTableUses.push_back(Record[Idx++]);
2961*67e74705SXin Li }
2962*67e74705SXin Li break;
2963*67e74705SXin Li
2964*67e74705SXin Li case PENDING_IMPLICIT_INSTANTIATIONS:
2965*67e74705SXin Li if (PendingInstantiations.size() % 2 != 0) {
2966*67e74705SXin Li Error("Invalid existing PendingInstantiations");
2967*67e74705SXin Li return Failure;
2968*67e74705SXin Li }
2969*67e74705SXin Li
2970*67e74705SXin Li if (Record.size() % 2 != 0) {
2971*67e74705SXin Li Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2972*67e74705SXin Li return Failure;
2973*67e74705SXin Li }
2974*67e74705SXin Li
2975*67e74705SXin Li for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2976*67e74705SXin Li PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2977*67e74705SXin Li PendingInstantiations.push_back(
2978*67e74705SXin Li ReadSourceLocation(F, Record, I).getRawEncoding());
2979*67e74705SXin Li }
2980*67e74705SXin Li break;
2981*67e74705SXin Li
2982*67e74705SXin Li case SEMA_DECL_REFS:
2983*67e74705SXin Li if (Record.size() != 2) {
2984*67e74705SXin Li Error("Invalid SEMA_DECL_REFS block");
2985*67e74705SXin Li return Failure;
2986*67e74705SXin Li }
2987*67e74705SXin Li for (unsigned I = 0, N = Record.size(); I != N; ++I)
2988*67e74705SXin Li SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2989*67e74705SXin Li break;
2990*67e74705SXin Li
2991*67e74705SXin Li case PPD_ENTITIES_OFFSETS: {
2992*67e74705SXin Li F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2993*67e74705SXin Li assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2994*67e74705SXin Li F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
2995*67e74705SXin Li
2996*67e74705SXin Li unsigned LocalBasePreprocessedEntityID = Record[0];
2997*67e74705SXin Li
2998*67e74705SXin Li unsigned StartingID;
2999*67e74705SXin Li if (!PP.getPreprocessingRecord())
3000*67e74705SXin Li PP.createPreprocessingRecord();
3001*67e74705SXin Li if (!PP.getPreprocessingRecord()->getExternalSource())
3002*67e74705SXin Li PP.getPreprocessingRecord()->SetExternalSource(*this);
3003*67e74705SXin Li StartingID
3004*67e74705SXin Li = PP.getPreprocessingRecord()
3005*67e74705SXin Li ->allocateLoadedEntities(F.NumPreprocessedEntities);
3006*67e74705SXin Li F.BasePreprocessedEntityID = StartingID;
3007*67e74705SXin Li
3008*67e74705SXin Li if (F.NumPreprocessedEntities > 0) {
3009*67e74705SXin Li // Introduce the global -> local mapping for preprocessed entities in
3010*67e74705SXin Li // this module.
3011*67e74705SXin Li GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3012*67e74705SXin Li
3013*67e74705SXin Li // Introduce the local -> global mapping for preprocessed entities in
3014*67e74705SXin Li // this module.
3015*67e74705SXin Li F.PreprocessedEntityRemap.insertOrReplace(
3016*67e74705SXin Li std::make_pair(LocalBasePreprocessedEntityID,
3017*67e74705SXin Li F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3018*67e74705SXin Li }
3019*67e74705SXin Li
3020*67e74705SXin Li break;
3021*67e74705SXin Li }
3022*67e74705SXin Li
3023*67e74705SXin Li case DECL_UPDATE_OFFSETS: {
3024*67e74705SXin Li if (Record.size() % 2 != 0) {
3025*67e74705SXin Li Error("invalid DECL_UPDATE_OFFSETS block in AST file");
3026*67e74705SXin Li return Failure;
3027*67e74705SXin Li }
3028*67e74705SXin Li for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3029*67e74705SXin Li GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3030*67e74705SXin Li DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3031*67e74705SXin Li
3032*67e74705SXin Li // If we've already loaded the decl, perform the updates when we finish
3033*67e74705SXin Li // loading this block.
3034*67e74705SXin Li if (Decl *D = GetExistingDecl(ID))
3035*67e74705SXin Li PendingUpdateRecords.push_back(std::make_pair(ID, D));
3036*67e74705SXin Li }
3037*67e74705SXin Li break;
3038*67e74705SXin Li }
3039*67e74705SXin Li
3040*67e74705SXin Li case OBJC_CATEGORIES_MAP: {
3041*67e74705SXin Li if (F.LocalNumObjCCategoriesInMap != 0) {
3042*67e74705SXin Li Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
3043*67e74705SXin Li return Failure;
3044*67e74705SXin Li }
3045*67e74705SXin Li
3046*67e74705SXin Li F.LocalNumObjCCategoriesInMap = Record[0];
3047*67e74705SXin Li F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3048*67e74705SXin Li break;
3049*67e74705SXin Li }
3050*67e74705SXin Li
3051*67e74705SXin Li case OBJC_CATEGORIES:
3052*67e74705SXin Li F.ObjCCategories.swap(Record);
3053*67e74705SXin Li break;
3054*67e74705SXin Li
3055*67e74705SXin Li case DIAG_PRAGMA_MAPPINGS:
3056*67e74705SXin Li if (F.PragmaDiagMappings.empty())
3057*67e74705SXin Li F.PragmaDiagMappings.swap(Record);
3058*67e74705SXin Li else
3059*67e74705SXin Li F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3060*67e74705SXin Li Record.begin(), Record.end());
3061*67e74705SXin Li break;
3062*67e74705SXin Li
3063*67e74705SXin Li case CUDA_SPECIAL_DECL_REFS:
3064*67e74705SXin Li // Later tables overwrite earlier ones.
3065*67e74705SXin Li // FIXME: Modules will have trouble with this.
3066*67e74705SXin Li CUDASpecialDeclRefs.clear();
3067*67e74705SXin Li for (unsigned I = 0, N = Record.size(); I != N; ++I)
3068*67e74705SXin Li CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3069*67e74705SXin Li break;
3070*67e74705SXin Li
3071*67e74705SXin Li case HEADER_SEARCH_TABLE: {
3072*67e74705SXin Li F.HeaderFileInfoTableData = Blob.data();
3073*67e74705SXin Li F.LocalNumHeaderFileInfos = Record[1];
3074*67e74705SXin Li if (Record[0]) {
3075*67e74705SXin Li F.HeaderFileInfoTable
3076*67e74705SXin Li = HeaderFileInfoLookupTable::Create(
3077*67e74705SXin Li (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3078*67e74705SXin Li (const unsigned char *)F.HeaderFileInfoTableData,
3079*67e74705SXin Li HeaderFileInfoTrait(*this, F,
3080*67e74705SXin Li &PP.getHeaderSearchInfo(),
3081*67e74705SXin Li Blob.data() + Record[2]));
3082*67e74705SXin Li
3083*67e74705SXin Li PP.getHeaderSearchInfo().SetExternalSource(this);
3084*67e74705SXin Li if (!PP.getHeaderSearchInfo().getExternalLookup())
3085*67e74705SXin Li PP.getHeaderSearchInfo().SetExternalLookup(this);
3086*67e74705SXin Li }
3087*67e74705SXin Li break;
3088*67e74705SXin Li }
3089*67e74705SXin Li
3090*67e74705SXin Li case FP_PRAGMA_OPTIONS:
3091*67e74705SXin Li // Later tables overwrite earlier ones.
3092*67e74705SXin Li FPPragmaOptions.swap(Record);
3093*67e74705SXin Li break;
3094*67e74705SXin Li
3095*67e74705SXin Li case OPENCL_EXTENSIONS:
3096*67e74705SXin Li // Later tables overwrite earlier ones.
3097*67e74705SXin Li OpenCLExtensions.swap(Record);
3098*67e74705SXin Li break;
3099*67e74705SXin Li
3100*67e74705SXin Li case TENTATIVE_DEFINITIONS:
3101*67e74705SXin Li for (unsigned I = 0, N = Record.size(); I != N; ++I)
3102*67e74705SXin Li TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3103*67e74705SXin Li break;
3104*67e74705SXin Li
3105*67e74705SXin Li case KNOWN_NAMESPACES:
3106*67e74705SXin Li for (unsigned I = 0, N = Record.size(); I != N; ++I)
3107*67e74705SXin Li KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3108*67e74705SXin Li break;
3109*67e74705SXin Li
3110*67e74705SXin Li case UNDEFINED_BUT_USED:
3111*67e74705SXin Li if (UndefinedButUsed.size() % 2 != 0) {
3112*67e74705SXin Li Error("Invalid existing UndefinedButUsed");
3113*67e74705SXin Li return Failure;
3114*67e74705SXin Li }
3115*67e74705SXin Li
3116*67e74705SXin Li if (Record.size() % 2 != 0) {
3117*67e74705SXin Li Error("invalid undefined-but-used record");
3118*67e74705SXin Li return Failure;
3119*67e74705SXin Li }
3120*67e74705SXin Li for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3121*67e74705SXin Li UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3122*67e74705SXin Li UndefinedButUsed.push_back(
3123*67e74705SXin Li ReadSourceLocation(F, Record, I).getRawEncoding());
3124*67e74705SXin Li }
3125*67e74705SXin Li break;
3126*67e74705SXin Li case DELETE_EXPRS_TO_ANALYZE:
3127*67e74705SXin Li for (unsigned I = 0, N = Record.size(); I != N;) {
3128*67e74705SXin Li DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3129*67e74705SXin Li const uint64_t Count = Record[I++];
3130*67e74705SXin Li DelayedDeleteExprs.push_back(Count);
3131*67e74705SXin Li for (uint64_t C = 0; C < Count; ++C) {
3132*67e74705SXin Li DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3133*67e74705SXin Li bool IsArrayForm = Record[I++] == 1;
3134*67e74705SXin Li DelayedDeleteExprs.push_back(IsArrayForm);
3135*67e74705SXin Li }
3136*67e74705SXin Li }
3137*67e74705SXin Li break;
3138*67e74705SXin Li
3139*67e74705SXin Li case IMPORTED_MODULES: {
3140*67e74705SXin Li if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
3141*67e74705SXin Li // If we aren't loading a module (which has its own exports), make
3142*67e74705SXin Li // all of the imported modules visible.
3143*67e74705SXin Li // FIXME: Deal with macros-only imports.
3144*67e74705SXin Li for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3145*67e74705SXin Li unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3146*67e74705SXin Li SourceLocation Loc = ReadSourceLocation(F, Record, I);
3147*67e74705SXin Li if (GlobalID)
3148*67e74705SXin Li ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3149*67e74705SXin Li }
3150*67e74705SXin Li }
3151*67e74705SXin Li break;
3152*67e74705SXin Li }
3153*67e74705SXin Li
3154*67e74705SXin Li case MACRO_OFFSET: {
3155*67e74705SXin Li if (F.LocalNumMacros != 0) {
3156*67e74705SXin Li Error("duplicate MACRO_OFFSET record in AST file");
3157*67e74705SXin Li return Failure;
3158*67e74705SXin Li }
3159*67e74705SXin Li F.MacroOffsets = (const uint32_t *)Blob.data();
3160*67e74705SXin Li F.LocalNumMacros = Record[0];
3161*67e74705SXin Li unsigned LocalBaseMacroID = Record[1];
3162*67e74705SXin Li F.BaseMacroID = getTotalNumMacros();
3163*67e74705SXin Li
3164*67e74705SXin Li if (F.LocalNumMacros > 0) {
3165*67e74705SXin Li // Introduce the global -> local mapping for macros within this module.
3166*67e74705SXin Li GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3167*67e74705SXin Li
3168*67e74705SXin Li // Introduce the local -> global mapping for macros within this module.
3169*67e74705SXin Li F.MacroRemap.insertOrReplace(
3170*67e74705SXin Li std::make_pair(LocalBaseMacroID,
3171*67e74705SXin Li F.BaseMacroID - LocalBaseMacroID));
3172*67e74705SXin Li
3173*67e74705SXin Li MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3174*67e74705SXin Li }
3175*67e74705SXin Li break;
3176*67e74705SXin Li }
3177*67e74705SXin Li
3178*67e74705SXin Li case LATE_PARSED_TEMPLATE: {
3179*67e74705SXin Li LateParsedTemplates.append(Record.begin(), Record.end());
3180*67e74705SXin Li break;
3181*67e74705SXin Li }
3182*67e74705SXin Li
3183*67e74705SXin Li case OPTIMIZE_PRAGMA_OPTIONS:
3184*67e74705SXin Li if (Record.size() != 1) {
3185*67e74705SXin Li Error("invalid pragma optimize record");
3186*67e74705SXin Li return Failure;
3187*67e74705SXin Li }
3188*67e74705SXin Li OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3189*67e74705SXin Li break;
3190*67e74705SXin Li
3191*67e74705SXin Li case MSSTRUCT_PRAGMA_OPTIONS:
3192*67e74705SXin Li if (Record.size() != 1) {
3193*67e74705SXin Li Error("invalid pragma ms_struct record");
3194*67e74705SXin Li return Failure;
3195*67e74705SXin Li }
3196*67e74705SXin Li PragmaMSStructState = Record[0];
3197*67e74705SXin Li break;
3198*67e74705SXin Li
3199*67e74705SXin Li case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3200*67e74705SXin Li if (Record.size() != 2) {
3201*67e74705SXin Li Error("invalid pragma ms_struct record");
3202*67e74705SXin Li return Failure;
3203*67e74705SXin Li }
3204*67e74705SXin Li PragmaMSPointersToMembersState = Record[0];
3205*67e74705SXin Li PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3206*67e74705SXin Li break;
3207*67e74705SXin Li
3208*67e74705SXin Li case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3209*67e74705SXin Li for (unsigned I = 0, N = Record.size(); I != N; ++I)
3210*67e74705SXin Li UnusedLocalTypedefNameCandidates.push_back(
3211*67e74705SXin Li getGlobalDeclID(F, Record[I]));
3212*67e74705SXin Li break;
3213*67e74705SXin Li }
3214*67e74705SXin Li }
3215*67e74705SXin Li }
3216*67e74705SXin Li
3217*67e74705SXin Li ASTReader::ASTReadResult
ReadModuleMapFileBlock(RecordData & Record,ModuleFile & F,const ModuleFile * ImportedBy,unsigned ClientLoadCapabilities)3218*67e74705SXin Li ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3219*67e74705SXin Li const ModuleFile *ImportedBy,
3220*67e74705SXin Li unsigned ClientLoadCapabilities) {
3221*67e74705SXin Li unsigned Idx = 0;
3222*67e74705SXin Li F.ModuleMapPath = ReadPath(F, Record, Idx);
3223*67e74705SXin Li
3224*67e74705SXin Li if (F.Kind == MK_ExplicitModule) {
3225*67e74705SXin Li // For an explicitly-loaded module, we don't care whether the original
3226*67e74705SXin Li // module map file exists or matches.
3227*67e74705SXin Li return Success;
3228*67e74705SXin Li }
3229*67e74705SXin Li
3230*67e74705SXin Li // Try to resolve ModuleName in the current header search context and
3231*67e74705SXin Li // verify that it is found in the same module map file as we saved. If the
3232*67e74705SXin Li // top-level AST file is a main file, skip this check because there is no
3233*67e74705SXin Li // usable header search context.
3234*67e74705SXin Li assert(!F.ModuleName.empty() &&
3235*67e74705SXin Li "MODULE_NAME should come before MODULE_MAP_FILE");
3236*67e74705SXin Li if (F.Kind == MK_ImplicitModule &&
3237*67e74705SXin Li (*ModuleMgr.begin())->Kind != MK_MainFile) {
3238*67e74705SXin Li // An implicitly-loaded module file should have its module listed in some
3239*67e74705SXin Li // module map file that we've already loaded.
3240*67e74705SXin Li Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
3241*67e74705SXin Li auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3242*67e74705SXin Li const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3243*67e74705SXin Li if (!ModMap) {
3244*67e74705SXin Li assert(ImportedBy && "top-level import should be verified");
3245*67e74705SXin Li if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3246*67e74705SXin Li if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3247*67e74705SXin Li // This module was defined by an imported (explicit) module.
3248*67e74705SXin Li Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3249*67e74705SXin Li << ASTFE->getName();
3250*67e74705SXin Li else
3251*67e74705SXin Li // This module was built with a different module map.
3252*67e74705SXin Li Diag(diag::err_imported_module_not_found)
3253*67e74705SXin Li << F.ModuleName << F.FileName << ImportedBy->FileName
3254*67e74705SXin Li << F.ModuleMapPath;
3255*67e74705SXin Li }
3256*67e74705SXin Li return OutOfDate;
3257*67e74705SXin Li }
3258*67e74705SXin Li
3259*67e74705SXin Li assert(M->Name == F.ModuleName && "found module with different name");
3260*67e74705SXin Li
3261*67e74705SXin Li // Check the primary module map file.
3262*67e74705SXin Li const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3263*67e74705SXin Li if (StoredModMap == nullptr || StoredModMap != ModMap) {
3264*67e74705SXin Li assert(ModMap && "found module is missing module map file");
3265*67e74705SXin Li assert(ImportedBy && "top-level import should be verified");
3266*67e74705SXin Li if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3267*67e74705SXin Li Diag(diag::err_imported_module_modmap_changed)
3268*67e74705SXin Li << F.ModuleName << ImportedBy->FileName
3269*67e74705SXin Li << ModMap->getName() << F.ModuleMapPath;
3270*67e74705SXin Li return OutOfDate;
3271*67e74705SXin Li }
3272*67e74705SXin Li
3273*67e74705SXin Li llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3274*67e74705SXin Li for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3275*67e74705SXin Li // FIXME: we should use input files rather than storing names.
3276*67e74705SXin Li std::string Filename = ReadPath(F, Record, Idx);
3277*67e74705SXin Li const FileEntry *F =
3278*67e74705SXin Li FileMgr.getFile(Filename, false, false);
3279*67e74705SXin Li if (F == nullptr) {
3280*67e74705SXin Li if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3281*67e74705SXin Li Error("could not find file '" + Filename +"' referenced by AST file");
3282*67e74705SXin Li return OutOfDate;
3283*67e74705SXin Li }
3284*67e74705SXin Li AdditionalStoredMaps.insert(F);
3285*67e74705SXin Li }
3286*67e74705SXin Li
3287*67e74705SXin Li // Check any additional module map files (e.g. module.private.modulemap)
3288*67e74705SXin Li // that are not in the pcm.
3289*67e74705SXin Li if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3290*67e74705SXin Li for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3291*67e74705SXin Li // Remove files that match
3292*67e74705SXin Li // Note: SmallPtrSet::erase is really remove
3293*67e74705SXin Li if (!AdditionalStoredMaps.erase(ModMap)) {
3294*67e74705SXin Li if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3295*67e74705SXin Li Diag(diag::err_module_different_modmap)
3296*67e74705SXin Li << F.ModuleName << /*new*/0 << ModMap->getName();
3297*67e74705SXin Li return OutOfDate;
3298*67e74705SXin Li }
3299*67e74705SXin Li }
3300*67e74705SXin Li }
3301*67e74705SXin Li
3302*67e74705SXin Li // Check any additional module map files that are in the pcm, but not
3303*67e74705SXin Li // found in header search. Cases that match are already removed.
3304*67e74705SXin Li for (const FileEntry *ModMap : AdditionalStoredMaps) {
3305*67e74705SXin Li if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3306*67e74705SXin Li Diag(diag::err_module_different_modmap)
3307*67e74705SXin Li << F.ModuleName << /*not new*/1 << ModMap->getName();
3308*67e74705SXin Li return OutOfDate;
3309*67e74705SXin Li }
3310*67e74705SXin Li }
3311*67e74705SXin Li
3312*67e74705SXin Li if (Listener)
3313*67e74705SXin Li Listener->ReadModuleMapFile(F.ModuleMapPath);
3314*67e74705SXin Li return Success;
3315*67e74705SXin Li }
3316*67e74705SXin Li
3317*67e74705SXin Li
3318*67e74705SXin Li /// \brief Move the given method to the back of the global list of methods.
moveMethodToBackOfGlobalList(Sema & S,ObjCMethodDecl * Method)3319*67e74705SXin Li static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3320*67e74705SXin Li // Find the entry for this selector in the method pool.
3321*67e74705SXin Li Sema::GlobalMethodPool::iterator Known
3322*67e74705SXin Li = S.MethodPool.find(Method->getSelector());
3323*67e74705SXin Li if (Known == S.MethodPool.end())
3324*67e74705SXin Li return;
3325*67e74705SXin Li
3326*67e74705SXin Li // Retrieve the appropriate method list.
3327*67e74705SXin Li ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3328*67e74705SXin Li : Known->second.second;
3329*67e74705SXin Li bool Found = false;
3330*67e74705SXin Li for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
3331*67e74705SXin Li if (!Found) {
3332*67e74705SXin Li if (List->getMethod() == Method) {
3333*67e74705SXin Li Found = true;
3334*67e74705SXin Li } else {
3335*67e74705SXin Li // Keep searching.
3336*67e74705SXin Li continue;
3337*67e74705SXin Li }
3338*67e74705SXin Li }
3339*67e74705SXin Li
3340*67e74705SXin Li if (List->getNext())
3341*67e74705SXin Li List->setMethod(List->getNext()->getMethod());
3342*67e74705SXin Li else
3343*67e74705SXin Li List->setMethod(Method);
3344*67e74705SXin Li }
3345*67e74705SXin Li }
3346*67e74705SXin Li
makeNamesVisible(const HiddenNames & Names,Module * Owner)3347*67e74705SXin Li void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
3348*67e74705SXin Li assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
3349*67e74705SXin Li for (Decl *D : Names) {
3350*67e74705SXin Li bool wasHidden = D->Hidden;
3351*67e74705SXin Li D->Hidden = false;
3352*67e74705SXin Li
3353*67e74705SXin Li if (wasHidden && SemaObj) {
3354*67e74705SXin Li if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3355*67e74705SXin Li moveMethodToBackOfGlobalList(*SemaObj, Method);
3356*67e74705SXin Li }
3357*67e74705SXin Li }
3358*67e74705SXin Li }
3359*67e74705SXin Li }
3360*67e74705SXin Li
makeModuleVisible(Module * Mod,Module::NameVisibilityKind NameVisibility,SourceLocation ImportLoc)3361*67e74705SXin Li void ASTReader::makeModuleVisible(Module *Mod,
3362*67e74705SXin Li Module::NameVisibilityKind NameVisibility,
3363*67e74705SXin Li SourceLocation ImportLoc) {
3364*67e74705SXin Li llvm::SmallPtrSet<Module *, 4> Visited;
3365*67e74705SXin Li SmallVector<Module *, 4> Stack;
3366*67e74705SXin Li Stack.push_back(Mod);
3367*67e74705SXin Li while (!Stack.empty()) {
3368*67e74705SXin Li Mod = Stack.pop_back_val();
3369*67e74705SXin Li
3370*67e74705SXin Li if (NameVisibility <= Mod->NameVisibility) {
3371*67e74705SXin Li // This module already has this level of visibility (or greater), so
3372*67e74705SXin Li // there is nothing more to do.
3373*67e74705SXin Li continue;
3374*67e74705SXin Li }
3375*67e74705SXin Li
3376*67e74705SXin Li if (!Mod->isAvailable()) {
3377*67e74705SXin Li // Modules that aren't available cannot be made visible.
3378*67e74705SXin Li continue;
3379*67e74705SXin Li }
3380*67e74705SXin Li
3381*67e74705SXin Li // Update the module's name visibility.
3382*67e74705SXin Li Mod->NameVisibility = NameVisibility;
3383*67e74705SXin Li
3384*67e74705SXin Li // If we've already deserialized any names from this module,
3385*67e74705SXin Li // mark them as visible.
3386*67e74705SXin Li HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3387*67e74705SXin Li if (Hidden != HiddenNamesMap.end()) {
3388*67e74705SXin Li auto HiddenNames = std::move(*Hidden);
3389*67e74705SXin Li HiddenNamesMap.erase(Hidden);
3390*67e74705SXin Li makeNamesVisible(HiddenNames.second, HiddenNames.first);
3391*67e74705SXin Li assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3392*67e74705SXin Li "making names visible added hidden names");
3393*67e74705SXin Li }
3394*67e74705SXin Li
3395*67e74705SXin Li // Push any exported modules onto the stack to be marked as visible.
3396*67e74705SXin Li SmallVector<Module *, 16> Exports;
3397*67e74705SXin Li Mod->getExportedModules(Exports);
3398*67e74705SXin Li for (SmallVectorImpl<Module *>::iterator
3399*67e74705SXin Li I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3400*67e74705SXin Li Module *Exported = *I;
3401*67e74705SXin Li if (Visited.insert(Exported).second)
3402*67e74705SXin Li Stack.push_back(Exported);
3403*67e74705SXin Li }
3404*67e74705SXin Li }
3405*67e74705SXin Li }
3406*67e74705SXin Li
loadGlobalIndex()3407*67e74705SXin Li bool ASTReader::loadGlobalIndex() {
3408*67e74705SXin Li if (GlobalIndex)
3409*67e74705SXin Li return false;
3410*67e74705SXin Li
3411*67e74705SXin Li if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3412*67e74705SXin Li !Context.getLangOpts().Modules)
3413*67e74705SXin Li return true;
3414*67e74705SXin Li
3415*67e74705SXin Li // Try to load the global index.
3416*67e74705SXin Li TriedLoadingGlobalIndex = true;
3417*67e74705SXin Li StringRef ModuleCachePath
3418*67e74705SXin Li = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3419*67e74705SXin Li std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
3420*67e74705SXin Li = GlobalModuleIndex::readIndex(ModuleCachePath);
3421*67e74705SXin Li if (!Result.first)
3422*67e74705SXin Li return true;
3423*67e74705SXin Li
3424*67e74705SXin Li GlobalIndex.reset(Result.first);
3425*67e74705SXin Li ModuleMgr.setGlobalIndex(GlobalIndex.get());
3426*67e74705SXin Li return false;
3427*67e74705SXin Li }
3428*67e74705SXin Li
isGlobalIndexUnavailable() const3429*67e74705SXin Li bool ASTReader::isGlobalIndexUnavailable() const {
3430*67e74705SXin Li return Context.getLangOpts().Modules && UseGlobalIndex &&
3431*67e74705SXin Li !hasGlobalIndex() && TriedLoadingGlobalIndex;
3432*67e74705SXin Li }
3433*67e74705SXin Li
updateModuleTimestamp(ModuleFile & MF)3434*67e74705SXin Li static void updateModuleTimestamp(ModuleFile &MF) {
3435*67e74705SXin Li // Overwrite the timestamp file contents so that file's mtime changes.
3436*67e74705SXin Li std::string TimestampFilename = MF.getTimestampFilename();
3437*67e74705SXin Li std::error_code EC;
3438*67e74705SXin Li llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3439*67e74705SXin Li if (EC)
3440*67e74705SXin Li return;
3441*67e74705SXin Li OS << "Timestamp file\n";
3442*67e74705SXin Li }
3443*67e74705SXin Li
3444*67e74705SXin Li /// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3445*67e74705SXin Li /// cursor into the start of the given block ID, returning false on success and
3446*67e74705SXin Li /// true on failure.
SkipCursorToBlock(BitstreamCursor & Cursor,unsigned BlockID)3447*67e74705SXin Li static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3448*67e74705SXin Li while (1) {
3449*67e74705SXin Li llvm::BitstreamEntry Entry = Cursor.advance();
3450*67e74705SXin Li switch (Entry.Kind) {
3451*67e74705SXin Li case llvm::BitstreamEntry::Error:
3452*67e74705SXin Li case llvm::BitstreamEntry::EndBlock:
3453*67e74705SXin Li return true;
3454*67e74705SXin Li
3455*67e74705SXin Li case llvm::BitstreamEntry::Record:
3456*67e74705SXin Li // Ignore top-level records.
3457*67e74705SXin Li Cursor.skipRecord(Entry.ID);
3458*67e74705SXin Li break;
3459*67e74705SXin Li
3460*67e74705SXin Li case llvm::BitstreamEntry::SubBlock:
3461*67e74705SXin Li if (Entry.ID == BlockID) {
3462*67e74705SXin Li if (Cursor.EnterSubBlock(BlockID))
3463*67e74705SXin Li return true;
3464*67e74705SXin Li // Found it!
3465*67e74705SXin Li return false;
3466*67e74705SXin Li }
3467*67e74705SXin Li
3468*67e74705SXin Li if (Cursor.SkipBlock())
3469*67e74705SXin Li return true;
3470*67e74705SXin Li }
3471*67e74705SXin Li }
3472*67e74705SXin Li }
3473*67e74705SXin Li
ReadAST(StringRef FileName,ModuleKind Type,SourceLocation ImportLoc,unsigned ClientLoadCapabilities)3474*67e74705SXin Li ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
3475*67e74705SXin Li ModuleKind Type,
3476*67e74705SXin Li SourceLocation ImportLoc,
3477*67e74705SXin Li unsigned ClientLoadCapabilities) {
3478*67e74705SXin Li llvm::SaveAndRestore<SourceLocation>
3479*67e74705SXin Li SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3480*67e74705SXin Li
3481*67e74705SXin Li // Defer any pending actions until we get to the end of reading the AST file.
3482*67e74705SXin Li Deserializing AnASTFile(this);
3483*67e74705SXin Li
3484*67e74705SXin Li // Bump the generation number.
3485*67e74705SXin Li unsigned PreviousGeneration = incrementGeneration(Context);
3486*67e74705SXin Li
3487*67e74705SXin Li unsigned NumModules = ModuleMgr.size();
3488*67e74705SXin Li SmallVector<ImportedModule, 4> Loaded;
3489*67e74705SXin Li switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3490*67e74705SXin Li /*ImportedBy=*/nullptr, Loaded,
3491*67e74705SXin Li 0, 0, 0,
3492*67e74705SXin Li ClientLoadCapabilities)) {
3493*67e74705SXin Li case Failure:
3494*67e74705SXin Li case Missing:
3495*67e74705SXin Li case OutOfDate:
3496*67e74705SXin Li case VersionMismatch:
3497*67e74705SXin Li case ConfigurationMismatch:
3498*67e74705SXin Li case HadErrors: {
3499*67e74705SXin Li llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3500*67e74705SXin Li for (const ImportedModule &IM : Loaded)
3501*67e74705SXin Li LoadedSet.insert(IM.Mod);
3502*67e74705SXin Li
3503*67e74705SXin Li ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3504*67e74705SXin Li LoadedSet,
3505*67e74705SXin Li Context.getLangOpts().Modules
3506*67e74705SXin Li ? &PP.getHeaderSearchInfo().getModuleMap()
3507*67e74705SXin Li : nullptr);
3508*67e74705SXin Li
3509*67e74705SXin Li // If we find that any modules are unusable, the global index is going
3510*67e74705SXin Li // to be out-of-date. Just remove it.
3511*67e74705SXin Li GlobalIndex.reset();
3512*67e74705SXin Li ModuleMgr.setGlobalIndex(nullptr);
3513*67e74705SXin Li return ReadResult;
3514*67e74705SXin Li }
3515*67e74705SXin Li case Success:
3516*67e74705SXin Li break;
3517*67e74705SXin Li }
3518*67e74705SXin Li
3519*67e74705SXin Li // Here comes stuff that we only do once the entire chain is loaded.
3520*67e74705SXin Li
3521*67e74705SXin Li // Load the AST blocks of all of the modules that we loaded.
3522*67e74705SXin Li for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3523*67e74705SXin Li MEnd = Loaded.end();
3524*67e74705SXin Li M != MEnd; ++M) {
3525*67e74705SXin Li ModuleFile &F = *M->Mod;
3526*67e74705SXin Li
3527*67e74705SXin Li // Read the AST block.
3528*67e74705SXin Li if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3529*67e74705SXin Li return Result;
3530*67e74705SXin Li
3531*67e74705SXin Li // Read the extension blocks.
3532*67e74705SXin Li while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3533*67e74705SXin Li if (ASTReadResult Result = ReadExtensionBlock(F))
3534*67e74705SXin Li return Result;
3535*67e74705SXin Li }
3536*67e74705SXin Li
3537*67e74705SXin Li // Once read, set the ModuleFile bit base offset and update the size in
3538*67e74705SXin Li // bits of all files we've seen.
3539*67e74705SXin Li F.GlobalBitOffset = TotalModulesSizeInBits;
3540*67e74705SXin Li TotalModulesSizeInBits += F.SizeInBits;
3541*67e74705SXin Li GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3542*67e74705SXin Li
3543*67e74705SXin Li // Preload SLocEntries.
3544*67e74705SXin Li for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3545*67e74705SXin Li int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3546*67e74705SXin Li // Load it through the SourceManager and don't call ReadSLocEntry()
3547*67e74705SXin Li // directly because the entry may have already been loaded in which case
3548*67e74705SXin Li // calling ReadSLocEntry() directly would trigger an assertion in
3549*67e74705SXin Li // SourceManager.
3550*67e74705SXin Li SourceMgr.getLoadedSLocEntryByID(Index);
3551*67e74705SXin Li }
3552*67e74705SXin Li
3553*67e74705SXin Li // Preload all the pending interesting identifiers by marking them out of
3554*67e74705SXin Li // date.
3555*67e74705SXin Li for (auto Offset : F.PreloadIdentifierOffsets) {
3556*67e74705SXin Li const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3557*67e74705SXin Li F.IdentifierTableData + Offset);
3558*67e74705SXin Li
3559*67e74705SXin Li ASTIdentifierLookupTrait Trait(*this, F);
3560*67e74705SXin Li auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3561*67e74705SXin Li auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3562*67e74705SXin Li auto &II = PP.getIdentifierTable().getOwn(Key);
3563*67e74705SXin Li II.setOutOfDate(true);
3564*67e74705SXin Li
3565*67e74705SXin Li // Mark this identifier as being from an AST file so that we can track
3566*67e74705SXin Li // whether we need to serialize it.
3567*67e74705SXin Li markIdentifierFromAST(*this, II);
3568*67e74705SXin Li
3569*67e74705SXin Li // Associate the ID with the identifier so that the writer can reuse it.
3570*67e74705SXin Li auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3571*67e74705SXin Li SetIdentifierInfo(ID, &II);
3572*67e74705SXin Li }
3573*67e74705SXin Li }
3574*67e74705SXin Li
3575*67e74705SXin Li // Setup the import locations and notify the module manager that we've
3576*67e74705SXin Li // committed to these module files.
3577*67e74705SXin Li for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3578*67e74705SXin Li MEnd = Loaded.end();
3579*67e74705SXin Li M != MEnd; ++M) {
3580*67e74705SXin Li ModuleFile &F = *M->Mod;
3581*67e74705SXin Li
3582*67e74705SXin Li ModuleMgr.moduleFileAccepted(&F);
3583*67e74705SXin Li
3584*67e74705SXin Li // Set the import location.
3585*67e74705SXin Li F.DirectImportLoc = ImportLoc;
3586*67e74705SXin Li // FIXME: We assume that locations from PCH / preamble do not need
3587*67e74705SXin Li // any translation.
3588*67e74705SXin Li if (!M->ImportedBy)
3589*67e74705SXin Li F.ImportLoc = M->ImportLoc;
3590*67e74705SXin Li else
3591*67e74705SXin Li F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
3592*67e74705SXin Li }
3593*67e74705SXin Li
3594*67e74705SXin Li if (!Context.getLangOpts().CPlusPlus ||
3595*67e74705SXin Li (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3596*67e74705SXin Li // Mark all of the identifiers in the identifier table as being out of date,
3597*67e74705SXin Li // so that various accessors know to check the loaded modules when the
3598*67e74705SXin Li // identifier is used.
3599*67e74705SXin Li //
3600*67e74705SXin Li // For C++ modules, we don't need information on many identifiers (just
3601*67e74705SXin Li // those that provide macros or are poisoned), so we mark all of
3602*67e74705SXin Li // the interesting ones via PreloadIdentifierOffsets.
3603*67e74705SXin Li for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3604*67e74705SXin Li IdEnd = PP.getIdentifierTable().end();
3605*67e74705SXin Li Id != IdEnd; ++Id)
3606*67e74705SXin Li Id->second->setOutOfDate(true);
3607*67e74705SXin Li }
3608*67e74705SXin Li // Mark selectors as out of date.
3609*67e74705SXin Li for (auto Sel : SelectorGeneration)
3610*67e74705SXin Li SelectorOutOfDate[Sel.first] = true;
3611*67e74705SXin Li
3612*67e74705SXin Li // Resolve any unresolved module exports.
3613*67e74705SXin Li for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3614*67e74705SXin Li UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
3615*67e74705SXin Li SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3616*67e74705SXin Li Module *ResolvedMod = getSubmodule(GlobalID);
3617*67e74705SXin Li
3618*67e74705SXin Li switch (Unresolved.Kind) {
3619*67e74705SXin Li case UnresolvedModuleRef::Conflict:
3620*67e74705SXin Li if (ResolvedMod) {
3621*67e74705SXin Li Module::Conflict Conflict;
3622*67e74705SXin Li Conflict.Other = ResolvedMod;
3623*67e74705SXin Li Conflict.Message = Unresolved.String.str();
3624*67e74705SXin Li Unresolved.Mod->Conflicts.push_back(Conflict);
3625*67e74705SXin Li }
3626*67e74705SXin Li continue;
3627*67e74705SXin Li
3628*67e74705SXin Li case UnresolvedModuleRef::Import:
3629*67e74705SXin Li if (ResolvedMod)
3630*67e74705SXin Li Unresolved.Mod->Imports.insert(ResolvedMod);
3631*67e74705SXin Li continue;
3632*67e74705SXin Li
3633*67e74705SXin Li case UnresolvedModuleRef::Export:
3634*67e74705SXin Li if (ResolvedMod || Unresolved.IsWildcard)
3635*67e74705SXin Li Unresolved.Mod->Exports.push_back(
3636*67e74705SXin Li Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3637*67e74705SXin Li continue;
3638*67e74705SXin Li }
3639*67e74705SXin Li }
3640*67e74705SXin Li UnresolvedModuleRefs.clear();
3641*67e74705SXin Li
3642*67e74705SXin Li // FIXME: How do we load the 'use'd modules? They may not be submodules.
3643*67e74705SXin Li // Might be unnecessary as use declarations are only used to build the
3644*67e74705SXin Li // module itself.
3645*67e74705SXin Li
3646*67e74705SXin Li InitializeContext();
3647*67e74705SXin Li
3648*67e74705SXin Li if (SemaObj)
3649*67e74705SXin Li UpdateSema();
3650*67e74705SXin Li
3651*67e74705SXin Li if (DeserializationListener)
3652*67e74705SXin Li DeserializationListener->ReaderInitialized(this);
3653*67e74705SXin Li
3654*67e74705SXin Li ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3655*67e74705SXin Li if (PrimaryModule.OriginalSourceFileID.isValid()) {
3656*67e74705SXin Li PrimaryModule.OriginalSourceFileID
3657*67e74705SXin Li = FileID::get(PrimaryModule.SLocEntryBaseID
3658*67e74705SXin Li + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3659*67e74705SXin Li
3660*67e74705SXin Li // If this AST file is a precompiled preamble, then set the
3661*67e74705SXin Li // preamble file ID of the source manager to the file source file
3662*67e74705SXin Li // from which the preamble was built.
3663*67e74705SXin Li if (Type == MK_Preamble) {
3664*67e74705SXin Li SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3665*67e74705SXin Li } else if (Type == MK_MainFile) {
3666*67e74705SXin Li SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3667*67e74705SXin Li }
3668*67e74705SXin Li }
3669*67e74705SXin Li
3670*67e74705SXin Li // For any Objective-C class definitions we have already loaded, make sure
3671*67e74705SXin Li // that we load any additional categories.
3672*67e74705SXin Li for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3673*67e74705SXin Li loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3674*67e74705SXin Li ObjCClassesLoaded[I],
3675*67e74705SXin Li PreviousGeneration);
3676*67e74705SXin Li }
3677*67e74705SXin Li
3678*67e74705SXin Li if (PP.getHeaderSearchInfo()
3679*67e74705SXin Li .getHeaderSearchOpts()
3680*67e74705SXin Li .ModulesValidateOncePerBuildSession) {
3681*67e74705SXin Li // Now we are certain that the module and all modules it depends on are
3682*67e74705SXin Li // up to date. Create or update timestamp files for modules that are
3683*67e74705SXin Li // located in the module cache (not for PCH files that could be anywhere
3684*67e74705SXin Li // in the filesystem).
3685*67e74705SXin Li for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3686*67e74705SXin Li ImportedModule &M = Loaded[I];
3687*67e74705SXin Li if (M.Mod->Kind == MK_ImplicitModule) {
3688*67e74705SXin Li updateModuleTimestamp(*M.Mod);
3689*67e74705SXin Li }
3690*67e74705SXin Li }
3691*67e74705SXin Li }
3692*67e74705SXin Li
3693*67e74705SXin Li return Success;
3694*67e74705SXin Li }
3695*67e74705SXin Li
3696*67e74705SXin Li static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3697*67e74705SXin Li
3698*67e74705SXin Li /// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
startsWithASTFileMagic(BitstreamCursor & Stream)3699*67e74705SXin Li static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3700*67e74705SXin Li return Stream.Read(8) == 'C' &&
3701*67e74705SXin Li Stream.Read(8) == 'P' &&
3702*67e74705SXin Li Stream.Read(8) == 'C' &&
3703*67e74705SXin Li Stream.Read(8) == 'H';
3704*67e74705SXin Li }
3705*67e74705SXin Li
moduleKindForDiagnostic(ModuleKind Kind)3706*67e74705SXin Li static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3707*67e74705SXin Li switch (Kind) {
3708*67e74705SXin Li case MK_PCH:
3709*67e74705SXin Li return 0; // PCH
3710*67e74705SXin Li case MK_ImplicitModule:
3711*67e74705SXin Li case MK_ExplicitModule:
3712*67e74705SXin Li return 1; // module
3713*67e74705SXin Li case MK_MainFile:
3714*67e74705SXin Li case MK_Preamble:
3715*67e74705SXin Li return 2; // main source file
3716*67e74705SXin Li }
3717*67e74705SXin Li llvm_unreachable("unknown module kind");
3718*67e74705SXin Li }
3719*67e74705SXin Li
3720*67e74705SXin Li ASTReader::ASTReadResult
ReadASTCore(StringRef FileName,ModuleKind Type,SourceLocation ImportLoc,ModuleFile * ImportedBy,SmallVectorImpl<ImportedModule> & Loaded,off_t ExpectedSize,time_t ExpectedModTime,ASTFileSignature ExpectedSignature,unsigned ClientLoadCapabilities)3721*67e74705SXin Li ASTReader::ReadASTCore(StringRef FileName,
3722*67e74705SXin Li ModuleKind Type,
3723*67e74705SXin Li SourceLocation ImportLoc,
3724*67e74705SXin Li ModuleFile *ImportedBy,
3725*67e74705SXin Li SmallVectorImpl<ImportedModule> &Loaded,
3726*67e74705SXin Li off_t ExpectedSize, time_t ExpectedModTime,
3727*67e74705SXin Li ASTFileSignature ExpectedSignature,
3728*67e74705SXin Li unsigned ClientLoadCapabilities) {
3729*67e74705SXin Li ModuleFile *M;
3730*67e74705SXin Li std::string ErrorStr;
3731*67e74705SXin Li ModuleManager::AddModuleResult AddResult
3732*67e74705SXin Li = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3733*67e74705SXin Li getGeneration(), ExpectedSize, ExpectedModTime,
3734*67e74705SXin Li ExpectedSignature, readASTFileSignature,
3735*67e74705SXin Li M, ErrorStr);
3736*67e74705SXin Li
3737*67e74705SXin Li switch (AddResult) {
3738*67e74705SXin Li case ModuleManager::AlreadyLoaded:
3739*67e74705SXin Li return Success;
3740*67e74705SXin Li
3741*67e74705SXin Li case ModuleManager::NewlyLoaded:
3742*67e74705SXin Li // Load module file below.
3743*67e74705SXin Li break;
3744*67e74705SXin Li
3745*67e74705SXin Li case ModuleManager::Missing:
3746*67e74705SXin Li // The module file was missing; if the client can handle that, return
3747*67e74705SXin Li // it.
3748*67e74705SXin Li if (ClientLoadCapabilities & ARR_Missing)
3749*67e74705SXin Li return Missing;
3750*67e74705SXin Li
3751*67e74705SXin Li // Otherwise, return an error.
3752*67e74705SXin Li Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3753*67e74705SXin Li << FileName << ErrorStr.empty()
3754*67e74705SXin Li << ErrorStr;
3755*67e74705SXin Li return Failure;
3756*67e74705SXin Li
3757*67e74705SXin Li case ModuleManager::OutOfDate:
3758*67e74705SXin Li // We couldn't load the module file because it is out-of-date. If the
3759*67e74705SXin Li // client can handle out-of-date, return it.
3760*67e74705SXin Li if (ClientLoadCapabilities & ARR_OutOfDate)
3761*67e74705SXin Li return OutOfDate;
3762*67e74705SXin Li
3763*67e74705SXin Li // Otherwise, return an error.
3764*67e74705SXin Li Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3765*67e74705SXin Li << FileName << ErrorStr.empty()
3766*67e74705SXin Li << ErrorStr;
3767*67e74705SXin Li return Failure;
3768*67e74705SXin Li }
3769*67e74705SXin Li
3770*67e74705SXin Li assert(M && "Missing module file");
3771*67e74705SXin Li
3772*67e74705SXin Li // FIXME: This seems rather a hack. Should CurrentDir be part of the
3773*67e74705SXin Li // module?
3774*67e74705SXin Li if (FileName != "-") {
3775*67e74705SXin Li CurrentDir = llvm::sys::path::parent_path(FileName);
3776*67e74705SXin Li if (CurrentDir.empty()) CurrentDir = ".";
3777*67e74705SXin Li }
3778*67e74705SXin Li
3779*67e74705SXin Li ModuleFile &F = *M;
3780*67e74705SXin Li BitstreamCursor &Stream = F.Stream;
3781*67e74705SXin Li PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
3782*67e74705SXin Li Stream.init(&F.StreamFile);
3783*67e74705SXin Li F.SizeInBits = F.Buffer->getBufferSize() * 8;
3784*67e74705SXin Li
3785*67e74705SXin Li // Sniff for the signature.
3786*67e74705SXin Li if (!startsWithASTFileMagic(Stream)) {
3787*67e74705SXin Li Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3788*67e74705SXin Li << FileName;
3789*67e74705SXin Li return Failure;
3790*67e74705SXin Li }
3791*67e74705SXin Li
3792*67e74705SXin Li // This is used for compatibility with older PCH formats.
3793*67e74705SXin Li bool HaveReadControlBlock = false;
3794*67e74705SXin Li while (1) {
3795*67e74705SXin Li llvm::BitstreamEntry Entry = Stream.advance();
3796*67e74705SXin Li
3797*67e74705SXin Li switch (Entry.Kind) {
3798*67e74705SXin Li case llvm::BitstreamEntry::Error:
3799*67e74705SXin Li case llvm::BitstreamEntry::Record:
3800*67e74705SXin Li case llvm::BitstreamEntry::EndBlock:
3801*67e74705SXin Li Error("invalid record at top-level of AST file");
3802*67e74705SXin Li return Failure;
3803*67e74705SXin Li
3804*67e74705SXin Li case llvm::BitstreamEntry::SubBlock:
3805*67e74705SXin Li break;
3806*67e74705SXin Li }
3807*67e74705SXin Li
3808*67e74705SXin Li switch (Entry.ID) {
3809*67e74705SXin Li case CONTROL_BLOCK_ID:
3810*67e74705SXin Li HaveReadControlBlock = true;
3811*67e74705SXin Li switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
3812*67e74705SXin Li case Success:
3813*67e74705SXin Li // Check that we didn't try to load a non-module AST file as a module.
3814*67e74705SXin Li //
3815*67e74705SXin Li // FIXME: Should we also perform the converse check? Loading a module as
3816*67e74705SXin Li // a PCH file sort of works, but it's a bit wonky.
3817*67e74705SXin Li if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule) &&
3818*67e74705SXin Li F.ModuleName.empty()) {
3819*67e74705SXin Li auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3820*67e74705SXin Li if (Result != OutOfDate ||
3821*67e74705SXin Li (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3822*67e74705SXin Li Diag(diag::err_module_file_not_module) << FileName;
3823*67e74705SXin Li return Result;
3824*67e74705SXin Li }
3825*67e74705SXin Li break;
3826*67e74705SXin Li
3827*67e74705SXin Li case Failure: return Failure;
3828*67e74705SXin Li case Missing: return Missing;
3829*67e74705SXin Li case OutOfDate: return OutOfDate;
3830*67e74705SXin Li case VersionMismatch: return VersionMismatch;
3831*67e74705SXin Li case ConfigurationMismatch: return ConfigurationMismatch;
3832*67e74705SXin Li case HadErrors: return HadErrors;
3833*67e74705SXin Li }
3834*67e74705SXin Li break;
3835*67e74705SXin Li
3836*67e74705SXin Li case AST_BLOCK_ID:
3837*67e74705SXin Li if (!HaveReadControlBlock) {
3838*67e74705SXin Li if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3839*67e74705SXin Li Diag(diag::err_pch_version_too_old);
3840*67e74705SXin Li return VersionMismatch;
3841*67e74705SXin Li }
3842*67e74705SXin Li
3843*67e74705SXin Li // Record that we've loaded this module.
3844*67e74705SXin Li Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3845*67e74705SXin Li return Success;
3846*67e74705SXin Li
3847*67e74705SXin Li default:
3848*67e74705SXin Li if (Stream.SkipBlock()) {
3849*67e74705SXin Li Error("malformed block record in AST file");
3850*67e74705SXin Li return Failure;
3851*67e74705SXin Li }
3852*67e74705SXin Li break;
3853*67e74705SXin Li }
3854*67e74705SXin Li }
3855*67e74705SXin Li
3856*67e74705SXin Li return Success;
3857*67e74705SXin Li }
3858*67e74705SXin Li
3859*67e74705SXin Li /// Parse a record and blob containing module file extension metadata.
parseModuleFileExtensionMetadata(const SmallVectorImpl<uint64_t> & Record,StringRef Blob,ModuleFileExtensionMetadata & Metadata)3860*67e74705SXin Li static bool parseModuleFileExtensionMetadata(
3861*67e74705SXin Li const SmallVectorImpl<uint64_t> &Record,
3862*67e74705SXin Li StringRef Blob,
3863*67e74705SXin Li ModuleFileExtensionMetadata &Metadata) {
3864*67e74705SXin Li if (Record.size() < 4) return true;
3865*67e74705SXin Li
3866*67e74705SXin Li Metadata.MajorVersion = Record[0];
3867*67e74705SXin Li Metadata.MinorVersion = Record[1];
3868*67e74705SXin Li
3869*67e74705SXin Li unsigned BlockNameLen = Record[2];
3870*67e74705SXin Li unsigned UserInfoLen = Record[3];
3871*67e74705SXin Li
3872*67e74705SXin Li if (BlockNameLen + UserInfoLen > Blob.size()) return true;
3873*67e74705SXin Li
3874*67e74705SXin Li Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
3875*67e74705SXin Li Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
3876*67e74705SXin Li Blob.data() + BlockNameLen + UserInfoLen);
3877*67e74705SXin Li return false;
3878*67e74705SXin Li }
3879*67e74705SXin Li
ReadExtensionBlock(ModuleFile & F)3880*67e74705SXin Li ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
3881*67e74705SXin Li BitstreamCursor &Stream = F.Stream;
3882*67e74705SXin Li
3883*67e74705SXin Li RecordData Record;
3884*67e74705SXin Li while (true) {
3885*67e74705SXin Li llvm::BitstreamEntry Entry = Stream.advance();
3886*67e74705SXin Li switch (Entry.Kind) {
3887*67e74705SXin Li case llvm::BitstreamEntry::SubBlock:
3888*67e74705SXin Li if (Stream.SkipBlock())
3889*67e74705SXin Li return Failure;
3890*67e74705SXin Li
3891*67e74705SXin Li continue;
3892*67e74705SXin Li
3893*67e74705SXin Li case llvm::BitstreamEntry::EndBlock:
3894*67e74705SXin Li return Success;
3895*67e74705SXin Li
3896*67e74705SXin Li case llvm::BitstreamEntry::Error:
3897*67e74705SXin Li return HadErrors;
3898*67e74705SXin Li
3899*67e74705SXin Li case llvm::BitstreamEntry::Record:
3900*67e74705SXin Li break;
3901*67e74705SXin Li }
3902*67e74705SXin Li
3903*67e74705SXin Li Record.clear();
3904*67e74705SXin Li StringRef Blob;
3905*67e74705SXin Li unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
3906*67e74705SXin Li switch (RecCode) {
3907*67e74705SXin Li case EXTENSION_METADATA: {
3908*67e74705SXin Li ModuleFileExtensionMetadata Metadata;
3909*67e74705SXin Li if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
3910*67e74705SXin Li return Failure;
3911*67e74705SXin Li
3912*67e74705SXin Li // Find a module file extension with this block name.
3913*67e74705SXin Li auto Known = ModuleFileExtensions.find(Metadata.BlockName);
3914*67e74705SXin Li if (Known == ModuleFileExtensions.end()) break;
3915*67e74705SXin Li
3916*67e74705SXin Li // Form a reader.
3917*67e74705SXin Li if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
3918*67e74705SXin Li F, Stream)) {
3919*67e74705SXin Li F.ExtensionReaders.push_back(std::move(Reader));
3920*67e74705SXin Li }
3921*67e74705SXin Li
3922*67e74705SXin Li break;
3923*67e74705SXin Li }
3924*67e74705SXin Li }
3925*67e74705SXin Li }
3926*67e74705SXin Li
3927*67e74705SXin Li return Success;
3928*67e74705SXin Li }
3929*67e74705SXin Li
InitializeContext()3930*67e74705SXin Li void ASTReader::InitializeContext() {
3931*67e74705SXin Li // If there's a listener, notify them that we "read" the translation unit.
3932*67e74705SXin Li if (DeserializationListener)
3933*67e74705SXin Li DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3934*67e74705SXin Li Context.getTranslationUnitDecl());
3935*67e74705SXin Li
3936*67e74705SXin Li // FIXME: Find a better way to deal with collisions between these
3937*67e74705SXin Li // built-in types. Right now, we just ignore the problem.
3938*67e74705SXin Li
3939*67e74705SXin Li // Load the special types.
3940*67e74705SXin Li if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3941*67e74705SXin Li if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3942*67e74705SXin Li if (!Context.CFConstantStringTypeDecl)
3943*67e74705SXin Li Context.setCFConstantStringType(GetType(String));
3944*67e74705SXin Li }
3945*67e74705SXin Li
3946*67e74705SXin Li if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3947*67e74705SXin Li QualType FileType = GetType(File);
3948*67e74705SXin Li if (FileType.isNull()) {
3949*67e74705SXin Li Error("FILE type is NULL");
3950*67e74705SXin Li return;
3951*67e74705SXin Li }
3952*67e74705SXin Li
3953*67e74705SXin Li if (!Context.FILEDecl) {
3954*67e74705SXin Li if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3955*67e74705SXin Li Context.setFILEDecl(Typedef->getDecl());
3956*67e74705SXin Li else {
3957*67e74705SXin Li const TagType *Tag = FileType->getAs<TagType>();
3958*67e74705SXin Li if (!Tag) {
3959*67e74705SXin Li Error("Invalid FILE type in AST file");
3960*67e74705SXin Li return;
3961*67e74705SXin Li }
3962*67e74705SXin Li Context.setFILEDecl(Tag->getDecl());
3963*67e74705SXin Li }
3964*67e74705SXin Li }
3965*67e74705SXin Li }
3966*67e74705SXin Li
3967*67e74705SXin Li if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3968*67e74705SXin Li QualType Jmp_bufType = GetType(Jmp_buf);
3969*67e74705SXin Li if (Jmp_bufType.isNull()) {
3970*67e74705SXin Li Error("jmp_buf type is NULL");
3971*67e74705SXin Li return;
3972*67e74705SXin Li }
3973*67e74705SXin Li
3974*67e74705SXin Li if (!Context.jmp_bufDecl) {
3975*67e74705SXin Li if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3976*67e74705SXin Li Context.setjmp_bufDecl(Typedef->getDecl());
3977*67e74705SXin Li else {
3978*67e74705SXin Li const TagType *Tag = Jmp_bufType->getAs<TagType>();
3979*67e74705SXin Li if (!Tag) {
3980*67e74705SXin Li Error("Invalid jmp_buf type in AST file");
3981*67e74705SXin Li return;
3982*67e74705SXin Li }
3983*67e74705SXin Li Context.setjmp_bufDecl(Tag->getDecl());
3984*67e74705SXin Li }
3985*67e74705SXin Li }
3986*67e74705SXin Li }
3987*67e74705SXin Li
3988*67e74705SXin Li if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3989*67e74705SXin Li QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3990*67e74705SXin Li if (Sigjmp_bufType.isNull()) {
3991*67e74705SXin Li Error("sigjmp_buf type is NULL");
3992*67e74705SXin Li return;
3993*67e74705SXin Li }
3994*67e74705SXin Li
3995*67e74705SXin Li if (!Context.sigjmp_bufDecl) {
3996*67e74705SXin Li if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3997*67e74705SXin Li Context.setsigjmp_bufDecl(Typedef->getDecl());
3998*67e74705SXin Li else {
3999*67e74705SXin Li const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4000*67e74705SXin Li assert(Tag && "Invalid sigjmp_buf type in AST file");
4001*67e74705SXin Li Context.setsigjmp_bufDecl(Tag->getDecl());
4002*67e74705SXin Li }
4003*67e74705SXin Li }
4004*67e74705SXin Li }
4005*67e74705SXin Li
4006*67e74705SXin Li if (unsigned ObjCIdRedef
4007*67e74705SXin Li = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4008*67e74705SXin Li if (Context.ObjCIdRedefinitionType.isNull())
4009*67e74705SXin Li Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4010*67e74705SXin Li }
4011*67e74705SXin Li
4012*67e74705SXin Li if (unsigned ObjCClassRedef
4013*67e74705SXin Li = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4014*67e74705SXin Li if (Context.ObjCClassRedefinitionType.isNull())
4015*67e74705SXin Li Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4016*67e74705SXin Li }
4017*67e74705SXin Li
4018*67e74705SXin Li if (unsigned ObjCSelRedef
4019*67e74705SXin Li = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4020*67e74705SXin Li if (Context.ObjCSelRedefinitionType.isNull())
4021*67e74705SXin Li Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4022*67e74705SXin Li }
4023*67e74705SXin Li
4024*67e74705SXin Li if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4025*67e74705SXin Li QualType Ucontext_tType = GetType(Ucontext_t);
4026*67e74705SXin Li if (Ucontext_tType.isNull()) {
4027*67e74705SXin Li Error("ucontext_t type is NULL");
4028*67e74705SXin Li return;
4029*67e74705SXin Li }
4030*67e74705SXin Li
4031*67e74705SXin Li if (!Context.ucontext_tDecl) {
4032*67e74705SXin Li if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4033*67e74705SXin Li Context.setucontext_tDecl(Typedef->getDecl());
4034*67e74705SXin Li else {
4035*67e74705SXin Li const TagType *Tag = Ucontext_tType->getAs<TagType>();
4036*67e74705SXin Li assert(Tag && "Invalid ucontext_t type in AST file");
4037*67e74705SXin Li Context.setucontext_tDecl(Tag->getDecl());
4038*67e74705SXin Li }
4039*67e74705SXin Li }
4040*67e74705SXin Li }
4041*67e74705SXin Li }
4042*67e74705SXin Li
4043*67e74705SXin Li ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4044*67e74705SXin Li
4045*67e74705SXin Li // If there were any CUDA special declarations, deserialize them.
4046*67e74705SXin Li if (!CUDASpecialDeclRefs.empty()) {
4047*67e74705SXin Li assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4048*67e74705SXin Li Context.setcudaConfigureCallDecl(
4049*67e74705SXin Li cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4050*67e74705SXin Li }
4051*67e74705SXin Li
4052*67e74705SXin Li // Re-export any modules that were imported by a non-module AST file.
4053*67e74705SXin Li // FIXME: This does not make macro-only imports visible again.
4054*67e74705SXin Li for (auto &Import : ImportedModules) {
4055*67e74705SXin Li if (Module *Imported = getSubmodule(Import.ID)) {
4056*67e74705SXin Li makeModuleVisible(Imported, Module::AllVisible,
4057*67e74705SXin Li /*ImportLoc=*/Import.ImportLoc);
4058*67e74705SXin Li if (Import.ImportLoc.isValid())
4059*67e74705SXin Li PP.makeModuleVisible(Imported, Import.ImportLoc);
4060*67e74705SXin Li // FIXME: should we tell Sema to make the module visible too?
4061*67e74705SXin Li }
4062*67e74705SXin Li }
4063*67e74705SXin Li ImportedModules.clear();
4064*67e74705SXin Li }
4065*67e74705SXin Li
finalizeForWriting()4066*67e74705SXin Li void ASTReader::finalizeForWriting() {
4067*67e74705SXin Li // Nothing to do for now.
4068*67e74705SXin Li }
4069*67e74705SXin Li
4070*67e74705SXin Li /// \brief Reads and return the signature record from \p StreamFile's control
4071*67e74705SXin Li /// block, or else returns 0.
readASTFileSignature(llvm::BitstreamReader & StreamFile)4072*67e74705SXin Li static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4073*67e74705SXin Li BitstreamCursor Stream(StreamFile);
4074*67e74705SXin Li if (!startsWithASTFileMagic(Stream))
4075*67e74705SXin Li return 0;
4076*67e74705SXin Li
4077*67e74705SXin Li // Scan for the CONTROL_BLOCK_ID block.
4078*67e74705SXin Li if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4079*67e74705SXin Li return 0;
4080*67e74705SXin Li
4081*67e74705SXin Li // Scan for SIGNATURE inside the control block.
4082*67e74705SXin Li ASTReader::RecordData Record;
4083*67e74705SXin Li while (1) {
4084*67e74705SXin Li llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4085*67e74705SXin Li if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4086*67e74705SXin Li Entry.Kind != llvm::BitstreamEntry::Record)
4087*67e74705SXin Li return 0;
4088*67e74705SXin Li
4089*67e74705SXin Li Record.clear();
4090*67e74705SXin Li StringRef Blob;
4091*67e74705SXin Li if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4092*67e74705SXin Li return Record[0];
4093*67e74705SXin Li }
4094*67e74705SXin Li }
4095*67e74705SXin Li
4096*67e74705SXin Li /// \brief Retrieve the name of the original source file name
4097*67e74705SXin Li /// directly from the AST file, without actually loading the AST
4098*67e74705SXin Li /// file.
getOriginalSourceFile(const std::string & ASTFileName,FileManager & FileMgr,const PCHContainerReader & PCHContainerRdr,DiagnosticsEngine & Diags)4099*67e74705SXin Li std::string ASTReader::getOriginalSourceFile(
4100*67e74705SXin Li const std::string &ASTFileName, FileManager &FileMgr,
4101*67e74705SXin Li const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
4102*67e74705SXin Li // Open the AST file.
4103*67e74705SXin Li auto Buffer = FileMgr.getBufferForFile(ASTFileName);
4104*67e74705SXin Li if (!Buffer) {
4105*67e74705SXin Li Diags.Report(diag::err_fe_unable_to_read_pch_file)
4106*67e74705SXin Li << ASTFileName << Buffer.getError().message();
4107*67e74705SXin Li return std::string();
4108*67e74705SXin Li }
4109*67e74705SXin Li
4110*67e74705SXin Li // Initialize the stream
4111*67e74705SXin Li llvm::BitstreamReader StreamFile;
4112*67e74705SXin Li PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
4113*67e74705SXin Li BitstreamCursor Stream(StreamFile);
4114*67e74705SXin Li
4115*67e74705SXin Li // Sniff for the signature.
4116*67e74705SXin Li if (!startsWithASTFileMagic(Stream)) {
4117*67e74705SXin Li Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4118*67e74705SXin Li return std::string();
4119*67e74705SXin Li }
4120*67e74705SXin Li
4121*67e74705SXin Li // Scan for the CONTROL_BLOCK_ID block.
4122*67e74705SXin Li if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
4123*67e74705SXin Li Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4124*67e74705SXin Li return std::string();
4125*67e74705SXin Li }
4126*67e74705SXin Li
4127*67e74705SXin Li // Scan for ORIGINAL_FILE inside the control block.
4128*67e74705SXin Li RecordData Record;
4129*67e74705SXin Li while (1) {
4130*67e74705SXin Li llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4131*67e74705SXin Li if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4132*67e74705SXin Li return std::string();
4133*67e74705SXin Li
4134*67e74705SXin Li if (Entry.Kind != llvm::BitstreamEntry::Record) {
4135*67e74705SXin Li Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4136*67e74705SXin Li return std::string();
4137*67e74705SXin Li }
4138*67e74705SXin Li
4139*67e74705SXin Li Record.clear();
4140*67e74705SXin Li StringRef Blob;
4141*67e74705SXin Li if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4142*67e74705SXin Li return Blob.str();
4143*67e74705SXin Li }
4144*67e74705SXin Li }
4145*67e74705SXin Li
4146*67e74705SXin Li namespace {
4147*67e74705SXin Li class SimplePCHValidator : public ASTReaderListener {
4148*67e74705SXin Li const LangOptions &ExistingLangOpts;
4149*67e74705SXin Li const TargetOptions &ExistingTargetOpts;
4150*67e74705SXin Li const PreprocessorOptions &ExistingPPOpts;
4151*67e74705SXin Li std::string ExistingModuleCachePath;
4152*67e74705SXin Li FileManager &FileMgr;
4153*67e74705SXin Li
4154*67e74705SXin Li public:
SimplePCHValidator(const LangOptions & ExistingLangOpts,const TargetOptions & ExistingTargetOpts,const PreprocessorOptions & ExistingPPOpts,StringRef ExistingModuleCachePath,FileManager & FileMgr)4155*67e74705SXin Li SimplePCHValidator(const LangOptions &ExistingLangOpts,
4156*67e74705SXin Li const TargetOptions &ExistingTargetOpts,
4157*67e74705SXin Li const PreprocessorOptions &ExistingPPOpts,
4158*67e74705SXin Li StringRef ExistingModuleCachePath,
4159*67e74705SXin Li FileManager &FileMgr)
4160*67e74705SXin Li : ExistingLangOpts(ExistingLangOpts),
4161*67e74705SXin Li ExistingTargetOpts(ExistingTargetOpts),
4162*67e74705SXin Li ExistingPPOpts(ExistingPPOpts),
4163*67e74705SXin Li ExistingModuleCachePath(ExistingModuleCachePath),
4164*67e74705SXin Li FileMgr(FileMgr)
4165*67e74705SXin Li {
4166*67e74705SXin Li }
4167*67e74705SXin Li
ReadLanguageOptions(const LangOptions & LangOpts,bool Complain,bool AllowCompatibleDifferences)4168*67e74705SXin Li bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4169*67e74705SXin Li bool AllowCompatibleDifferences) override {
4170*67e74705SXin Li return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4171*67e74705SXin Li AllowCompatibleDifferences);
4172*67e74705SXin Li }
ReadTargetOptions(const TargetOptions & TargetOpts,bool Complain,bool AllowCompatibleDifferences)4173*67e74705SXin Li bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4174*67e74705SXin Li bool AllowCompatibleDifferences) override {
4175*67e74705SXin Li return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4176*67e74705SXin Li AllowCompatibleDifferences);
4177*67e74705SXin Li }
ReadHeaderSearchOptions(const HeaderSearchOptions & HSOpts,StringRef SpecificModuleCachePath,bool Complain)4178*67e74705SXin Li bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4179*67e74705SXin Li StringRef SpecificModuleCachePath,
4180*67e74705SXin Li bool Complain) override {
4181*67e74705SXin Li return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4182*67e74705SXin Li ExistingModuleCachePath,
4183*67e74705SXin Li nullptr, ExistingLangOpts);
4184*67e74705SXin Li }
ReadPreprocessorOptions(const PreprocessorOptions & PPOpts,bool Complain,std::string & SuggestedPredefines)4185*67e74705SXin Li bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4186*67e74705SXin Li bool Complain,
4187*67e74705SXin Li std::string &SuggestedPredefines) override {
4188*67e74705SXin Li return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
4189*67e74705SXin Li SuggestedPredefines, ExistingLangOpts);
4190*67e74705SXin Li }
4191*67e74705SXin Li };
4192*67e74705SXin Li }
4193*67e74705SXin Li
readASTFileControlBlock(StringRef Filename,FileManager & FileMgr,const PCHContainerReader & PCHContainerRdr,bool FindModuleFileExtensions,ASTReaderListener & Listener)4194*67e74705SXin Li bool ASTReader::readASTFileControlBlock(
4195*67e74705SXin Li StringRef Filename, FileManager &FileMgr,
4196*67e74705SXin Li const PCHContainerReader &PCHContainerRdr,
4197*67e74705SXin Li bool FindModuleFileExtensions,
4198*67e74705SXin Li ASTReaderListener &Listener) {
4199*67e74705SXin Li // Open the AST file.
4200*67e74705SXin Li // FIXME: This allows use of the VFS; we do not allow use of the
4201*67e74705SXin Li // VFS when actually loading a module.
4202*67e74705SXin Li auto Buffer = FileMgr.getBufferForFile(Filename);
4203*67e74705SXin Li if (!Buffer) {
4204*67e74705SXin Li return true;
4205*67e74705SXin Li }
4206*67e74705SXin Li
4207*67e74705SXin Li // Initialize the stream
4208*67e74705SXin Li llvm::BitstreamReader StreamFile;
4209*67e74705SXin Li PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
4210*67e74705SXin Li BitstreamCursor Stream(StreamFile);
4211*67e74705SXin Li
4212*67e74705SXin Li // Sniff for the signature.
4213*67e74705SXin Li if (!startsWithASTFileMagic(Stream))
4214*67e74705SXin Li return true;
4215*67e74705SXin Li
4216*67e74705SXin Li // Scan for the CONTROL_BLOCK_ID block.
4217*67e74705SXin Li if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4218*67e74705SXin Li return true;
4219*67e74705SXin Li
4220*67e74705SXin Li bool NeedsInputFiles = Listener.needsInputFileVisitation();
4221*67e74705SXin Li bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
4222*67e74705SXin Li bool NeedsImports = Listener.needsImportVisitation();
4223*67e74705SXin Li BitstreamCursor InputFilesCursor;
4224*67e74705SXin Li
4225*67e74705SXin Li RecordData Record;
4226*67e74705SXin Li std::string ModuleDir;
4227*67e74705SXin Li bool DoneWithControlBlock = false;
4228*67e74705SXin Li while (!DoneWithControlBlock) {
4229*67e74705SXin Li llvm::BitstreamEntry Entry = Stream.advance();
4230*67e74705SXin Li
4231*67e74705SXin Li switch (Entry.Kind) {
4232*67e74705SXin Li case llvm::BitstreamEntry::SubBlock: {
4233*67e74705SXin Li switch (Entry.ID) {
4234*67e74705SXin Li case OPTIONS_BLOCK_ID: {
4235*67e74705SXin Li std::string IgnoredSuggestedPredefines;
4236*67e74705SXin Li if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4237*67e74705SXin Li /*AllowCompatibleConfigurationMismatch*/ false,
4238*67e74705SXin Li Listener, IgnoredSuggestedPredefines) != Success)
4239*67e74705SXin Li return true;
4240*67e74705SXin Li break;
4241*67e74705SXin Li }
4242*67e74705SXin Li
4243*67e74705SXin Li case INPUT_FILES_BLOCK_ID:
4244*67e74705SXin Li InputFilesCursor = Stream;
4245*67e74705SXin Li if (Stream.SkipBlock() ||
4246*67e74705SXin Li (NeedsInputFiles &&
4247*67e74705SXin Li ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4248*67e74705SXin Li return true;
4249*67e74705SXin Li break;
4250*67e74705SXin Li
4251*67e74705SXin Li default:
4252*67e74705SXin Li if (Stream.SkipBlock())
4253*67e74705SXin Li return true;
4254*67e74705SXin Li break;
4255*67e74705SXin Li }
4256*67e74705SXin Li
4257*67e74705SXin Li continue;
4258*67e74705SXin Li }
4259*67e74705SXin Li
4260*67e74705SXin Li case llvm::BitstreamEntry::EndBlock:
4261*67e74705SXin Li DoneWithControlBlock = true;
4262*67e74705SXin Li break;
4263*67e74705SXin Li
4264*67e74705SXin Li case llvm::BitstreamEntry::Error:
4265*67e74705SXin Li return true;
4266*67e74705SXin Li
4267*67e74705SXin Li case llvm::BitstreamEntry::Record:
4268*67e74705SXin Li break;
4269*67e74705SXin Li }
4270*67e74705SXin Li
4271*67e74705SXin Li if (DoneWithControlBlock) break;
4272*67e74705SXin Li
4273*67e74705SXin Li Record.clear();
4274*67e74705SXin Li StringRef Blob;
4275*67e74705SXin Li unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4276*67e74705SXin Li switch ((ControlRecordTypes)RecCode) {
4277*67e74705SXin Li case METADATA: {
4278*67e74705SXin Li if (Record[0] != VERSION_MAJOR)
4279*67e74705SXin Li return true;
4280*67e74705SXin Li
4281*67e74705SXin Li if (Listener.ReadFullVersionInformation(Blob))
4282*67e74705SXin Li return true;
4283*67e74705SXin Li
4284*67e74705SXin Li break;
4285*67e74705SXin Li }
4286*67e74705SXin Li case MODULE_NAME:
4287*67e74705SXin Li Listener.ReadModuleName(Blob);
4288*67e74705SXin Li break;
4289*67e74705SXin Li case MODULE_DIRECTORY:
4290*67e74705SXin Li ModuleDir = Blob;
4291*67e74705SXin Li break;
4292*67e74705SXin Li case MODULE_MAP_FILE: {
4293*67e74705SXin Li unsigned Idx = 0;
4294*67e74705SXin Li auto Path = ReadString(Record, Idx);
4295*67e74705SXin Li ResolveImportedPath(Path, ModuleDir);
4296*67e74705SXin Li Listener.ReadModuleMapFile(Path);
4297*67e74705SXin Li break;
4298*67e74705SXin Li }
4299*67e74705SXin Li case INPUT_FILE_OFFSETS: {
4300*67e74705SXin Li if (!NeedsInputFiles)
4301*67e74705SXin Li break;
4302*67e74705SXin Li
4303*67e74705SXin Li unsigned NumInputFiles = Record[0];
4304*67e74705SXin Li unsigned NumUserFiles = Record[1];
4305*67e74705SXin Li const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
4306*67e74705SXin Li for (unsigned I = 0; I != NumInputFiles; ++I) {
4307*67e74705SXin Li // Go find this input file.
4308*67e74705SXin Li bool isSystemFile = I >= NumUserFiles;
4309*67e74705SXin Li
4310*67e74705SXin Li if (isSystemFile && !NeedsSystemInputFiles)
4311*67e74705SXin Li break; // the rest are system input files
4312*67e74705SXin Li
4313*67e74705SXin Li BitstreamCursor &Cursor = InputFilesCursor;
4314*67e74705SXin Li SavedStreamPosition SavedPosition(Cursor);
4315*67e74705SXin Li Cursor.JumpToBit(InputFileOffs[I]);
4316*67e74705SXin Li
4317*67e74705SXin Li unsigned Code = Cursor.ReadCode();
4318*67e74705SXin Li RecordData Record;
4319*67e74705SXin Li StringRef Blob;
4320*67e74705SXin Li bool shouldContinue = false;
4321*67e74705SXin Li switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4322*67e74705SXin Li case INPUT_FILE:
4323*67e74705SXin Li bool Overridden = static_cast<bool>(Record[3]);
4324*67e74705SXin Li std::string Filename = Blob;
4325*67e74705SXin Li ResolveImportedPath(Filename, ModuleDir);
4326*67e74705SXin Li shouldContinue = Listener.visitInputFile(
4327*67e74705SXin Li Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
4328*67e74705SXin Li break;
4329*67e74705SXin Li }
4330*67e74705SXin Li if (!shouldContinue)
4331*67e74705SXin Li break;
4332*67e74705SXin Li }
4333*67e74705SXin Li break;
4334*67e74705SXin Li }
4335*67e74705SXin Li
4336*67e74705SXin Li case IMPORTS: {
4337*67e74705SXin Li if (!NeedsImports)
4338*67e74705SXin Li break;
4339*67e74705SXin Li
4340*67e74705SXin Li unsigned Idx = 0, N = Record.size();
4341*67e74705SXin Li while (Idx < N) {
4342*67e74705SXin Li // Read information about the AST file.
4343*67e74705SXin Li Idx += 5; // ImportLoc, Size, ModTime, Signature
4344*67e74705SXin Li std::string Filename = ReadString(Record, Idx);
4345*67e74705SXin Li ResolveImportedPath(Filename, ModuleDir);
4346*67e74705SXin Li Listener.visitImport(Filename);
4347*67e74705SXin Li }
4348*67e74705SXin Li break;
4349*67e74705SXin Li }
4350*67e74705SXin Li
4351*67e74705SXin Li default:
4352*67e74705SXin Li // No other validation to perform.
4353*67e74705SXin Li break;
4354*67e74705SXin Li }
4355*67e74705SXin Li }
4356*67e74705SXin Li
4357*67e74705SXin Li // Look for module file extension blocks, if requested.
4358*67e74705SXin Li if (FindModuleFileExtensions) {
4359*67e74705SXin Li while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4360*67e74705SXin Li bool DoneWithExtensionBlock = false;
4361*67e74705SXin Li while (!DoneWithExtensionBlock) {
4362*67e74705SXin Li llvm::BitstreamEntry Entry = Stream.advance();
4363*67e74705SXin Li
4364*67e74705SXin Li switch (Entry.Kind) {
4365*67e74705SXin Li case llvm::BitstreamEntry::SubBlock:
4366*67e74705SXin Li if (Stream.SkipBlock())
4367*67e74705SXin Li return true;
4368*67e74705SXin Li
4369*67e74705SXin Li continue;
4370*67e74705SXin Li
4371*67e74705SXin Li case llvm::BitstreamEntry::EndBlock:
4372*67e74705SXin Li DoneWithExtensionBlock = true;
4373*67e74705SXin Li continue;
4374*67e74705SXin Li
4375*67e74705SXin Li case llvm::BitstreamEntry::Error:
4376*67e74705SXin Li return true;
4377*67e74705SXin Li
4378*67e74705SXin Li case llvm::BitstreamEntry::Record:
4379*67e74705SXin Li break;
4380*67e74705SXin Li }
4381*67e74705SXin Li
4382*67e74705SXin Li Record.clear();
4383*67e74705SXin Li StringRef Blob;
4384*67e74705SXin Li unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4385*67e74705SXin Li switch (RecCode) {
4386*67e74705SXin Li case EXTENSION_METADATA: {
4387*67e74705SXin Li ModuleFileExtensionMetadata Metadata;
4388*67e74705SXin Li if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4389*67e74705SXin Li return true;
4390*67e74705SXin Li
4391*67e74705SXin Li Listener.readModuleFileExtension(Metadata);
4392*67e74705SXin Li break;
4393*67e74705SXin Li }
4394*67e74705SXin Li }
4395*67e74705SXin Li }
4396*67e74705SXin Li }
4397*67e74705SXin Li }
4398*67e74705SXin Li
4399*67e74705SXin Li return false;
4400*67e74705SXin Li }
4401*67e74705SXin Li
isAcceptableASTFile(StringRef Filename,FileManager & FileMgr,const PCHContainerReader & PCHContainerRdr,const LangOptions & LangOpts,const TargetOptions & TargetOpts,const PreprocessorOptions & PPOpts,std::string ExistingModuleCachePath)4402*67e74705SXin Li bool ASTReader::isAcceptableASTFile(
4403*67e74705SXin Li StringRef Filename, FileManager &FileMgr,
4404*67e74705SXin Li const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
4405*67e74705SXin Li const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4406*67e74705SXin Li std::string ExistingModuleCachePath) {
4407*67e74705SXin Li SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4408*67e74705SXin Li ExistingModuleCachePath, FileMgr);
4409*67e74705SXin Li return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
4410*67e74705SXin Li /*FindModuleFileExtensions=*/false,
4411*67e74705SXin Li validator);
4412*67e74705SXin Li }
4413*67e74705SXin Li
4414*67e74705SXin Li ASTReader::ASTReadResult
ReadSubmoduleBlock(ModuleFile & F,unsigned ClientLoadCapabilities)4415*67e74705SXin Li ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
4416*67e74705SXin Li // Enter the submodule block.
4417*67e74705SXin Li if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4418*67e74705SXin Li Error("malformed submodule block record in AST file");
4419*67e74705SXin Li return Failure;
4420*67e74705SXin Li }
4421*67e74705SXin Li
4422*67e74705SXin Li ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4423*67e74705SXin Li bool First = true;
4424*67e74705SXin Li Module *CurrentModule = nullptr;
4425*67e74705SXin Li RecordData Record;
4426*67e74705SXin Li while (true) {
4427*67e74705SXin Li llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4428*67e74705SXin Li
4429*67e74705SXin Li switch (Entry.Kind) {
4430*67e74705SXin Li case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4431*67e74705SXin Li case llvm::BitstreamEntry::Error:
4432*67e74705SXin Li Error("malformed block record in AST file");
4433*67e74705SXin Li return Failure;
4434*67e74705SXin Li case llvm::BitstreamEntry::EndBlock:
4435*67e74705SXin Li return Success;
4436*67e74705SXin Li case llvm::BitstreamEntry::Record:
4437*67e74705SXin Li // The interesting case.
4438*67e74705SXin Li break;
4439*67e74705SXin Li }
4440*67e74705SXin Li
4441*67e74705SXin Li // Read a record.
4442*67e74705SXin Li StringRef Blob;
4443*67e74705SXin Li Record.clear();
4444*67e74705SXin Li auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4445*67e74705SXin Li
4446*67e74705SXin Li if ((Kind == SUBMODULE_METADATA) != First) {
4447*67e74705SXin Li Error("submodule metadata record should be at beginning of block");
4448*67e74705SXin Li return Failure;
4449*67e74705SXin Li }
4450*67e74705SXin Li First = false;
4451*67e74705SXin Li
4452*67e74705SXin Li // Submodule information is only valid if we have a current module.
4453*67e74705SXin Li // FIXME: Should we error on these cases?
4454*67e74705SXin Li if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4455*67e74705SXin Li Kind != SUBMODULE_DEFINITION)
4456*67e74705SXin Li continue;
4457*67e74705SXin Li
4458*67e74705SXin Li switch (Kind) {
4459*67e74705SXin Li default: // Default behavior: ignore.
4460*67e74705SXin Li break;
4461*67e74705SXin Li
4462*67e74705SXin Li case SUBMODULE_DEFINITION: {
4463*67e74705SXin Li if (Record.size() < 8) {
4464*67e74705SXin Li Error("malformed module definition");
4465*67e74705SXin Li return Failure;
4466*67e74705SXin Li }
4467*67e74705SXin Li
4468*67e74705SXin Li StringRef Name = Blob;
4469*67e74705SXin Li unsigned Idx = 0;
4470*67e74705SXin Li SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4471*67e74705SXin Li SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4472*67e74705SXin Li bool IsFramework = Record[Idx++];
4473*67e74705SXin Li bool IsExplicit = Record[Idx++];
4474*67e74705SXin Li bool IsSystem = Record[Idx++];
4475*67e74705SXin Li bool IsExternC = Record[Idx++];
4476*67e74705SXin Li bool InferSubmodules = Record[Idx++];
4477*67e74705SXin Li bool InferExplicitSubmodules = Record[Idx++];
4478*67e74705SXin Li bool InferExportWildcard = Record[Idx++];
4479*67e74705SXin Li bool ConfigMacrosExhaustive = Record[Idx++];
4480*67e74705SXin Li
4481*67e74705SXin Li Module *ParentModule = nullptr;
4482*67e74705SXin Li if (Parent)
4483*67e74705SXin Li ParentModule = getSubmodule(Parent);
4484*67e74705SXin Li
4485*67e74705SXin Li // Retrieve this (sub)module from the module map, creating it if
4486*67e74705SXin Li // necessary.
4487*67e74705SXin Li CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
4488*67e74705SXin Li IsExplicit).first;
4489*67e74705SXin Li
4490*67e74705SXin Li // FIXME: set the definition loc for CurrentModule, or call
4491*67e74705SXin Li // ModMap.setInferredModuleAllowedBy()
4492*67e74705SXin Li
4493*67e74705SXin Li SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4494*67e74705SXin Li if (GlobalIndex >= SubmodulesLoaded.size() ||
4495*67e74705SXin Li SubmodulesLoaded[GlobalIndex]) {
4496*67e74705SXin Li Error("too many submodules");
4497*67e74705SXin Li return Failure;
4498*67e74705SXin Li }
4499*67e74705SXin Li
4500*67e74705SXin Li if (!ParentModule) {
4501*67e74705SXin Li if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4502*67e74705SXin Li if (CurFile != F.File) {
4503*67e74705SXin Li if (!Diags.isDiagnosticInFlight()) {
4504*67e74705SXin Li Diag(diag::err_module_file_conflict)
4505*67e74705SXin Li << CurrentModule->getTopLevelModuleName()
4506*67e74705SXin Li << CurFile->getName()
4507*67e74705SXin Li << F.File->getName();
4508*67e74705SXin Li }
4509*67e74705SXin Li return Failure;
4510*67e74705SXin Li }
4511*67e74705SXin Li }
4512*67e74705SXin Li
4513*67e74705SXin Li CurrentModule->setASTFile(F.File);
4514*67e74705SXin Li }
4515*67e74705SXin Li
4516*67e74705SXin Li CurrentModule->Signature = F.Signature;
4517*67e74705SXin Li CurrentModule->IsFromModuleFile = true;
4518*67e74705SXin Li CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
4519*67e74705SXin Li CurrentModule->IsExternC = IsExternC;
4520*67e74705SXin Li CurrentModule->InferSubmodules = InferSubmodules;
4521*67e74705SXin Li CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4522*67e74705SXin Li CurrentModule->InferExportWildcard = InferExportWildcard;
4523*67e74705SXin Li CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
4524*67e74705SXin Li if (DeserializationListener)
4525*67e74705SXin Li DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4526*67e74705SXin Li
4527*67e74705SXin Li SubmodulesLoaded[GlobalIndex] = CurrentModule;
4528*67e74705SXin Li
4529*67e74705SXin Li // Clear out data that will be replaced by what is in the module file.
4530*67e74705SXin Li CurrentModule->LinkLibraries.clear();
4531*67e74705SXin Li CurrentModule->ConfigMacros.clear();
4532*67e74705SXin Li CurrentModule->UnresolvedConflicts.clear();
4533*67e74705SXin Li CurrentModule->Conflicts.clear();
4534*67e74705SXin Li
4535*67e74705SXin Li // The module is available unless it's missing a requirement; relevant
4536*67e74705SXin Li // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4537*67e74705SXin Li // Missing headers that were present when the module was built do not
4538*67e74705SXin Li // make it unavailable -- if we got this far, this must be an explicitly
4539*67e74705SXin Li // imported module file.
4540*67e74705SXin Li CurrentModule->Requirements.clear();
4541*67e74705SXin Li CurrentModule->MissingHeaders.clear();
4542*67e74705SXin Li CurrentModule->IsMissingRequirement =
4543*67e74705SXin Li ParentModule && ParentModule->IsMissingRequirement;
4544*67e74705SXin Li CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
4545*67e74705SXin Li break;
4546*67e74705SXin Li }
4547*67e74705SXin Li
4548*67e74705SXin Li case SUBMODULE_UMBRELLA_HEADER: {
4549*67e74705SXin Li std::string Filename = Blob;
4550*67e74705SXin Li ResolveImportedPath(F, Filename);
4551*67e74705SXin Li if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
4552*67e74705SXin Li if (!CurrentModule->getUmbrellaHeader())
4553*67e74705SXin Li ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4554*67e74705SXin Li else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
4555*67e74705SXin Li // This can be a spurious difference caused by changing the VFS to
4556*67e74705SXin Li // point to a different copy of the file, and it is too late to
4557*67e74705SXin Li // to rebuild safely.
4558*67e74705SXin Li // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4559*67e74705SXin Li // after input file validation only real problems would remain and we
4560*67e74705SXin Li // could just error. For now, assume it's okay.
4561*67e74705SXin Li break;
4562*67e74705SXin Li }
4563*67e74705SXin Li }
4564*67e74705SXin Li break;
4565*67e74705SXin Li }
4566*67e74705SXin Li
4567*67e74705SXin Li case SUBMODULE_HEADER:
4568*67e74705SXin Li case SUBMODULE_EXCLUDED_HEADER:
4569*67e74705SXin Li case SUBMODULE_PRIVATE_HEADER:
4570*67e74705SXin Li // We lazily associate headers with their modules via the HeaderInfo table.
4571*67e74705SXin Li // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4572*67e74705SXin Li // of complete filenames or remove it entirely.
4573*67e74705SXin Li break;
4574*67e74705SXin Li
4575*67e74705SXin Li case SUBMODULE_TEXTUAL_HEADER:
4576*67e74705SXin Li case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4577*67e74705SXin Li // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4578*67e74705SXin Li // them here.
4579*67e74705SXin Li break;
4580*67e74705SXin Li
4581*67e74705SXin Li case SUBMODULE_TOPHEADER: {
4582*67e74705SXin Li CurrentModule->addTopHeaderFilename(Blob);
4583*67e74705SXin Li break;
4584*67e74705SXin Li }
4585*67e74705SXin Li
4586*67e74705SXin Li case SUBMODULE_UMBRELLA_DIR: {
4587*67e74705SXin Li std::string Dirname = Blob;
4588*67e74705SXin Li ResolveImportedPath(F, Dirname);
4589*67e74705SXin Li if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
4590*67e74705SXin Li if (!CurrentModule->getUmbrellaDir())
4591*67e74705SXin Li ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4592*67e74705SXin Li else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
4593*67e74705SXin Li if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4594*67e74705SXin Li Error("mismatched umbrella directories in submodule");
4595*67e74705SXin Li return OutOfDate;
4596*67e74705SXin Li }
4597*67e74705SXin Li }
4598*67e74705SXin Li break;
4599*67e74705SXin Li }
4600*67e74705SXin Li
4601*67e74705SXin Li case SUBMODULE_METADATA: {
4602*67e74705SXin Li F.BaseSubmoduleID = getTotalNumSubmodules();
4603*67e74705SXin Li F.LocalNumSubmodules = Record[0];
4604*67e74705SXin Li unsigned LocalBaseSubmoduleID = Record[1];
4605*67e74705SXin Li if (F.LocalNumSubmodules > 0) {
4606*67e74705SXin Li // Introduce the global -> local mapping for submodules within this
4607*67e74705SXin Li // module.
4608*67e74705SXin Li GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4609*67e74705SXin Li
4610*67e74705SXin Li // Introduce the local -> global mapping for submodules within this
4611*67e74705SXin Li // module.
4612*67e74705SXin Li F.SubmoduleRemap.insertOrReplace(
4613*67e74705SXin Li std::make_pair(LocalBaseSubmoduleID,
4614*67e74705SXin Li F.BaseSubmoduleID - LocalBaseSubmoduleID));
4615*67e74705SXin Li
4616*67e74705SXin Li SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4617*67e74705SXin Li }
4618*67e74705SXin Li break;
4619*67e74705SXin Li }
4620*67e74705SXin Li
4621*67e74705SXin Li case SUBMODULE_IMPORTS: {
4622*67e74705SXin Li for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
4623*67e74705SXin Li UnresolvedModuleRef Unresolved;
4624*67e74705SXin Li Unresolved.File = &F;
4625*67e74705SXin Li Unresolved.Mod = CurrentModule;
4626*67e74705SXin Li Unresolved.ID = Record[Idx];
4627*67e74705SXin Li Unresolved.Kind = UnresolvedModuleRef::Import;
4628*67e74705SXin Li Unresolved.IsWildcard = false;
4629*67e74705SXin Li UnresolvedModuleRefs.push_back(Unresolved);
4630*67e74705SXin Li }
4631*67e74705SXin Li break;
4632*67e74705SXin Li }
4633*67e74705SXin Li
4634*67e74705SXin Li case SUBMODULE_EXPORTS: {
4635*67e74705SXin Li for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
4636*67e74705SXin Li UnresolvedModuleRef Unresolved;
4637*67e74705SXin Li Unresolved.File = &F;
4638*67e74705SXin Li Unresolved.Mod = CurrentModule;
4639*67e74705SXin Li Unresolved.ID = Record[Idx];
4640*67e74705SXin Li Unresolved.Kind = UnresolvedModuleRef::Export;
4641*67e74705SXin Li Unresolved.IsWildcard = Record[Idx + 1];
4642*67e74705SXin Li UnresolvedModuleRefs.push_back(Unresolved);
4643*67e74705SXin Li }
4644*67e74705SXin Li
4645*67e74705SXin Li // Once we've loaded the set of exports, there's no reason to keep
4646*67e74705SXin Li // the parsed, unresolved exports around.
4647*67e74705SXin Li CurrentModule->UnresolvedExports.clear();
4648*67e74705SXin Li break;
4649*67e74705SXin Li }
4650*67e74705SXin Li case SUBMODULE_REQUIRES: {
4651*67e74705SXin Li CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
4652*67e74705SXin Li Context.getTargetInfo());
4653*67e74705SXin Li break;
4654*67e74705SXin Li }
4655*67e74705SXin Li
4656*67e74705SXin Li case SUBMODULE_LINK_LIBRARY:
4657*67e74705SXin Li CurrentModule->LinkLibraries.push_back(
4658*67e74705SXin Li Module::LinkLibrary(Blob, Record[0]));
4659*67e74705SXin Li break;
4660*67e74705SXin Li
4661*67e74705SXin Li case SUBMODULE_CONFIG_MACRO:
4662*67e74705SXin Li CurrentModule->ConfigMacros.push_back(Blob.str());
4663*67e74705SXin Li break;
4664*67e74705SXin Li
4665*67e74705SXin Li case SUBMODULE_CONFLICT: {
4666*67e74705SXin Li UnresolvedModuleRef Unresolved;
4667*67e74705SXin Li Unresolved.File = &F;
4668*67e74705SXin Li Unresolved.Mod = CurrentModule;
4669*67e74705SXin Li Unresolved.ID = Record[0];
4670*67e74705SXin Li Unresolved.Kind = UnresolvedModuleRef::Conflict;
4671*67e74705SXin Li Unresolved.IsWildcard = false;
4672*67e74705SXin Li Unresolved.String = Blob;
4673*67e74705SXin Li UnresolvedModuleRefs.push_back(Unresolved);
4674*67e74705SXin Li break;
4675*67e74705SXin Li }
4676*67e74705SXin Li }
4677*67e74705SXin Li }
4678*67e74705SXin Li }
4679*67e74705SXin Li
4680*67e74705SXin Li /// \brief Parse the record that corresponds to a LangOptions data
4681*67e74705SXin Li /// structure.
4682*67e74705SXin Li ///
4683*67e74705SXin Li /// This routine parses the language options from the AST file and then gives
4684*67e74705SXin Li /// them to the AST listener if one is set.
4685*67e74705SXin Li ///
4686*67e74705SXin Li /// \returns true if the listener deems the file unacceptable, false otherwise.
ParseLanguageOptions(const RecordData & Record,bool Complain,ASTReaderListener & Listener,bool AllowCompatibleDifferences)4687*67e74705SXin Li bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4688*67e74705SXin Li bool Complain,
4689*67e74705SXin Li ASTReaderListener &Listener,
4690*67e74705SXin Li bool AllowCompatibleDifferences) {
4691*67e74705SXin Li LangOptions LangOpts;
4692*67e74705SXin Li unsigned Idx = 0;
4693*67e74705SXin Li #define LANGOPT(Name, Bits, Default, Description) \
4694*67e74705SXin Li LangOpts.Name = Record[Idx++];
4695*67e74705SXin Li #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4696*67e74705SXin Li LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4697*67e74705SXin Li #include "clang/Basic/LangOptions.def"
4698*67e74705SXin Li #define SANITIZER(NAME, ID) \
4699*67e74705SXin Li LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
4700*67e74705SXin Li #include "clang/Basic/Sanitizers.def"
4701*67e74705SXin Li
4702*67e74705SXin Li for (unsigned N = Record[Idx++]; N; --N)
4703*67e74705SXin Li LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4704*67e74705SXin Li
4705*67e74705SXin Li ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4706*67e74705SXin Li VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4707*67e74705SXin Li LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4708*67e74705SXin Li
4709*67e74705SXin Li LangOpts.CurrentModule = ReadString(Record, Idx);
4710*67e74705SXin Li
4711*67e74705SXin Li // Comment options.
4712*67e74705SXin Li for (unsigned N = Record[Idx++]; N; --N) {
4713*67e74705SXin Li LangOpts.CommentOpts.BlockCommandNames.push_back(
4714*67e74705SXin Li ReadString(Record, Idx));
4715*67e74705SXin Li }
4716*67e74705SXin Li LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
4717*67e74705SXin Li
4718*67e74705SXin Li // OpenMP offloading options.
4719*67e74705SXin Li for (unsigned N = Record[Idx++]; N; --N) {
4720*67e74705SXin Li LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
4721*67e74705SXin Li }
4722*67e74705SXin Li
4723*67e74705SXin Li LangOpts.OMPHostIRFile = ReadString(Record, Idx);
4724*67e74705SXin Li
4725*67e74705SXin Li return Listener.ReadLanguageOptions(LangOpts, Complain,
4726*67e74705SXin Li AllowCompatibleDifferences);
4727*67e74705SXin Li }
4728*67e74705SXin Li
ParseTargetOptions(const RecordData & Record,bool Complain,ASTReaderListener & Listener,bool AllowCompatibleDifferences)4729*67e74705SXin Li bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4730*67e74705SXin Li ASTReaderListener &Listener,
4731*67e74705SXin Li bool AllowCompatibleDifferences) {
4732*67e74705SXin Li unsigned Idx = 0;
4733*67e74705SXin Li TargetOptions TargetOpts;
4734*67e74705SXin Li TargetOpts.Triple = ReadString(Record, Idx);
4735*67e74705SXin Li TargetOpts.CPU = ReadString(Record, Idx);
4736*67e74705SXin Li TargetOpts.ABI = ReadString(Record, Idx);
4737*67e74705SXin Li for (unsigned N = Record[Idx++]; N; --N) {
4738*67e74705SXin Li TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4739*67e74705SXin Li }
4740*67e74705SXin Li for (unsigned N = Record[Idx++]; N; --N) {
4741*67e74705SXin Li TargetOpts.Features.push_back(ReadString(Record, Idx));
4742*67e74705SXin Li }
4743*67e74705SXin Li
4744*67e74705SXin Li return Listener.ReadTargetOptions(TargetOpts, Complain,
4745*67e74705SXin Li AllowCompatibleDifferences);
4746*67e74705SXin Li }
4747*67e74705SXin Li
ParseDiagnosticOptions(const RecordData & Record,bool Complain,ASTReaderListener & Listener)4748*67e74705SXin Li bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4749*67e74705SXin Li ASTReaderListener &Listener) {
4750*67e74705SXin Li IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
4751*67e74705SXin Li unsigned Idx = 0;
4752*67e74705SXin Li #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
4753*67e74705SXin Li #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4754*67e74705SXin Li DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
4755*67e74705SXin Li #include "clang/Basic/DiagnosticOptions.def"
4756*67e74705SXin Li
4757*67e74705SXin Li for (unsigned N = Record[Idx++]; N; --N)
4758*67e74705SXin Li DiagOpts->Warnings.push_back(ReadString(Record, Idx));
4759*67e74705SXin Li for (unsigned N = Record[Idx++]; N; --N)
4760*67e74705SXin Li DiagOpts->Remarks.push_back(ReadString(Record, Idx));
4761*67e74705SXin Li
4762*67e74705SXin Li return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4763*67e74705SXin Li }
4764*67e74705SXin Li
ParseFileSystemOptions(const RecordData & Record,bool Complain,ASTReaderListener & Listener)4765*67e74705SXin Li bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4766*67e74705SXin Li ASTReaderListener &Listener) {
4767*67e74705SXin Li FileSystemOptions FSOpts;
4768*67e74705SXin Li unsigned Idx = 0;
4769*67e74705SXin Li FSOpts.WorkingDir = ReadString(Record, Idx);
4770*67e74705SXin Li return Listener.ReadFileSystemOptions(FSOpts, Complain);
4771*67e74705SXin Li }
4772*67e74705SXin Li
ParseHeaderSearchOptions(const RecordData & Record,bool Complain,ASTReaderListener & Listener)4773*67e74705SXin Li bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4774*67e74705SXin Li bool Complain,
4775*67e74705SXin Li ASTReaderListener &Listener) {
4776*67e74705SXin Li HeaderSearchOptions HSOpts;
4777*67e74705SXin Li unsigned Idx = 0;
4778*67e74705SXin Li HSOpts.Sysroot = ReadString(Record, Idx);
4779*67e74705SXin Li
4780*67e74705SXin Li // Include entries.
4781*67e74705SXin Li for (unsigned N = Record[Idx++]; N; --N) {
4782*67e74705SXin Li std::string Path = ReadString(Record, Idx);
4783*67e74705SXin Li frontend::IncludeDirGroup Group
4784*67e74705SXin Li = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
4785*67e74705SXin Li bool IsFramework = Record[Idx++];
4786*67e74705SXin Li bool IgnoreSysRoot = Record[Idx++];
4787*67e74705SXin Li HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4788*67e74705SXin Li IgnoreSysRoot);
4789*67e74705SXin Li }
4790*67e74705SXin Li
4791*67e74705SXin Li // System header prefixes.
4792*67e74705SXin Li for (unsigned N = Record[Idx++]; N; --N) {
4793*67e74705SXin Li std::string Prefix = ReadString(Record, Idx);
4794*67e74705SXin Li bool IsSystemHeader = Record[Idx++];
4795*67e74705SXin Li HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
4796*67e74705SXin Li }
4797*67e74705SXin Li
4798*67e74705SXin Li HSOpts.ResourceDir = ReadString(Record, Idx);
4799*67e74705SXin Li HSOpts.ModuleCachePath = ReadString(Record, Idx);
4800*67e74705SXin Li HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
4801*67e74705SXin Li HSOpts.DisableModuleHash = Record[Idx++];
4802*67e74705SXin Li HSOpts.UseBuiltinIncludes = Record[Idx++];
4803*67e74705SXin Li HSOpts.UseStandardSystemIncludes = Record[Idx++];
4804*67e74705SXin Li HSOpts.UseStandardCXXIncludes = Record[Idx++];
4805*67e74705SXin Li HSOpts.UseLibcxx = Record[Idx++];
4806*67e74705SXin Li std::string SpecificModuleCachePath = ReadString(Record, Idx);
4807*67e74705SXin Li
4808*67e74705SXin Li return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4809*67e74705SXin Li Complain);
4810*67e74705SXin Li }
4811*67e74705SXin Li
ParsePreprocessorOptions(const RecordData & Record,bool Complain,ASTReaderListener & Listener,std::string & SuggestedPredefines)4812*67e74705SXin Li bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4813*67e74705SXin Li bool Complain,
4814*67e74705SXin Li ASTReaderListener &Listener,
4815*67e74705SXin Li std::string &SuggestedPredefines) {
4816*67e74705SXin Li PreprocessorOptions PPOpts;
4817*67e74705SXin Li unsigned Idx = 0;
4818*67e74705SXin Li
4819*67e74705SXin Li // Macro definitions/undefs
4820*67e74705SXin Li for (unsigned N = Record[Idx++]; N; --N) {
4821*67e74705SXin Li std::string Macro = ReadString(Record, Idx);
4822*67e74705SXin Li bool IsUndef = Record[Idx++];
4823*67e74705SXin Li PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4824*67e74705SXin Li }
4825*67e74705SXin Li
4826*67e74705SXin Li // Includes
4827*67e74705SXin Li for (unsigned N = Record[Idx++]; N; --N) {
4828*67e74705SXin Li PPOpts.Includes.push_back(ReadString(Record, Idx));
4829*67e74705SXin Li }
4830*67e74705SXin Li
4831*67e74705SXin Li // Macro Includes
4832*67e74705SXin Li for (unsigned N = Record[Idx++]; N; --N) {
4833*67e74705SXin Li PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4834*67e74705SXin Li }
4835*67e74705SXin Li
4836*67e74705SXin Li PPOpts.UsePredefines = Record[Idx++];
4837*67e74705SXin Li PPOpts.DetailedRecord = Record[Idx++];
4838*67e74705SXin Li PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4839*67e74705SXin Li PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4840*67e74705SXin Li PPOpts.ObjCXXARCStandardLibrary =
4841*67e74705SXin Li static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4842*67e74705SXin Li SuggestedPredefines.clear();
4843*67e74705SXin Li return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4844*67e74705SXin Li SuggestedPredefines);
4845*67e74705SXin Li }
4846*67e74705SXin Li
4847*67e74705SXin Li std::pair<ModuleFile *, unsigned>
getModulePreprocessedEntity(unsigned GlobalIndex)4848*67e74705SXin Li ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4849*67e74705SXin Li GlobalPreprocessedEntityMapType::iterator
4850*67e74705SXin Li I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4851*67e74705SXin Li assert(I != GlobalPreprocessedEntityMap.end() &&
4852*67e74705SXin Li "Corrupted global preprocessed entity map");
4853*67e74705SXin Li ModuleFile *M = I->second;
4854*67e74705SXin Li unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4855*67e74705SXin Li return std::make_pair(M, LocalIndex);
4856*67e74705SXin Li }
4857*67e74705SXin Li
4858*67e74705SXin Li llvm::iterator_range<PreprocessingRecord::iterator>
getModulePreprocessedEntities(ModuleFile & Mod) const4859*67e74705SXin Li ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4860*67e74705SXin Li if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4861*67e74705SXin Li return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4862*67e74705SXin Li Mod.NumPreprocessedEntities);
4863*67e74705SXin Li
4864*67e74705SXin Li return llvm::make_range(PreprocessingRecord::iterator(),
4865*67e74705SXin Li PreprocessingRecord::iterator());
4866*67e74705SXin Li }
4867*67e74705SXin Li
4868*67e74705SXin Li llvm::iterator_range<ASTReader::ModuleDeclIterator>
getModuleFileLevelDecls(ModuleFile & Mod)4869*67e74705SXin Li ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4870*67e74705SXin Li return llvm::make_range(
4871*67e74705SXin Li ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4872*67e74705SXin Li ModuleDeclIterator(this, &Mod,
4873*67e74705SXin Li Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4874*67e74705SXin Li }
4875*67e74705SXin Li
ReadPreprocessedEntity(unsigned Index)4876*67e74705SXin Li PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4877*67e74705SXin Li PreprocessedEntityID PPID = Index+1;
4878*67e74705SXin Li std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4879*67e74705SXin Li ModuleFile &M = *PPInfo.first;
4880*67e74705SXin Li unsigned LocalIndex = PPInfo.second;
4881*67e74705SXin Li const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4882*67e74705SXin Li
4883*67e74705SXin Li if (!PP.getPreprocessingRecord()) {
4884*67e74705SXin Li Error("no preprocessing record");
4885*67e74705SXin Li return nullptr;
4886*67e74705SXin Li }
4887*67e74705SXin Li
4888*67e74705SXin Li SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4889*67e74705SXin Li M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4890*67e74705SXin Li
4891*67e74705SXin Li llvm::BitstreamEntry Entry =
4892*67e74705SXin Li M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4893*67e74705SXin Li if (Entry.Kind != llvm::BitstreamEntry::Record)
4894*67e74705SXin Li return nullptr;
4895*67e74705SXin Li
4896*67e74705SXin Li // Read the record.
4897*67e74705SXin Li SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
4898*67e74705SXin Li TranslateSourceLocation(M, PPOffs.getEnd()));
4899*67e74705SXin Li PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
4900*67e74705SXin Li StringRef Blob;
4901*67e74705SXin Li RecordData Record;
4902*67e74705SXin Li PreprocessorDetailRecordTypes RecType =
4903*67e74705SXin Li (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4904*67e74705SXin Li Entry.ID, Record, &Blob);
4905*67e74705SXin Li switch (RecType) {
4906*67e74705SXin Li case PPD_MACRO_EXPANSION: {
4907*67e74705SXin Li bool isBuiltin = Record[0];
4908*67e74705SXin Li IdentifierInfo *Name = nullptr;
4909*67e74705SXin Li MacroDefinitionRecord *Def = nullptr;
4910*67e74705SXin Li if (isBuiltin)
4911*67e74705SXin Li Name = getLocalIdentifier(M, Record[1]);
4912*67e74705SXin Li else {
4913*67e74705SXin Li PreprocessedEntityID GlobalID =
4914*67e74705SXin Li getGlobalPreprocessedEntityID(M, Record[1]);
4915*67e74705SXin Li Def = cast<MacroDefinitionRecord>(
4916*67e74705SXin Li PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
4917*67e74705SXin Li }
4918*67e74705SXin Li
4919*67e74705SXin Li MacroExpansion *ME;
4920*67e74705SXin Li if (isBuiltin)
4921*67e74705SXin Li ME = new (PPRec) MacroExpansion(Name, Range);
4922*67e74705SXin Li else
4923*67e74705SXin Li ME = new (PPRec) MacroExpansion(Def, Range);
4924*67e74705SXin Li
4925*67e74705SXin Li return ME;
4926*67e74705SXin Li }
4927*67e74705SXin Li
4928*67e74705SXin Li case PPD_MACRO_DEFINITION: {
4929*67e74705SXin Li // Decode the identifier info and then check again; if the macro is
4930*67e74705SXin Li // still defined and associated with the identifier,
4931*67e74705SXin Li IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4932*67e74705SXin Li MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
4933*67e74705SXin Li
4934*67e74705SXin Li if (DeserializationListener)
4935*67e74705SXin Li DeserializationListener->MacroDefinitionRead(PPID, MD);
4936*67e74705SXin Li
4937*67e74705SXin Li return MD;
4938*67e74705SXin Li }
4939*67e74705SXin Li
4940*67e74705SXin Li case PPD_INCLUSION_DIRECTIVE: {
4941*67e74705SXin Li const char *FullFileNameStart = Blob.data() + Record[0];
4942*67e74705SXin Li StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
4943*67e74705SXin Li const FileEntry *File = nullptr;
4944*67e74705SXin Li if (!FullFileName.empty())
4945*67e74705SXin Li File = PP.getFileManager().getFile(FullFileName);
4946*67e74705SXin Li
4947*67e74705SXin Li // FIXME: Stable encoding
4948*67e74705SXin Li InclusionDirective::InclusionKind Kind
4949*67e74705SXin Li = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4950*67e74705SXin Li InclusionDirective *ID
4951*67e74705SXin Li = new (PPRec) InclusionDirective(PPRec, Kind,
4952*67e74705SXin Li StringRef(Blob.data(), Record[0]),
4953*67e74705SXin Li Record[1], Record[3],
4954*67e74705SXin Li File,
4955*67e74705SXin Li Range);
4956*67e74705SXin Li return ID;
4957*67e74705SXin Li }
4958*67e74705SXin Li }
4959*67e74705SXin Li
4960*67e74705SXin Li llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4961*67e74705SXin Li }
4962*67e74705SXin Li
4963*67e74705SXin Li /// \brief \arg SLocMapI points at a chunk of a module that contains no
4964*67e74705SXin Li /// preprocessed entities or the entities it contains are not the ones we are
4965*67e74705SXin Li /// looking for. Find the next module that contains entities and return the ID
4966*67e74705SXin Li /// of the first entry.
findNextPreprocessedEntity(GlobalSLocOffsetMapType::const_iterator SLocMapI) const4967*67e74705SXin Li PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4968*67e74705SXin Li GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4969*67e74705SXin Li ++SLocMapI;
4970*67e74705SXin Li for (GlobalSLocOffsetMapType::const_iterator
4971*67e74705SXin Li EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4972*67e74705SXin Li ModuleFile &M = *SLocMapI->second;
4973*67e74705SXin Li if (M.NumPreprocessedEntities)
4974*67e74705SXin Li return M.BasePreprocessedEntityID;
4975*67e74705SXin Li }
4976*67e74705SXin Li
4977*67e74705SXin Li return getTotalNumPreprocessedEntities();
4978*67e74705SXin Li }
4979*67e74705SXin Li
4980*67e74705SXin Li namespace {
4981*67e74705SXin Li
4982*67e74705SXin Li struct PPEntityComp {
4983*67e74705SXin Li const ASTReader &Reader;
4984*67e74705SXin Li ModuleFile &M;
4985*67e74705SXin Li
PPEntityComp__anon1bdd35ba0711::PPEntityComp4986*67e74705SXin Li PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4987*67e74705SXin Li
operator ()__anon1bdd35ba0711::PPEntityComp4988*67e74705SXin Li bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4989*67e74705SXin Li SourceLocation LHS = getLoc(L);
4990*67e74705SXin Li SourceLocation RHS = getLoc(R);
4991*67e74705SXin Li return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4992*67e74705SXin Li }
4993*67e74705SXin Li
operator ()__anon1bdd35ba0711::PPEntityComp4994*67e74705SXin Li bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4995*67e74705SXin Li SourceLocation LHS = getLoc(L);
4996*67e74705SXin Li return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4997*67e74705SXin Li }
4998*67e74705SXin Li
operator ()__anon1bdd35ba0711::PPEntityComp4999*67e74705SXin Li bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5000*67e74705SXin Li SourceLocation RHS = getLoc(R);
5001*67e74705SXin Li return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5002*67e74705SXin Li }
5003*67e74705SXin Li
getLoc__anon1bdd35ba0711::PPEntityComp5004*67e74705SXin Li SourceLocation getLoc(const PPEntityOffset &PPE) const {
5005*67e74705SXin Li return Reader.TranslateSourceLocation(M, PPE.getBegin());
5006*67e74705SXin Li }
5007*67e74705SXin Li };
5008*67e74705SXin Li
5009*67e74705SXin Li }
5010*67e74705SXin Li
findPreprocessedEntity(SourceLocation Loc,bool EndsAfter) const5011*67e74705SXin Li PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5012*67e74705SXin Li bool EndsAfter) const {
5013*67e74705SXin Li if (SourceMgr.isLocalSourceLocation(Loc))
5014*67e74705SXin Li return getTotalNumPreprocessedEntities();
5015*67e74705SXin Li
5016*67e74705SXin Li GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5017*67e74705SXin Li SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
5018*67e74705SXin Li assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5019*67e74705SXin Li "Corrupted global sloc offset map");
5020*67e74705SXin Li
5021*67e74705SXin Li if (SLocMapI->second->NumPreprocessedEntities == 0)
5022*67e74705SXin Li return findNextPreprocessedEntity(SLocMapI);
5023*67e74705SXin Li
5024*67e74705SXin Li ModuleFile &M = *SLocMapI->second;
5025*67e74705SXin Li typedef const PPEntityOffset *pp_iterator;
5026*67e74705SXin Li pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5027*67e74705SXin Li pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5028*67e74705SXin Li
5029*67e74705SXin Li size_t Count = M.NumPreprocessedEntities;
5030*67e74705SXin Li size_t Half;
5031*67e74705SXin Li pp_iterator First = pp_begin;
5032*67e74705SXin Li pp_iterator PPI;
5033*67e74705SXin Li
5034*67e74705SXin Li if (EndsAfter) {
5035*67e74705SXin Li PPI = std::upper_bound(pp_begin, pp_end, Loc,
5036*67e74705SXin Li PPEntityComp(*this, M));
5037*67e74705SXin Li } else {
5038*67e74705SXin Li // Do a binary search manually instead of using std::lower_bound because
5039*67e74705SXin Li // The end locations of entities may be unordered (when a macro expansion
5040*67e74705SXin Li // is inside another macro argument), but for this case it is not important
5041*67e74705SXin Li // whether we get the first macro expansion or its containing macro.
5042*67e74705SXin Li while (Count > 0) {
5043*67e74705SXin Li Half = Count / 2;
5044*67e74705SXin Li PPI = First;
5045*67e74705SXin Li std::advance(PPI, Half);
5046*67e74705SXin Li if (SourceMgr.isBeforeInTranslationUnit(
5047*67e74705SXin Li TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
5048*67e74705SXin Li First = PPI;
5049*67e74705SXin Li ++First;
5050*67e74705SXin Li Count = Count - Half - 1;
5051*67e74705SXin Li } else
5052*67e74705SXin Li Count = Half;
5053*67e74705SXin Li }
5054*67e74705SXin Li }
5055*67e74705SXin Li
5056*67e74705SXin Li if (PPI == pp_end)
5057*67e74705SXin Li return findNextPreprocessedEntity(SLocMapI);
5058*67e74705SXin Li
5059*67e74705SXin Li return M.BasePreprocessedEntityID + (PPI - pp_begin);
5060*67e74705SXin Li }
5061*67e74705SXin Li
5062*67e74705SXin Li /// \brief Returns a pair of [Begin, End) indices of preallocated
5063*67e74705SXin Li /// preprocessed entities that \arg Range encompasses.
5064*67e74705SXin Li std::pair<unsigned, unsigned>
findPreprocessedEntitiesInRange(SourceRange Range)5065*67e74705SXin Li ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5066*67e74705SXin Li if (Range.isInvalid())
5067*67e74705SXin Li return std::make_pair(0,0);
5068*67e74705SXin Li assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5069*67e74705SXin Li
5070*67e74705SXin Li PreprocessedEntityID BeginID =
5071*67e74705SXin Li findPreprocessedEntity(Range.getBegin(), false);
5072*67e74705SXin Li PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
5073*67e74705SXin Li return std::make_pair(BeginID, EndID);
5074*67e74705SXin Li }
5075*67e74705SXin Li
5076*67e74705SXin Li /// \brief Optionally returns true or false if the preallocated preprocessed
5077*67e74705SXin Li /// entity with index \arg Index came from file \arg FID.
isPreprocessedEntityInFileID(unsigned Index,FileID FID)5078*67e74705SXin Li Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
5079*67e74705SXin Li FileID FID) {
5080*67e74705SXin Li if (FID.isInvalid())
5081*67e74705SXin Li return false;
5082*67e74705SXin Li
5083*67e74705SXin Li std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5084*67e74705SXin Li ModuleFile &M = *PPInfo.first;
5085*67e74705SXin Li unsigned LocalIndex = PPInfo.second;
5086*67e74705SXin Li const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5087*67e74705SXin Li
5088*67e74705SXin Li SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
5089*67e74705SXin Li if (Loc.isInvalid())
5090*67e74705SXin Li return false;
5091*67e74705SXin Li
5092*67e74705SXin Li if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5093*67e74705SXin Li return true;
5094*67e74705SXin Li else
5095*67e74705SXin Li return false;
5096*67e74705SXin Li }
5097*67e74705SXin Li
5098*67e74705SXin Li namespace {
5099*67e74705SXin Li /// \brief Visitor used to search for information about a header file.
5100*67e74705SXin Li class HeaderFileInfoVisitor {
5101*67e74705SXin Li const FileEntry *FE;
5102*67e74705SXin Li
5103*67e74705SXin Li Optional<HeaderFileInfo> HFI;
5104*67e74705SXin Li
5105*67e74705SXin Li public:
HeaderFileInfoVisitor(const FileEntry * FE)5106*67e74705SXin Li explicit HeaderFileInfoVisitor(const FileEntry *FE)
5107*67e74705SXin Li : FE(FE) { }
5108*67e74705SXin Li
operator ()(ModuleFile & M)5109*67e74705SXin Li bool operator()(ModuleFile &M) {
5110*67e74705SXin Li HeaderFileInfoLookupTable *Table
5111*67e74705SXin Li = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5112*67e74705SXin Li if (!Table)
5113*67e74705SXin Li return false;
5114*67e74705SXin Li
5115*67e74705SXin Li // Look in the on-disk hash table for an entry for this file name.
5116*67e74705SXin Li HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
5117*67e74705SXin Li if (Pos == Table->end())
5118*67e74705SXin Li return false;
5119*67e74705SXin Li
5120*67e74705SXin Li HFI = *Pos;
5121*67e74705SXin Li return true;
5122*67e74705SXin Li }
5123*67e74705SXin Li
getHeaderFileInfo() const5124*67e74705SXin Li Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
5125*67e74705SXin Li };
5126*67e74705SXin Li }
5127*67e74705SXin Li
GetHeaderFileInfo(const FileEntry * FE)5128*67e74705SXin Li HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
5129*67e74705SXin Li HeaderFileInfoVisitor Visitor(FE);
5130*67e74705SXin Li ModuleMgr.visit(Visitor);
5131*67e74705SXin Li if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
5132*67e74705SXin Li return *HFI;
5133*67e74705SXin Li
5134*67e74705SXin Li return HeaderFileInfo();
5135*67e74705SXin Li }
5136*67e74705SXin Li
ReadPragmaDiagnosticMappings(DiagnosticsEngine & Diag)5137*67e74705SXin Li void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5138*67e74705SXin Li // FIXME: Make it work properly with modules.
5139*67e74705SXin Li SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
5140*67e74705SXin Li for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5141*67e74705SXin Li ModuleFile &F = *(*I);
5142*67e74705SXin Li unsigned Idx = 0;
5143*67e74705SXin Li DiagStates.clear();
5144*67e74705SXin Li assert(!Diag.DiagStates.empty());
5145*67e74705SXin Li DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5146*67e74705SXin Li while (Idx < F.PragmaDiagMappings.size()) {
5147*67e74705SXin Li SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5148*67e74705SXin Li unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5149*67e74705SXin Li if (DiagStateID != 0) {
5150*67e74705SXin Li Diag.DiagStatePoints.push_back(
5151*67e74705SXin Li DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5152*67e74705SXin Li FullSourceLoc(Loc, SourceMgr)));
5153*67e74705SXin Li continue;
5154*67e74705SXin Li }
5155*67e74705SXin Li
5156*67e74705SXin Li assert(DiagStateID == 0);
5157*67e74705SXin Li // A new DiagState was created here.
5158*67e74705SXin Li Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5159*67e74705SXin Li DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5160*67e74705SXin Li DiagStates.push_back(NewState);
5161*67e74705SXin Li Diag.DiagStatePoints.push_back(
5162*67e74705SXin Li DiagnosticsEngine::DiagStatePoint(NewState,
5163*67e74705SXin Li FullSourceLoc(Loc, SourceMgr)));
5164*67e74705SXin Li while (1) {
5165*67e74705SXin Li assert(Idx < F.PragmaDiagMappings.size() &&
5166*67e74705SXin Li "Invalid data, didn't find '-1' marking end of diag/map pairs");
5167*67e74705SXin Li if (Idx >= F.PragmaDiagMappings.size()) {
5168*67e74705SXin Li break; // Something is messed up but at least avoid infinite loop in
5169*67e74705SXin Li // release build.
5170*67e74705SXin Li }
5171*67e74705SXin Li unsigned DiagID = F.PragmaDiagMappings[Idx++];
5172*67e74705SXin Li if (DiagID == (unsigned)-1) {
5173*67e74705SXin Li break; // no more diag/map pairs for this location.
5174*67e74705SXin Li }
5175*67e74705SXin Li diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5176*67e74705SXin Li DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5177*67e74705SXin Li Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
5178*67e74705SXin Li }
5179*67e74705SXin Li }
5180*67e74705SXin Li }
5181*67e74705SXin Li }
5182*67e74705SXin Li
5183*67e74705SXin Li /// \brief Get the correct cursor and offset for loading a type.
TypeCursorForIndex(unsigned Index)5184*67e74705SXin Li ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5185*67e74705SXin Li GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5186*67e74705SXin Li assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5187*67e74705SXin Li ModuleFile *M = I->second;
5188*67e74705SXin Li return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5189*67e74705SXin Li }
5190*67e74705SXin Li
5191*67e74705SXin Li /// \brief Read and return the type with the given index..
5192*67e74705SXin Li ///
5193*67e74705SXin Li /// The index is the type ID, shifted and minus the number of predefs. This
5194*67e74705SXin Li /// routine actually reads the record corresponding to the type at the given
5195*67e74705SXin Li /// location. It is a helper routine for GetType, which deals with reading type
5196*67e74705SXin Li /// IDs.
readTypeRecord(unsigned Index)5197*67e74705SXin Li QualType ASTReader::readTypeRecord(unsigned Index) {
5198*67e74705SXin Li RecordLocation Loc = TypeCursorForIndex(Index);
5199*67e74705SXin Li BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
5200*67e74705SXin Li
5201*67e74705SXin Li // Keep track of where we are in the stream, then jump back there
5202*67e74705SXin Li // after reading this type.
5203*67e74705SXin Li SavedStreamPosition SavedPosition(DeclsCursor);
5204*67e74705SXin Li
5205*67e74705SXin Li ReadingKindTracker ReadingKind(Read_Type, *this);
5206*67e74705SXin Li
5207*67e74705SXin Li // Note that we are loading a type record.
5208*67e74705SXin Li Deserializing AType(this);
5209*67e74705SXin Li
5210*67e74705SXin Li unsigned Idx = 0;
5211*67e74705SXin Li DeclsCursor.JumpToBit(Loc.Offset);
5212*67e74705SXin Li RecordData Record;
5213*67e74705SXin Li unsigned Code = DeclsCursor.ReadCode();
5214*67e74705SXin Li switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
5215*67e74705SXin Li case TYPE_EXT_QUAL: {
5216*67e74705SXin Li if (Record.size() != 2) {
5217*67e74705SXin Li Error("Incorrect encoding of extended qualifier type");
5218*67e74705SXin Li return QualType();
5219*67e74705SXin Li }
5220*67e74705SXin Li QualType Base = readType(*Loc.F, Record, Idx);
5221*67e74705SXin Li Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5222*67e74705SXin Li return Context.getQualifiedType(Base, Quals);
5223*67e74705SXin Li }
5224*67e74705SXin Li
5225*67e74705SXin Li case TYPE_COMPLEX: {
5226*67e74705SXin Li if (Record.size() != 1) {
5227*67e74705SXin Li Error("Incorrect encoding of complex type");
5228*67e74705SXin Li return QualType();
5229*67e74705SXin Li }
5230*67e74705SXin Li QualType ElemType = readType(*Loc.F, Record, Idx);
5231*67e74705SXin Li return Context.getComplexType(ElemType);
5232*67e74705SXin Li }
5233*67e74705SXin Li
5234*67e74705SXin Li case TYPE_POINTER: {
5235*67e74705SXin Li if (Record.size() != 1) {
5236*67e74705SXin Li Error("Incorrect encoding of pointer type");
5237*67e74705SXin Li return QualType();
5238*67e74705SXin Li }
5239*67e74705SXin Li QualType PointeeType = readType(*Loc.F, Record, Idx);
5240*67e74705SXin Li return Context.getPointerType(PointeeType);
5241*67e74705SXin Li }
5242*67e74705SXin Li
5243*67e74705SXin Li case TYPE_DECAYED: {
5244*67e74705SXin Li if (Record.size() != 1) {
5245*67e74705SXin Li Error("Incorrect encoding of decayed type");
5246*67e74705SXin Li return QualType();
5247*67e74705SXin Li }
5248*67e74705SXin Li QualType OriginalType = readType(*Loc.F, Record, Idx);
5249*67e74705SXin Li QualType DT = Context.getAdjustedParameterType(OriginalType);
5250*67e74705SXin Li if (!isa<DecayedType>(DT))
5251*67e74705SXin Li Error("Decayed type does not decay");
5252*67e74705SXin Li return DT;
5253*67e74705SXin Li }
5254*67e74705SXin Li
5255*67e74705SXin Li case TYPE_ADJUSTED: {
5256*67e74705SXin Li if (Record.size() != 2) {
5257*67e74705SXin Li Error("Incorrect encoding of adjusted type");
5258*67e74705SXin Li return QualType();
5259*67e74705SXin Li }
5260*67e74705SXin Li QualType OriginalTy = readType(*Loc.F, Record, Idx);
5261*67e74705SXin Li QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5262*67e74705SXin Li return Context.getAdjustedType(OriginalTy, AdjustedTy);
5263*67e74705SXin Li }
5264*67e74705SXin Li
5265*67e74705SXin Li case TYPE_BLOCK_POINTER: {
5266*67e74705SXin Li if (Record.size() != 1) {
5267*67e74705SXin Li Error("Incorrect encoding of block pointer type");
5268*67e74705SXin Li return QualType();
5269*67e74705SXin Li }
5270*67e74705SXin Li QualType PointeeType = readType(*Loc.F, Record, Idx);
5271*67e74705SXin Li return Context.getBlockPointerType(PointeeType);
5272*67e74705SXin Li }
5273*67e74705SXin Li
5274*67e74705SXin Li case TYPE_LVALUE_REFERENCE: {
5275*67e74705SXin Li if (Record.size() != 2) {
5276*67e74705SXin Li Error("Incorrect encoding of lvalue reference type");
5277*67e74705SXin Li return QualType();
5278*67e74705SXin Li }
5279*67e74705SXin Li QualType PointeeType = readType(*Loc.F, Record, Idx);
5280*67e74705SXin Li return Context.getLValueReferenceType(PointeeType, Record[1]);
5281*67e74705SXin Li }
5282*67e74705SXin Li
5283*67e74705SXin Li case TYPE_RVALUE_REFERENCE: {
5284*67e74705SXin Li if (Record.size() != 1) {
5285*67e74705SXin Li Error("Incorrect encoding of rvalue reference type");
5286*67e74705SXin Li return QualType();
5287*67e74705SXin Li }
5288*67e74705SXin Li QualType PointeeType = readType(*Loc.F, Record, Idx);
5289*67e74705SXin Li return Context.getRValueReferenceType(PointeeType);
5290*67e74705SXin Li }
5291*67e74705SXin Li
5292*67e74705SXin Li case TYPE_MEMBER_POINTER: {
5293*67e74705SXin Li if (Record.size() != 2) {
5294*67e74705SXin Li Error("Incorrect encoding of member pointer type");
5295*67e74705SXin Li return QualType();
5296*67e74705SXin Li }
5297*67e74705SXin Li QualType PointeeType = readType(*Loc.F, Record, Idx);
5298*67e74705SXin Li QualType ClassType = readType(*Loc.F, Record, Idx);
5299*67e74705SXin Li if (PointeeType.isNull() || ClassType.isNull())
5300*67e74705SXin Li return QualType();
5301*67e74705SXin Li
5302*67e74705SXin Li return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5303*67e74705SXin Li }
5304*67e74705SXin Li
5305*67e74705SXin Li case TYPE_CONSTANT_ARRAY: {
5306*67e74705SXin Li QualType ElementType = readType(*Loc.F, Record, Idx);
5307*67e74705SXin Li ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5308*67e74705SXin Li unsigned IndexTypeQuals = Record[2];
5309*67e74705SXin Li unsigned Idx = 3;
5310*67e74705SXin Li llvm::APInt Size = ReadAPInt(Record, Idx);
5311*67e74705SXin Li return Context.getConstantArrayType(ElementType, Size,
5312*67e74705SXin Li ASM, IndexTypeQuals);
5313*67e74705SXin Li }
5314*67e74705SXin Li
5315*67e74705SXin Li case TYPE_INCOMPLETE_ARRAY: {
5316*67e74705SXin Li QualType ElementType = readType(*Loc.F, Record, Idx);
5317*67e74705SXin Li ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5318*67e74705SXin Li unsigned IndexTypeQuals = Record[2];
5319*67e74705SXin Li return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5320*67e74705SXin Li }
5321*67e74705SXin Li
5322*67e74705SXin Li case TYPE_VARIABLE_ARRAY: {
5323*67e74705SXin Li QualType ElementType = readType(*Loc.F, Record, Idx);
5324*67e74705SXin Li ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5325*67e74705SXin Li unsigned IndexTypeQuals = Record[2];
5326*67e74705SXin Li SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5327*67e74705SXin Li SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5328*67e74705SXin Li return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5329*67e74705SXin Li ASM, IndexTypeQuals,
5330*67e74705SXin Li SourceRange(LBLoc, RBLoc));
5331*67e74705SXin Li }
5332*67e74705SXin Li
5333*67e74705SXin Li case TYPE_VECTOR: {
5334*67e74705SXin Li if (Record.size() != 3) {
5335*67e74705SXin Li Error("incorrect encoding of vector type in AST file");
5336*67e74705SXin Li return QualType();
5337*67e74705SXin Li }
5338*67e74705SXin Li
5339*67e74705SXin Li QualType ElementType = readType(*Loc.F, Record, Idx);
5340*67e74705SXin Li unsigned NumElements = Record[1];
5341*67e74705SXin Li unsigned VecKind = Record[2];
5342*67e74705SXin Li return Context.getVectorType(ElementType, NumElements,
5343*67e74705SXin Li (VectorType::VectorKind)VecKind);
5344*67e74705SXin Li }
5345*67e74705SXin Li
5346*67e74705SXin Li case TYPE_EXT_VECTOR: {
5347*67e74705SXin Li if (Record.size() != 3) {
5348*67e74705SXin Li Error("incorrect encoding of extended vector type in AST file");
5349*67e74705SXin Li return QualType();
5350*67e74705SXin Li }
5351*67e74705SXin Li
5352*67e74705SXin Li QualType ElementType = readType(*Loc.F, Record, Idx);
5353*67e74705SXin Li unsigned NumElements = Record[1];
5354*67e74705SXin Li return Context.getExtVectorType(ElementType, NumElements);
5355*67e74705SXin Li }
5356*67e74705SXin Li
5357*67e74705SXin Li case TYPE_FUNCTION_NO_PROTO: {
5358*67e74705SXin Li if (Record.size() != 6) {
5359*67e74705SXin Li Error("incorrect encoding of no-proto function type");
5360*67e74705SXin Li return QualType();
5361*67e74705SXin Li }
5362*67e74705SXin Li QualType ResultType = readType(*Loc.F, Record, Idx);
5363*67e74705SXin Li FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5364*67e74705SXin Li (CallingConv)Record[4], Record[5]);
5365*67e74705SXin Li return Context.getFunctionNoProtoType(ResultType, Info);
5366*67e74705SXin Li }
5367*67e74705SXin Li
5368*67e74705SXin Li case TYPE_FUNCTION_PROTO: {
5369*67e74705SXin Li QualType ResultType = readType(*Loc.F, Record, Idx);
5370*67e74705SXin Li
5371*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI;
5372*67e74705SXin Li EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5373*67e74705SXin Li /*hasregparm*/ Record[2],
5374*67e74705SXin Li /*regparm*/ Record[3],
5375*67e74705SXin Li static_cast<CallingConv>(Record[4]),
5376*67e74705SXin Li /*produces*/ Record[5]);
5377*67e74705SXin Li
5378*67e74705SXin Li unsigned Idx = 6;
5379*67e74705SXin Li
5380*67e74705SXin Li EPI.Variadic = Record[Idx++];
5381*67e74705SXin Li EPI.HasTrailingReturn = Record[Idx++];
5382*67e74705SXin Li EPI.TypeQuals = Record[Idx++];
5383*67e74705SXin Li EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
5384*67e74705SXin Li SmallVector<QualType, 8> ExceptionStorage;
5385*67e74705SXin Li readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
5386*67e74705SXin Li
5387*67e74705SXin Li unsigned NumParams = Record[Idx++];
5388*67e74705SXin Li SmallVector<QualType, 16> ParamTypes;
5389*67e74705SXin Li for (unsigned I = 0; I != NumParams; ++I)
5390*67e74705SXin Li ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5391*67e74705SXin Li
5392*67e74705SXin Li SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5393*67e74705SXin Li if (Idx != Record.size()) {
5394*67e74705SXin Li for (unsigned I = 0; I != NumParams; ++I)
5395*67e74705SXin Li ExtParameterInfos.push_back(
5396*67e74705SXin Li FunctionProtoType::ExtParameterInfo
5397*67e74705SXin Li ::getFromOpaqueValue(Record[Idx++]));
5398*67e74705SXin Li EPI.ExtParameterInfos = ExtParameterInfos.data();
5399*67e74705SXin Li }
5400*67e74705SXin Li
5401*67e74705SXin Li assert(Idx == Record.size());
5402*67e74705SXin Li
5403*67e74705SXin Li return Context.getFunctionType(ResultType, ParamTypes, EPI);
5404*67e74705SXin Li }
5405*67e74705SXin Li
5406*67e74705SXin Li case TYPE_UNRESOLVED_USING: {
5407*67e74705SXin Li unsigned Idx = 0;
5408*67e74705SXin Li return Context.getTypeDeclType(
5409*67e74705SXin Li ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5410*67e74705SXin Li }
5411*67e74705SXin Li
5412*67e74705SXin Li case TYPE_TYPEDEF: {
5413*67e74705SXin Li if (Record.size() != 2) {
5414*67e74705SXin Li Error("incorrect encoding of typedef type");
5415*67e74705SXin Li return QualType();
5416*67e74705SXin Li }
5417*67e74705SXin Li unsigned Idx = 0;
5418*67e74705SXin Li TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5419*67e74705SXin Li QualType Canonical = readType(*Loc.F, Record, Idx);
5420*67e74705SXin Li if (!Canonical.isNull())
5421*67e74705SXin Li Canonical = Context.getCanonicalType(Canonical);
5422*67e74705SXin Li return Context.getTypedefType(Decl, Canonical);
5423*67e74705SXin Li }
5424*67e74705SXin Li
5425*67e74705SXin Li case TYPE_TYPEOF_EXPR:
5426*67e74705SXin Li return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5427*67e74705SXin Li
5428*67e74705SXin Li case TYPE_TYPEOF: {
5429*67e74705SXin Li if (Record.size() != 1) {
5430*67e74705SXin Li Error("incorrect encoding of typeof(type) in AST file");
5431*67e74705SXin Li return QualType();
5432*67e74705SXin Li }
5433*67e74705SXin Li QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5434*67e74705SXin Li return Context.getTypeOfType(UnderlyingType);
5435*67e74705SXin Li }
5436*67e74705SXin Li
5437*67e74705SXin Li case TYPE_DECLTYPE: {
5438*67e74705SXin Li QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5439*67e74705SXin Li return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5440*67e74705SXin Li }
5441*67e74705SXin Li
5442*67e74705SXin Li case TYPE_UNARY_TRANSFORM: {
5443*67e74705SXin Li QualType BaseType = readType(*Loc.F, Record, Idx);
5444*67e74705SXin Li QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5445*67e74705SXin Li UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5446*67e74705SXin Li return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5447*67e74705SXin Li }
5448*67e74705SXin Li
5449*67e74705SXin Li case TYPE_AUTO: {
5450*67e74705SXin Li QualType Deduced = readType(*Loc.F, Record, Idx);
5451*67e74705SXin Li AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
5452*67e74705SXin Li bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5453*67e74705SXin Li return Context.getAutoType(Deduced, Keyword, IsDependent);
5454*67e74705SXin Li }
5455*67e74705SXin Li
5456*67e74705SXin Li case TYPE_RECORD: {
5457*67e74705SXin Li if (Record.size() != 2) {
5458*67e74705SXin Li Error("incorrect encoding of record type");
5459*67e74705SXin Li return QualType();
5460*67e74705SXin Li }
5461*67e74705SXin Li unsigned Idx = 0;
5462*67e74705SXin Li bool IsDependent = Record[Idx++];
5463*67e74705SXin Li RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5464*67e74705SXin Li RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5465*67e74705SXin Li QualType T = Context.getRecordType(RD);
5466*67e74705SXin Li const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5467*67e74705SXin Li return T;
5468*67e74705SXin Li }
5469*67e74705SXin Li
5470*67e74705SXin Li case TYPE_ENUM: {
5471*67e74705SXin Li if (Record.size() != 2) {
5472*67e74705SXin Li Error("incorrect encoding of enum type");
5473*67e74705SXin Li return QualType();
5474*67e74705SXin Li }
5475*67e74705SXin Li unsigned Idx = 0;
5476*67e74705SXin Li bool IsDependent = Record[Idx++];
5477*67e74705SXin Li QualType T
5478*67e74705SXin Li = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5479*67e74705SXin Li const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5480*67e74705SXin Li return T;
5481*67e74705SXin Li }
5482*67e74705SXin Li
5483*67e74705SXin Li case TYPE_ATTRIBUTED: {
5484*67e74705SXin Li if (Record.size() != 3) {
5485*67e74705SXin Li Error("incorrect encoding of attributed type");
5486*67e74705SXin Li return QualType();
5487*67e74705SXin Li }
5488*67e74705SXin Li QualType modifiedType = readType(*Loc.F, Record, Idx);
5489*67e74705SXin Li QualType equivalentType = readType(*Loc.F, Record, Idx);
5490*67e74705SXin Li AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5491*67e74705SXin Li return Context.getAttributedType(kind, modifiedType, equivalentType);
5492*67e74705SXin Li }
5493*67e74705SXin Li
5494*67e74705SXin Li case TYPE_PAREN: {
5495*67e74705SXin Li if (Record.size() != 1) {
5496*67e74705SXin Li Error("incorrect encoding of paren type");
5497*67e74705SXin Li return QualType();
5498*67e74705SXin Li }
5499*67e74705SXin Li QualType InnerType = readType(*Loc.F, Record, Idx);
5500*67e74705SXin Li return Context.getParenType(InnerType);
5501*67e74705SXin Li }
5502*67e74705SXin Li
5503*67e74705SXin Li case TYPE_PACK_EXPANSION: {
5504*67e74705SXin Li if (Record.size() != 2) {
5505*67e74705SXin Li Error("incorrect encoding of pack expansion type");
5506*67e74705SXin Li return QualType();
5507*67e74705SXin Li }
5508*67e74705SXin Li QualType Pattern = readType(*Loc.F, Record, Idx);
5509*67e74705SXin Li if (Pattern.isNull())
5510*67e74705SXin Li return QualType();
5511*67e74705SXin Li Optional<unsigned> NumExpansions;
5512*67e74705SXin Li if (Record[1])
5513*67e74705SXin Li NumExpansions = Record[1] - 1;
5514*67e74705SXin Li return Context.getPackExpansionType(Pattern, NumExpansions);
5515*67e74705SXin Li }
5516*67e74705SXin Li
5517*67e74705SXin Li case TYPE_ELABORATED: {
5518*67e74705SXin Li unsigned Idx = 0;
5519*67e74705SXin Li ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5520*67e74705SXin Li NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5521*67e74705SXin Li QualType NamedType = readType(*Loc.F, Record, Idx);
5522*67e74705SXin Li return Context.getElaboratedType(Keyword, NNS, NamedType);
5523*67e74705SXin Li }
5524*67e74705SXin Li
5525*67e74705SXin Li case TYPE_OBJC_INTERFACE: {
5526*67e74705SXin Li unsigned Idx = 0;
5527*67e74705SXin Li ObjCInterfaceDecl *ItfD
5528*67e74705SXin Li = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5529*67e74705SXin Li return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5530*67e74705SXin Li }
5531*67e74705SXin Li
5532*67e74705SXin Li case TYPE_OBJC_OBJECT: {
5533*67e74705SXin Li unsigned Idx = 0;
5534*67e74705SXin Li QualType Base = readType(*Loc.F, Record, Idx);
5535*67e74705SXin Li unsigned NumTypeArgs = Record[Idx++];
5536*67e74705SXin Li SmallVector<QualType, 4> TypeArgs;
5537*67e74705SXin Li for (unsigned I = 0; I != NumTypeArgs; ++I)
5538*67e74705SXin Li TypeArgs.push_back(readType(*Loc.F, Record, Idx));
5539*67e74705SXin Li unsigned NumProtos = Record[Idx++];
5540*67e74705SXin Li SmallVector<ObjCProtocolDecl*, 4> Protos;
5541*67e74705SXin Li for (unsigned I = 0; I != NumProtos; ++I)
5542*67e74705SXin Li Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5543*67e74705SXin Li bool IsKindOf = Record[Idx++];
5544*67e74705SXin Li return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
5545*67e74705SXin Li }
5546*67e74705SXin Li
5547*67e74705SXin Li case TYPE_OBJC_OBJECT_POINTER: {
5548*67e74705SXin Li unsigned Idx = 0;
5549*67e74705SXin Li QualType Pointee = readType(*Loc.F, Record, Idx);
5550*67e74705SXin Li return Context.getObjCObjectPointerType(Pointee);
5551*67e74705SXin Li }
5552*67e74705SXin Li
5553*67e74705SXin Li case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5554*67e74705SXin Li unsigned Idx = 0;
5555*67e74705SXin Li QualType Parm = readType(*Loc.F, Record, Idx);
5556*67e74705SXin Li QualType Replacement = readType(*Loc.F, Record, Idx);
5557*67e74705SXin Li return Context.getSubstTemplateTypeParmType(
5558*67e74705SXin Li cast<TemplateTypeParmType>(Parm),
5559*67e74705SXin Li Context.getCanonicalType(Replacement));
5560*67e74705SXin Li }
5561*67e74705SXin Li
5562*67e74705SXin Li case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5563*67e74705SXin Li unsigned Idx = 0;
5564*67e74705SXin Li QualType Parm = readType(*Loc.F, Record, Idx);
5565*67e74705SXin Li TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5566*67e74705SXin Li return Context.getSubstTemplateTypeParmPackType(
5567*67e74705SXin Li cast<TemplateTypeParmType>(Parm),
5568*67e74705SXin Li ArgPack);
5569*67e74705SXin Li }
5570*67e74705SXin Li
5571*67e74705SXin Li case TYPE_INJECTED_CLASS_NAME: {
5572*67e74705SXin Li CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5573*67e74705SXin Li QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5574*67e74705SXin Li // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5575*67e74705SXin Li // for AST reading, too much interdependencies.
5576*67e74705SXin Li const Type *T = nullptr;
5577*67e74705SXin Li for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5578*67e74705SXin Li if (const Type *Existing = DI->getTypeForDecl()) {
5579*67e74705SXin Li T = Existing;
5580*67e74705SXin Li break;
5581*67e74705SXin Li }
5582*67e74705SXin Li }
5583*67e74705SXin Li if (!T) {
5584*67e74705SXin Li T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5585*67e74705SXin Li for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5586*67e74705SXin Li DI->setTypeForDecl(T);
5587*67e74705SXin Li }
5588*67e74705SXin Li return QualType(T, 0);
5589*67e74705SXin Li }
5590*67e74705SXin Li
5591*67e74705SXin Li case TYPE_TEMPLATE_TYPE_PARM: {
5592*67e74705SXin Li unsigned Idx = 0;
5593*67e74705SXin Li unsigned Depth = Record[Idx++];
5594*67e74705SXin Li unsigned Index = Record[Idx++];
5595*67e74705SXin Li bool Pack = Record[Idx++];
5596*67e74705SXin Li TemplateTypeParmDecl *D
5597*67e74705SXin Li = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5598*67e74705SXin Li return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5599*67e74705SXin Li }
5600*67e74705SXin Li
5601*67e74705SXin Li case TYPE_DEPENDENT_NAME: {
5602*67e74705SXin Li unsigned Idx = 0;
5603*67e74705SXin Li ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5604*67e74705SXin Li NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5605*67e74705SXin Li const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
5606*67e74705SXin Li QualType Canon = readType(*Loc.F, Record, Idx);
5607*67e74705SXin Li if (!Canon.isNull())
5608*67e74705SXin Li Canon = Context.getCanonicalType(Canon);
5609*67e74705SXin Li return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5610*67e74705SXin Li }
5611*67e74705SXin Li
5612*67e74705SXin Li case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5613*67e74705SXin Li unsigned Idx = 0;
5614*67e74705SXin Li ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5615*67e74705SXin Li NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5616*67e74705SXin Li const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
5617*67e74705SXin Li unsigned NumArgs = Record[Idx++];
5618*67e74705SXin Li SmallVector<TemplateArgument, 8> Args;
5619*67e74705SXin Li Args.reserve(NumArgs);
5620*67e74705SXin Li while (NumArgs--)
5621*67e74705SXin Li Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5622*67e74705SXin Li return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5623*67e74705SXin Li Args);
5624*67e74705SXin Li }
5625*67e74705SXin Li
5626*67e74705SXin Li case TYPE_DEPENDENT_SIZED_ARRAY: {
5627*67e74705SXin Li unsigned Idx = 0;
5628*67e74705SXin Li
5629*67e74705SXin Li // ArrayType
5630*67e74705SXin Li QualType ElementType = readType(*Loc.F, Record, Idx);
5631*67e74705SXin Li ArrayType::ArraySizeModifier ASM
5632*67e74705SXin Li = (ArrayType::ArraySizeModifier)Record[Idx++];
5633*67e74705SXin Li unsigned IndexTypeQuals = Record[Idx++];
5634*67e74705SXin Li
5635*67e74705SXin Li // DependentSizedArrayType
5636*67e74705SXin Li Expr *NumElts = ReadExpr(*Loc.F);
5637*67e74705SXin Li SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5638*67e74705SXin Li
5639*67e74705SXin Li return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5640*67e74705SXin Li IndexTypeQuals, Brackets);
5641*67e74705SXin Li }
5642*67e74705SXin Li
5643*67e74705SXin Li case TYPE_TEMPLATE_SPECIALIZATION: {
5644*67e74705SXin Li unsigned Idx = 0;
5645*67e74705SXin Li bool IsDependent = Record[Idx++];
5646*67e74705SXin Li TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5647*67e74705SXin Li SmallVector<TemplateArgument, 8> Args;
5648*67e74705SXin Li ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5649*67e74705SXin Li QualType Underlying = readType(*Loc.F, Record, Idx);
5650*67e74705SXin Li QualType T;
5651*67e74705SXin Li if (Underlying.isNull())
5652*67e74705SXin Li T = Context.getCanonicalTemplateSpecializationType(Name, Args);
5653*67e74705SXin Li else
5654*67e74705SXin Li T = Context.getTemplateSpecializationType(Name, Args, Underlying);
5655*67e74705SXin Li const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5656*67e74705SXin Li return T;
5657*67e74705SXin Li }
5658*67e74705SXin Li
5659*67e74705SXin Li case TYPE_ATOMIC: {
5660*67e74705SXin Li if (Record.size() != 1) {
5661*67e74705SXin Li Error("Incorrect encoding of atomic type");
5662*67e74705SXin Li return QualType();
5663*67e74705SXin Li }
5664*67e74705SXin Li QualType ValueType = readType(*Loc.F, Record, Idx);
5665*67e74705SXin Li return Context.getAtomicType(ValueType);
5666*67e74705SXin Li }
5667*67e74705SXin Li
5668*67e74705SXin Li case TYPE_PIPE: {
5669*67e74705SXin Li if (Record.size() != 1) {
5670*67e74705SXin Li Error("Incorrect encoding of pipe type");
5671*67e74705SXin Li return QualType();
5672*67e74705SXin Li }
5673*67e74705SXin Li
5674*67e74705SXin Li // Reading the pipe element type.
5675*67e74705SXin Li QualType ElementType = readType(*Loc.F, Record, Idx);
5676*67e74705SXin Li return Context.getPipeType(ElementType);
5677*67e74705SXin Li }
5678*67e74705SXin Li }
5679*67e74705SXin Li llvm_unreachable("Invalid TypeCode!");
5680*67e74705SXin Li }
5681*67e74705SXin Li
readExceptionSpec(ModuleFile & ModuleFile,SmallVectorImpl<QualType> & Exceptions,FunctionProtoType::ExceptionSpecInfo & ESI,const RecordData & Record,unsigned & Idx)5682*67e74705SXin Li void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5683*67e74705SXin Li SmallVectorImpl<QualType> &Exceptions,
5684*67e74705SXin Li FunctionProtoType::ExceptionSpecInfo &ESI,
5685*67e74705SXin Li const RecordData &Record, unsigned &Idx) {
5686*67e74705SXin Li ExceptionSpecificationType EST =
5687*67e74705SXin Li static_cast<ExceptionSpecificationType>(Record[Idx++]);
5688*67e74705SXin Li ESI.Type = EST;
5689*67e74705SXin Li if (EST == EST_Dynamic) {
5690*67e74705SXin Li for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
5691*67e74705SXin Li Exceptions.push_back(readType(ModuleFile, Record, Idx));
5692*67e74705SXin Li ESI.Exceptions = Exceptions;
5693*67e74705SXin Li } else if (EST == EST_ComputedNoexcept) {
5694*67e74705SXin Li ESI.NoexceptExpr = ReadExpr(ModuleFile);
5695*67e74705SXin Li } else if (EST == EST_Uninstantiated) {
5696*67e74705SXin Li ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5697*67e74705SXin Li ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5698*67e74705SXin Li } else if (EST == EST_Unevaluated) {
5699*67e74705SXin Li ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5700*67e74705SXin Li }
5701*67e74705SXin Li }
5702*67e74705SXin Li
5703*67e74705SXin Li class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5704*67e74705SXin Li ASTReader &Reader;
5705*67e74705SXin Li ModuleFile &F;
5706*67e74705SXin Li const ASTReader::RecordData &Record;
5707*67e74705SXin Li unsigned &Idx;
5708*67e74705SXin Li
ReadSourceLocation(const ASTReader::RecordData & R,unsigned & I)5709*67e74705SXin Li SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5710*67e74705SXin Li unsigned &I) {
5711*67e74705SXin Li return Reader.ReadSourceLocation(F, R, I);
5712*67e74705SXin Li }
5713*67e74705SXin Li
5714*67e74705SXin Li template<typename T>
ReadDeclAs(const ASTReader::RecordData & Record,unsigned & Idx)5715*67e74705SXin Li T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5716*67e74705SXin Li return Reader.ReadDeclAs<T>(F, Record, Idx);
5717*67e74705SXin Li }
5718*67e74705SXin Li
5719*67e74705SXin Li public:
TypeLocReader(ASTReader & Reader,ModuleFile & F,const ASTReader::RecordData & Record,unsigned & Idx)5720*67e74705SXin Li TypeLocReader(ASTReader &Reader, ModuleFile &F,
5721*67e74705SXin Li const ASTReader::RecordData &Record, unsigned &Idx)
5722*67e74705SXin Li : Reader(Reader), F(F), Record(Record), Idx(Idx)
5723*67e74705SXin Li { }
5724*67e74705SXin Li
5725*67e74705SXin Li // We want compile-time assurance that we've enumerated all of
5726*67e74705SXin Li // these, so unfortunately we have to declare them first, then
5727*67e74705SXin Li // define them out-of-line.
5728*67e74705SXin Li #define ABSTRACT_TYPELOC(CLASS, PARENT)
5729*67e74705SXin Li #define TYPELOC(CLASS, PARENT) \
5730*67e74705SXin Li void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5731*67e74705SXin Li #include "clang/AST/TypeLocNodes.def"
5732*67e74705SXin Li
5733*67e74705SXin Li void VisitFunctionTypeLoc(FunctionTypeLoc);
5734*67e74705SXin Li void VisitArrayTypeLoc(ArrayTypeLoc);
5735*67e74705SXin Li };
5736*67e74705SXin Li
VisitQualifiedTypeLoc(QualifiedTypeLoc TL)5737*67e74705SXin Li void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5738*67e74705SXin Li // nothing to do
5739*67e74705SXin Li }
VisitBuiltinTypeLoc(BuiltinTypeLoc TL)5740*67e74705SXin Li void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5741*67e74705SXin Li TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5742*67e74705SXin Li if (TL.needsExtraLocalData()) {
5743*67e74705SXin Li TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5744*67e74705SXin Li TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5745*67e74705SXin Li TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5746*67e74705SXin Li TL.setModeAttr(Record[Idx++]);
5747*67e74705SXin Li }
5748*67e74705SXin Li }
VisitComplexTypeLoc(ComplexTypeLoc TL)5749*67e74705SXin Li void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5750*67e74705SXin Li TL.setNameLoc(ReadSourceLocation(Record, Idx));
5751*67e74705SXin Li }
VisitPointerTypeLoc(PointerTypeLoc TL)5752*67e74705SXin Li void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5753*67e74705SXin Li TL.setStarLoc(ReadSourceLocation(Record, Idx));
5754*67e74705SXin Li }
VisitDecayedTypeLoc(DecayedTypeLoc TL)5755*67e74705SXin Li void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5756*67e74705SXin Li // nothing to do
5757*67e74705SXin Li }
VisitAdjustedTypeLoc(AdjustedTypeLoc TL)5758*67e74705SXin Li void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5759*67e74705SXin Li // nothing to do
5760*67e74705SXin Li }
VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL)5761*67e74705SXin Li void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5762*67e74705SXin Li TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5763*67e74705SXin Li }
VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL)5764*67e74705SXin Li void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5765*67e74705SXin Li TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5766*67e74705SXin Li }
VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL)5767*67e74705SXin Li void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5768*67e74705SXin Li TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5769*67e74705SXin Li }
VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL)5770*67e74705SXin Li void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5771*67e74705SXin Li TL.setStarLoc(ReadSourceLocation(Record, Idx));
5772*67e74705SXin Li TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5773*67e74705SXin Li }
VisitArrayTypeLoc(ArrayTypeLoc TL)5774*67e74705SXin Li void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5775*67e74705SXin Li TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5776*67e74705SXin Li TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5777*67e74705SXin Li if (Record[Idx++])
5778*67e74705SXin Li TL.setSizeExpr(Reader.ReadExpr(F));
5779*67e74705SXin Li else
5780*67e74705SXin Li TL.setSizeExpr(nullptr);
5781*67e74705SXin Li }
VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL)5782*67e74705SXin Li void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5783*67e74705SXin Li VisitArrayTypeLoc(TL);
5784*67e74705SXin Li }
VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL)5785*67e74705SXin Li void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5786*67e74705SXin Li VisitArrayTypeLoc(TL);
5787*67e74705SXin Li }
VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL)5788*67e74705SXin Li void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5789*67e74705SXin Li VisitArrayTypeLoc(TL);
5790*67e74705SXin Li }
VisitDependentSizedArrayTypeLoc(DependentSizedArrayTypeLoc TL)5791*67e74705SXin Li void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5792*67e74705SXin Li DependentSizedArrayTypeLoc TL) {
5793*67e74705SXin Li VisitArrayTypeLoc(TL);
5794*67e74705SXin Li }
VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL)5795*67e74705SXin Li void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5796*67e74705SXin Li DependentSizedExtVectorTypeLoc TL) {
5797*67e74705SXin Li TL.setNameLoc(ReadSourceLocation(Record, Idx));
5798*67e74705SXin Li }
VisitVectorTypeLoc(VectorTypeLoc TL)5799*67e74705SXin Li void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5800*67e74705SXin Li TL.setNameLoc(ReadSourceLocation(Record, Idx));
5801*67e74705SXin Li }
VisitExtVectorTypeLoc(ExtVectorTypeLoc TL)5802*67e74705SXin Li void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5803*67e74705SXin Li TL.setNameLoc(ReadSourceLocation(Record, Idx));
5804*67e74705SXin Li }
VisitFunctionTypeLoc(FunctionTypeLoc TL)5805*67e74705SXin Li void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5806*67e74705SXin Li TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5807*67e74705SXin Li TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5808*67e74705SXin Li TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5809*67e74705SXin Li TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
5810*67e74705SXin Li for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5811*67e74705SXin Li TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
5812*67e74705SXin Li }
5813*67e74705SXin Li }
VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL)5814*67e74705SXin Li void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5815*67e74705SXin Li VisitFunctionTypeLoc(TL);
5816*67e74705SXin Li }
VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL)5817*67e74705SXin Li void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5818*67e74705SXin Li VisitFunctionTypeLoc(TL);
5819*67e74705SXin Li }
VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL)5820*67e74705SXin Li void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5821*67e74705SXin Li TL.setNameLoc(ReadSourceLocation(Record, Idx));
5822*67e74705SXin Li }
VisitTypedefTypeLoc(TypedefTypeLoc TL)5823*67e74705SXin Li void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5824*67e74705SXin Li TL.setNameLoc(ReadSourceLocation(Record, Idx));
5825*67e74705SXin Li }
VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL)5826*67e74705SXin Li void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5827*67e74705SXin Li TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5828*67e74705SXin Li TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5829*67e74705SXin Li TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5830*67e74705SXin Li }
VisitTypeOfTypeLoc(TypeOfTypeLoc TL)5831*67e74705SXin Li void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5832*67e74705SXin Li TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5833*67e74705SXin Li TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5834*67e74705SXin Li TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5835*67e74705SXin Li TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5836*67e74705SXin Li }
VisitDecltypeTypeLoc(DecltypeTypeLoc TL)5837*67e74705SXin Li void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5838*67e74705SXin Li TL.setNameLoc(ReadSourceLocation(Record, Idx));
5839*67e74705SXin Li }
VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL)5840*67e74705SXin Li void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5841*67e74705SXin Li TL.setKWLoc(ReadSourceLocation(Record, Idx));
5842*67e74705SXin Li TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5843*67e74705SXin Li TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5844*67e74705SXin Li TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5845*67e74705SXin Li }
VisitAutoTypeLoc(AutoTypeLoc TL)5846*67e74705SXin Li void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5847*67e74705SXin Li TL.setNameLoc(ReadSourceLocation(Record, Idx));
5848*67e74705SXin Li }
VisitRecordTypeLoc(RecordTypeLoc TL)5849*67e74705SXin Li void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5850*67e74705SXin Li TL.setNameLoc(ReadSourceLocation(Record, Idx));
5851*67e74705SXin Li }
VisitEnumTypeLoc(EnumTypeLoc TL)5852*67e74705SXin Li void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5853*67e74705SXin Li TL.setNameLoc(ReadSourceLocation(Record, Idx));
5854*67e74705SXin Li }
VisitAttributedTypeLoc(AttributedTypeLoc TL)5855*67e74705SXin Li void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5856*67e74705SXin Li TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5857*67e74705SXin Li if (TL.hasAttrOperand()) {
5858*67e74705SXin Li SourceRange range;
5859*67e74705SXin Li range.setBegin(ReadSourceLocation(Record, Idx));
5860*67e74705SXin Li range.setEnd(ReadSourceLocation(Record, Idx));
5861*67e74705SXin Li TL.setAttrOperandParensRange(range);
5862*67e74705SXin Li }
5863*67e74705SXin Li if (TL.hasAttrExprOperand()) {
5864*67e74705SXin Li if (Record[Idx++])
5865*67e74705SXin Li TL.setAttrExprOperand(Reader.ReadExpr(F));
5866*67e74705SXin Li else
5867*67e74705SXin Li TL.setAttrExprOperand(nullptr);
5868*67e74705SXin Li } else if (TL.hasAttrEnumOperand())
5869*67e74705SXin Li TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5870*67e74705SXin Li }
VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL)5871*67e74705SXin Li void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5872*67e74705SXin Li TL.setNameLoc(ReadSourceLocation(Record, Idx));
5873*67e74705SXin Li }
VisitSubstTemplateTypeParmTypeLoc(SubstTemplateTypeParmTypeLoc TL)5874*67e74705SXin Li void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5875*67e74705SXin Li SubstTemplateTypeParmTypeLoc TL) {
5876*67e74705SXin Li TL.setNameLoc(ReadSourceLocation(Record, Idx));
5877*67e74705SXin Li }
VisitSubstTemplateTypeParmPackTypeLoc(SubstTemplateTypeParmPackTypeLoc TL)5878*67e74705SXin Li void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5879*67e74705SXin Li SubstTemplateTypeParmPackTypeLoc TL) {
5880*67e74705SXin Li TL.setNameLoc(ReadSourceLocation(Record, Idx));
5881*67e74705SXin Li }
VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL)5882*67e74705SXin Li void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5883*67e74705SXin Li TemplateSpecializationTypeLoc TL) {
5884*67e74705SXin Li TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5885*67e74705SXin Li TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5886*67e74705SXin Li TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5887*67e74705SXin Li TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5888*67e74705SXin Li for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5889*67e74705SXin Li TL.setArgLocInfo(i,
5890*67e74705SXin Li Reader.GetTemplateArgumentLocInfo(F,
5891*67e74705SXin Li TL.getTypePtr()->getArg(i).getKind(),
5892*67e74705SXin Li Record, Idx));
5893*67e74705SXin Li }
VisitParenTypeLoc(ParenTypeLoc TL)5894*67e74705SXin Li void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5895*67e74705SXin Li TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5896*67e74705SXin Li TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5897*67e74705SXin Li }
VisitElaboratedTypeLoc(ElaboratedTypeLoc TL)5898*67e74705SXin Li void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5899*67e74705SXin Li TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5900*67e74705SXin Li TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5901*67e74705SXin Li }
VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL)5902*67e74705SXin Li void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5903*67e74705SXin Li TL.setNameLoc(ReadSourceLocation(Record, Idx));
5904*67e74705SXin Li }
VisitDependentNameTypeLoc(DependentNameTypeLoc TL)5905*67e74705SXin Li void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5906*67e74705SXin Li TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5907*67e74705SXin Li TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5908*67e74705SXin Li TL.setNameLoc(ReadSourceLocation(Record, Idx));
5909*67e74705SXin Li }
VisitDependentTemplateSpecializationTypeLoc(DependentTemplateSpecializationTypeLoc TL)5910*67e74705SXin Li void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5911*67e74705SXin Li DependentTemplateSpecializationTypeLoc TL) {
5912*67e74705SXin Li TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5913*67e74705SXin Li TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5914*67e74705SXin Li TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5915*67e74705SXin Li TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5916*67e74705SXin Li TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5917*67e74705SXin Li TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5918*67e74705SXin Li for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5919*67e74705SXin Li TL.setArgLocInfo(I,
5920*67e74705SXin Li Reader.GetTemplateArgumentLocInfo(F,
5921*67e74705SXin Li TL.getTypePtr()->getArg(I).getKind(),
5922*67e74705SXin Li Record, Idx));
5923*67e74705SXin Li }
VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL)5924*67e74705SXin Li void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5925*67e74705SXin Li TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5926*67e74705SXin Li }
VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL)5927*67e74705SXin Li void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5928*67e74705SXin Li TL.setNameLoc(ReadSourceLocation(Record, Idx));
5929*67e74705SXin Li }
VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL)5930*67e74705SXin Li void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5931*67e74705SXin Li TL.setHasBaseTypeAsWritten(Record[Idx++]);
5932*67e74705SXin Li TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5933*67e74705SXin Li TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5934*67e74705SXin Li for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5935*67e74705SXin Li TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5936*67e74705SXin Li TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5937*67e74705SXin Li TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
5938*67e74705SXin Li for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5939*67e74705SXin Li TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5940*67e74705SXin Li }
VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL)5941*67e74705SXin Li void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5942*67e74705SXin Li TL.setStarLoc(ReadSourceLocation(Record, Idx));
5943*67e74705SXin Li }
VisitAtomicTypeLoc(AtomicTypeLoc TL)5944*67e74705SXin Li void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5945*67e74705SXin Li TL.setKWLoc(ReadSourceLocation(Record, Idx));
5946*67e74705SXin Li TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5947*67e74705SXin Li TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5948*67e74705SXin Li }
VisitPipeTypeLoc(PipeTypeLoc TL)5949*67e74705SXin Li void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
5950*67e74705SXin Li TL.setKWLoc(ReadSourceLocation(Record, Idx));
5951*67e74705SXin Li }
5952*67e74705SXin Li
GetTypeSourceInfo(ModuleFile & F,const RecordData & Record,unsigned & Idx)5953*67e74705SXin Li TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5954*67e74705SXin Li const RecordData &Record,
5955*67e74705SXin Li unsigned &Idx) {
5956*67e74705SXin Li QualType InfoTy = readType(F, Record, Idx);
5957*67e74705SXin Li if (InfoTy.isNull())
5958*67e74705SXin Li return nullptr;
5959*67e74705SXin Li
5960*67e74705SXin Li TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5961*67e74705SXin Li TypeLocReader TLR(*this, F, Record, Idx);
5962*67e74705SXin Li for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5963*67e74705SXin Li TLR.Visit(TL);
5964*67e74705SXin Li return TInfo;
5965*67e74705SXin Li }
5966*67e74705SXin Li
GetType(TypeID ID)5967*67e74705SXin Li QualType ASTReader::GetType(TypeID ID) {
5968*67e74705SXin Li unsigned FastQuals = ID & Qualifiers::FastMask;
5969*67e74705SXin Li unsigned Index = ID >> Qualifiers::FastWidth;
5970*67e74705SXin Li
5971*67e74705SXin Li if (Index < NUM_PREDEF_TYPE_IDS) {
5972*67e74705SXin Li QualType T;
5973*67e74705SXin Li switch ((PredefinedTypeIDs)Index) {
5974*67e74705SXin Li case PREDEF_TYPE_NULL_ID:
5975*67e74705SXin Li return QualType();
5976*67e74705SXin Li case PREDEF_TYPE_VOID_ID:
5977*67e74705SXin Li T = Context.VoidTy;
5978*67e74705SXin Li break;
5979*67e74705SXin Li case PREDEF_TYPE_BOOL_ID:
5980*67e74705SXin Li T = Context.BoolTy;
5981*67e74705SXin Li break;
5982*67e74705SXin Li
5983*67e74705SXin Li case PREDEF_TYPE_CHAR_U_ID:
5984*67e74705SXin Li case PREDEF_TYPE_CHAR_S_ID:
5985*67e74705SXin Li // FIXME: Check that the signedness of CharTy is correct!
5986*67e74705SXin Li T = Context.CharTy;
5987*67e74705SXin Li break;
5988*67e74705SXin Li
5989*67e74705SXin Li case PREDEF_TYPE_UCHAR_ID:
5990*67e74705SXin Li T = Context.UnsignedCharTy;
5991*67e74705SXin Li break;
5992*67e74705SXin Li case PREDEF_TYPE_USHORT_ID:
5993*67e74705SXin Li T = Context.UnsignedShortTy;
5994*67e74705SXin Li break;
5995*67e74705SXin Li case PREDEF_TYPE_UINT_ID:
5996*67e74705SXin Li T = Context.UnsignedIntTy;
5997*67e74705SXin Li break;
5998*67e74705SXin Li case PREDEF_TYPE_ULONG_ID:
5999*67e74705SXin Li T = Context.UnsignedLongTy;
6000*67e74705SXin Li break;
6001*67e74705SXin Li case PREDEF_TYPE_ULONGLONG_ID:
6002*67e74705SXin Li T = Context.UnsignedLongLongTy;
6003*67e74705SXin Li break;
6004*67e74705SXin Li case PREDEF_TYPE_UINT128_ID:
6005*67e74705SXin Li T = Context.UnsignedInt128Ty;
6006*67e74705SXin Li break;
6007*67e74705SXin Li case PREDEF_TYPE_SCHAR_ID:
6008*67e74705SXin Li T = Context.SignedCharTy;
6009*67e74705SXin Li break;
6010*67e74705SXin Li case PREDEF_TYPE_WCHAR_ID:
6011*67e74705SXin Li T = Context.WCharTy;
6012*67e74705SXin Li break;
6013*67e74705SXin Li case PREDEF_TYPE_SHORT_ID:
6014*67e74705SXin Li T = Context.ShortTy;
6015*67e74705SXin Li break;
6016*67e74705SXin Li case PREDEF_TYPE_INT_ID:
6017*67e74705SXin Li T = Context.IntTy;
6018*67e74705SXin Li break;
6019*67e74705SXin Li case PREDEF_TYPE_LONG_ID:
6020*67e74705SXin Li T = Context.LongTy;
6021*67e74705SXin Li break;
6022*67e74705SXin Li case PREDEF_TYPE_LONGLONG_ID:
6023*67e74705SXin Li T = Context.LongLongTy;
6024*67e74705SXin Li break;
6025*67e74705SXin Li case PREDEF_TYPE_INT128_ID:
6026*67e74705SXin Li T = Context.Int128Ty;
6027*67e74705SXin Li break;
6028*67e74705SXin Li case PREDEF_TYPE_HALF_ID:
6029*67e74705SXin Li T = Context.HalfTy;
6030*67e74705SXin Li break;
6031*67e74705SXin Li case PREDEF_TYPE_FLOAT_ID:
6032*67e74705SXin Li T = Context.FloatTy;
6033*67e74705SXin Li break;
6034*67e74705SXin Li case PREDEF_TYPE_DOUBLE_ID:
6035*67e74705SXin Li T = Context.DoubleTy;
6036*67e74705SXin Li break;
6037*67e74705SXin Li case PREDEF_TYPE_LONGDOUBLE_ID:
6038*67e74705SXin Li T = Context.LongDoubleTy;
6039*67e74705SXin Li break;
6040*67e74705SXin Li case PREDEF_TYPE_FLOAT128_ID:
6041*67e74705SXin Li T = Context.Float128Ty;
6042*67e74705SXin Li break;
6043*67e74705SXin Li case PREDEF_TYPE_OVERLOAD_ID:
6044*67e74705SXin Li T = Context.OverloadTy;
6045*67e74705SXin Li break;
6046*67e74705SXin Li case PREDEF_TYPE_BOUND_MEMBER:
6047*67e74705SXin Li T = Context.BoundMemberTy;
6048*67e74705SXin Li break;
6049*67e74705SXin Li case PREDEF_TYPE_PSEUDO_OBJECT:
6050*67e74705SXin Li T = Context.PseudoObjectTy;
6051*67e74705SXin Li break;
6052*67e74705SXin Li case PREDEF_TYPE_DEPENDENT_ID:
6053*67e74705SXin Li T = Context.DependentTy;
6054*67e74705SXin Li break;
6055*67e74705SXin Li case PREDEF_TYPE_UNKNOWN_ANY:
6056*67e74705SXin Li T = Context.UnknownAnyTy;
6057*67e74705SXin Li break;
6058*67e74705SXin Li case PREDEF_TYPE_NULLPTR_ID:
6059*67e74705SXin Li T = Context.NullPtrTy;
6060*67e74705SXin Li break;
6061*67e74705SXin Li case PREDEF_TYPE_CHAR16_ID:
6062*67e74705SXin Li T = Context.Char16Ty;
6063*67e74705SXin Li break;
6064*67e74705SXin Li case PREDEF_TYPE_CHAR32_ID:
6065*67e74705SXin Li T = Context.Char32Ty;
6066*67e74705SXin Li break;
6067*67e74705SXin Li case PREDEF_TYPE_OBJC_ID:
6068*67e74705SXin Li T = Context.ObjCBuiltinIdTy;
6069*67e74705SXin Li break;
6070*67e74705SXin Li case PREDEF_TYPE_OBJC_CLASS:
6071*67e74705SXin Li T = Context.ObjCBuiltinClassTy;
6072*67e74705SXin Li break;
6073*67e74705SXin Li case PREDEF_TYPE_OBJC_SEL:
6074*67e74705SXin Li T = Context.ObjCBuiltinSelTy;
6075*67e74705SXin Li break;
6076*67e74705SXin Li #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6077*67e74705SXin Li case PREDEF_TYPE_##Id##_ID: \
6078*67e74705SXin Li T = Context.SingletonId; \
6079*67e74705SXin Li break;
6080*67e74705SXin Li #include "clang/Basic/OpenCLImageTypes.def"
6081*67e74705SXin Li case PREDEF_TYPE_SAMPLER_ID:
6082*67e74705SXin Li T = Context.OCLSamplerTy;
6083*67e74705SXin Li break;
6084*67e74705SXin Li case PREDEF_TYPE_EVENT_ID:
6085*67e74705SXin Li T = Context.OCLEventTy;
6086*67e74705SXin Li break;
6087*67e74705SXin Li case PREDEF_TYPE_CLK_EVENT_ID:
6088*67e74705SXin Li T = Context.OCLClkEventTy;
6089*67e74705SXin Li break;
6090*67e74705SXin Li case PREDEF_TYPE_QUEUE_ID:
6091*67e74705SXin Li T = Context.OCLQueueTy;
6092*67e74705SXin Li break;
6093*67e74705SXin Li case PREDEF_TYPE_NDRANGE_ID:
6094*67e74705SXin Li T = Context.OCLNDRangeTy;
6095*67e74705SXin Li break;
6096*67e74705SXin Li case PREDEF_TYPE_RESERVE_ID_ID:
6097*67e74705SXin Li T = Context.OCLReserveIDTy;
6098*67e74705SXin Li break;
6099*67e74705SXin Li case PREDEF_TYPE_AUTO_DEDUCT:
6100*67e74705SXin Li T = Context.getAutoDeductType();
6101*67e74705SXin Li break;
6102*67e74705SXin Li
6103*67e74705SXin Li case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6104*67e74705SXin Li T = Context.getAutoRRefDeductType();
6105*67e74705SXin Li break;
6106*67e74705SXin Li
6107*67e74705SXin Li case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6108*67e74705SXin Li T = Context.ARCUnbridgedCastTy;
6109*67e74705SXin Li break;
6110*67e74705SXin Li
6111*67e74705SXin Li case PREDEF_TYPE_BUILTIN_FN:
6112*67e74705SXin Li T = Context.BuiltinFnTy;
6113*67e74705SXin Li break;
6114*67e74705SXin Li
6115*67e74705SXin Li case PREDEF_TYPE_OMP_ARRAY_SECTION:
6116*67e74705SXin Li T = Context.OMPArraySectionTy;
6117*67e74705SXin Li break;
6118*67e74705SXin Li }
6119*67e74705SXin Li
6120*67e74705SXin Li assert(!T.isNull() && "Unknown predefined type");
6121*67e74705SXin Li return T.withFastQualifiers(FastQuals);
6122*67e74705SXin Li }
6123*67e74705SXin Li
6124*67e74705SXin Li Index -= NUM_PREDEF_TYPE_IDS;
6125*67e74705SXin Li assert(Index < TypesLoaded.size() && "Type index out-of-range");
6126*67e74705SXin Li if (TypesLoaded[Index].isNull()) {
6127*67e74705SXin Li TypesLoaded[Index] = readTypeRecord(Index);
6128*67e74705SXin Li if (TypesLoaded[Index].isNull())
6129*67e74705SXin Li return QualType();
6130*67e74705SXin Li
6131*67e74705SXin Li TypesLoaded[Index]->setFromAST();
6132*67e74705SXin Li if (DeserializationListener)
6133*67e74705SXin Li DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6134*67e74705SXin Li TypesLoaded[Index]);
6135*67e74705SXin Li }
6136*67e74705SXin Li
6137*67e74705SXin Li return TypesLoaded[Index].withFastQualifiers(FastQuals);
6138*67e74705SXin Li }
6139*67e74705SXin Li
getLocalType(ModuleFile & F,unsigned LocalID)6140*67e74705SXin Li QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6141*67e74705SXin Li return GetType(getGlobalTypeID(F, LocalID));
6142*67e74705SXin Li }
6143*67e74705SXin Li
6144*67e74705SXin Li serialization::TypeID
getGlobalTypeID(ModuleFile & F,unsigned LocalID) const6145*67e74705SXin Li ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6146*67e74705SXin Li unsigned FastQuals = LocalID & Qualifiers::FastMask;
6147*67e74705SXin Li unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6148*67e74705SXin Li
6149*67e74705SXin Li if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6150*67e74705SXin Li return LocalID;
6151*67e74705SXin Li
6152*67e74705SXin Li ContinuousRangeMap<uint32_t, int, 2>::iterator I
6153*67e74705SXin Li = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6154*67e74705SXin Li assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6155*67e74705SXin Li
6156*67e74705SXin Li unsigned GlobalIndex = LocalIndex + I->second;
6157*67e74705SXin Li return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6158*67e74705SXin Li }
6159*67e74705SXin Li
6160*67e74705SXin Li TemplateArgumentLocInfo
GetTemplateArgumentLocInfo(ModuleFile & F,TemplateArgument::ArgKind Kind,const RecordData & Record,unsigned & Index)6161*67e74705SXin Li ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6162*67e74705SXin Li TemplateArgument::ArgKind Kind,
6163*67e74705SXin Li const RecordData &Record,
6164*67e74705SXin Li unsigned &Index) {
6165*67e74705SXin Li switch (Kind) {
6166*67e74705SXin Li case TemplateArgument::Expression:
6167*67e74705SXin Li return ReadExpr(F);
6168*67e74705SXin Li case TemplateArgument::Type:
6169*67e74705SXin Li return GetTypeSourceInfo(F, Record, Index);
6170*67e74705SXin Li case TemplateArgument::Template: {
6171*67e74705SXin Li NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6172*67e74705SXin Li Index);
6173*67e74705SXin Li SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6174*67e74705SXin Li return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6175*67e74705SXin Li SourceLocation());
6176*67e74705SXin Li }
6177*67e74705SXin Li case TemplateArgument::TemplateExpansion: {
6178*67e74705SXin Li NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6179*67e74705SXin Li Index);
6180*67e74705SXin Li SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6181*67e74705SXin Li SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6182*67e74705SXin Li return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6183*67e74705SXin Li EllipsisLoc);
6184*67e74705SXin Li }
6185*67e74705SXin Li case TemplateArgument::Null:
6186*67e74705SXin Li case TemplateArgument::Integral:
6187*67e74705SXin Li case TemplateArgument::Declaration:
6188*67e74705SXin Li case TemplateArgument::NullPtr:
6189*67e74705SXin Li case TemplateArgument::Pack:
6190*67e74705SXin Li // FIXME: Is this right?
6191*67e74705SXin Li return TemplateArgumentLocInfo();
6192*67e74705SXin Li }
6193*67e74705SXin Li llvm_unreachable("unexpected template argument loc");
6194*67e74705SXin Li }
6195*67e74705SXin Li
6196*67e74705SXin Li TemplateArgumentLoc
ReadTemplateArgumentLoc(ModuleFile & F,const RecordData & Record,unsigned & Index)6197*67e74705SXin Li ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6198*67e74705SXin Li const RecordData &Record, unsigned &Index) {
6199*67e74705SXin Li TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6200*67e74705SXin Li
6201*67e74705SXin Li if (Arg.getKind() == TemplateArgument::Expression) {
6202*67e74705SXin Li if (Record[Index++]) // bool InfoHasSameExpr.
6203*67e74705SXin Li return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6204*67e74705SXin Li }
6205*67e74705SXin Li return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6206*67e74705SXin Li Record, Index));
6207*67e74705SXin Li }
6208*67e74705SXin Li
6209*67e74705SXin Li const ASTTemplateArgumentListInfo*
ReadASTTemplateArgumentListInfo(ModuleFile & F,const RecordData & Record,unsigned & Index)6210*67e74705SXin Li ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6211*67e74705SXin Li const RecordData &Record,
6212*67e74705SXin Li unsigned &Index) {
6213*67e74705SXin Li SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6214*67e74705SXin Li SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6215*67e74705SXin Li unsigned NumArgsAsWritten = Record[Index++];
6216*67e74705SXin Li TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6217*67e74705SXin Li for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6218*67e74705SXin Li TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6219*67e74705SXin Li return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6220*67e74705SXin Li }
6221*67e74705SXin Li
GetExternalDecl(uint32_t ID)6222*67e74705SXin Li Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6223*67e74705SXin Li return GetDecl(ID);
6224*67e74705SXin Li }
6225*67e74705SXin Li
6226*67e74705SXin Li template<typename TemplateSpecializationDecl>
completeRedeclChainForTemplateSpecialization(Decl * D)6227*67e74705SXin Li static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6228*67e74705SXin Li if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6229*67e74705SXin Li TSD->getSpecializedTemplate()->LoadLazySpecializations();
6230*67e74705SXin Li }
6231*67e74705SXin Li
CompleteRedeclChain(const Decl * D)6232*67e74705SXin Li void ASTReader::CompleteRedeclChain(const Decl *D) {
6233*67e74705SXin Li if (NumCurrentElementsDeserializing) {
6234*67e74705SXin Li // We arrange to not care about the complete redeclaration chain while we're
6235*67e74705SXin Li // deserializing. Just remember that the AST has marked this one as complete
6236*67e74705SXin Li // but that it's not actually complete yet, so we know we still need to
6237*67e74705SXin Li // complete it later.
6238*67e74705SXin Li PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6239*67e74705SXin Li return;
6240*67e74705SXin Li }
6241*67e74705SXin Li
6242*67e74705SXin Li const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6243*67e74705SXin Li
6244*67e74705SXin Li // If this is a named declaration, complete it by looking it up
6245*67e74705SXin Li // within its context.
6246*67e74705SXin Li //
6247*67e74705SXin Li // FIXME: Merging a function definition should merge
6248*67e74705SXin Li // all mergeable entities within it.
6249*67e74705SXin Li if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6250*67e74705SXin Li isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6251*67e74705SXin Li if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6252*67e74705SXin Li if (!getContext().getLangOpts().CPlusPlus &&
6253*67e74705SXin Li isa<TranslationUnitDecl>(DC)) {
6254*67e74705SXin Li // Outside of C++, we don't have a lookup table for the TU, so update
6255*67e74705SXin Li // the identifier instead. (For C++ modules, we don't store decls
6256*67e74705SXin Li // in the serialized identifier table, so we do the lookup in the TU.)
6257*67e74705SXin Li auto *II = Name.getAsIdentifierInfo();
6258*67e74705SXin Li assert(II && "non-identifier name in C?");
6259*67e74705SXin Li if (II->isOutOfDate())
6260*67e74705SXin Li updateOutOfDateIdentifier(*II);
6261*67e74705SXin Li } else
6262*67e74705SXin Li DC->lookup(Name);
6263*67e74705SXin Li } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6264*67e74705SXin Li // Find all declarations of this kind from the relevant context.
6265*67e74705SXin Li for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6266*67e74705SXin Li auto *DC = cast<DeclContext>(DCDecl);
6267*67e74705SXin Li SmallVector<Decl*, 8> Decls;
6268*67e74705SXin Li FindExternalLexicalDecls(
6269*67e74705SXin Li DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6270*67e74705SXin Li }
6271*67e74705SXin Li }
6272*67e74705SXin Li }
6273*67e74705SXin Li
6274*67e74705SXin Li if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6275*67e74705SXin Li CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6276*67e74705SXin Li if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6277*67e74705SXin Li VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6278*67e74705SXin Li if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6279*67e74705SXin Li if (auto *Template = FD->getPrimaryTemplate())
6280*67e74705SXin Li Template->LoadLazySpecializations();
6281*67e74705SXin Li }
6282*67e74705SXin Li }
6283*67e74705SXin Li
6284*67e74705SXin Li CXXCtorInitializer **
GetExternalCXXCtorInitializers(uint64_t Offset)6285*67e74705SXin Li ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6286*67e74705SXin Li RecordLocation Loc = getLocalBitOffset(Offset);
6287*67e74705SXin Li BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6288*67e74705SXin Li SavedStreamPosition SavedPosition(Cursor);
6289*67e74705SXin Li Cursor.JumpToBit(Loc.Offset);
6290*67e74705SXin Li ReadingKindTracker ReadingKind(Read_Decl, *this);
6291*67e74705SXin Li
6292*67e74705SXin Li RecordData Record;
6293*67e74705SXin Li unsigned Code = Cursor.ReadCode();
6294*67e74705SXin Li unsigned RecCode = Cursor.readRecord(Code, Record);
6295*67e74705SXin Li if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6296*67e74705SXin Li Error("malformed AST file: missing C++ ctor initializers");
6297*67e74705SXin Li return nullptr;
6298*67e74705SXin Li }
6299*67e74705SXin Li
6300*67e74705SXin Li unsigned Idx = 0;
6301*67e74705SXin Li return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6302*67e74705SXin Li }
6303*67e74705SXin Li
GetExternalCXXBaseSpecifiers(uint64_t Offset)6304*67e74705SXin Li CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6305*67e74705SXin Li RecordLocation Loc = getLocalBitOffset(Offset);
6306*67e74705SXin Li BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6307*67e74705SXin Li SavedStreamPosition SavedPosition(Cursor);
6308*67e74705SXin Li Cursor.JumpToBit(Loc.Offset);
6309*67e74705SXin Li ReadingKindTracker ReadingKind(Read_Decl, *this);
6310*67e74705SXin Li RecordData Record;
6311*67e74705SXin Li unsigned Code = Cursor.ReadCode();
6312*67e74705SXin Li unsigned RecCode = Cursor.readRecord(Code, Record);
6313*67e74705SXin Li if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
6314*67e74705SXin Li Error("malformed AST file: missing C++ base specifiers");
6315*67e74705SXin Li return nullptr;
6316*67e74705SXin Li }
6317*67e74705SXin Li
6318*67e74705SXin Li unsigned Idx = 0;
6319*67e74705SXin Li unsigned NumBases = Record[Idx++];
6320*67e74705SXin Li void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6321*67e74705SXin Li CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6322*67e74705SXin Li for (unsigned I = 0; I != NumBases; ++I)
6323*67e74705SXin Li Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6324*67e74705SXin Li return Bases;
6325*67e74705SXin Li }
6326*67e74705SXin Li
6327*67e74705SXin Li serialization::DeclID
getGlobalDeclID(ModuleFile & F,LocalDeclID LocalID) const6328*67e74705SXin Li ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6329*67e74705SXin Li if (LocalID < NUM_PREDEF_DECL_IDS)
6330*67e74705SXin Li return LocalID;
6331*67e74705SXin Li
6332*67e74705SXin Li ContinuousRangeMap<uint32_t, int, 2>::iterator I
6333*67e74705SXin Li = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6334*67e74705SXin Li assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6335*67e74705SXin Li
6336*67e74705SXin Li return LocalID + I->second;
6337*67e74705SXin Li }
6338*67e74705SXin Li
isDeclIDFromModule(serialization::GlobalDeclID ID,ModuleFile & M) const6339*67e74705SXin Li bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6340*67e74705SXin Li ModuleFile &M) const {
6341*67e74705SXin Li // Predefined decls aren't from any module.
6342*67e74705SXin Li if (ID < NUM_PREDEF_DECL_IDS)
6343*67e74705SXin Li return false;
6344*67e74705SXin Li
6345*67e74705SXin Li return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6346*67e74705SXin Li ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
6347*67e74705SXin Li }
6348*67e74705SXin Li
getOwningModuleFile(const Decl * D)6349*67e74705SXin Li ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
6350*67e74705SXin Li if (!D->isFromASTFile())
6351*67e74705SXin Li return nullptr;
6352*67e74705SXin Li GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6353*67e74705SXin Li assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6354*67e74705SXin Li return I->second;
6355*67e74705SXin Li }
6356*67e74705SXin Li
getSourceLocationForDeclID(GlobalDeclID ID)6357*67e74705SXin Li SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6358*67e74705SXin Li if (ID < NUM_PREDEF_DECL_IDS)
6359*67e74705SXin Li return SourceLocation();
6360*67e74705SXin Li
6361*67e74705SXin Li unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6362*67e74705SXin Li
6363*67e74705SXin Li if (Index > DeclsLoaded.size()) {
6364*67e74705SXin Li Error("declaration ID out-of-range for AST file");
6365*67e74705SXin Li return SourceLocation();
6366*67e74705SXin Li }
6367*67e74705SXin Li
6368*67e74705SXin Li if (Decl *D = DeclsLoaded[Index])
6369*67e74705SXin Li return D->getLocation();
6370*67e74705SXin Li
6371*67e74705SXin Li SourceLocation Loc;
6372*67e74705SXin Li DeclCursorForID(ID, Loc);
6373*67e74705SXin Li return Loc;
6374*67e74705SXin Li }
6375*67e74705SXin Li
getPredefinedDecl(ASTContext & Context,PredefinedDeclIDs ID)6376*67e74705SXin Li static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6377*67e74705SXin Li switch (ID) {
6378*67e74705SXin Li case PREDEF_DECL_NULL_ID:
6379*67e74705SXin Li return nullptr;
6380*67e74705SXin Li
6381*67e74705SXin Li case PREDEF_DECL_TRANSLATION_UNIT_ID:
6382*67e74705SXin Li return Context.getTranslationUnitDecl();
6383*67e74705SXin Li
6384*67e74705SXin Li case PREDEF_DECL_OBJC_ID_ID:
6385*67e74705SXin Li return Context.getObjCIdDecl();
6386*67e74705SXin Li
6387*67e74705SXin Li case PREDEF_DECL_OBJC_SEL_ID:
6388*67e74705SXin Li return Context.getObjCSelDecl();
6389*67e74705SXin Li
6390*67e74705SXin Li case PREDEF_DECL_OBJC_CLASS_ID:
6391*67e74705SXin Li return Context.getObjCClassDecl();
6392*67e74705SXin Li
6393*67e74705SXin Li case PREDEF_DECL_OBJC_PROTOCOL_ID:
6394*67e74705SXin Li return Context.getObjCProtocolDecl();
6395*67e74705SXin Li
6396*67e74705SXin Li case PREDEF_DECL_INT_128_ID:
6397*67e74705SXin Li return Context.getInt128Decl();
6398*67e74705SXin Li
6399*67e74705SXin Li case PREDEF_DECL_UNSIGNED_INT_128_ID:
6400*67e74705SXin Li return Context.getUInt128Decl();
6401*67e74705SXin Li
6402*67e74705SXin Li case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6403*67e74705SXin Li return Context.getObjCInstanceTypeDecl();
6404*67e74705SXin Li
6405*67e74705SXin Li case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6406*67e74705SXin Li return Context.getBuiltinVaListDecl();
6407*67e74705SXin Li
6408*67e74705SXin Li case PREDEF_DECL_VA_LIST_TAG:
6409*67e74705SXin Li return Context.getVaListTagDecl();
6410*67e74705SXin Li
6411*67e74705SXin Li case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6412*67e74705SXin Li return Context.getBuiltinMSVaListDecl();
6413*67e74705SXin Li
6414*67e74705SXin Li case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6415*67e74705SXin Li return Context.getExternCContextDecl();
6416*67e74705SXin Li
6417*67e74705SXin Li case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6418*67e74705SXin Li return Context.getMakeIntegerSeqDecl();
6419*67e74705SXin Li
6420*67e74705SXin Li case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6421*67e74705SXin Li return Context.getCFConstantStringDecl();
6422*67e74705SXin Li
6423*67e74705SXin Li case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6424*67e74705SXin Li return Context.getCFConstantStringTagDecl();
6425*67e74705SXin Li
6426*67e74705SXin Li case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6427*67e74705SXin Li return Context.getTypePackElementDecl();
6428*67e74705SXin Li }
6429*67e74705SXin Li llvm_unreachable("PredefinedDeclIDs unknown enum value");
6430*67e74705SXin Li }
6431*67e74705SXin Li
GetExistingDecl(DeclID ID)6432*67e74705SXin Li Decl *ASTReader::GetExistingDecl(DeclID ID) {
6433*67e74705SXin Li if (ID < NUM_PREDEF_DECL_IDS) {
6434*67e74705SXin Li Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6435*67e74705SXin Li if (D) {
6436*67e74705SXin Li // Track that we have merged the declaration with ID \p ID into the
6437*67e74705SXin Li // pre-existing predefined declaration \p D.
6438*67e74705SXin Li auto &Merged = KeyDecls[D->getCanonicalDecl()];
6439*67e74705SXin Li if (Merged.empty())
6440*67e74705SXin Li Merged.push_back(ID);
6441*67e74705SXin Li }
6442*67e74705SXin Li return D;
6443*67e74705SXin Li }
6444*67e74705SXin Li
6445*67e74705SXin Li unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6446*67e74705SXin Li
6447*67e74705SXin Li if (Index >= DeclsLoaded.size()) {
6448*67e74705SXin Li assert(0 && "declaration ID out-of-range for AST file");
6449*67e74705SXin Li Error("declaration ID out-of-range for AST file");
6450*67e74705SXin Li return nullptr;
6451*67e74705SXin Li }
6452*67e74705SXin Li
6453*67e74705SXin Li return DeclsLoaded[Index];
6454*67e74705SXin Li }
6455*67e74705SXin Li
GetDecl(DeclID ID)6456*67e74705SXin Li Decl *ASTReader::GetDecl(DeclID ID) {
6457*67e74705SXin Li if (ID < NUM_PREDEF_DECL_IDS)
6458*67e74705SXin Li return GetExistingDecl(ID);
6459*67e74705SXin Li
6460*67e74705SXin Li unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6461*67e74705SXin Li
6462*67e74705SXin Li if (Index >= DeclsLoaded.size()) {
6463*67e74705SXin Li assert(0 && "declaration ID out-of-range for AST file");
6464*67e74705SXin Li Error("declaration ID out-of-range for AST file");
6465*67e74705SXin Li return nullptr;
6466*67e74705SXin Li }
6467*67e74705SXin Li
6468*67e74705SXin Li if (!DeclsLoaded[Index]) {
6469*67e74705SXin Li ReadDeclRecord(ID);
6470*67e74705SXin Li if (DeserializationListener)
6471*67e74705SXin Li DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6472*67e74705SXin Li }
6473*67e74705SXin Li
6474*67e74705SXin Li return DeclsLoaded[Index];
6475*67e74705SXin Li }
6476*67e74705SXin Li
mapGlobalIDToModuleFileGlobalID(ModuleFile & M,DeclID GlobalID)6477*67e74705SXin Li DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6478*67e74705SXin Li DeclID GlobalID) {
6479*67e74705SXin Li if (GlobalID < NUM_PREDEF_DECL_IDS)
6480*67e74705SXin Li return GlobalID;
6481*67e74705SXin Li
6482*67e74705SXin Li GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6483*67e74705SXin Li assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6484*67e74705SXin Li ModuleFile *Owner = I->second;
6485*67e74705SXin Li
6486*67e74705SXin Li llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6487*67e74705SXin Li = M.GlobalToLocalDeclIDs.find(Owner);
6488*67e74705SXin Li if (Pos == M.GlobalToLocalDeclIDs.end())
6489*67e74705SXin Li return 0;
6490*67e74705SXin Li
6491*67e74705SXin Li return GlobalID - Owner->BaseDeclID + Pos->second;
6492*67e74705SXin Li }
6493*67e74705SXin Li
ReadDeclID(ModuleFile & F,const RecordData & Record,unsigned & Idx)6494*67e74705SXin Li serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6495*67e74705SXin Li const RecordData &Record,
6496*67e74705SXin Li unsigned &Idx) {
6497*67e74705SXin Li if (Idx >= Record.size()) {
6498*67e74705SXin Li Error("Corrupted AST file");
6499*67e74705SXin Li return 0;
6500*67e74705SXin Li }
6501*67e74705SXin Li
6502*67e74705SXin Li return getGlobalDeclID(F, Record[Idx++]);
6503*67e74705SXin Li }
6504*67e74705SXin Li
6505*67e74705SXin Li /// \brief Resolve the offset of a statement into a statement.
6506*67e74705SXin Li ///
6507*67e74705SXin Li /// This operation will read a new statement from the external
6508*67e74705SXin Li /// source each time it is called, and is meant to be used via a
6509*67e74705SXin Li /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
GetExternalDeclStmt(uint64_t Offset)6510*67e74705SXin Li Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6511*67e74705SXin Li // Switch case IDs are per Decl.
6512*67e74705SXin Li ClearSwitchCaseIDs();
6513*67e74705SXin Li
6514*67e74705SXin Li // Offset here is a global offset across the entire chain.
6515*67e74705SXin Li RecordLocation Loc = getLocalBitOffset(Offset);
6516*67e74705SXin Li Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6517*67e74705SXin Li return ReadStmtFromStream(*Loc.F);
6518*67e74705SXin Li }
6519*67e74705SXin Li
FindExternalLexicalDecls(const DeclContext * DC,llvm::function_ref<bool (Decl::Kind)> IsKindWeWant,SmallVectorImpl<Decl * > & Decls)6520*67e74705SXin Li void ASTReader::FindExternalLexicalDecls(
6521*67e74705SXin Li const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6522*67e74705SXin Li SmallVectorImpl<Decl *> &Decls) {
6523*67e74705SXin Li bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6524*67e74705SXin Li
6525*67e74705SXin Li auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
6526*67e74705SXin Li assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6527*67e74705SXin Li for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6528*67e74705SXin Li auto K = (Decl::Kind)+LexicalDecls[I];
6529*67e74705SXin Li if (!IsKindWeWant(K))
6530*67e74705SXin Li continue;
6531*67e74705SXin Li
6532*67e74705SXin Li auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6533*67e74705SXin Li
6534*67e74705SXin Li // Don't add predefined declarations to the lexical context more
6535*67e74705SXin Li // than once.
6536*67e74705SXin Li if (ID < NUM_PREDEF_DECL_IDS) {
6537*67e74705SXin Li if (PredefsVisited[ID])
6538*67e74705SXin Li continue;
6539*67e74705SXin Li
6540*67e74705SXin Li PredefsVisited[ID] = true;
6541*67e74705SXin Li }
6542*67e74705SXin Li
6543*67e74705SXin Li if (Decl *D = GetLocalDecl(*M, ID)) {
6544*67e74705SXin Li assert(D->getKind() == K && "wrong kind for lexical decl");
6545*67e74705SXin Li if (!DC->isDeclInLexicalTraversal(D))
6546*67e74705SXin Li Decls.push_back(D);
6547*67e74705SXin Li }
6548*67e74705SXin Li }
6549*67e74705SXin Li };
6550*67e74705SXin Li
6551*67e74705SXin Li if (isa<TranslationUnitDecl>(DC)) {
6552*67e74705SXin Li for (auto Lexical : TULexicalDecls)
6553*67e74705SXin Li Visit(Lexical.first, Lexical.second);
6554*67e74705SXin Li } else {
6555*67e74705SXin Li auto I = LexicalDecls.find(DC);
6556*67e74705SXin Li if (I != LexicalDecls.end())
6557*67e74705SXin Li Visit(I->second.first, I->second.second);
6558*67e74705SXin Li }
6559*67e74705SXin Li
6560*67e74705SXin Li ++NumLexicalDeclContextsRead;
6561*67e74705SXin Li }
6562*67e74705SXin Li
6563*67e74705SXin Li namespace {
6564*67e74705SXin Li
6565*67e74705SXin Li class DeclIDComp {
6566*67e74705SXin Li ASTReader &Reader;
6567*67e74705SXin Li ModuleFile &Mod;
6568*67e74705SXin Li
6569*67e74705SXin Li public:
DeclIDComp(ASTReader & Reader,ModuleFile & M)6570*67e74705SXin Li DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6571*67e74705SXin Li
operator ()(LocalDeclID L,LocalDeclID R) const6572*67e74705SXin Li bool operator()(LocalDeclID L, LocalDeclID R) const {
6573*67e74705SXin Li SourceLocation LHS = getLocation(L);
6574*67e74705SXin Li SourceLocation RHS = getLocation(R);
6575*67e74705SXin Li return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6576*67e74705SXin Li }
6577*67e74705SXin Li
operator ()(SourceLocation LHS,LocalDeclID R) const6578*67e74705SXin Li bool operator()(SourceLocation LHS, LocalDeclID R) const {
6579*67e74705SXin Li SourceLocation RHS = getLocation(R);
6580*67e74705SXin Li return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6581*67e74705SXin Li }
6582*67e74705SXin Li
operator ()(LocalDeclID L,SourceLocation RHS) const6583*67e74705SXin Li bool operator()(LocalDeclID L, SourceLocation RHS) const {
6584*67e74705SXin Li SourceLocation LHS = getLocation(L);
6585*67e74705SXin Li return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6586*67e74705SXin Li }
6587*67e74705SXin Li
getLocation(LocalDeclID ID) const6588*67e74705SXin Li SourceLocation getLocation(LocalDeclID ID) const {
6589*67e74705SXin Li return Reader.getSourceManager().getFileLoc(
6590*67e74705SXin Li Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6591*67e74705SXin Li }
6592*67e74705SXin Li };
6593*67e74705SXin Li
6594*67e74705SXin Li }
6595*67e74705SXin Li
FindFileRegionDecls(FileID File,unsigned Offset,unsigned Length,SmallVectorImpl<Decl * > & Decls)6596*67e74705SXin Li void ASTReader::FindFileRegionDecls(FileID File,
6597*67e74705SXin Li unsigned Offset, unsigned Length,
6598*67e74705SXin Li SmallVectorImpl<Decl *> &Decls) {
6599*67e74705SXin Li SourceManager &SM = getSourceManager();
6600*67e74705SXin Li
6601*67e74705SXin Li llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6602*67e74705SXin Li if (I == FileDeclIDs.end())
6603*67e74705SXin Li return;
6604*67e74705SXin Li
6605*67e74705SXin Li FileDeclsInfo &DInfo = I->second;
6606*67e74705SXin Li if (DInfo.Decls.empty())
6607*67e74705SXin Li return;
6608*67e74705SXin Li
6609*67e74705SXin Li SourceLocation
6610*67e74705SXin Li BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6611*67e74705SXin Li SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6612*67e74705SXin Li
6613*67e74705SXin Li DeclIDComp DIDComp(*this, *DInfo.Mod);
6614*67e74705SXin Li ArrayRef<serialization::LocalDeclID>::iterator
6615*67e74705SXin Li BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6616*67e74705SXin Li BeginLoc, DIDComp);
6617*67e74705SXin Li if (BeginIt != DInfo.Decls.begin())
6618*67e74705SXin Li --BeginIt;
6619*67e74705SXin Li
6620*67e74705SXin Li // If we are pointing at a top-level decl inside an objc container, we need
6621*67e74705SXin Li // to backtrack until we find it otherwise we will fail to report that the
6622*67e74705SXin Li // region overlaps with an objc container.
6623*67e74705SXin Li while (BeginIt != DInfo.Decls.begin() &&
6624*67e74705SXin Li GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6625*67e74705SXin Li ->isTopLevelDeclInObjCContainer())
6626*67e74705SXin Li --BeginIt;
6627*67e74705SXin Li
6628*67e74705SXin Li ArrayRef<serialization::LocalDeclID>::iterator
6629*67e74705SXin Li EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6630*67e74705SXin Li EndLoc, DIDComp);
6631*67e74705SXin Li if (EndIt != DInfo.Decls.end())
6632*67e74705SXin Li ++EndIt;
6633*67e74705SXin Li
6634*67e74705SXin Li for (ArrayRef<serialization::LocalDeclID>::iterator
6635*67e74705SXin Li DIt = BeginIt; DIt != EndIt; ++DIt)
6636*67e74705SXin Li Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6637*67e74705SXin Li }
6638*67e74705SXin Li
6639*67e74705SXin Li bool
FindExternalVisibleDeclsByName(const DeclContext * DC,DeclarationName Name)6640*67e74705SXin Li ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6641*67e74705SXin Li DeclarationName Name) {
6642*67e74705SXin Li assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
6643*67e74705SXin Li "DeclContext has no visible decls in storage");
6644*67e74705SXin Li if (!Name)
6645*67e74705SXin Li return false;
6646*67e74705SXin Li
6647*67e74705SXin Li auto It = Lookups.find(DC);
6648*67e74705SXin Li if (It == Lookups.end())
6649*67e74705SXin Li return false;
6650*67e74705SXin Li
6651*67e74705SXin Li Deserializing LookupResults(this);
6652*67e74705SXin Li
6653*67e74705SXin Li // Load the list of declarations.
6654*67e74705SXin Li SmallVector<NamedDecl *, 64> Decls;
6655*67e74705SXin Li for (DeclID ID : It->second.Table.find(Name)) {
6656*67e74705SXin Li NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6657*67e74705SXin Li if (ND->getDeclName() == Name)
6658*67e74705SXin Li Decls.push_back(ND);
6659*67e74705SXin Li }
6660*67e74705SXin Li
6661*67e74705SXin Li ++NumVisibleDeclContextsRead;
6662*67e74705SXin Li SetExternalVisibleDeclsForName(DC, Name, Decls);
6663*67e74705SXin Li return !Decls.empty();
6664*67e74705SXin Li }
6665*67e74705SXin Li
completeVisibleDeclsMap(const DeclContext * DC)6666*67e74705SXin Li void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6667*67e74705SXin Li if (!DC->hasExternalVisibleStorage())
6668*67e74705SXin Li return;
6669*67e74705SXin Li
6670*67e74705SXin Li auto It = Lookups.find(DC);
6671*67e74705SXin Li assert(It != Lookups.end() &&
6672*67e74705SXin Li "have external visible storage but no lookup tables");
6673*67e74705SXin Li
6674*67e74705SXin Li DeclsMap Decls;
6675*67e74705SXin Li
6676*67e74705SXin Li for (DeclID ID : It->second.Table.findAll()) {
6677*67e74705SXin Li NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6678*67e74705SXin Li Decls[ND->getDeclName()].push_back(ND);
6679*67e74705SXin Li }
6680*67e74705SXin Li
6681*67e74705SXin Li ++NumVisibleDeclContextsRead;
6682*67e74705SXin Li
6683*67e74705SXin Li for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
6684*67e74705SXin Li SetExternalVisibleDeclsForName(DC, I->first, I->second);
6685*67e74705SXin Li }
6686*67e74705SXin Li const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6687*67e74705SXin Li }
6688*67e74705SXin Li
6689*67e74705SXin Li const serialization::reader::DeclContextLookupTable *
getLoadedLookupTables(DeclContext * Primary) const6690*67e74705SXin Li ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6691*67e74705SXin Li auto I = Lookups.find(Primary);
6692*67e74705SXin Li return I == Lookups.end() ? nullptr : &I->second;
6693*67e74705SXin Li }
6694*67e74705SXin Li
6695*67e74705SXin Li /// \brief Under non-PCH compilation the consumer receives the objc methods
6696*67e74705SXin Li /// before receiving the implementation, and codegen depends on this.
6697*67e74705SXin Li /// We simulate this by deserializing and passing to consumer the methods of the
6698*67e74705SXin Li /// implementation before passing the deserialized implementation decl.
PassObjCImplDeclToConsumer(ObjCImplDecl * ImplD,ASTConsumer * Consumer)6699*67e74705SXin Li static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6700*67e74705SXin Li ASTConsumer *Consumer) {
6701*67e74705SXin Li assert(ImplD && Consumer);
6702*67e74705SXin Li
6703*67e74705SXin Li for (auto *I : ImplD->methods())
6704*67e74705SXin Li Consumer->HandleInterestingDecl(DeclGroupRef(I));
6705*67e74705SXin Li
6706*67e74705SXin Li Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6707*67e74705SXin Li }
6708*67e74705SXin Li
PassInterestingDeclsToConsumer()6709*67e74705SXin Li void ASTReader::PassInterestingDeclsToConsumer() {
6710*67e74705SXin Li assert(Consumer);
6711*67e74705SXin Li
6712*67e74705SXin Li if (PassingDeclsToConsumer)
6713*67e74705SXin Li return;
6714*67e74705SXin Li
6715*67e74705SXin Li // Guard variable to avoid recursively redoing the process of passing
6716*67e74705SXin Li // decls to consumer.
6717*67e74705SXin Li SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6718*67e74705SXin Li true);
6719*67e74705SXin Li
6720*67e74705SXin Li // Ensure that we've loaded all potentially-interesting declarations
6721*67e74705SXin Li // that need to be eagerly loaded.
6722*67e74705SXin Li for (auto ID : EagerlyDeserializedDecls)
6723*67e74705SXin Li GetDecl(ID);
6724*67e74705SXin Li EagerlyDeserializedDecls.clear();
6725*67e74705SXin Li
6726*67e74705SXin Li while (!InterestingDecls.empty()) {
6727*67e74705SXin Li Decl *D = InterestingDecls.front();
6728*67e74705SXin Li InterestingDecls.pop_front();
6729*67e74705SXin Li
6730*67e74705SXin Li PassInterestingDeclToConsumer(D);
6731*67e74705SXin Li }
6732*67e74705SXin Li }
6733*67e74705SXin Li
PassInterestingDeclToConsumer(Decl * D)6734*67e74705SXin Li void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6735*67e74705SXin Li if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6736*67e74705SXin Li PassObjCImplDeclToConsumer(ImplD, Consumer);
6737*67e74705SXin Li else
6738*67e74705SXin Li Consumer->HandleInterestingDecl(DeclGroupRef(D));
6739*67e74705SXin Li }
6740*67e74705SXin Li
StartTranslationUnit(ASTConsumer * Consumer)6741*67e74705SXin Li void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6742*67e74705SXin Li this->Consumer = Consumer;
6743*67e74705SXin Li
6744*67e74705SXin Li if (Consumer)
6745*67e74705SXin Li PassInterestingDeclsToConsumer();
6746*67e74705SXin Li
6747*67e74705SXin Li if (DeserializationListener)
6748*67e74705SXin Li DeserializationListener->ReaderInitialized(this);
6749*67e74705SXin Li }
6750*67e74705SXin Li
PrintStats()6751*67e74705SXin Li void ASTReader::PrintStats() {
6752*67e74705SXin Li std::fprintf(stderr, "*** AST File Statistics:\n");
6753*67e74705SXin Li
6754*67e74705SXin Li unsigned NumTypesLoaded
6755*67e74705SXin Li = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6756*67e74705SXin Li QualType());
6757*67e74705SXin Li unsigned NumDeclsLoaded
6758*67e74705SXin Li = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6759*67e74705SXin Li (Decl *)nullptr);
6760*67e74705SXin Li unsigned NumIdentifiersLoaded
6761*67e74705SXin Li = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6762*67e74705SXin Li IdentifiersLoaded.end(),
6763*67e74705SXin Li (IdentifierInfo *)nullptr);
6764*67e74705SXin Li unsigned NumMacrosLoaded
6765*67e74705SXin Li = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6766*67e74705SXin Li MacrosLoaded.end(),
6767*67e74705SXin Li (MacroInfo *)nullptr);
6768*67e74705SXin Li unsigned NumSelectorsLoaded
6769*67e74705SXin Li = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6770*67e74705SXin Li SelectorsLoaded.end(),
6771*67e74705SXin Li Selector());
6772*67e74705SXin Li
6773*67e74705SXin Li if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6774*67e74705SXin Li std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6775*67e74705SXin Li NumSLocEntriesRead, TotalNumSLocEntries,
6776*67e74705SXin Li ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6777*67e74705SXin Li if (!TypesLoaded.empty())
6778*67e74705SXin Li std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6779*67e74705SXin Li NumTypesLoaded, (unsigned)TypesLoaded.size(),
6780*67e74705SXin Li ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6781*67e74705SXin Li if (!DeclsLoaded.empty())
6782*67e74705SXin Li std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6783*67e74705SXin Li NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6784*67e74705SXin Li ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6785*67e74705SXin Li if (!IdentifiersLoaded.empty())
6786*67e74705SXin Li std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6787*67e74705SXin Li NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6788*67e74705SXin Li ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6789*67e74705SXin Li if (!MacrosLoaded.empty())
6790*67e74705SXin Li std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6791*67e74705SXin Li NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6792*67e74705SXin Li ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6793*67e74705SXin Li if (!SelectorsLoaded.empty())
6794*67e74705SXin Li std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6795*67e74705SXin Li NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6796*67e74705SXin Li ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6797*67e74705SXin Li if (TotalNumStatements)
6798*67e74705SXin Li std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6799*67e74705SXin Li NumStatementsRead, TotalNumStatements,
6800*67e74705SXin Li ((float)NumStatementsRead/TotalNumStatements * 100));
6801*67e74705SXin Li if (TotalNumMacros)
6802*67e74705SXin Li std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6803*67e74705SXin Li NumMacrosRead, TotalNumMacros,
6804*67e74705SXin Li ((float)NumMacrosRead/TotalNumMacros * 100));
6805*67e74705SXin Li if (TotalLexicalDeclContexts)
6806*67e74705SXin Li std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6807*67e74705SXin Li NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6808*67e74705SXin Li ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6809*67e74705SXin Li * 100));
6810*67e74705SXin Li if (TotalVisibleDeclContexts)
6811*67e74705SXin Li std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6812*67e74705SXin Li NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6813*67e74705SXin Li ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6814*67e74705SXin Li * 100));
6815*67e74705SXin Li if (TotalNumMethodPoolEntries) {
6816*67e74705SXin Li std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6817*67e74705SXin Li NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6818*67e74705SXin Li ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6819*67e74705SXin Li * 100));
6820*67e74705SXin Li }
6821*67e74705SXin Li if (NumMethodPoolLookups) {
6822*67e74705SXin Li std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6823*67e74705SXin Li NumMethodPoolHits, NumMethodPoolLookups,
6824*67e74705SXin Li ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6825*67e74705SXin Li }
6826*67e74705SXin Li if (NumMethodPoolTableLookups) {
6827*67e74705SXin Li std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6828*67e74705SXin Li NumMethodPoolTableHits, NumMethodPoolTableLookups,
6829*67e74705SXin Li ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6830*67e74705SXin Li * 100.0));
6831*67e74705SXin Li }
6832*67e74705SXin Li
6833*67e74705SXin Li if (NumIdentifierLookupHits) {
6834*67e74705SXin Li std::fprintf(stderr,
6835*67e74705SXin Li " %u / %u identifier table lookups succeeded (%f%%)\n",
6836*67e74705SXin Li NumIdentifierLookupHits, NumIdentifierLookups,
6837*67e74705SXin Li (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6838*67e74705SXin Li }
6839*67e74705SXin Li
6840*67e74705SXin Li if (GlobalIndex) {
6841*67e74705SXin Li std::fprintf(stderr, "\n");
6842*67e74705SXin Li GlobalIndex->printStats();
6843*67e74705SXin Li }
6844*67e74705SXin Li
6845*67e74705SXin Li std::fprintf(stderr, "\n");
6846*67e74705SXin Li dump();
6847*67e74705SXin Li std::fprintf(stderr, "\n");
6848*67e74705SXin Li }
6849*67e74705SXin Li
6850*67e74705SXin Li template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6851*67e74705SXin Li static void
dumpModuleIDMap(StringRef Name,const ContinuousRangeMap<Key,ModuleFile *,InitialCapacity> & Map)6852*67e74705SXin Li dumpModuleIDMap(StringRef Name,
6853*67e74705SXin Li const ContinuousRangeMap<Key, ModuleFile *,
6854*67e74705SXin Li InitialCapacity> &Map) {
6855*67e74705SXin Li if (Map.begin() == Map.end())
6856*67e74705SXin Li return;
6857*67e74705SXin Li
6858*67e74705SXin Li typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6859*67e74705SXin Li llvm::errs() << Name << ":\n";
6860*67e74705SXin Li for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6861*67e74705SXin Li I != IEnd; ++I) {
6862*67e74705SXin Li llvm::errs() << " " << I->first << " -> " << I->second->FileName
6863*67e74705SXin Li << "\n";
6864*67e74705SXin Li }
6865*67e74705SXin Li }
6866*67e74705SXin Li
dump()6867*67e74705SXin Li LLVM_DUMP_METHOD void ASTReader::dump() {
6868*67e74705SXin Li llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6869*67e74705SXin Li dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6870*67e74705SXin Li dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6871*67e74705SXin Li dumpModuleIDMap("Global type map", GlobalTypeMap);
6872*67e74705SXin Li dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6873*67e74705SXin Li dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6874*67e74705SXin Li dumpModuleIDMap("Global macro map", GlobalMacroMap);
6875*67e74705SXin Li dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6876*67e74705SXin Li dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6877*67e74705SXin Li dumpModuleIDMap("Global preprocessed entity map",
6878*67e74705SXin Li GlobalPreprocessedEntityMap);
6879*67e74705SXin Li
6880*67e74705SXin Li llvm::errs() << "\n*** PCH/Modules Loaded:";
6881*67e74705SXin Li for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6882*67e74705SXin Li MEnd = ModuleMgr.end();
6883*67e74705SXin Li M != MEnd; ++M)
6884*67e74705SXin Li (*M)->dump();
6885*67e74705SXin Li }
6886*67e74705SXin Li
6887*67e74705SXin Li /// Return the amount of memory used by memory buffers, breaking down
6888*67e74705SXin Li /// by heap-backed versus mmap'ed memory.
getMemoryBufferSizes(MemoryBufferSizes & sizes) const6889*67e74705SXin Li void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6890*67e74705SXin Li for (ModuleConstIterator I = ModuleMgr.begin(),
6891*67e74705SXin Li E = ModuleMgr.end(); I != E; ++I) {
6892*67e74705SXin Li if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6893*67e74705SXin Li size_t bytes = buf->getBufferSize();
6894*67e74705SXin Li switch (buf->getBufferKind()) {
6895*67e74705SXin Li case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6896*67e74705SXin Li sizes.malloc_bytes += bytes;
6897*67e74705SXin Li break;
6898*67e74705SXin Li case llvm::MemoryBuffer::MemoryBuffer_MMap:
6899*67e74705SXin Li sizes.mmap_bytes += bytes;
6900*67e74705SXin Li break;
6901*67e74705SXin Li }
6902*67e74705SXin Li }
6903*67e74705SXin Li }
6904*67e74705SXin Li }
6905*67e74705SXin Li
InitializeSema(Sema & S)6906*67e74705SXin Li void ASTReader::InitializeSema(Sema &S) {
6907*67e74705SXin Li SemaObj = &S;
6908*67e74705SXin Li S.addExternalSource(this);
6909*67e74705SXin Li
6910*67e74705SXin Li // Makes sure any declarations that were deserialized "too early"
6911*67e74705SXin Li // still get added to the identifier's declaration chains.
6912*67e74705SXin Li for (uint64_t ID : PreloadedDeclIDs) {
6913*67e74705SXin Li NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6914*67e74705SXin Li pushExternalDeclIntoScope(D, D->getDeclName());
6915*67e74705SXin Li }
6916*67e74705SXin Li PreloadedDeclIDs.clear();
6917*67e74705SXin Li
6918*67e74705SXin Li // FIXME: What happens if these are changed by a module import?
6919*67e74705SXin Li if (!FPPragmaOptions.empty()) {
6920*67e74705SXin Li assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6921*67e74705SXin Li SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6922*67e74705SXin Li }
6923*67e74705SXin Li
6924*67e74705SXin Li // FIXME: What happens if these are changed by a module import?
6925*67e74705SXin Li if (!OpenCLExtensions.empty()) {
6926*67e74705SXin Li unsigned I = 0;
6927*67e74705SXin Li #define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6928*67e74705SXin Li #include "clang/Basic/OpenCLExtensions.def"
6929*67e74705SXin Li
6930*67e74705SXin Li assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6931*67e74705SXin Li }
6932*67e74705SXin Li
6933*67e74705SXin Li UpdateSema();
6934*67e74705SXin Li }
6935*67e74705SXin Li
UpdateSema()6936*67e74705SXin Li void ASTReader::UpdateSema() {
6937*67e74705SXin Li assert(SemaObj && "no Sema to update");
6938*67e74705SXin Li
6939*67e74705SXin Li // Load the offsets of the declarations that Sema references.
6940*67e74705SXin Li // They will be lazily deserialized when needed.
6941*67e74705SXin Li if (!SemaDeclRefs.empty()) {
6942*67e74705SXin Li assert(SemaDeclRefs.size() % 2 == 0);
6943*67e74705SXin Li for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6944*67e74705SXin Li if (!SemaObj->StdNamespace)
6945*67e74705SXin Li SemaObj->StdNamespace = SemaDeclRefs[I];
6946*67e74705SXin Li if (!SemaObj->StdBadAlloc)
6947*67e74705SXin Li SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6948*67e74705SXin Li }
6949*67e74705SXin Li SemaDeclRefs.clear();
6950*67e74705SXin Li }
6951*67e74705SXin Li
6952*67e74705SXin Li // Update the state of pragmas. Use the same API as if we had encountered the
6953*67e74705SXin Li // pragma in the source.
6954*67e74705SXin Li if(OptimizeOffPragmaLocation.isValid())
6955*67e74705SXin Li SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
6956*67e74705SXin Li if (PragmaMSStructState != -1)
6957*67e74705SXin Li SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
6958*67e74705SXin Li if (PointersToMembersPragmaLocation.isValid()) {
6959*67e74705SXin Li SemaObj->ActOnPragmaMSPointersToMembers(
6960*67e74705SXin Li (LangOptions::PragmaMSPointersToMembersKind)
6961*67e74705SXin Li PragmaMSPointersToMembersState,
6962*67e74705SXin Li PointersToMembersPragmaLocation);
6963*67e74705SXin Li }
6964*67e74705SXin Li }
6965*67e74705SXin Li
get(StringRef Name)6966*67e74705SXin Li IdentifierInfo *ASTReader::get(StringRef Name) {
6967*67e74705SXin Li // Note that we are loading an identifier.
6968*67e74705SXin Li Deserializing AnIdentifier(this);
6969*67e74705SXin Li
6970*67e74705SXin Li IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
6971*67e74705SXin Li NumIdentifierLookups,
6972*67e74705SXin Li NumIdentifierLookupHits);
6973*67e74705SXin Li
6974*67e74705SXin Li // We don't need to do identifier table lookups in C++ modules (we preload
6975*67e74705SXin Li // all interesting declarations, and don't need to use the scope for name
6976*67e74705SXin Li // lookups). Perform the lookup in PCH files, though, since we don't build
6977*67e74705SXin Li // a complete initial identifier table if we're carrying on from a PCH.
6978*67e74705SXin Li if (Context.getLangOpts().CPlusPlus) {
6979*67e74705SXin Li for (auto F : ModuleMgr.pch_modules())
6980*67e74705SXin Li if (Visitor(*F))
6981*67e74705SXin Li break;
6982*67e74705SXin Li } else {
6983*67e74705SXin Li // If there is a global index, look there first to determine which modules
6984*67e74705SXin Li // provably do not have any results for this identifier.
6985*67e74705SXin Li GlobalModuleIndex::HitSet Hits;
6986*67e74705SXin Li GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6987*67e74705SXin Li if (!loadGlobalIndex()) {
6988*67e74705SXin Li if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6989*67e74705SXin Li HitsPtr = &Hits;
6990*67e74705SXin Li }
6991*67e74705SXin Li }
6992*67e74705SXin Li
6993*67e74705SXin Li ModuleMgr.visit(Visitor, HitsPtr);
6994*67e74705SXin Li }
6995*67e74705SXin Li
6996*67e74705SXin Li IdentifierInfo *II = Visitor.getIdentifierInfo();
6997*67e74705SXin Li markIdentifierUpToDate(II);
6998*67e74705SXin Li return II;
6999*67e74705SXin Li }
7000*67e74705SXin Li
7001*67e74705SXin Li namespace clang {
7002*67e74705SXin Li /// \brief An identifier-lookup iterator that enumerates all of the
7003*67e74705SXin Li /// identifiers stored within a set of AST files.
7004*67e74705SXin Li class ASTIdentifierIterator : public IdentifierIterator {
7005*67e74705SXin Li /// \brief The AST reader whose identifiers are being enumerated.
7006*67e74705SXin Li const ASTReader &Reader;
7007*67e74705SXin Li
7008*67e74705SXin Li /// \brief The current index into the chain of AST files stored in
7009*67e74705SXin Li /// the AST reader.
7010*67e74705SXin Li unsigned Index;
7011*67e74705SXin Li
7012*67e74705SXin Li /// \brief The current position within the identifier lookup table
7013*67e74705SXin Li /// of the current AST file.
7014*67e74705SXin Li ASTIdentifierLookupTable::key_iterator Current;
7015*67e74705SXin Li
7016*67e74705SXin Li /// \brief The end position within the identifier lookup table of
7017*67e74705SXin Li /// the current AST file.
7018*67e74705SXin Li ASTIdentifierLookupTable::key_iterator End;
7019*67e74705SXin Li
7020*67e74705SXin Li /// \brief Whether to skip any modules in the ASTReader.
7021*67e74705SXin Li bool SkipModules;
7022*67e74705SXin Li
7023*67e74705SXin Li public:
7024*67e74705SXin Li explicit ASTIdentifierIterator(const ASTReader &Reader,
7025*67e74705SXin Li bool SkipModules = false);
7026*67e74705SXin Li
7027*67e74705SXin Li StringRef Next() override;
7028*67e74705SXin Li };
7029*67e74705SXin Li }
7030*67e74705SXin Li
ASTIdentifierIterator(const ASTReader & Reader,bool SkipModules)7031*67e74705SXin Li ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7032*67e74705SXin Li bool SkipModules)
7033*67e74705SXin Li : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
7034*67e74705SXin Li }
7035*67e74705SXin Li
Next()7036*67e74705SXin Li StringRef ASTIdentifierIterator::Next() {
7037*67e74705SXin Li while (Current == End) {
7038*67e74705SXin Li // If we have exhausted all of our AST files, we're done.
7039*67e74705SXin Li if (Index == 0)
7040*67e74705SXin Li return StringRef();
7041*67e74705SXin Li
7042*67e74705SXin Li --Index;
7043*67e74705SXin Li ModuleFile &F = Reader.ModuleMgr[Index];
7044*67e74705SXin Li if (SkipModules && F.isModule())
7045*67e74705SXin Li continue;
7046*67e74705SXin Li
7047*67e74705SXin Li ASTIdentifierLookupTable *IdTable =
7048*67e74705SXin Li (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
7049*67e74705SXin Li Current = IdTable->key_begin();
7050*67e74705SXin Li End = IdTable->key_end();
7051*67e74705SXin Li }
7052*67e74705SXin Li
7053*67e74705SXin Li // We have any identifiers remaining in the current AST file; return
7054*67e74705SXin Li // the next one.
7055*67e74705SXin Li StringRef Result = *Current;
7056*67e74705SXin Li ++Current;
7057*67e74705SXin Li return Result;
7058*67e74705SXin Li }
7059*67e74705SXin Li
7060*67e74705SXin Li namespace {
7061*67e74705SXin Li /// A utility for appending two IdentifierIterators.
7062*67e74705SXin Li class ChainedIdentifierIterator : public IdentifierIterator {
7063*67e74705SXin Li std::unique_ptr<IdentifierIterator> Current;
7064*67e74705SXin Li std::unique_ptr<IdentifierIterator> Queued;
7065*67e74705SXin Li
7066*67e74705SXin Li public:
ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,std::unique_ptr<IdentifierIterator> Second)7067*67e74705SXin Li ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7068*67e74705SXin Li std::unique_ptr<IdentifierIterator> Second)
7069*67e74705SXin Li : Current(std::move(First)), Queued(std::move(Second)) {}
7070*67e74705SXin Li
Next()7071*67e74705SXin Li StringRef Next() override {
7072*67e74705SXin Li if (!Current)
7073*67e74705SXin Li return StringRef();
7074*67e74705SXin Li
7075*67e74705SXin Li StringRef result = Current->Next();
7076*67e74705SXin Li if (!result.empty())
7077*67e74705SXin Li return result;
7078*67e74705SXin Li
7079*67e74705SXin Li // Try the queued iterator, which may itself be empty.
7080*67e74705SXin Li Current.reset();
7081*67e74705SXin Li std::swap(Current, Queued);
7082*67e74705SXin Li return Next();
7083*67e74705SXin Li }
7084*67e74705SXin Li };
7085*67e74705SXin Li } // end anonymous namespace.
7086*67e74705SXin Li
getIdentifiers()7087*67e74705SXin Li IdentifierIterator *ASTReader::getIdentifiers() {
7088*67e74705SXin Li if (!loadGlobalIndex()) {
7089*67e74705SXin Li std::unique_ptr<IdentifierIterator> ReaderIter(
7090*67e74705SXin Li new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7091*67e74705SXin Li std::unique_ptr<IdentifierIterator> ModulesIter(
7092*67e74705SXin Li GlobalIndex->createIdentifierIterator());
7093*67e74705SXin Li return new ChainedIdentifierIterator(std::move(ReaderIter),
7094*67e74705SXin Li std::move(ModulesIter));
7095*67e74705SXin Li }
7096*67e74705SXin Li
7097*67e74705SXin Li return new ASTIdentifierIterator(*this);
7098*67e74705SXin Li }
7099*67e74705SXin Li
7100*67e74705SXin Li namespace clang { namespace serialization {
7101*67e74705SXin Li class ReadMethodPoolVisitor {
7102*67e74705SXin Li ASTReader &Reader;
7103*67e74705SXin Li Selector Sel;
7104*67e74705SXin Li unsigned PriorGeneration;
7105*67e74705SXin Li unsigned InstanceBits;
7106*67e74705SXin Li unsigned FactoryBits;
7107*67e74705SXin Li bool InstanceHasMoreThanOneDecl;
7108*67e74705SXin Li bool FactoryHasMoreThanOneDecl;
7109*67e74705SXin Li SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7110*67e74705SXin Li SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
7111*67e74705SXin Li
7112*67e74705SXin Li public:
ReadMethodPoolVisitor(ASTReader & Reader,Selector Sel,unsigned PriorGeneration)7113*67e74705SXin Li ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
7114*67e74705SXin Li unsigned PriorGeneration)
7115*67e74705SXin Li : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
7116*67e74705SXin Li InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7117*67e74705SXin Li FactoryHasMoreThanOneDecl(false) {}
7118*67e74705SXin Li
operator ()(ModuleFile & M)7119*67e74705SXin Li bool operator()(ModuleFile &M) {
7120*67e74705SXin Li if (!M.SelectorLookupTable)
7121*67e74705SXin Li return false;
7122*67e74705SXin Li
7123*67e74705SXin Li // If we've already searched this module file, skip it now.
7124*67e74705SXin Li if (M.Generation <= PriorGeneration)
7125*67e74705SXin Li return true;
7126*67e74705SXin Li
7127*67e74705SXin Li ++Reader.NumMethodPoolTableLookups;
7128*67e74705SXin Li ASTSelectorLookupTable *PoolTable
7129*67e74705SXin Li = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7130*67e74705SXin Li ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
7131*67e74705SXin Li if (Pos == PoolTable->end())
7132*67e74705SXin Li return false;
7133*67e74705SXin Li
7134*67e74705SXin Li ++Reader.NumMethodPoolTableHits;
7135*67e74705SXin Li ++Reader.NumSelectorsRead;
7136*67e74705SXin Li // FIXME: Not quite happy with the statistics here. We probably should
7137*67e74705SXin Li // disable this tracking when called via LoadSelector.
7138*67e74705SXin Li // Also, should entries without methods count as misses?
7139*67e74705SXin Li ++Reader.NumMethodPoolEntriesRead;
7140*67e74705SXin Li ASTSelectorLookupTrait::data_type Data = *Pos;
7141*67e74705SXin Li if (Reader.DeserializationListener)
7142*67e74705SXin Li Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
7143*67e74705SXin Li
7144*67e74705SXin Li InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7145*67e74705SXin Li FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7146*67e74705SXin Li InstanceBits = Data.InstanceBits;
7147*67e74705SXin Li FactoryBits = Data.FactoryBits;
7148*67e74705SXin Li InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7149*67e74705SXin Li FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
7150*67e74705SXin Li return true;
7151*67e74705SXin Li }
7152*67e74705SXin Li
7153*67e74705SXin Li /// \brief Retrieve the instance methods found by this visitor.
getInstanceMethods() const7154*67e74705SXin Li ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7155*67e74705SXin Li return InstanceMethods;
7156*67e74705SXin Li }
7157*67e74705SXin Li
7158*67e74705SXin Li /// \brief Retrieve the instance methods found by this visitor.
getFactoryMethods() const7159*67e74705SXin Li ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7160*67e74705SXin Li return FactoryMethods;
7161*67e74705SXin Li }
7162*67e74705SXin Li
getInstanceBits() const7163*67e74705SXin Li unsigned getInstanceBits() const { return InstanceBits; }
getFactoryBits() const7164*67e74705SXin Li unsigned getFactoryBits() const { return FactoryBits; }
instanceHasMoreThanOneDecl() const7165*67e74705SXin Li bool instanceHasMoreThanOneDecl() const {
7166*67e74705SXin Li return InstanceHasMoreThanOneDecl;
7167*67e74705SXin Li }
factoryHasMoreThanOneDecl() const7168*67e74705SXin Li bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
7169*67e74705SXin Li };
7170*67e74705SXin Li } } // end namespace clang::serialization
7171*67e74705SXin Li
7172*67e74705SXin Li /// \brief Add the given set of methods to the method list.
addMethodsToPool(Sema & S,ArrayRef<ObjCMethodDecl * > Methods,ObjCMethodList & List)7173*67e74705SXin Li static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7174*67e74705SXin Li ObjCMethodList &List) {
7175*67e74705SXin Li for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7176*67e74705SXin Li S.addMethodToGlobalList(&List, Methods[I]);
7177*67e74705SXin Li }
7178*67e74705SXin Li }
7179*67e74705SXin Li
ReadMethodPool(Selector Sel)7180*67e74705SXin Li void ASTReader::ReadMethodPool(Selector Sel) {
7181*67e74705SXin Li // Get the selector generation and update it to the current generation.
7182*67e74705SXin Li unsigned &Generation = SelectorGeneration[Sel];
7183*67e74705SXin Li unsigned PriorGeneration = Generation;
7184*67e74705SXin Li Generation = getGeneration();
7185*67e74705SXin Li SelectorOutOfDate[Sel] = false;
7186*67e74705SXin Li
7187*67e74705SXin Li // Search for methods defined with this selector.
7188*67e74705SXin Li ++NumMethodPoolLookups;
7189*67e74705SXin Li ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7190*67e74705SXin Li ModuleMgr.visit(Visitor);
7191*67e74705SXin Li
7192*67e74705SXin Li if (Visitor.getInstanceMethods().empty() &&
7193*67e74705SXin Li Visitor.getFactoryMethods().empty())
7194*67e74705SXin Li return;
7195*67e74705SXin Li
7196*67e74705SXin Li ++NumMethodPoolHits;
7197*67e74705SXin Li
7198*67e74705SXin Li if (!getSema())
7199*67e74705SXin Li return;
7200*67e74705SXin Li
7201*67e74705SXin Li Sema &S = *getSema();
7202*67e74705SXin Li Sema::GlobalMethodPool::iterator Pos
7203*67e74705SXin Li = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7204*67e74705SXin Li
7205*67e74705SXin Li Pos->second.first.setBits(Visitor.getInstanceBits());
7206*67e74705SXin Li Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
7207*67e74705SXin Li Pos->second.second.setBits(Visitor.getFactoryBits());
7208*67e74705SXin Li Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
7209*67e74705SXin Li
7210*67e74705SXin Li // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7211*67e74705SXin Li // when building a module we keep every method individually and may need to
7212*67e74705SXin Li // update hasMoreThanOneDecl as we add the methods.
7213*67e74705SXin Li addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7214*67e74705SXin Li addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
7215*67e74705SXin Li }
7216*67e74705SXin Li
updateOutOfDateSelector(Selector Sel)7217*67e74705SXin Li void ASTReader::updateOutOfDateSelector(Selector Sel) {
7218*67e74705SXin Li if (SelectorOutOfDate[Sel])
7219*67e74705SXin Li ReadMethodPool(Sel);
7220*67e74705SXin Li }
7221*67e74705SXin Li
ReadKnownNamespaces(SmallVectorImpl<NamespaceDecl * > & Namespaces)7222*67e74705SXin Li void ASTReader::ReadKnownNamespaces(
7223*67e74705SXin Li SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7224*67e74705SXin Li Namespaces.clear();
7225*67e74705SXin Li
7226*67e74705SXin Li for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7227*67e74705SXin Li if (NamespaceDecl *Namespace
7228*67e74705SXin Li = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7229*67e74705SXin Li Namespaces.push_back(Namespace);
7230*67e74705SXin Li }
7231*67e74705SXin Li }
7232*67e74705SXin Li
ReadUndefinedButUsed(llvm::MapVector<NamedDecl *,SourceLocation> & Undefined)7233*67e74705SXin Li void ASTReader::ReadUndefinedButUsed(
7234*67e74705SXin Li llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
7235*67e74705SXin Li for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7236*67e74705SXin Li NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
7237*67e74705SXin Li SourceLocation Loc =
7238*67e74705SXin Li SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
7239*67e74705SXin Li Undefined.insert(std::make_pair(D, Loc));
7240*67e74705SXin Li }
7241*67e74705SXin Li }
7242*67e74705SXin Li
ReadMismatchingDeleteExpressions(llvm::MapVector<FieldDecl *,llvm::SmallVector<std::pair<SourceLocation,bool>,4>> & Exprs)7243*67e74705SXin Li void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7244*67e74705SXin Li FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7245*67e74705SXin Li Exprs) {
7246*67e74705SXin Li for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7247*67e74705SXin Li FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7248*67e74705SXin Li uint64_t Count = DelayedDeleteExprs[Idx++];
7249*67e74705SXin Li for (uint64_t C = 0; C < Count; ++C) {
7250*67e74705SXin Li SourceLocation DeleteLoc =
7251*67e74705SXin Li SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7252*67e74705SXin Li const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7253*67e74705SXin Li Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7254*67e74705SXin Li }
7255*67e74705SXin Li }
7256*67e74705SXin Li }
7257*67e74705SXin Li
ReadTentativeDefinitions(SmallVectorImpl<VarDecl * > & TentativeDefs)7258*67e74705SXin Li void ASTReader::ReadTentativeDefinitions(
7259*67e74705SXin Li SmallVectorImpl<VarDecl *> &TentativeDefs) {
7260*67e74705SXin Li for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7261*67e74705SXin Li VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7262*67e74705SXin Li if (Var)
7263*67e74705SXin Li TentativeDefs.push_back(Var);
7264*67e74705SXin Li }
7265*67e74705SXin Li TentativeDefinitions.clear();
7266*67e74705SXin Li }
7267*67e74705SXin Li
ReadUnusedFileScopedDecls(SmallVectorImpl<const DeclaratorDecl * > & Decls)7268*67e74705SXin Li void ASTReader::ReadUnusedFileScopedDecls(
7269*67e74705SXin Li SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7270*67e74705SXin Li for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7271*67e74705SXin Li DeclaratorDecl *D
7272*67e74705SXin Li = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7273*67e74705SXin Li if (D)
7274*67e74705SXin Li Decls.push_back(D);
7275*67e74705SXin Li }
7276*67e74705SXin Li UnusedFileScopedDecls.clear();
7277*67e74705SXin Li }
7278*67e74705SXin Li
ReadDelegatingConstructors(SmallVectorImpl<CXXConstructorDecl * > & Decls)7279*67e74705SXin Li void ASTReader::ReadDelegatingConstructors(
7280*67e74705SXin Li SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7281*67e74705SXin Li for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7282*67e74705SXin Li CXXConstructorDecl *D
7283*67e74705SXin Li = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7284*67e74705SXin Li if (D)
7285*67e74705SXin Li Decls.push_back(D);
7286*67e74705SXin Li }
7287*67e74705SXin Li DelegatingCtorDecls.clear();
7288*67e74705SXin Li }
7289*67e74705SXin Li
ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl * > & Decls)7290*67e74705SXin Li void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7291*67e74705SXin Li for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7292*67e74705SXin Li TypedefNameDecl *D
7293*67e74705SXin Li = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7294*67e74705SXin Li if (D)
7295*67e74705SXin Li Decls.push_back(D);
7296*67e74705SXin Li }
7297*67e74705SXin Li ExtVectorDecls.clear();
7298*67e74705SXin Li }
7299*67e74705SXin Li
ReadUnusedLocalTypedefNameCandidates(llvm::SmallSetVector<const TypedefNameDecl *,4> & Decls)7300*67e74705SXin Li void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7301*67e74705SXin Li llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7302*67e74705SXin Li for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7303*67e74705SXin Li ++I) {
7304*67e74705SXin Li TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7305*67e74705SXin Li GetDecl(UnusedLocalTypedefNameCandidates[I]));
7306*67e74705SXin Li if (D)
7307*67e74705SXin Li Decls.insert(D);
7308*67e74705SXin Li }
7309*67e74705SXin Li UnusedLocalTypedefNameCandidates.clear();
7310*67e74705SXin Li }
7311*67e74705SXin Li
ReadReferencedSelectors(SmallVectorImpl<std::pair<Selector,SourceLocation>> & Sels)7312*67e74705SXin Li void ASTReader::ReadReferencedSelectors(
7313*67e74705SXin Li SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7314*67e74705SXin Li if (ReferencedSelectorsData.empty())
7315*67e74705SXin Li return;
7316*67e74705SXin Li
7317*67e74705SXin Li // If there are @selector references added them to its pool. This is for
7318*67e74705SXin Li // implementation of -Wselector.
7319*67e74705SXin Li unsigned int DataSize = ReferencedSelectorsData.size()-1;
7320*67e74705SXin Li unsigned I = 0;
7321*67e74705SXin Li while (I < DataSize) {
7322*67e74705SXin Li Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7323*67e74705SXin Li SourceLocation SelLoc
7324*67e74705SXin Li = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7325*67e74705SXin Li Sels.push_back(std::make_pair(Sel, SelLoc));
7326*67e74705SXin Li }
7327*67e74705SXin Li ReferencedSelectorsData.clear();
7328*67e74705SXin Li }
7329*67e74705SXin Li
ReadWeakUndeclaredIdentifiers(SmallVectorImpl<std::pair<IdentifierInfo *,WeakInfo>> & WeakIDs)7330*67e74705SXin Li void ASTReader::ReadWeakUndeclaredIdentifiers(
7331*67e74705SXin Li SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7332*67e74705SXin Li if (WeakUndeclaredIdentifiers.empty())
7333*67e74705SXin Li return;
7334*67e74705SXin Li
7335*67e74705SXin Li for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7336*67e74705SXin Li IdentifierInfo *WeakId
7337*67e74705SXin Li = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7338*67e74705SXin Li IdentifierInfo *AliasId
7339*67e74705SXin Li = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7340*67e74705SXin Li SourceLocation Loc
7341*67e74705SXin Li = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7342*67e74705SXin Li bool Used = WeakUndeclaredIdentifiers[I++];
7343*67e74705SXin Li WeakInfo WI(AliasId, Loc);
7344*67e74705SXin Li WI.setUsed(Used);
7345*67e74705SXin Li WeakIDs.push_back(std::make_pair(WeakId, WI));
7346*67e74705SXin Li }
7347*67e74705SXin Li WeakUndeclaredIdentifiers.clear();
7348*67e74705SXin Li }
7349*67e74705SXin Li
ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> & VTables)7350*67e74705SXin Li void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7351*67e74705SXin Li for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7352*67e74705SXin Li ExternalVTableUse VT;
7353*67e74705SXin Li VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7354*67e74705SXin Li VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7355*67e74705SXin Li VT.DefinitionRequired = VTableUses[Idx++];
7356*67e74705SXin Li VTables.push_back(VT);
7357*67e74705SXin Li }
7358*67e74705SXin Li
7359*67e74705SXin Li VTableUses.clear();
7360*67e74705SXin Li }
7361*67e74705SXin Li
ReadPendingInstantiations(SmallVectorImpl<std::pair<ValueDecl *,SourceLocation>> & Pending)7362*67e74705SXin Li void ASTReader::ReadPendingInstantiations(
7363*67e74705SXin Li SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7364*67e74705SXin Li for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7365*67e74705SXin Li ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7366*67e74705SXin Li SourceLocation Loc
7367*67e74705SXin Li = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7368*67e74705SXin Li
7369*67e74705SXin Li Pending.push_back(std::make_pair(D, Loc));
7370*67e74705SXin Li }
7371*67e74705SXin Li PendingInstantiations.clear();
7372*67e74705SXin Li }
7373*67e74705SXin Li
ReadLateParsedTemplates(llvm::MapVector<const FunctionDecl *,LateParsedTemplate * > & LPTMap)7374*67e74705SXin Li void ASTReader::ReadLateParsedTemplates(
7375*67e74705SXin Li llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7376*67e74705SXin Li for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7377*67e74705SXin Li /* In loop */) {
7378*67e74705SXin Li FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7379*67e74705SXin Li
7380*67e74705SXin Li LateParsedTemplate *LT = new LateParsedTemplate;
7381*67e74705SXin Li LT->D = GetDecl(LateParsedTemplates[Idx++]);
7382*67e74705SXin Li
7383*67e74705SXin Li ModuleFile *F = getOwningModuleFile(LT->D);
7384*67e74705SXin Li assert(F && "No module");
7385*67e74705SXin Li
7386*67e74705SXin Li unsigned TokN = LateParsedTemplates[Idx++];
7387*67e74705SXin Li LT->Toks.reserve(TokN);
7388*67e74705SXin Li for (unsigned T = 0; T < TokN; ++T)
7389*67e74705SXin Li LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7390*67e74705SXin Li
7391*67e74705SXin Li LPTMap.insert(std::make_pair(FD, LT));
7392*67e74705SXin Li }
7393*67e74705SXin Li
7394*67e74705SXin Li LateParsedTemplates.clear();
7395*67e74705SXin Li }
7396*67e74705SXin Li
LoadSelector(Selector Sel)7397*67e74705SXin Li void ASTReader::LoadSelector(Selector Sel) {
7398*67e74705SXin Li // It would be complicated to avoid reading the methods anyway. So don't.
7399*67e74705SXin Li ReadMethodPool(Sel);
7400*67e74705SXin Li }
7401*67e74705SXin Li
SetIdentifierInfo(IdentifierID ID,IdentifierInfo * II)7402*67e74705SXin Li void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7403*67e74705SXin Li assert(ID && "Non-zero identifier ID required");
7404*67e74705SXin Li assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7405*67e74705SXin Li IdentifiersLoaded[ID - 1] = II;
7406*67e74705SXin Li if (DeserializationListener)
7407*67e74705SXin Li DeserializationListener->IdentifierRead(ID, II);
7408*67e74705SXin Li }
7409*67e74705SXin Li
7410*67e74705SXin Li /// \brief Set the globally-visible declarations associated with the given
7411*67e74705SXin Li /// identifier.
7412*67e74705SXin Li ///
7413*67e74705SXin Li /// If the AST reader is currently in a state where the given declaration IDs
7414*67e74705SXin Li /// cannot safely be resolved, they are queued until it is safe to resolve
7415*67e74705SXin Li /// them.
7416*67e74705SXin Li ///
7417*67e74705SXin Li /// \param II an IdentifierInfo that refers to one or more globally-visible
7418*67e74705SXin Li /// declarations.
7419*67e74705SXin Li ///
7420*67e74705SXin Li /// \param DeclIDs the set of declaration IDs with the name @p II that are
7421*67e74705SXin Li /// visible at global scope.
7422*67e74705SXin Li ///
7423*67e74705SXin Li /// \param Decls if non-null, this vector will be populated with the set of
7424*67e74705SXin Li /// deserialized declarations. These declarations will not be pushed into
7425*67e74705SXin Li /// scope.
7426*67e74705SXin Li void
SetGloballyVisibleDecls(IdentifierInfo * II,const SmallVectorImpl<uint32_t> & DeclIDs,SmallVectorImpl<Decl * > * Decls)7427*67e74705SXin Li ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7428*67e74705SXin Li const SmallVectorImpl<uint32_t> &DeclIDs,
7429*67e74705SXin Li SmallVectorImpl<Decl *> *Decls) {
7430*67e74705SXin Li if (NumCurrentElementsDeserializing && !Decls) {
7431*67e74705SXin Li PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
7432*67e74705SXin Li return;
7433*67e74705SXin Li }
7434*67e74705SXin Li
7435*67e74705SXin Li for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7436*67e74705SXin Li if (!SemaObj) {
7437*67e74705SXin Li // Queue this declaration so that it will be added to the
7438*67e74705SXin Li // translation unit scope and identifier's declaration chain
7439*67e74705SXin Li // once a Sema object is known.
7440*67e74705SXin Li PreloadedDeclIDs.push_back(DeclIDs[I]);
7441*67e74705SXin Li continue;
7442*67e74705SXin Li }
7443*67e74705SXin Li
7444*67e74705SXin Li NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7445*67e74705SXin Li
7446*67e74705SXin Li // If we're simply supposed to record the declarations, do so now.
7447*67e74705SXin Li if (Decls) {
7448*67e74705SXin Li Decls->push_back(D);
7449*67e74705SXin Li continue;
7450*67e74705SXin Li }
7451*67e74705SXin Li
7452*67e74705SXin Li // Introduce this declaration into the translation-unit scope
7453*67e74705SXin Li // and add it to the declaration chain for this identifier, so
7454*67e74705SXin Li // that (unqualified) name lookup will find it.
7455*67e74705SXin Li pushExternalDeclIntoScope(D, II);
7456*67e74705SXin Li }
7457*67e74705SXin Li }
7458*67e74705SXin Li
DecodeIdentifierInfo(IdentifierID ID)7459*67e74705SXin Li IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
7460*67e74705SXin Li if (ID == 0)
7461*67e74705SXin Li return nullptr;
7462*67e74705SXin Li
7463*67e74705SXin Li if (IdentifiersLoaded.empty()) {
7464*67e74705SXin Li Error("no identifier table in AST file");
7465*67e74705SXin Li return nullptr;
7466*67e74705SXin Li }
7467*67e74705SXin Li
7468*67e74705SXin Li ID -= 1;
7469*67e74705SXin Li if (!IdentifiersLoaded[ID]) {
7470*67e74705SXin Li GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7471*67e74705SXin Li assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7472*67e74705SXin Li ModuleFile *M = I->second;
7473*67e74705SXin Li unsigned Index = ID - M->BaseIdentifierID;
7474*67e74705SXin Li const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7475*67e74705SXin Li
7476*67e74705SXin Li // All of the strings in the AST file are preceded by a 16-bit length.
7477*67e74705SXin Li // Extract that 16-bit length to avoid having to execute strlen().
7478*67e74705SXin Li // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7479*67e74705SXin Li // unsigned integers. This is important to avoid integer overflow when
7480*67e74705SXin Li // we cast them to 'unsigned'.
7481*67e74705SXin Li const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7482*67e74705SXin Li unsigned StrLen = (((unsigned) StrLenPtr[0])
7483*67e74705SXin Li | (((unsigned) StrLenPtr[1]) << 8)) - 1;
7484*67e74705SXin Li auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7485*67e74705SXin Li IdentifiersLoaded[ID] = &II;
7486*67e74705SXin Li markIdentifierFromAST(*this, II);
7487*67e74705SXin Li if (DeserializationListener)
7488*67e74705SXin Li DeserializationListener->IdentifierRead(ID + 1, &II);
7489*67e74705SXin Li }
7490*67e74705SXin Li
7491*67e74705SXin Li return IdentifiersLoaded[ID];
7492*67e74705SXin Li }
7493*67e74705SXin Li
getLocalIdentifier(ModuleFile & M,unsigned LocalID)7494*67e74705SXin Li IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7495*67e74705SXin Li return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
7496*67e74705SXin Li }
7497*67e74705SXin Li
getGlobalIdentifierID(ModuleFile & M,unsigned LocalID)7498*67e74705SXin Li IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7499*67e74705SXin Li if (LocalID < NUM_PREDEF_IDENT_IDS)
7500*67e74705SXin Li return LocalID;
7501*67e74705SXin Li
7502*67e74705SXin Li ContinuousRangeMap<uint32_t, int, 2>::iterator I
7503*67e74705SXin Li = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7504*67e74705SXin Li assert(I != M.IdentifierRemap.end()
7505*67e74705SXin Li && "Invalid index into identifier index remap");
7506*67e74705SXin Li
7507*67e74705SXin Li return LocalID + I->second;
7508*67e74705SXin Li }
7509*67e74705SXin Li
getMacro(MacroID ID)7510*67e74705SXin Li MacroInfo *ASTReader::getMacro(MacroID ID) {
7511*67e74705SXin Li if (ID == 0)
7512*67e74705SXin Li return nullptr;
7513*67e74705SXin Li
7514*67e74705SXin Li if (MacrosLoaded.empty()) {
7515*67e74705SXin Li Error("no macro table in AST file");
7516*67e74705SXin Li return nullptr;
7517*67e74705SXin Li }
7518*67e74705SXin Li
7519*67e74705SXin Li ID -= NUM_PREDEF_MACRO_IDS;
7520*67e74705SXin Li if (!MacrosLoaded[ID]) {
7521*67e74705SXin Li GlobalMacroMapType::iterator I
7522*67e74705SXin Li = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7523*67e74705SXin Li assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7524*67e74705SXin Li ModuleFile *M = I->second;
7525*67e74705SXin Li unsigned Index = ID - M->BaseMacroID;
7526*67e74705SXin Li MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7527*67e74705SXin Li
7528*67e74705SXin Li if (DeserializationListener)
7529*67e74705SXin Li DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7530*67e74705SXin Li MacrosLoaded[ID]);
7531*67e74705SXin Li }
7532*67e74705SXin Li
7533*67e74705SXin Li return MacrosLoaded[ID];
7534*67e74705SXin Li }
7535*67e74705SXin Li
getGlobalMacroID(ModuleFile & M,unsigned LocalID)7536*67e74705SXin Li MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7537*67e74705SXin Li if (LocalID < NUM_PREDEF_MACRO_IDS)
7538*67e74705SXin Li return LocalID;
7539*67e74705SXin Li
7540*67e74705SXin Li ContinuousRangeMap<uint32_t, int, 2>::iterator I
7541*67e74705SXin Li = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7542*67e74705SXin Li assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7543*67e74705SXin Li
7544*67e74705SXin Li return LocalID + I->second;
7545*67e74705SXin Li }
7546*67e74705SXin Li
7547*67e74705SXin Li serialization::SubmoduleID
getGlobalSubmoduleID(ModuleFile & M,unsigned LocalID)7548*67e74705SXin Li ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7549*67e74705SXin Li if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7550*67e74705SXin Li return LocalID;
7551*67e74705SXin Li
7552*67e74705SXin Li ContinuousRangeMap<uint32_t, int, 2>::iterator I
7553*67e74705SXin Li = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7554*67e74705SXin Li assert(I != M.SubmoduleRemap.end()
7555*67e74705SXin Li && "Invalid index into submodule index remap");
7556*67e74705SXin Li
7557*67e74705SXin Li return LocalID + I->second;
7558*67e74705SXin Li }
7559*67e74705SXin Li
getSubmodule(SubmoduleID GlobalID)7560*67e74705SXin Li Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7561*67e74705SXin Li if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7562*67e74705SXin Li assert(GlobalID == 0 && "Unhandled global submodule ID");
7563*67e74705SXin Li return nullptr;
7564*67e74705SXin Li }
7565*67e74705SXin Li
7566*67e74705SXin Li if (GlobalID > SubmodulesLoaded.size()) {
7567*67e74705SXin Li Error("submodule ID out of range in AST file");
7568*67e74705SXin Li return nullptr;
7569*67e74705SXin Li }
7570*67e74705SXin Li
7571*67e74705SXin Li return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7572*67e74705SXin Li }
7573*67e74705SXin Li
getModule(unsigned ID)7574*67e74705SXin Li Module *ASTReader::getModule(unsigned ID) {
7575*67e74705SXin Li return getSubmodule(ID);
7576*67e74705SXin Li }
7577*67e74705SXin Li
getLocalModuleFile(ModuleFile & F,unsigned ID)7578*67e74705SXin Li ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7579*67e74705SXin Li if (ID & 1) {
7580*67e74705SXin Li // It's a module, look it up by submodule ID.
7581*67e74705SXin Li auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7582*67e74705SXin Li return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7583*67e74705SXin Li } else {
7584*67e74705SXin Li // It's a prefix (preamble, PCH, ...). Look it up by index.
7585*67e74705SXin Li unsigned IndexFromEnd = ID >> 1;
7586*67e74705SXin Li assert(IndexFromEnd && "got reference to unknown module file");
7587*67e74705SXin Li return getModuleManager().pch_modules().end()[-IndexFromEnd];
7588*67e74705SXin Li }
7589*67e74705SXin Li }
7590*67e74705SXin Li
getModuleFileID(ModuleFile * F)7591*67e74705SXin Li unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7592*67e74705SXin Li if (!F)
7593*67e74705SXin Li return 1;
7594*67e74705SXin Li
7595*67e74705SXin Li // For a file representing a module, use the submodule ID of the top-level
7596*67e74705SXin Li // module as the file ID. For any other kind of file, the number of such
7597*67e74705SXin Li // files loaded beforehand will be the same on reload.
7598*67e74705SXin Li // FIXME: Is this true even if we have an explicit module file and a PCH?
7599*67e74705SXin Li if (F->isModule())
7600*67e74705SXin Li return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7601*67e74705SXin Li
7602*67e74705SXin Li auto PCHModules = getModuleManager().pch_modules();
7603*67e74705SXin Li auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7604*67e74705SXin Li assert(I != PCHModules.end() && "emitting reference to unknown file");
7605*67e74705SXin Li return (I - PCHModules.end()) << 1;
7606*67e74705SXin Li }
7607*67e74705SXin Li
7608*67e74705SXin Li llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
getSourceDescriptor(unsigned ID)7609*67e74705SXin Li ASTReader::getSourceDescriptor(unsigned ID) {
7610*67e74705SXin Li if (const Module *M = getSubmodule(ID))
7611*67e74705SXin Li return ExternalASTSource::ASTSourceDescriptor(*M);
7612*67e74705SXin Li
7613*67e74705SXin Li // If there is only a single PCH, return it instead.
7614*67e74705SXin Li // Chained PCH are not suported.
7615*67e74705SXin Li if (ModuleMgr.size() == 1) {
7616*67e74705SXin Li ModuleFile &MF = ModuleMgr.getPrimaryModule();
7617*67e74705SXin Li StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
7618*67e74705SXin Li StringRef FileName = llvm::sys::path::filename(MF.FileName);
7619*67e74705SXin Li return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
7620*67e74705SXin Li MF.Signature);
7621*67e74705SXin Li }
7622*67e74705SXin Li return None;
7623*67e74705SXin Li }
7624*67e74705SXin Li
getLocalSelector(ModuleFile & M,unsigned LocalID)7625*67e74705SXin Li Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7626*67e74705SXin Li return DecodeSelector(getGlobalSelectorID(M, LocalID));
7627*67e74705SXin Li }
7628*67e74705SXin Li
DecodeSelector(serialization::SelectorID ID)7629*67e74705SXin Li Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7630*67e74705SXin Li if (ID == 0)
7631*67e74705SXin Li return Selector();
7632*67e74705SXin Li
7633*67e74705SXin Li if (ID > SelectorsLoaded.size()) {
7634*67e74705SXin Li Error("selector ID out of range in AST file");
7635*67e74705SXin Li return Selector();
7636*67e74705SXin Li }
7637*67e74705SXin Li
7638*67e74705SXin Li if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
7639*67e74705SXin Li // Load this selector from the selector table.
7640*67e74705SXin Li GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7641*67e74705SXin Li assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7642*67e74705SXin Li ModuleFile &M = *I->second;
7643*67e74705SXin Li ASTSelectorLookupTrait Trait(*this, M);
7644*67e74705SXin Li unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7645*67e74705SXin Li SelectorsLoaded[ID - 1] =
7646*67e74705SXin Li Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7647*67e74705SXin Li if (DeserializationListener)
7648*67e74705SXin Li DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7649*67e74705SXin Li }
7650*67e74705SXin Li
7651*67e74705SXin Li return SelectorsLoaded[ID - 1];
7652*67e74705SXin Li }
7653*67e74705SXin Li
GetExternalSelector(serialization::SelectorID ID)7654*67e74705SXin Li Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7655*67e74705SXin Li return DecodeSelector(ID);
7656*67e74705SXin Li }
7657*67e74705SXin Li
GetNumExternalSelectors()7658*67e74705SXin Li uint32_t ASTReader::GetNumExternalSelectors() {
7659*67e74705SXin Li // ID 0 (the null selector) is considered an external selector.
7660*67e74705SXin Li return getTotalNumSelectors() + 1;
7661*67e74705SXin Li }
7662*67e74705SXin Li
7663*67e74705SXin Li serialization::SelectorID
getGlobalSelectorID(ModuleFile & M,unsigned LocalID) const7664*67e74705SXin Li ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7665*67e74705SXin Li if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7666*67e74705SXin Li return LocalID;
7667*67e74705SXin Li
7668*67e74705SXin Li ContinuousRangeMap<uint32_t, int, 2>::iterator I
7669*67e74705SXin Li = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7670*67e74705SXin Li assert(I != M.SelectorRemap.end()
7671*67e74705SXin Li && "Invalid index into selector index remap");
7672*67e74705SXin Li
7673*67e74705SXin Li return LocalID + I->second;
7674*67e74705SXin Li }
7675*67e74705SXin Li
7676*67e74705SXin Li DeclarationName
ReadDeclarationName(ModuleFile & F,const RecordData & Record,unsigned & Idx)7677*67e74705SXin Li ASTReader::ReadDeclarationName(ModuleFile &F,
7678*67e74705SXin Li const RecordData &Record, unsigned &Idx) {
7679*67e74705SXin Li DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7680*67e74705SXin Li switch (Kind) {
7681*67e74705SXin Li case DeclarationName::Identifier:
7682*67e74705SXin Li return DeclarationName(GetIdentifierInfo(F, Record, Idx));
7683*67e74705SXin Li
7684*67e74705SXin Li case DeclarationName::ObjCZeroArgSelector:
7685*67e74705SXin Li case DeclarationName::ObjCOneArgSelector:
7686*67e74705SXin Li case DeclarationName::ObjCMultiArgSelector:
7687*67e74705SXin Li return DeclarationName(ReadSelector(F, Record, Idx));
7688*67e74705SXin Li
7689*67e74705SXin Li case DeclarationName::CXXConstructorName:
7690*67e74705SXin Li return Context.DeclarationNames.getCXXConstructorName(
7691*67e74705SXin Li Context.getCanonicalType(readType(F, Record, Idx)));
7692*67e74705SXin Li
7693*67e74705SXin Li case DeclarationName::CXXDestructorName:
7694*67e74705SXin Li return Context.DeclarationNames.getCXXDestructorName(
7695*67e74705SXin Li Context.getCanonicalType(readType(F, Record, Idx)));
7696*67e74705SXin Li
7697*67e74705SXin Li case DeclarationName::CXXConversionFunctionName:
7698*67e74705SXin Li return Context.DeclarationNames.getCXXConversionFunctionName(
7699*67e74705SXin Li Context.getCanonicalType(readType(F, Record, Idx)));
7700*67e74705SXin Li
7701*67e74705SXin Li case DeclarationName::CXXOperatorName:
7702*67e74705SXin Li return Context.DeclarationNames.getCXXOperatorName(
7703*67e74705SXin Li (OverloadedOperatorKind)Record[Idx++]);
7704*67e74705SXin Li
7705*67e74705SXin Li case DeclarationName::CXXLiteralOperatorName:
7706*67e74705SXin Li return Context.DeclarationNames.getCXXLiteralOperatorName(
7707*67e74705SXin Li GetIdentifierInfo(F, Record, Idx));
7708*67e74705SXin Li
7709*67e74705SXin Li case DeclarationName::CXXUsingDirective:
7710*67e74705SXin Li return DeclarationName::getUsingDirectiveName();
7711*67e74705SXin Li }
7712*67e74705SXin Li
7713*67e74705SXin Li llvm_unreachable("Invalid NameKind!");
7714*67e74705SXin Li }
7715*67e74705SXin Li
ReadDeclarationNameLoc(ModuleFile & F,DeclarationNameLoc & DNLoc,DeclarationName Name,const RecordData & Record,unsigned & Idx)7716*67e74705SXin Li void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7717*67e74705SXin Li DeclarationNameLoc &DNLoc,
7718*67e74705SXin Li DeclarationName Name,
7719*67e74705SXin Li const RecordData &Record, unsigned &Idx) {
7720*67e74705SXin Li switch (Name.getNameKind()) {
7721*67e74705SXin Li case DeclarationName::CXXConstructorName:
7722*67e74705SXin Li case DeclarationName::CXXDestructorName:
7723*67e74705SXin Li case DeclarationName::CXXConversionFunctionName:
7724*67e74705SXin Li DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7725*67e74705SXin Li break;
7726*67e74705SXin Li
7727*67e74705SXin Li case DeclarationName::CXXOperatorName:
7728*67e74705SXin Li DNLoc.CXXOperatorName.BeginOpNameLoc
7729*67e74705SXin Li = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7730*67e74705SXin Li DNLoc.CXXOperatorName.EndOpNameLoc
7731*67e74705SXin Li = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7732*67e74705SXin Li break;
7733*67e74705SXin Li
7734*67e74705SXin Li case DeclarationName::CXXLiteralOperatorName:
7735*67e74705SXin Li DNLoc.CXXLiteralOperatorName.OpNameLoc
7736*67e74705SXin Li = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7737*67e74705SXin Li break;
7738*67e74705SXin Li
7739*67e74705SXin Li case DeclarationName::Identifier:
7740*67e74705SXin Li case DeclarationName::ObjCZeroArgSelector:
7741*67e74705SXin Li case DeclarationName::ObjCOneArgSelector:
7742*67e74705SXin Li case DeclarationName::ObjCMultiArgSelector:
7743*67e74705SXin Li case DeclarationName::CXXUsingDirective:
7744*67e74705SXin Li break;
7745*67e74705SXin Li }
7746*67e74705SXin Li }
7747*67e74705SXin Li
ReadDeclarationNameInfo(ModuleFile & F,DeclarationNameInfo & NameInfo,const RecordData & Record,unsigned & Idx)7748*67e74705SXin Li void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7749*67e74705SXin Li DeclarationNameInfo &NameInfo,
7750*67e74705SXin Li const RecordData &Record, unsigned &Idx) {
7751*67e74705SXin Li NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7752*67e74705SXin Li NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7753*67e74705SXin Li DeclarationNameLoc DNLoc;
7754*67e74705SXin Li ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7755*67e74705SXin Li NameInfo.setInfo(DNLoc);
7756*67e74705SXin Li }
7757*67e74705SXin Li
ReadQualifierInfo(ModuleFile & F,QualifierInfo & Info,const RecordData & Record,unsigned & Idx)7758*67e74705SXin Li void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7759*67e74705SXin Li const RecordData &Record, unsigned &Idx) {
7760*67e74705SXin Li Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7761*67e74705SXin Li unsigned NumTPLists = Record[Idx++];
7762*67e74705SXin Li Info.NumTemplParamLists = NumTPLists;
7763*67e74705SXin Li if (NumTPLists) {
7764*67e74705SXin Li Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7765*67e74705SXin Li for (unsigned i=0; i != NumTPLists; ++i)
7766*67e74705SXin Li Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7767*67e74705SXin Li }
7768*67e74705SXin Li }
7769*67e74705SXin Li
7770*67e74705SXin Li TemplateName
ReadTemplateName(ModuleFile & F,const RecordData & Record,unsigned & Idx)7771*67e74705SXin Li ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7772*67e74705SXin Li unsigned &Idx) {
7773*67e74705SXin Li TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7774*67e74705SXin Li switch (Kind) {
7775*67e74705SXin Li case TemplateName::Template:
7776*67e74705SXin Li return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7777*67e74705SXin Li
7778*67e74705SXin Li case TemplateName::OverloadedTemplate: {
7779*67e74705SXin Li unsigned size = Record[Idx++];
7780*67e74705SXin Li UnresolvedSet<8> Decls;
7781*67e74705SXin Li while (size--)
7782*67e74705SXin Li Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7783*67e74705SXin Li
7784*67e74705SXin Li return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7785*67e74705SXin Li }
7786*67e74705SXin Li
7787*67e74705SXin Li case TemplateName::QualifiedTemplate: {
7788*67e74705SXin Li NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7789*67e74705SXin Li bool hasTemplKeyword = Record[Idx++];
7790*67e74705SXin Li TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7791*67e74705SXin Li return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7792*67e74705SXin Li }
7793*67e74705SXin Li
7794*67e74705SXin Li case TemplateName::DependentTemplate: {
7795*67e74705SXin Li NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7796*67e74705SXin Li if (Record[Idx++]) // isIdentifier
7797*67e74705SXin Li return Context.getDependentTemplateName(NNS,
7798*67e74705SXin Li GetIdentifierInfo(F, Record,
7799*67e74705SXin Li Idx));
7800*67e74705SXin Li return Context.getDependentTemplateName(NNS,
7801*67e74705SXin Li (OverloadedOperatorKind)Record[Idx++]);
7802*67e74705SXin Li }
7803*67e74705SXin Li
7804*67e74705SXin Li case TemplateName::SubstTemplateTemplateParm: {
7805*67e74705SXin Li TemplateTemplateParmDecl *param
7806*67e74705SXin Li = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7807*67e74705SXin Li if (!param) return TemplateName();
7808*67e74705SXin Li TemplateName replacement = ReadTemplateName(F, Record, Idx);
7809*67e74705SXin Li return Context.getSubstTemplateTemplateParm(param, replacement);
7810*67e74705SXin Li }
7811*67e74705SXin Li
7812*67e74705SXin Li case TemplateName::SubstTemplateTemplateParmPack: {
7813*67e74705SXin Li TemplateTemplateParmDecl *Param
7814*67e74705SXin Li = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7815*67e74705SXin Li if (!Param)
7816*67e74705SXin Li return TemplateName();
7817*67e74705SXin Li
7818*67e74705SXin Li TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7819*67e74705SXin Li if (ArgPack.getKind() != TemplateArgument::Pack)
7820*67e74705SXin Li return TemplateName();
7821*67e74705SXin Li
7822*67e74705SXin Li return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7823*67e74705SXin Li }
7824*67e74705SXin Li }
7825*67e74705SXin Li
7826*67e74705SXin Li llvm_unreachable("Unhandled template name kind!");
7827*67e74705SXin Li }
7828*67e74705SXin Li
ReadTemplateArgument(ModuleFile & F,const RecordData & Record,unsigned & Idx,bool Canonicalize)7829*67e74705SXin Li TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7830*67e74705SXin Li const RecordData &Record,
7831*67e74705SXin Li unsigned &Idx,
7832*67e74705SXin Li bool Canonicalize) {
7833*67e74705SXin Li if (Canonicalize) {
7834*67e74705SXin Li // The caller wants a canonical template argument. Sometimes the AST only
7835*67e74705SXin Li // wants template arguments in canonical form (particularly as the template
7836*67e74705SXin Li // argument lists of template specializations) so ensure we preserve that
7837*67e74705SXin Li // canonical form across serialization.
7838*67e74705SXin Li TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7839*67e74705SXin Li return Context.getCanonicalTemplateArgument(Arg);
7840*67e74705SXin Li }
7841*67e74705SXin Li
7842*67e74705SXin Li TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7843*67e74705SXin Li switch (Kind) {
7844*67e74705SXin Li case TemplateArgument::Null:
7845*67e74705SXin Li return TemplateArgument();
7846*67e74705SXin Li case TemplateArgument::Type:
7847*67e74705SXin Li return TemplateArgument(readType(F, Record, Idx));
7848*67e74705SXin Li case TemplateArgument::Declaration: {
7849*67e74705SXin Li ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7850*67e74705SXin Li return TemplateArgument(D, readType(F, Record, Idx));
7851*67e74705SXin Li }
7852*67e74705SXin Li case TemplateArgument::NullPtr:
7853*67e74705SXin Li return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7854*67e74705SXin Li case TemplateArgument::Integral: {
7855*67e74705SXin Li llvm::APSInt Value = ReadAPSInt(Record, Idx);
7856*67e74705SXin Li QualType T = readType(F, Record, Idx);
7857*67e74705SXin Li return TemplateArgument(Context, Value, T);
7858*67e74705SXin Li }
7859*67e74705SXin Li case TemplateArgument::Template:
7860*67e74705SXin Li return TemplateArgument(ReadTemplateName(F, Record, Idx));
7861*67e74705SXin Li case TemplateArgument::TemplateExpansion: {
7862*67e74705SXin Li TemplateName Name = ReadTemplateName(F, Record, Idx);
7863*67e74705SXin Li Optional<unsigned> NumTemplateExpansions;
7864*67e74705SXin Li if (unsigned NumExpansions = Record[Idx++])
7865*67e74705SXin Li NumTemplateExpansions = NumExpansions - 1;
7866*67e74705SXin Li return TemplateArgument(Name, NumTemplateExpansions);
7867*67e74705SXin Li }
7868*67e74705SXin Li case TemplateArgument::Expression:
7869*67e74705SXin Li return TemplateArgument(ReadExpr(F));
7870*67e74705SXin Li case TemplateArgument::Pack: {
7871*67e74705SXin Li unsigned NumArgs = Record[Idx++];
7872*67e74705SXin Li TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7873*67e74705SXin Li for (unsigned I = 0; I != NumArgs; ++I)
7874*67e74705SXin Li Args[I] = ReadTemplateArgument(F, Record, Idx);
7875*67e74705SXin Li return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
7876*67e74705SXin Li }
7877*67e74705SXin Li }
7878*67e74705SXin Li
7879*67e74705SXin Li llvm_unreachable("Unhandled template argument kind!");
7880*67e74705SXin Li }
7881*67e74705SXin Li
7882*67e74705SXin Li TemplateParameterList *
ReadTemplateParameterList(ModuleFile & F,const RecordData & Record,unsigned & Idx)7883*67e74705SXin Li ASTReader::ReadTemplateParameterList(ModuleFile &F,
7884*67e74705SXin Li const RecordData &Record, unsigned &Idx) {
7885*67e74705SXin Li SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7886*67e74705SXin Li SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7887*67e74705SXin Li SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7888*67e74705SXin Li
7889*67e74705SXin Li unsigned NumParams = Record[Idx++];
7890*67e74705SXin Li SmallVector<NamedDecl *, 16> Params;
7891*67e74705SXin Li Params.reserve(NumParams);
7892*67e74705SXin Li while (NumParams--)
7893*67e74705SXin Li Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7894*67e74705SXin Li
7895*67e74705SXin Li TemplateParameterList* TemplateParams =
7896*67e74705SXin Li TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7897*67e74705SXin Li Params, RAngleLoc);
7898*67e74705SXin Li return TemplateParams;
7899*67e74705SXin Li }
7900*67e74705SXin Li
7901*67e74705SXin Li void
7902*67e74705SXin Li ASTReader::
ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> & TemplArgs,ModuleFile & F,const RecordData & Record,unsigned & Idx,bool Canonicalize)7903*67e74705SXin Li ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
7904*67e74705SXin Li ModuleFile &F, const RecordData &Record,
7905*67e74705SXin Li unsigned &Idx, bool Canonicalize) {
7906*67e74705SXin Li unsigned NumTemplateArgs = Record[Idx++];
7907*67e74705SXin Li TemplArgs.reserve(NumTemplateArgs);
7908*67e74705SXin Li while (NumTemplateArgs--)
7909*67e74705SXin Li TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
7910*67e74705SXin Li }
7911*67e74705SXin Li
7912*67e74705SXin Li /// \brief Read a UnresolvedSet structure.
ReadUnresolvedSet(ModuleFile & F,LazyASTUnresolvedSet & Set,const RecordData & Record,unsigned & Idx)7913*67e74705SXin Li void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
7914*67e74705SXin Li const RecordData &Record, unsigned &Idx) {
7915*67e74705SXin Li unsigned NumDecls = Record[Idx++];
7916*67e74705SXin Li Set.reserve(Context, NumDecls);
7917*67e74705SXin Li while (NumDecls--) {
7918*67e74705SXin Li DeclID ID = ReadDeclID(F, Record, Idx);
7919*67e74705SXin Li AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
7920*67e74705SXin Li Set.addLazyDecl(Context, ID, AS);
7921*67e74705SXin Li }
7922*67e74705SXin Li }
7923*67e74705SXin Li
7924*67e74705SXin Li CXXBaseSpecifier
ReadCXXBaseSpecifier(ModuleFile & F,const RecordData & Record,unsigned & Idx)7925*67e74705SXin Li ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7926*67e74705SXin Li const RecordData &Record, unsigned &Idx) {
7927*67e74705SXin Li bool isVirtual = static_cast<bool>(Record[Idx++]);
7928*67e74705SXin Li bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7929*67e74705SXin Li AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7930*67e74705SXin Li bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7931*67e74705SXin Li TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7932*67e74705SXin Li SourceRange Range = ReadSourceRange(F, Record, Idx);
7933*67e74705SXin Li SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7934*67e74705SXin Li CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7935*67e74705SXin Li EllipsisLoc);
7936*67e74705SXin Li Result.setInheritConstructors(inheritConstructors);
7937*67e74705SXin Li return Result;
7938*67e74705SXin Li }
7939*67e74705SXin Li
7940*67e74705SXin Li CXXCtorInitializer **
ReadCXXCtorInitializers(ModuleFile & F,const RecordData & Record,unsigned & Idx)7941*67e74705SXin Li ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7942*67e74705SXin Li unsigned &Idx) {
7943*67e74705SXin Li unsigned NumInitializers = Record[Idx++];
7944*67e74705SXin Li assert(NumInitializers && "wrote ctor initializers but have no inits");
7945*67e74705SXin Li auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7946*67e74705SXin Li for (unsigned i = 0; i != NumInitializers; ++i) {
7947*67e74705SXin Li TypeSourceInfo *TInfo = nullptr;
7948*67e74705SXin Li bool IsBaseVirtual = false;
7949*67e74705SXin Li FieldDecl *Member = nullptr;
7950*67e74705SXin Li IndirectFieldDecl *IndirectMember = nullptr;
7951*67e74705SXin Li
7952*67e74705SXin Li CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7953*67e74705SXin Li switch (Type) {
7954*67e74705SXin Li case CTOR_INITIALIZER_BASE:
7955*67e74705SXin Li TInfo = GetTypeSourceInfo(F, Record, Idx);
7956*67e74705SXin Li IsBaseVirtual = Record[Idx++];
7957*67e74705SXin Li break;
7958*67e74705SXin Li
7959*67e74705SXin Li case CTOR_INITIALIZER_DELEGATING:
7960*67e74705SXin Li TInfo = GetTypeSourceInfo(F, Record, Idx);
7961*67e74705SXin Li break;
7962*67e74705SXin Li
7963*67e74705SXin Li case CTOR_INITIALIZER_MEMBER:
7964*67e74705SXin Li Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7965*67e74705SXin Li break;
7966*67e74705SXin Li
7967*67e74705SXin Li case CTOR_INITIALIZER_INDIRECT_MEMBER:
7968*67e74705SXin Li IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7969*67e74705SXin Li break;
7970*67e74705SXin Li }
7971*67e74705SXin Li
7972*67e74705SXin Li SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7973*67e74705SXin Li Expr *Init = ReadExpr(F);
7974*67e74705SXin Li SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7975*67e74705SXin Li SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7976*67e74705SXin Li bool IsWritten = Record[Idx++];
7977*67e74705SXin Li unsigned SourceOrderOrNumArrayIndices;
7978*67e74705SXin Li SmallVector<VarDecl *, 8> Indices;
7979*67e74705SXin Li if (IsWritten) {
7980*67e74705SXin Li SourceOrderOrNumArrayIndices = Record[Idx++];
7981*67e74705SXin Li } else {
7982*67e74705SXin Li SourceOrderOrNumArrayIndices = Record[Idx++];
7983*67e74705SXin Li Indices.reserve(SourceOrderOrNumArrayIndices);
7984*67e74705SXin Li for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7985*67e74705SXin Li Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7986*67e74705SXin Li }
7987*67e74705SXin Li
7988*67e74705SXin Li CXXCtorInitializer *BOMInit;
7989*67e74705SXin Li if (Type == CTOR_INITIALIZER_BASE) {
7990*67e74705SXin Li BOMInit = new (Context)
7991*67e74705SXin Li CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7992*67e74705SXin Li RParenLoc, MemberOrEllipsisLoc);
7993*67e74705SXin Li } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7994*67e74705SXin Li BOMInit = new (Context)
7995*67e74705SXin Li CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7996*67e74705SXin Li } else if (IsWritten) {
7997*67e74705SXin Li if (Member)
7998*67e74705SXin Li BOMInit = new (Context) CXXCtorInitializer(
7999*67e74705SXin Li Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
8000*67e74705SXin Li else
8001*67e74705SXin Li BOMInit = new (Context)
8002*67e74705SXin Li CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8003*67e74705SXin Li LParenLoc, Init, RParenLoc);
8004*67e74705SXin Li } else {
8005*67e74705SXin Li if (IndirectMember) {
8006*67e74705SXin Li assert(Indices.empty() && "Indirect field improperly initialized");
8007*67e74705SXin Li BOMInit = new (Context)
8008*67e74705SXin Li CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8009*67e74705SXin Li LParenLoc, Init, RParenLoc);
8010*67e74705SXin Li } else {
8011*67e74705SXin Li BOMInit = CXXCtorInitializer::Create(
8012*67e74705SXin Li Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
8013*67e74705SXin Li Indices.data(), Indices.size());
8014*67e74705SXin Li }
8015*67e74705SXin Li }
8016*67e74705SXin Li
8017*67e74705SXin Li if (IsWritten)
8018*67e74705SXin Li BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
8019*67e74705SXin Li CtorInitializers[i] = BOMInit;
8020*67e74705SXin Li }
8021*67e74705SXin Li
8022*67e74705SXin Li return CtorInitializers;
8023*67e74705SXin Li }
8024*67e74705SXin Li
8025*67e74705SXin Li NestedNameSpecifier *
ReadNestedNameSpecifier(ModuleFile & F,const RecordData & Record,unsigned & Idx)8026*67e74705SXin Li ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8027*67e74705SXin Li const RecordData &Record, unsigned &Idx) {
8028*67e74705SXin Li unsigned N = Record[Idx++];
8029*67e74705SXin Li NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
8030*67e74705SXin Li for (unsigned I = 0; I != N; ++I) {
8031*67e74705SXin Li NestedNameSpecifier::SpecifierKind Kind
8032*67e74705SXin Li = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8033*67e74705SXin Li switch (Kind) {
8034*67e74705SXin Li case NestedNameSpecifier::Identifier: {
8035*67e74705SXin Li IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8036*67e74705SXin Li NNS = NestedNameSpecifier::Create(Context, Prev, II);
8037*67e74705SXin Li break;
8038*67e74705SXin Li }
8039*67e74705SXin Li
8040*67e74705SXin Li case NestedNameSpecifier::Namespace: {
8041*67e74705SXin Li NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8042*67e74705SXin Li NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8043*67e74705SXin Li break;
8044*67e74705SXin Li }
8045*67e74705SXin Li
8046*67e74705SXin Li case NestedNameSpecifier::NamespaceAlias: {
8047*67e74705SXin Li NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8048*67e74705SXin Li NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8049*67e74705SXin Li break;
8050*67e74705SXin Li }
8051*67e74705SXin Li
8052*67e74705SXin Li case NestedNameSpecifier::TypeSpec:
8053*67e74705SXin Li case NestedNameSpecifier::TypeSpecWithTemplate: {
8054*67e74705SXin Li const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8055*67e74705SXin Li if (!T)
8056*67e74705SXin Li return nullptr;
8057*67e74705SXin Li
8058*67e74705SXin Li bool Template = Record[Idx++];
8059*67e74705SXin Li NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8060*67e74705SXin Li break;
8061*67e74705SXin Li }
8062*67e74705SXin Li
8063*67e74705SXin Li case NestedNameSpecifier::Global: {
8064*67e74705SXin Li NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8065*67e74705SXin Li // No associated value, and there can't be a prefix.
8066*67e74705SXin Li break;
8067*67e74705SXin Li }
8068*67e74705SXin Li
8069*67e74705SXin Li case NestedNameSpecifier::Super: {
8070*67e74705SXin Li CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8071*67e74705SXin Li NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8072*67e74705SXin Li break;
8073*67e74705SXin Li }
8074*67e74705SXin Li }
8075*67e74705SXin Li Prev = NNS;
8076*67e74705SXin Li }
8077*67e74705SXin Li return NNS;
8078*67e74705SXin Li }
8079*67e74705SXin Li
8080*67e74705SXin Li NestedNameSpecifierLoc
ReadNestedNameSpecifierLoc(ModuleFile & F,const RecordData & Record,unsigned & Idx)8081*67e74705SXin Li ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8082*67e74705SXin Li unsigned &Idx) {
8083*67e74705SXin Li unsigned N = Record[Idx++];
8084*67e74705SXin Li NestedNameSpecifierLocBuilder Builder;
8085*67e74705SXin Li for (unsigned I = 0; I != N; ++I) {
8086*67e74705SXin Li NestedNameSpecifier::SpecifierKind Kind
8087*67e74705SXin Li = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8088*67e74705SXin Li switch (Kind) {
8089*67e74705SXin Li case NestedNameSpecifier::Identifier: {
8090*67e74705SXin Li IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8091*67e74705SXin Li SourceRange Range = ReadSourceRange(F, Record, Idx);
8092*67e74705SXin Li Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8093*67e74705SXin Li break;
8094*67e74705SXin Li }
8095*67e74705SXin Li
8096*67e74705SXin Li case NestedNameSpecifier::Namespace: {
8097*67e74705SXin Li NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8098*67e74705SXin Li SourceRange Range = ReadSourceRange(F, Record, Idx);
8099*67e74705SXin Li Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8100*67e74705SXin Li break;
8101*67e74705SXin Li }
8102*67e74705SXin Li
8103*67e74705SXin Li case NestedNameSpecifier::NamespaceAlias: {
8104*67e74705SXin Li NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8105*67e74705SXin Li SourceRange Range = ReadSourceRange(F, Record, Idx);
8106*67e74705SXin Li Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8107*67e74705SXin Li break;
8108*67e74705SXin Li }
8109*67e74705SXin Li
8110*67e74705SXin Li case NestedNameSpecifier::TypeSpec:
8111*67e74705SXin Li case NestedNameSpecifier::TypeSpecWithTemplate: {
8112*67e74705SXin Li bool Template = Record[Idx++];
8113*67e74705SXin Li TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8114*67e74705SXin Li if (!T)
8115*67e74705SXin Li return NestedNameSpecifierLoc();
8116*67e74705SXin Li SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8117*67e74705SXin Li
8118*67e74705SXin Li // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8119*67e74705SXin Li Builder.Extend(Context,
8120*67e74705SXin Li Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8121*67e74705SXin Li T->getTypeLoc(), ColonColonLoc);
8122*67e74705SXin Li break;
8123*67e74705SXin Li }
8124*67e74705SXin Li
8125*67e74705SXin Li case NestedNameSpecifier::Global: {
8126*67e74705SXin Li SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8127*67e74705SXin Li Builder.MakeGlobal(Context, ColonColonLoc);
8128*67e74705SXin Li break;
8129*67e74705SXin Li }
8130*67e74705SXin Li
8131*67e74705SXin Li case NestedNameSpecifier::Super: {
8132*67e74705SXin Li CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8133*67e74705SXin Li SourceRange Range = ReadSourceRange(F, Record, Idx);
8134*67e74705SXin Li Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8135*67e74705SXin Li break;
8136*67e74705SXin Li }
8137*67e74705SXin Li }
8138*67e74705SXin Li }
8139*67e74705SXin Li
8140*67e74705SXin Li return Builder.getWithLocInContext(Context);
8141*67e74705SXin Li }
8142*67e74705SXin Li
8143*67e74705SXin Li SourceRange
ReadSourceRange(ModuleFile & F,const RecordData & Record,unsigned & Idx)8144*67e74705SXin Li ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8145*67e74705SXin Li unsigned &Idx) {
8146*67e74705SXin Li SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8147*67e74705SXin Li SourceLocation end = ReadSourceLocation(F, Record, Idx);
8148*67e74705SXin Li return SourceRange(beg, end);
8149*67e74705SXin Li }
8150*67e74705SXin Li
8151*67e74705SXin Li /// \brief Read an integral value
ReadAPInt(const RecordData & Record,unsigned & Idx)8152*67e74705SXin Li llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8153*67e74705SXin Li unsigned BitWidth = Record[Idx++];
8154*67e74705SXin Li unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8155*67e74705SXin Li llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8156*67e74705SXin Li Idx += NumWords;
8157*67e74705SXin Li return Result;
8158*67e74705SXin Li }
8159*67e74705SXin Li
8160*67e74705SXin Li /// \brief Read a signed integral value
ReadAPSInt(const RecordData & Record,unsigned & Idx)8161*67e74705SXin Li llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8162*67e74705SXin Li bool isUnsigned = Record[Idx++];
8163*67e74705SXin Li return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8164*67e74705SXin Li }
8165*67e74705SXin Li
8166*67e74705SXin Li /// \brief Read a floating-point value
ReadAPFloat(const RecordData & Record,const llvm::fltSemantics & Sem,unsigned & Idx)8167*67e74705SXin Li llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8168*67e74705SXin Li const llvm::fltSemantics &Sem,
8169*67e74705SXin Li unsigned &Idx) {
8170*67e74705SXin Li return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
8171*67e74705SXin Li }
8172*67e74705SXin Li
8173*67e74705SXin Li // \brief Read a string
ReadString(const RecordData & Record,unsigned & Idx)8174*67e74705SXin Li std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8175*67e74705SXin Li unsigned Len = Record[Idx++];
8176*67e74705SXin Li std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8177*67e74705SXin Li Idx += Len;
8178*67e74705SXin Li return Result;
8179*67e74705SXin Li }
8180*67e74705SXin Li
ReadPath(ModuleFile & F,const RecordData & Record,unsigned & Idx)8181*67e74705SXin Li std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8182*67e74705SXin Li unsigned &Idx) {
8183*67e74705SXin Li std::string Filename = ReadString(Record, Idx);
8184*67e74705SXin Li ResolveImportedPath(F, Filename);
8185*67e74705SXin Li return Filename;
8186*67e74705SXin Li }
8187*67e74705SXin Li
ReadVersionTuple(const RecordData & Record,unsigned & Idx)8188*67e74705SXin Li VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8189*67e74705SXin Li unsigned &Idx) {
8190*67e74705SXin Li unsigned Major = Record[Idx++];
8191*67e74705SXin Li unsigned Minor = Record[Idx++];
8192*67e74705SXin Li unsigned Subminor = Record[Idx++];
8193*67e74705SXin Li if (Minor == 0)
8194*67e74705SXin Li return VersionTuple(Major);
8195*67e74705SXin Li if (Subminor == 0)
8196*67e74705SXin Li return VersionTuple(Major, Minor - 1);
8197*67e74705SXin Li return VersionTuple(Major, Minor - 1, Subminor - 1);
8198*67e74705SXin Li }
8199*67e74705SXin Li
ReadCXXTemporary(ModuleFile & F,const RecordData & Record,unsigned & Idx)8200*67e74705SXin Li CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8201*67e74705SXin Li const RecordData &Record,
8202*67e74705SXin Li unsigned &Idx) {
8203*67e74705SXin Li CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8204*67e74705SXin Li return CXXTemporary::Create(Context, Decl);
8205*67e74705SXin Li }
8206*67e74705SXin Li
Diag(unsigned DiagID)8207*67e74705SXin Li DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
8208*67e74705SXin Li return Diag(CurrentImportLoc, DiagID);
8209*67e74705SXin Li }
8210*67e74705SXin Li
Diag(SourceLocation Loc,unsigned DiagID)8211*67e74705SXin Li DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8212*67e74705SXin Li return Diags.Report(Loc, DiagID);
8213*67e74705SXin Li }
8214*67e74705SXin Li
8215*67e74705SXin Li /// \brief Retrieve the identifier table associated with the
8216*67e74705SXin Li /// preprocessor.
getIdentifierTable()8217*67e74705SXin Li IdentifierTable &ASTReader::getIdentifierTable() {
8218*67e74705SXin Li return PP.getIdentifierTable();
8219*67e74705SXin Li }
8220*67e74705SXin Li
8221*67e74705SXin Li /// \brief Record that the given ID maps to the given switch-case
8222*67e74705SXin Li /// statement.
RecordSwitchCaseID(SwitchCase * SC,unsigned ID)8223*67e74705SXin Li void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
8224*67e74705SXin Li assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
8225*67e74705SXin Li "Already have a SwitchCase with this ID");
8226*67e74705SXin Li (*CurrSwitchCaseStmts)[ID] = SC;
8227*67e74705SXin Li }
8228*67e74705SXin Li
8229*67e74705SXin Li /// \brief Retrieve the switch-case statement with the given ID.
getSwitchCaseWithID(unsigned ID)8230*67e74705SXin Li SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
8231*67e74705SXin Li assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
8232*67e74705SXin Li return (*CurrSwitchCaseStmts)[ID];
8233*67e74705SXin Li }
8234*67e74705SXin Li
ClearSwitchCaseIDs()8235*67e74705SXin Li void ASTReader::ClearSwitchCaseIDs() {
8236*67e74705SXin Li CurrSwitchCaseStmts->clear();
8237*67e74705SXin Li }
8238*67e74705SXin Li
ReadComments()8239*67e74705SXin Li void ASTReader::ReadComments() {
8240*67e74705SXin Li std::vector<RawComment *> Comments;
8241*67e74705SXin Li for (SmallVectorImpl<std::pair<BitstreamCursor,
8242*67e74705SXin Li serialization::ModuleFile *> >::iterator
8243*67e74705SXin Li I = CommentsCursors.begin(),
8244*67e74705SXin Li E = CommentsCursors.end();
8245*67e74705SXin Li I != E; ++I) {
8246*67e74705SXin Li Comments.clear();
8247*67e74705SXin Li BitstreamCursor &Cursor = I->first;
8248*67e74705SXin Li serialization::ModuleFile &F = *I->second;
8249*67e74705SXin Li SavedStreamPosition SavedPosition(Cursor);
8250*67e74705SXin Li
8251*67e74705SXin Li RecordData Record;
8252*67e74705SXin Li while (true) {
8253*67e74705SXin Li llvm::BitstreamEntry Entry =
8254*67e74705SXin Li Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
8255*67e74705SXin Li
8256*67e74705SXin Li switch (Entry.Kind) {
8257*67e74705SXin Li case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8258*67e74705SXin Li case llvm::BitstreamEntry::Error:
8259*67e74705SXin Li Error("malformed block record in AST file");
8260*67e74705SXin Li return;
8261*67e74705SXin Li case llvm::BitstreamEntry::EndBlock:
8262*67e74705SXin Li goto NextCursor;
8263*67e74705SXin Li case llvm::BitstreamEntry::Record:
8264*67e74705SXin Li // The interesting case.
8265*67e74705SXin Li break;
8266*67e74705SXin Li }
8267*67e74705SXin Li
8268*67e74705SXin Li // Read a record.
8269*67e74705SXin Li Record.clear();
8270*67e74705SXin Li switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
8271*67e74705SXin Li case COMMENTS_RAW_COMMENT: {
8272*67e74705SXin Li unsigned Idx = 0;
8273*67e74705SXin Li SourceRange SR = ReadSourceRange(F, Record, Idx);
8274*67e74705SXin Li RawComment::CommentKind Kind =
8275*67e74705SXin Li (RawComment::CommentKind) Record[Idx++];
8276*67e74705SXin Li bool IsTrailingComment = Record[Idx++];
8277*67e74705SXin Li bool IsAlmostTrailingComment = Record[Idx++];
8278*67e74705SXin Li Comments.push_back(new (Context) RawComment(
8279*67e74705SXin Li SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8280*67e74705SXin Li Context.getLangOpts().CommentOpts.ParseAllComments));
8281*67e74705SXin Li break;
8282*67e74705SXin Li }
8283*67e74705SXin Li }
8284*67e74705SXin Li }
8285*67e74705SXin Li NextCursor:
8286*67e74705SXin Li Context.Comments.addDeserializedComments(Comments);
8287*67e74705SXin Li }
8288*67e74705SXin Li }
8289*67e74705SXin Li
getOwningModuleNameForDiagnostic(const Decl * D)8290*67e74705SXin Li std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8291*67e74705SXin Li // If we know the owning module, use it.
8292*67e74705SXin Li if (Module *M = D->getImportedOwningModule())
8293*67e74705SXin Li return M->getFullModuleName();
8294*67e74705SXin Li
8295*67e74705SXin Li // Otherwise, use the name of the top-level module the decl is within.
8296*67e74705SXin Li if (ModuleFile *M = getOwningModuleFile(D))
8297*67e74705SXin Li return M->ModuleName;
8298*67e74705SXin Li
8299*67e74705SXin Li // Not from a module.
8300*67e74705SXin Li return "";
8301*67e74705SXin Li }
8302*67e74705SXin Li
finishPendingActions()8303*67e74705SXin Li void ASTReader::finishPendingActions() {
8304*67e74705SXin Li while (!PendingIdentifierInfos.empty() ||
8305*67e74705SXin Li !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
8306*67e74705SXin Li !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
8307*67e74705SXin Li !PendingUpdateRecords.empty()) {
8308*67e74705SXin Li // If any identifiers with corresponding top-level declarations have
8309*67e74705SXin Li // been loaded, load those declarations now.
8310*67e74705SXin Li typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8311*67e74705SXin Li TopLevelDeclsMap;
8312*67e74705SXin Li TopLevelDeclsMap TopLevelDecls;
8313*67e74705SXin Li
8314*67e74705SXin Li while (!PendingIdentifierInfos.empty()) {
8315*67e74705SXin Li IdentifierInfo *II = PendingIdentifierInfos.back().first;
8316*67e74705SXin Li SmallVector<uint32_t, 4> DeclIDs =
8317*67e74705SXin Li std::move(PendingIdentifierInfos.back().second);
8318*67e74705SXin Li PendingIdentifierInfos.pop_back();
8319*67e74705SXin Li
8320*67e74705SXin Li SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
8321*67e74705SXin Li }
8322*67e74705SXin Li
8323*67e74705SXin Li // For each decl chain that we wanted to complete while deserializing, mark
8324*67e74705SXin Li // it as "still needs to be completed".
8325*67e74705SXin Li for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8326*67e74705SXin Li markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8327*67e74705SXin Li }
8328*67e74705SXin Li PendingIncompleteDeclChains.clear();
8329*67e74705SXin Li
8330*67e74705SXin Li // Load pending declaration chains.
8331*67e74705SXin Li for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
8332*67e74705SXin Li loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
8333*67e74705SXin Li PendingDeclChains.clear();
8334*67e74705SXin Li
8335*67e74705SXin Li // Make the most recent of the top-level declarations visible.
8336*67e74705SXin Li for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8337*67e74705SXin Li TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
8338*67e74705SXin Li IdentifierInfo *II = TLD->first;
8339*67e74705SXin Li for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
8340*67e74705SXin Li pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
8341*67e74705SXin Li }
8342*67e74705SXin Li }
8343*67e74705SXin Li
8344*67e74705SXin Li // Load any pending macro definitions.
8345*67e74705SXin Li for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
8346*67e74705SXin Li IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8347*67e74705SXin Li SmallVector<PendingMacroInfo, 2> GlobalIDs;
8348*67e74705SXin Li GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8349*67e74705SXin Li // Initialize the macro history from chained-PCHs ahead of module imports.
8350*67e74705SXin Li for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8351*67e74705SXin Li ++IDIdx) {
8352*67e74705SXin Li const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8353*67e74705SXin Li if (Info.M->Kind != MK_ImplicitModule &&
8354*67e74705SXin Li Info.M->Kind != MK_ExplicitModule)
8355*67e74705SXin Li resolvePendingMacro(II, Info);
8356*67e74705SXin Li }
8357*67e74705SXin Li // Handle module imports.
8358*67e74705SXin Li for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8359*67e74705SXin Li ++IDIdx) {
8360*67e74705SXin Li const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8361*67e74705SXin Li if (Info.M->Kind == MK_ImplicitModule ||
8362*67e74705SXin Li Info.M->Kind == MK_ExplicitModule)
8363*67e74705SXin Li resolvePendingMacro(II, Info);
8364*67e74705SXin Li }
8365*67e74705SXin Li }
8366*67e74705SXin Li PendingMacroIDs.clear();
8367*67e74705SXin Li
8368*67e74705SXin Li // Wire up the DeclContexts for Decls that we delayed setting until
8369*67e74705SXin Li // recursive loading is completed.
8370*67e74705SXin Li while (!PendingDeclContextInfos.empty()) {
8371*67e74705SXin Li PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8372*67e74705SXin Li PendingDeclContextInfos.pop_front();
8373*67e74705SXin Li DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8374*67e74705SXin Li DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8375*67e74705SXin Li Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8376*67e74705SXin Li }
8377*67e74705SXin Li
8378*67e74705SXin Li // Perform any pending declaration updates.
8379*67e74705SXin Li while (!PendingUpdateRecords.empty()) {
8380*67e74705SXin Li auto Update = PendingUpdateRecords.pop_back_val();
8381*67e74705SXin Li ReadingKindTracker ReadingKind(Read_Decl, *this);
8382*67e74705SXin Li loadDeclUpdateRecords(Update.first, Update.second);
8383*67e74705SXin Li }
8384*67e74705SXin Li }
8385*67e74705SXin Li
8386*67e74705SXin Li // At this point, all update records for loaded decls are in place, so any
8387*67e74705SXin Li // fake class definitions should have become real.
8388*67e74705SXin Li assert(PendingFakeDefinitionData.empty() &&
8389*67e74705SXin Li "faked up a class definition but never saw the real one");
8390*67e74705SXin Li
8391*67e74705SXin Li // If we deserialized any C++ or Objective-C class definitions, any
8392*67e74705SXin Li // Objective-C protocol definitions, or any redeclarable templates, make sure
8393*67e74705SXin Li // that all redeclarations point to the definitions. Note that this can only
8394*67e74705SXin Li // happen now, after the redeclaration chains have been fully wired.
8395*67e74705SXin Li for (Decl *D : PendingDefinitions) {
8396*67e74705SXin Li if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8397*67e74705SXin Li if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
8398*67e74705SXin Li // Make sure that the TagType points at the definition.
8399*67e74705SXin Li const_cast<TagType*>(TagT)->decl = TD;
8400*67e74705SXin Li }
8401*67e74705SXin Li
8402*67e74705SXin Li if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
8403*67e74705SXin Li for (auto *R = getMostRecentExistingDecl(RD); R;
8404*67e74705SXin Li R = R->getPreviousDecl()) {
8405*67e74705SXin Li assert((R == D) ==
8406*67e74705SXin Li cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
8407*67e74705SXin Li "declaration thinks it's the definition but it isn't");
8408*67e74705SXin Li cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
8409*67e74705SXin Li }
8410*67e74705SXin Li }
8411*67e74705SXin Li
8412*67e74705SXin Li continue;
8413*67e74705SXin Li }
8414*67e74705SXin Li
8415*67e74705SXin Li if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
8416*67e74705SXin Li // Make sure that the ObjCInterfaceType points at the definition.
8417*67e74705SXin Li const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8418*67e74705SXin Li ->Decl = ID;
8419*67e74705SXin Li
8420*67e74705SXin Li for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8421*67e74705SXin Li cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8422*67e74705SXin Li
8423*67e74705SXin Li continue;
8424*67e74705SXin Li }
8425*67e74705SXin Li
8426*67e74705SXin Li if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
8427*67e74705SXin Li for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8428*67e74705SXin Li cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8429*67e74705SXin Li
8430*67e74705SXin Li continue;
8431*67e74705SXin Li }
8432*67e74705SXin Li
8433*67e74705SXin Li auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
8434*67e74705SXin Li for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8435*67e74705SXin Li cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
8436*67e74705SXin Li }
8437*67e74705SXin Li PendingDefinitions.clear();
8438*67e74705SXin Li
8439*67e74705SXin Li // Load the bodies of any functions or methods we've encountered. We do
8440*67e74705SXin Li // this now (delayed) so that we can be sure that the declaration chains
8441*67e74705SXin Li // have been fully wired up (hasBody relies on this).
8442*67e74705SXin Li // FIXME: We shouldn't require complete redeclaration chains here.
8443*67e74705SXin Li for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8444*67e74705SXin Li PBEnd = PendingBodies.end();
8445*67e74705SXin Li PB != PBEnd; ++PB) {
8446*67e74705SXin Li if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8447*67e74705SXin Li // FIXME: Check for =delete/=default?
8448*67e74705SXin Li // FIXME: Complain about ODR violations here?
8449*67e74705SXin Li if (!getContext().getLangOpts().Modules || !FD->hasBody())
8450*67e74705SXin Li FD->setLazyBody(PB->second);
8451*67e74705SXin Li continue;
8452*67e74705SXin Li }
8453*67e74705SXin Li
8454*67e74705SXin Li ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8455*67e74705SXin Li if (!getContext().getLangOpts().Modules || !MD->hasBody())
8456*67e74705SXin Li MD->setLazyBody(PB->second);
8457*67e74705SXin Li }
8458*67e74705SXin Li PendingBodies.clear();
8459*67e74705SXin Li
8460*67e74705SXin Li // Do some cleanup.
8461*67e74705SXin Li for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8462*67e74705SXin Li getContext().deduplicateMergedDefinitonsFor(ND);
8463*67e74705SXin Li PendingMergedDefinitionsToDeduplicate.clear();
8464*67e74705SXin Li }
8465*67e74705SXin Li
diagnoseOdrViolations()8466*67e74705SXin Li void ASTReader::diagnoseOdrViolations() {
8467*67e74705SXin Li if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8468*67e74705SXin Li return;
8469*67e74705SXin Li
8470*67e74705SXin Li // Trigger the import of the full definition of each class that had any
8471*67e74705SXin Li // odr-merging problems, so we can produce better diagnostics for them.
8472*67e74705SXin Li // These updates may in turn find and diagnose some ODR failures, so take
8473*67e74705SXin Li // ownership of the set first.
8474*67e74705SXin Li auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8475*67e74705SXin Li PendingOdrMergeFailures.clear();
8476*67e74705SXin Li for (auto &Merge : OdrMergeFailures) {
8477*67e74705SXin Li Merge.first->buildLookup();
8478*67e74705SXin Li Merge.first->decls_begin();
8479*67e74705SXin Li Merge.first->bases_begin();
8480*67e74705SXin Li Merge.first->vbases_begin();
8481*67e74705SXin Li for (auto *RD : Merge.second) {
8482*67e74705SXin Li RD->decls_begin();
8483*67e74705SXin Li RD->bases_begin();
8484*67e74705SXin Li RD->vbases_begin();
8485*67e74705SXin Li }
8486*67e74705SXin Li }
8487*67e74705SXin Li
8488*67e74705SXin Li // For each declaration from a merged context, check that the canonical
8489*67e74705SXin Li // definition of that context also contains a declaration of the same
8490*67e74705SXin Li // entity.
8491*67e74705SXin Li //
8492*67e74705SXin Li // Caution: this loop does things that might invalidate iterators into
8493*67e74705SXin Li // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8494*67e74705SXin Li while (!PendingOdrMergeChecks.empty()) {
8495*67e74705SXin Li NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8496*67e74705SXin Li
8497*67e74705SXin Li // FIXME: Skip over implicit declarations for now. This matters for things
8498*67e74705SXin Li // like implicitly-declared special member functions. This isn't entirely
8499*67e74705SXin Li // correct; we can end up with multiple unmerged declarations of the same
8500*67e74705SXin Li // implicit entity.
8501*67e74705SXin Li if (D->isImplicit())
8502*67e74705SXin Li continue;
8503*67e74705SXin Li
8504*67e74705SXin Li DeclContext *CanonDef = D->getDeclContext();
8505*67e74705SXin Li
8506*67e74705SXin Li bool Found = false;
8507*67e74705SXin Li const Decl *DCanon = D->getCanonicalDecl();
8508*67e74705SXin Li
8509*67e74705SXin Li for (auto RI : D->redecls()) {
8510*67e74705SXin Li if (RI->getLexicalDeclContext() == CanonDef) {
8511*67e74705SXin Li Found = true;
8512*67e74705SXin Li break;
8513*67e74705SXin Li }
8514*67e74705SXin Li }
8515*67e74705SXin Li if (Found)
8516*67e74705SXin Li continue;
8517*67e74705SXin Li
8518*67e74705SXin Li // Quick check failed, time to do the slow thing. Note, we can't just
8519*67e74705SXin Li // look up the name of D in CanonDef here, because the member that is
8520*67e74705SXin Li // in CanonDef might not be found by name lookup (it might have been
8521*67e74705SXin Li // replaced by a more recent declaration in the lookup table), and we
8522*67e74705SXin Li // can't necessarily find it in the redeclaration chain because it might
8523*67e74705SXin Li // be merely mergeable, not redeclarable.
8524*67e74705SXin Li llvm::SmallVector<const NamedDecl*, 4> Candidates;
8525*67e74705SXin Li for (auto *CanonMember : CanonDef->decls()) {
8526*67e74705SXin Li if (CanonMember->getCanonicalDecl() == DCanon) {
8527*67e74705SXin Li // This can happen if the declaration is merely mergeable and not
8528*67e74705SXin Li // actually redeclarable (we looked for redeclarations earlier).
8529*67e74705SXin Li //
8530*67e74705SXin Li // FIXME: We should be able to detect this more efficiently, without
8531*67e74705SXin Li // pulling in all of the members of CanonDef.
8532*67e74705SXin Li Found = true;
8533*67e74705SXin Li break;
8534*67e74705SXin Li }
8535*67e74705SXin Li if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8536*67e74705SXin Li if (ND->getDeclName() == D->getDeclName())
8537*67e74705SXin Li Candidates.push_back(ND);
8538*67e74705SXin Li }
8539*67e74705SXin Li
8540*67e74705SXin Li if (!Found) {
8541*67e74705SXin Li // The AST doesn't like TagDecls becoming invalid after they've been
8542*67e74705SXin Li // completed. We only really need to mark FieldDecls as invalid here.
8543*67e74705SXin Li if (!isa<TagDecl>(D))
8544*67e74705SXin Li D->setInvalidDecl();
8545*67e74705SXin Li
8546*67e74705SXin Li // Ensure we don't accidentally recursively enter deserialization while
8547*67e74705SXin Li // we're producing our diagnostic.
8548*67e74705SXin Li Deserializing RecursionGuard(this);
8549*67e74705SXin Li
8550*67e74705SXin Li std::string CanonDefModule =
8551*67e74705SXin Li getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8552*67e74705SXin Li Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8553*67e74705SXin Li << D << getOwningModuleNameForDiagnostic(D)
8554*67e74705SXin Li << CanonDef << CanonDefModule.empty() << CanonDefModule;
8555*67e74705SXin Li
8556*67e74705SXin Li if (Candidates.empty())
8557*67e74705SXin Li Diag(cast<Decl>(CanonDef)->getLocation(),
8558*67e74705SXin Li diag::note_module_odr_violation_no_possible_decls) << D;
8559*67e74705SXin Li else {
8560*67e74705SXin Li for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8561*67e74705SXin Li Diag(Candidates[I]->getLocation(),
8562*67e74705SXin Li diag::note_module_odr_violation_possible_decl)
8563*67e74705SXin Li << Candidates[I];
8564*67e74705SXin Li }
8565*67e74705SXin Li
8566*67e74705SXin Li DiagnosedOdrMergeFailures.insert(CanonDef);
8567*67e74705SXin Li }
8568*67e74705SXin Li }
8569*67e74705SXin Li
8570*67e74705SXin Li if (OdrMergeFailures.empty())
8571*67e74705SXin Li return;
8572*67e74705SXin Li
8573*67e74705SXin Li // Ensure we don't accidentally recursively enter deserialization while
8574*67e74705SXin Li // we're producing our diagnostics.
8575*67e74705SXin Li Deserializing RecursionGuard(this);
8576*67e74705SXin Li
8577*67e74705SXin Li // Issue any pending ODR-failure diagnostics.
8578*67e74705SXin Li for (auto &Merge : OdrMergeFailures) {
8579*67e74705SXin Li // If we've already pointed out a specific problem with this class, don't
8580*67e74705SXin Li // bother issuing a general "something's different" diagnostic.
8581*67e74705SXin Li if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
8582*67e74705SXin Li continue;
8583*67e74705SXin Li
8584*67e74705SXin Li bool Diagnosed = false;
8585*67e74705SXin Li for (auto *RD : Merge.second) {
8586*67e74705SXin Li // Multiple different declarations got merged together; tell the user
8587*67e74705SXin Li // where they came from.
8588*67e74705SXin Li if (Merge.first != RD) {
8589*67e74705SXin Li // FIXME: Walk the definition, figure out what's different,
8590*67e74705SXin Li // and diagnose that.
8591*67e74705SXin Li if (!Diagnosed) {
8592*67e74705SXin Li std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8593*67e74705SXin Li Diag(Merge.first->getLocation(),
8594*67e74705SXin Li diag::err_module_odr_violation_different_definitions)
8595*67e74705SXin Li << Merge.first << Module.empty() << Module;
8596*67e74705SXin Li Diagnosed = true;
8597*67e74705SXin Li }
8598*67e74705SXin Li
8599*67e74705SXin Li Diag(RD->getLocation(),
8600*67e74705SXin Li diag::note_module_odr_violation_different_definitions)
8601*67e74705SXin Li << getOwningModuleNameForDiagnostic(RD);
8602*67e74705SXin Li }
8603*67e74705SXin Li }
8604*67e74705SXin Li
8605*67e74705SXin Li if (!Diagnosed) {
8606*67e74705SXin Li // All definitions are updates to the same declaration. This happens if a
8607*67e74705SXin Li // module instantiates the declaration of a class template specialization
8608*67e74705SXin Li // and two or more other modules instantiate its definition.
8609*67e74705SXin Li //
8610*67e74705SXin Li // FIXME: Indicate which modules had instantiations of this definition.
8611*67e74705SXin Li // FIXME: How can this even happen?
8612*67e74705SXin Li Diag(Merge.first->getLocation(),
8613*67e74705SXin Li diag::err_module_odr_violation_different_instantiations)
8614*67e74705SXin Li << Merge.first;
8615*67e74705SXin Li }
8616*67e74705SXin Li }
8617*67e74705SXin Li }
8618*67e74705SXin Li
StartedDeserializing()8619*67e74705SXin Li void ASTReader::StartedDeserializing() {
8620*67e74705SXin Li if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8621*67e74705SXin Li ReadTimer->startTimer();
8622*67e74705SXin Li }
8623*67e74705SXin Li
FinishedDeserializing()8624*67e74705SXin Li void ASTReader::FinishedDeserializing() {
8625*67e74705SXin Li assert(NumCurrentElementsDeserializing &&
8626*67e74705SXin Li "FinishedDeserializing not paired with StartedDeserializing");
8627*67e74705SXin Li if (NumCurrentElementsDeserializing == 1) {
8628*67e74705SXin Li // We decrease NumCurrentElementsDeserializing only after pending actions
8629*67e74705SXin Li // are finished, to avoid recursively re-calling finishPendingActions().
8630*67e74705SXin Li finishPendingActions();
8631*67e74705SXin Li }
8632*67e74705SXin Li --NumCurrentElementsDeserializing;
8633*67e74705SXin Li
8634*67e74705SXin Li if (NumCurrentElementsDeserializing == 0) {
8635*67e74705SXin Li // Propagate exception specification updates along redeclaration chains.
8636*67e74705SXin Li while (!PendingExceptionSpecUpdates.empty()) {
8637*67e74705SXin Li auto Updates = std::move(PendingExceptionSpecUpdates);
8638*67e74705SXin Li PendingExceptionSpecUpdates.clear();
8639*67e74705SXin Li for (auto Update : Updates) {
8640*67e74705SXin Li auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8641*67e74705SXin Li auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
8642*67e74705SXin Li if (auto *Listener = Context.getASTMutationListener())
8643*67e74705SXin Li Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
8644*67e74705SXin Li for (auto *Redecl : Update.second->redecls())
8645*67e74705SXin Li Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
8646*67e74705SXin Li }
8647*67e74705SXin Li }
8648*67e74705SXin Li
8649*67e74705SXin Li if (ReadTimer)
8650*67e74705SXin Li ReadTimer->stopTimer();
8651*67e74705SXin Li
8652*67e74705SXin Li diagnoseOdrViolations();
8653*67e74705SXin Li
8654*67e74705SXin Li // We are not in recursive loading, so it's safe to pass the "interesting"
8655*67e74705SXin Li // decls to the consumer.
8656*67e74705SXin Li if (Consumer)
8657*67e74705SXin Li PassInterestingDeclsToConsumer();
8658*67e74705SXin Li }
8659*67e74705SXin Li }
8660*67e74705SXin Li
pushExternalDeclIntoScope(NamedDecl * D,DeclarationName Name)8661*67e74705SXin Li void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
8662*67e74705SXin Li if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8663*67e74705SXin Li // Remove any fake results before adding any real ones.
8664*67e74705SXin Li auto It = PendingFakeLookupResults.find(II);
8665*67e74705SXin Li if (It != PendingFakeLookupResults.end()) {
8666*67e74705SXin Li for (auto *ND : It->second)
8667*67e74705SXin Li SemaObj->IdResolver.RemoveDecl(ND);
8668*67e74705SXin Li // FIXME: this works around module+PCH performance issue.
8669*67e74705SXin Li // Rather than erase the result from the map, which is O(n), just clear
8670*67e74705SXin Li // the vector of NamedDecls.
8671*67e74705SXin Li It->second.clear();
8672*67e74705SXin Li }
8673*67e74705SXin Li }
8674*67e74705SXin Li
8675*67e74705SXin Li if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8676*67e74705SXin Li SemaObj->TUScope->AddDecl(D);
8677*67e74705SXin Li } else if (SemaObj->TUScope) {
8678*67e74705SXin Li // Adding the decl to IdResolver may have failed because it was already in
8679*67e74705SXin Li // (even though it was not added in scope). If it is already in, make sure
8680*67e74705SXin Li // it gets in the scope as well.
8681*67e74705SXin Li if (std::find(SemaObj->IdResolver.begin(Name),
8682*67e74705SXin Li SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8683*67e74705SXin Li SemaObj->TUScope->AddDecl(D);
8684*67e74705SXin Li }
8685*67e74705SXin Li }
8686*67e74705SXin Li
ASTReader(Preprocessor & PP,ASTContext & Context,const PCHContainerReader & PCHContainerRdr,ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,StringRef isysroot,bool DisableValidation,bool AllowASTWithCompilerErrors,bool AllowConfigurationMismatch,bool ValidateSystemInputs,bool UseGlobalIndex,std::unique_ptr<llvm::Timer> ReadTimer)8687*67e74705SXin Li ASTReader::ASTReader(
8688*67e74705SXin Li Preprocessor &PP, ASTContext &Context,
8689*67e74705SXin Li const PCHContainerReader &PCHContainerRdr,
8690*67e74705SXin Li ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
8691*67e74705SXin Li StringRef isysroot, bool DisableValidation,
8692*67e74705SXin Li bool AllowASTWithCompilerErrors,
8693*67e74705SXin Li bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8694*67e74705SXin Li bool UseGlobalIndex,
8695*67e74705SXin Li std::unique_ptr<llvm::Timer> ReadTimer)
8696*67e74705SXin Li : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
8697*67e74705SXin Li OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
8698*67e74705SXin Li FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
8699*67e74705SXin Li Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
8700*67e74705SXin Li Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
8701*67e74705SXin Li DummyIdResolver(PP),
8702*67e74705SXin Li ReadTimer(std::move(ReadTimer)),
8703*67e74705SXin Li PragmaMSStructState(-1),
8704*67e74705SXin Li PragmaMSPointersToMembersState(-1),
8705*67e74705SXin Li isysroot(isysroot), DisableValidation(DisableValidation),
8706*67e74705SXin Li AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8707*67e74705SXin Li AllowConfigurationMismatch(AllowConfigurationMismatch),
8708*67e74705SXin Li ValidateSystemInputs(ValidateSystemInputs),
8709*67e74705SXin Li UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
8710*67e74705SXin Li CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8711*67e74705SXin Li TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8712*67e74705SXin Li NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8713*67e74705SXin Li NumIdentifierLookupHits(0), NumSelectorsRead(0),
8714*67e74705SXin Li NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8715*67e74705SXin Li NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8716*67e74705SXin Li NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8717*67e74705SXin Li NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8718*67e74705SXin Li NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8719*67e74705SXin Li TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8720*67e74705SXin Li PassingDeclsToConsumer(false), ReadingKind(Read_None) {
8721*67e74705SXin Li SourceMgr.setExternalSLocEntrySource(this);
8722*67e74705SXin Li
8723*67e74705SXin Li for (const auto &Ext : Extensions) {
8724*67e74705SXin Li auto BlockName = Ext->getExtensionMetadata().BlockName;
8725*67e74705SXin Li auto Known = ModuleFileExtensions.find(BlockName);
8726*67e74705SXin Li if (Known != ModuleFileExtensions.end()) {
8727*67e74705SXin Li Diags.Report(diag::warn_duplicate_module_file_extension)
8728*67e74705SXin Li << BlockName;
8729*67e74705SXin Li continue;
8730*67e74705SXin Li }
8731*67e74705SXin Li
8732*67e74705SXin Li ModuleFileExtensions.insert({BlockName, Ext});
8733*67e74705SXin Li }
8734*67e74705SXin Li }
8735*67e74705SXin Li
~ASTReader()8736*67e74705SXin Li ASTReader::~ASTReader() {
8737*67e74705SXin Li if (OwnsDeserializationListener)
8738*67e74705SXin Li delete DeserializationListener;
8739*67e74705SXin Li }
8740*67e74705SXin Li
getIdResolver()8741*67e74705SXin Li IdentifierResolver &ASTReader::getIdResolver() {
8742*67e74705SXin Li return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
8743*67e74705SXin Li }
8744