blob: 16d686b66e52f9709693d34738b5c1802cc8525a [file] [log] [blame]
Richard Smith9e2341d2015-03-23 03:25:59 +00001//===-- ASTReader.cpp - AST File Reader ----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
Adrian Prantlbb165fb2015-06-20 18:53:08 +000022#include "clang/Frontend/PCHContainerOperations.h"
Richard Smithd88a7f12015-09-01 20:35:42 +000023#include "clang/AST/ASTMutationListener.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000024#include "clang/AST/NestedNameSpecifier.h"
25#include "clang/AST/Type.h"
26#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000027#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000029#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/SourceManagerInternals.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/TargetOptions.h"
33#include "clang/Basic/Version.h"
34#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000035#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/Lex/HeaderSearch.h"
37#include "clang/Lex/HeaderSearchOptions.h"
38#include "clang/Lex/MacroInfo.h"
39#include "clang/Lex/PreprocessingRecord.h"
40#include "clang/Lex/Preprocessor.h"
41#include "clang/Lex/PreprocessorOptions.h"
42#include "clang/Sema/Scope.h"
43#include "clang/Sema/Sema.h"
44#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000045#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000046#include "clang/Serialization/ModuleManager.h"
47#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000048#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000049#include "llvm/ADT/StringExtras.h"
50#include "llvm/Bitcode/BitstreamReader.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/FileSystem.h"
53#include "llvm/Support/MemoryBuffer.h"
54#include "llvm/Support/Path.h"
55#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000056#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000058#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000059#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000060#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000061
62using namespace clang;
63using namespace clang::serialization;
64using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000065using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000066
Ben Langmuircb69b572014-03-07 06:40:32 +000067
68//===----------------------------------------------------------------------===//
69// ChainedASTReaderListener implementation
70//===----------------------------------------------------------------------===//
71
72bool
73ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
74 return First->ReadFullVersionInformation(FullVersion) ||
75 Second->ReadFullVersionInformation(FullVersion);
76}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000077void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
78 First->ReadModuleName(ModuleName);
79 Second->ReadModuleName(ModuleName);
80}
81void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
82 First->ReadModuleMapFile(ModuleMapPath);
83 Second->ReadModuleMapFile(ModuleMapPath);
84}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000085bool
86ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
87 bool Complain,
88 bool AllowCompatibleDifferences) {
89 return First->ReadLanguageOptions(LangOpts, Complain,
90 AllowCompatibleDifferences) ||
91 Second->ReadLanguageOptions(LangOpts, Complain,
92 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000093}
Chandler Carruth0d745bc2015-03-14 04:47:43 +000094bool ChainedASTReaderListener::ReadTargetOptions(
95 const TargetOptions &TargetOpts, bool Complain,
96 bool AllowCompatibleDifferences) {
97 return First->ReadTargetOptions(TargetOpts, Complain,
98 AllowCompatibleDifferences) ||
99 Second->ReadTargetOptions(TargetOpts, Complain,
100 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000101}
102bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000103 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000104 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
105 Second->ReadDiagnosticOptions(DiagOpts, Complain);
106}
107bool
108ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
109 bool Complain) {
110 return First->ReadFileSystemOptions(FSOpts, Complain) ||
111 Second->ReadFileSystemOptions(FSOpts, Complain);
112}
113
114bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000115 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
116 bool Complain) {
117 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
118 Complain) ||
119 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
120 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000121}
122bool ChainedASTReaderListener::ReadPreprocessorOptions(
123 const PreprocessorOptions &PPOpts, bool Complain,
124 std::string &SuggestedPredefines) {
125 return First->ReadPreprocessorOptions(PPOpts, Complain,
126 SuggestedPredefines) ||
127 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
128}
129void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
130 unsigned Value) {
131 First->ReadCounter(M, Value);
132 Second->ReadCounter(M, Value);
133}
134bool ChainedASTReaderListener::needsInputFileVisitation() {
135 return First->needsInputFileVisitation() ||
136 Second->needsInputFileVisitation();
137}
138bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
139 return First->needsSystemInputFileVisitation() ||
140 Second->needsSystemInputFileVisitation();
141}
Richard Smith216a3bd2015-08-13 17:57:10 +0000142void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
143 ModuleKind Kind) {
144 First->visitModuleFile(Filename, Kind);
145 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000146}
Ben Langmuircb69b572014-03-07 06:40:32 +0000147bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000148 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000149 bool isOverridden,
150 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000151 bool Continue = false;
152 if (First->needsInputFileVisitation() &&
153 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000154 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
155 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000156 if (Second->needsInputFileVisitation() &&
157 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000158 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
159 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000160 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000161}
162
Guy Benyei11169dd2012-12-18 14:30:41 +0000163//===----------------------------------------------------------------------===//
164// PCH validator implementation
165//===----------------------------------------------------------------------===//
166
167ASTReaderListener::~ASTReaderListener() {}
168
169/// \brief Compare the given set of language options against an existing set of
170/// language options.
171///
172/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000173/// \param AllowCompatibleDifferences If true, differences between compatible
174/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000175///
176/// \returns true if the languagae options mis-match, false otherwise.
177static bool checkLanguageOptions(const LangOptions &LangOpts,
178 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000179 DiagnosticsEngine *Diags,
180 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000181#define LANGOPT(Name, Bits, Default, Description) \
182 if (ExistingLangOpts.Name != LangOpts.Name) { \
183 if (Diags) \
184 Diags->Report(diag::err_pch_langopt_mismatch) \
185 << Description << LangOpts.Name << ExistingLangOpts.Name; \
186 return true; \
187 }
188
189#define VALUE_LANGOPT(Name, Bits, Default, Description) \
190 if (ExistingLangOpts.Name != LangOpts.Name) { \
191 if (Diags) \
192 Diags->Report(diag::err_pch_langopt_value_mismatch) \
193 << Description; \
194 return true; \
195 }
196
197#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
198 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
199 if (Diags) \
200 Diags->Report(diag::err_pch_langopt_value_mismatch) \
201 << Description; \
202 return true; \
203 }
204
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000205#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
206 if (!AllowCompatibleDifferences) \
207 LANGOPT(Name, Bits, Default, Description)
208
209#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
210 if (!AllowCompatibleDifferences) \
211 ENUM_LANGOPT(Name, Bits, Default, Description)
212
Guy Benyei11169dd2012-12-18 14:30:41 +0000213#define BENIGN_LANGOPT(Name, Bits, Default, Description)
214#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
215#include "clang/Basic/LangOptions.def"
216
Ben Langmuircd98cb72015-06-23 18:20:18 +0000217 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
218 if (Diags)
219 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
220 return true;
221 }
222
Guy Benyei11169dd2012-12-18 14:30:41 +0000223 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
224 if (Diags)
225 Diags->Report(diag::err_pch_langopt_value_mismatch)
226 << "target Objective-C runtime";
227 return true;
228 }
229
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000230 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
231 LangOpts.CommentOpts.BlockCommandNames) {
232 if (Diags)
233 Diags->Report(diag::err_pch_langopt_value_mismatch)
234 << "block command names";
235 return true;
236 }
237
Guy Benyei11169dd2012-12-18 14:30:41 +0000238 return false;
239}
240
241/// \brief Compare the given set of target options against an existing set of
242/// target options.
243///
244/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
245///
246/// \returns true if the target options mis-match, false otherwise.
247static bool checkTargetOptions(const TargetOptions &TargetOpts,
248 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000249 DiagnosticsEngine *Diags,
250 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000251#define CHECK_TARGET_OPT(Field, Name) \
252 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
253 if (Diags) \
254 Diags->Report(diag::err_pch_targetopt_mismatch) \
255 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
256 return true; \
257 }
258
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000259 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000260 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000261 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000262
263 // We can tolerate different CPUs in many cases, notably when one CPU
264 // supports a strict superset of another. When allowing compatible
265 // differences skip this check.
266 if (!AllowCompatibleDifferences)
267 CHECK_TARGET_OPT(CPU, "target CPU");
268
Guy Benyei11169dd2012-12-18 14:30:41 +0000269#undef CHECK_TARGET_OPT
270
271 // Compare feature sets.
272 SmallVector<StringRef, 4> ExistingFeatures(
273 ExistingTargetOpts.FeaturesAsWritten.begin(),
274 ExistingTargetOpts.FeaturesAsWritten.end());
275 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
276 TargetOpts.FeaturesAsWritten.end());
277 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
278 std::sort(ReadFeatures.begin(), ReadFeatures.end());
279
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000280 // We compute the set difference in both directions explicitly so that we can
281 // diagnose the differences differently.
282 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
283 std::set_difference(
284 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
285 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
286 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
287 ExistingFeatures.begin(), ExistingFeatures.end(),
288 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000289
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000290 // If we are allowing compatible differences and the read feature set is
291 // a strict subset of the existing feature set, there is nothing to diagnose.
292 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
293 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000294
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000295 if (Diags) {
296 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000297 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000298 << /* is-existing-feature */ false << Feature;
299 for (StringRef Feature : UnmatchedExistingFeatures)
300 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
301 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000302 }
303
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000304 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000305}
306
307bool
308PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000309 bool Complain,
310 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000311 const LangOptions &ExistingLangOpts = PP.getLangOpts();
312 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000313 Complain ? &Reader.Diags : nullptr,
314 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000315}
316
317bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000318 bool Complain,
319 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000320 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
321 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000322 Complain ? &Reader.Diags : nullptr,
323 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000324}
325
326namespace {
327 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
328 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000329 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
330 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000331}
332
Ben Langmuirb92de022014-04-29 16:25:26 +0000333static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
334 DiagnosticsEngine &Diags,
335 bool Complain) {
336 typedef DiagnosticsEngine::Level Level;
337
338 // Check current mappings for new -Werror mappings, and the stored mappings
339 // for cases that were explicitly mapped to *not* be errors that are now
340 // errors because of options like -Werror.
341 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
342
343 for (DiagnosticsEngine *MappingSource : MappingSources) {
344 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
345 diag::kind DiagID = DiagIDMappingPair.first;
346 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
347 if (CurLevel < DiagnosticsEngine::Error)
348 continue; // not significant
349 Level StoredLevel =
350 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
351 if (StoredLevel < DiagnosticsEngine::Error) {
352 if (Complain)
353 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
354 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
355 return true;
356 }
357 }
358 }
359
360 return false;
361}
362
Alp Tokerac4e8e52014-06-22 21:58:33 +0000363static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
364 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
365 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
366 return true;
367 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000368}
369
370static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
371 DiagnosticsEngine &Diags,
372 bool IsSystem, bool Complain) {
373 // Top-level options
374 if (IsSystem) {
375 if (Diags.getSuppressSystemWarnings())
376 return false;
377 // If -Wsystem-headers was not enabled before, be conservative
378 if (StoredDiags.getSuppressSystemWarnings()) {
379 if (Complain)
380 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
381 return true;
382 }
383 }
384
385 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
386 if (Complain)
387 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
388 return true;
389 }
390
391 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
392 !StoredDiags.getEnableAllWarnings()) {
393 if (Complain)
394 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
395 return true;
396 }
397
398 if (isExtHandlingFromDiagsError(Diags) &&
399 !isExtHandlingFromDiagsError(StoredDiags)) {
400 if (Complain)
401 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
402 return true;
403 }
404
405 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
406}
407
408bool PCHValidator::ReadDiagnosticOptions(
409 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
410 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
411 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
412 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000413 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000414 // This should never fail, because we would have processed these options
415 // before writing them to an ASTFile.
416 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
417
418 ModuleManager &ModuleMgr = Reader.getModuleManager();
419 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
420
421 // If the original import came from a file explicitly generated by the user,
422 // don't check the diagnostic mappings.
423 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000424 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000425 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
426 // the transitive closure of its imports, since unrelated modules cannot be
427 // imported until after this module finishes validation.
428 ModuleFile *TopImport = *ModuleMgr.rbegin();
429 while (!TopImport->ImportedBy.empty())
430 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000431 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000432 return false;
433
434 StringRef ModuleName = TopImport->ModuleName;
435 assert(!ModuleName.empty() && "diagnostic options read before module name");
436
437 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
438 assert(M && "missing module");
439
440 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
441 // contains the union of their flags.
442 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
443}
444
Guy Benyei11169dd2012-12-18 14:30:41 +0000445/// \brief Collect the macro definitions provided by the given preprocessor
446/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000447static void
448collectMacroDefinitions(const PreprocessorOptions &PPOpts,
449 MacroDefinitionsMap &Macros,
450 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000451 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
452 StringRef Macro = PPOpts.Macros[I].first;
453 bool IsUndef = PPOpts.Macros[I].second;
454
455 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
456 StringRef MacroName = MacroPair.first;
457 StringRef MacroBody = MacroPair.second;
458
459 // For an #undef'd macro, we only care about the name.
460 if (IsUndef) {
461 if (MacroNames && !Macros.count(MacroName))
462 MacroNames->push_back(MacroName);
463
464 Macros[MacroName] = std::make_pair("", true);
465 continue;
466 }
467
468 // For a #define'd macro, figure out the actual definition.
469 if (MacroName.size() == Macro.size())
470 MacroBody = "1";
471 else {
472 // Note: GCC drops anything following an end-of-line character.
473 StringRef::size_type End = MacroBody.find_first_of("\n\r");
474 MacroBody = MacroBody.substr(0, End);
475 }
476
477 if (MacroNames && !Macros.count(MacroName))
478 MacroNames->push_back(MacroName);
479 Macros[MacroName] = std::make_pair(MacroBody, false);
480 }
481}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000482
Guy Benyei11169dd2012-12-18 14:30:41 +0000483/// \brief Check the preprocessor options deserialized from the control block
484/// against the preprocessor options in an existing preprocessor.
485///
486/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
487static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
488 const PreprocessorOptions &ExistingPPOpts,
489 DiagnosticsEngine *Diags,
490 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000491 std::string &SuggestedPredefines,
492 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000493 // Check macro definitions.
494 MacroDefinitionsMap ASTFileMacros;
495 collectMacroDefinitions(PPOpts, ASTFileMacros);
496 MacroDefinitionsMap ExistingMacros;
497 SmallVector<StringRef, 4> ExistingMacroNames;
498 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
499
500 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
501 // Dig out the macro definition in the existing preprocessor options.
502 StringRef MacroName = ExistingMacroNames[I];
503 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
504
505 // Check whether we know anything about this macro name or not.
506 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
507 = ASTFileMacros.find(MacroName);
508 if (Known == ASTFileMacros.end()) {
509 // FIXME: Check whether this identifier was referenced anywhere in the
510 // AST file. If so, we should reject the AST file. Unfortunately, this
511 // information isn't in the control block. What shall we do about it?
512
513 if (Existing.second) {
514 SuggestedPredefines += "#undef ";
515 SuggestedPredefines += MacroName.str();
516 SuggestedPredefines += '\n';
517 } else {
518 SuggestedPredefines += "#define ";
519 SuggestedPredefines += MacroName.str();
520 SuggestedPredefines += ' ';
521 SuggestedPredefines += Existing.first.str();
522 SuggestedPredefines += '\n';
523 }
524 continue;
525 }
526
527 // If the macro was defined in one but undef'd in the other, we have a
528 // conflict.
529 if (Existing.second != Known->second.second) {
530 if (Diags) {
531 Diags->Report(diag::err_pch_macro_def_undef)
532 << MacroName << Known->second.second;
533 }
534 return true;
535 }
536
537 // If the macro was #undef'd in both, or if the macro bodies are identical,
538 // it's fine.
539 if (Existing.second || Existing.first == Known->second.first)
540 continue;
541
542 // The macro bodies differ; complain.
543 if (Diags) {
544 Diags->Report(diag::err_pch_macro_def_conflict)
545 << MacroName << Known->second.first << Existing.first;
546 }
547 return true;
548 }
549
550 // Check whether we're using predefines.
551 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
552 if (Diags) {
553 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
554 }
555 return true;
556 }
557
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000558 // Detailed record is important since it is used for the module cache hash.
559 if (LangOpts.Modules &&
560 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
561 if (Diags) {
562 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
563 }
564 return true;
565 }
566
Guy Benyei11169dd2012-12-18 14:30:41 +0000567 // Compute the #include and #include_macros lines we need.
568 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
569 StringRef File = ExistingPPOpts.Includes[I];
570 if (File == ExistingPPOpts.ImplicitPCHInclude)
571 continue;
572
573 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
574 != PPOpts.Includes.end())
575 continue;
576
577 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000578 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000579 SuggestedPredefines += "\"\n";
580 }
581
582 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
583 StringRef File = ExistingPPOpts.MacroIncludes[I];
584 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
585 File)
586 != PPOpts.MacroIncludes.end())
587 continue;
588
589 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000590 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000591 SuggestedPredefines += "\"\n##\n";
592 }
593
594 return false;
595}
596
597bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
598 bool Complain,
599 std::string &SuggestedPredefines) {
600 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
601
602 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000603 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000604 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000605 SuggestedPredefines,
606 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000607}
608
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000609/// Check the header search options deserialized from the control block
610/// against the header search options in an existing preprocessor.
611///
612/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
613static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
614 StringRef SpecificModuleCachePath,
615 StringRef ExistingModuleCachePath,
616 DiagnosticsEngine *Diags,
617 const LangOptions &LangOpts) {
618 if (LangOpts.Modules) {
619 if (SpecificModuleCachePath != ExistingModuleCachePath) {
620 if (Diags)
621 Diags->Report(diag::err_pch_modulecache_mismatch)
622 << SpecificModuleCachePath << ExistingModuleCachePath;
623 return true;
624 }
625 }
626
627 return false;
628}
629
630bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
631 StringRef SpecificModuleCachePath,
632 bool Complain) {
633 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
634 PP.getHeaderSearchInfo().getModuleCachePath(),
635 Complain ? &Reader.Diags : nullptr,
636 PP.getLangOpts());
637}
638
Guy Benyei11169dd2012-12-18 14:30:41 +0000639void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
640 PP.setCounterValue(Value);
641}
642
643//===----------------------------------------------------------------------===//
644// AST reader implementation
645//===----------------------------------------------------------------------===//
646
Nico Weber824285e2014-05-08 04:26:47 +0000647void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
648 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000649 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000650 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000651}
652
653
654
655unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
656 return serialization::ComputeHash(Sel);
657}
658
659
660std::pair<unsigned, unsigned>
661ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000662 using namespace llvm::support;
663 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
664 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000665 return std::make_pair(KeyLen, DataLen);
666}
667
668ASTSelectorLookupTrait::internal_key_type
669ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000670 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000671 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000672 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
673 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
674 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000675 if (N == 0)
676 return SelTable.getNullarySelector(FirstII);
677 else if (N == 1)
678 return SelTable.getUnarySelector(FirstII);
679
680 SmallVector<IdentifierInfo *, 16> Args;
681 Args.push_back(FirstII);
682 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000683 Args.push_back(Reader.getLocalIdentifier(
684 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000685
686 return SelTable.getSelector(N, Args.data());
687}
688
689ASTSelectorLookupTrait::data_type
690ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
691 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000692 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000693
694 data_type Result;
695
Justin Bogner57ba0b22014-03-28 22:03:24 +0000696 Result.ID = Reader.getGlobalSelectorID(
697 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000698 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
699 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
700 Result.InstanceBits = FullInstanceBits & 0x3;
701 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
702 Result.FactoryBits = FullFactoryBits & 0x3;
703 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
704 unsigned NumInstanceMethods = FullInstanceBits >> 3;
705 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000706
707 // Load instance methods
708 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000709 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
710 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000711 Result.Instance.push_back(Method);
712 }
713
714 // Load factory methods
715 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000716 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
717 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000718 Result.Factory.push_back(Method);
719 }
720
721 return Result;
722}
723
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000724unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
725 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000726}
727
728std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000729ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000730 using namespace llvm::support;
731 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
732 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000733 return std::make_pair(KeyLen, DataLen);
734}
735
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000736ASTIdentifierLookupTraitBase::internal_key_type
737ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000738 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000739 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000740}
741
Douglas Gregordcf25082013-02-11 18:16:18 +0000742/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000743static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
744 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000745 return II.hadMacroDefinition() ||
746 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000747 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000748 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000749 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
750 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000751}
752
Richard Smith76c2f2c2015-07-17 20:09:43 +0000753static bool readBit(unsigned &Bits) {
754 bool Value = Bits & 0x1;
755 Bits >>= 1;
756 return Value;
757}
758
Richard Smith79bf9202015-08-24 03:33:22 +0000759IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
760 using namespace llvm::support;
761 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
762 return Reader.getGlobalIdentifierID(F, RawID >> 1);
763}
764
Guy Benyei11169dd2012-12-18 14:30:41 +0000765IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
766 const unsigned char* d,
767 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000768 using namespace llvm::support;
769 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000770 bool IsInteresting = RawID & 0x01;
771
772 // Wipe out the "is interesting" bit.
773 RawID = RawID >> 1;
774
Richard Smith76c2f2c2015-07-17 20:09:43 +0000775 // Build the IdentifierInfo and link the identifier ID with it.
776 IdentifierInfo *II = KnownII;
777 if (!II) {
778 II = &Reader.getIdentifierTable().getOwn(k);
779 KnownII = II;
780 }
781 if (!II->isFromAST()) {
782 II->setIsFromAST();
Richard Smitha534a312015-07-21 23:54:07 +0000783 if (isInterestingIdentifier(Reader, *II, F.isModule()))
Richard Smith76c2f2c2015-07-17 20:09:43 +0000784 II->setChangedSinceDeserialization();
785 }
786 Reader.markIdentifierUpToDate(II);
787
Guy Benyei11169dd2012-12-18 14:30:41 +0000788 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
789 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000790 // For uninteresting identifiers, there's nothing else to do. Just notify
791 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000792 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000793 return II;
794 }
795
Justin Bogner57ba0b22014-03-28 22:03:24 +0000796 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
797 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000798 bool CPlusPlusOperatorKeyword = readBit(Bits);
799 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000800 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000801 bool Poisoned = readBit(Bits);
802 bool ExtensionToken = readBit(Bits);
803 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000804
805 assert(Bits == 0 && "Extra bits in the identifier?");
806 DataLen -= 8;
807
Guy Benyei11169dd2012-12-18 14:30:41 +0000808 // Set or check the various bits in the IdentifierInfo structure.
809 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000810 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000811 II->revertTokenIDToIdentifier();
812 if (!F.isModule())
813 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
814 else if (HasRevertedBuiltin && II->getBuiltinID()) {
815 II->revertBuiltin();
816 assert((II->hasRevertedBuiltin() ||
817 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
818 "Incorrect ObjC keyword or builtin ID");
819 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000820 assert(II->isExtensionToken() == ExtensionToken &&
821 "Incorrect extension token flag");
822 (void)ExtensionToken;
823 if (Poisoned)
824 II->setIsPoisoned(true);
825 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
826 "Incorrect C++ operator keyword flag");
827 (void)CPlusPlusOperatorKeyword;
828
829 // If this identifier is a macro, deserialize the macro
830 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000831 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000832 uint32_t MacroDirectivesOffset =
833 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000834 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000835
Richard Smithd7329392015-04-21 21:46:32 +0000836 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000837 }
838
839 Reader.SetIdentifierInfo(ID, II);
840
841 // Read all of the declarations visible at global scope with this
842 // name.
843 if (DataLen > 0) {
844 SmallVector<uint32_t, 4> DeclIDs;
845 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000846 DeclIDs.push_back(Reader.getGlobalDeclID(
847 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000848 Reader.SetGloballyVisibleDecls(II, DeclIDs);
849 }
850
851 return II;
852}
853
Richard Smitha06c7e62015-08-26 23:55:49 +0000854DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
855 : Kind(Name.getNameKind()) {
856 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000857 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000858 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000859 break;
860 case DeclarationName::ObjCZeroArgSelector:
861 case DeclarationName::ObjCOneArgSelector:
862 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000863 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000864 break;
865 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000866 Data = Name.getCXXOverloadedOperator();
867 break;
868 case DeclarationName::CXXLiteralOperatorName:
869 Data = (uint64_t)Name.getCXXLiteralIdentifier();
870 break;
871 case DeclarationName::CXXConstructorName:
872 case DeclarationName::CXXDestructorName:
873 case DeclarationName::CXXConversionFunctionName:
874 case DeclarationName::CXXUsingDirective:
875 Data = 0;
876 break;
877 }
878}
879
880unsigned DeclarationNameKey::getHash() const {
881 llvm::FoldingSetNodeID ID;
882 ID.AddInteger(Kind);
883
884 switch (Kind) {
885 case DeclarationName::Identifier:
886 case DeclarationName::CXXLiteralOperatorName:
887 ID.AddString(((IdentifierInfo*)Data)->getName());
888 break;
889 case DeclarationName::ObjCZeroArgSelector:
890 case DeclarationName::ObjCOneArgSelector:
891 case DeclarationName::ObjCMultiArgSelector:
892 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
893 break;
894 case DeclarationName::CXXOperatorName:
895 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000896 break;
897 case DeclarationName::CXXConstructorName:
898 case DeclarationName::CXXDestructorName:
899 case DeclarationName::CXXConversionFunctionName:
900 case DeclarationName::CXXUsingDirective:
901 break;
902 }
903
904 return ID.ComputeHash();
905}
906
Richard Smithd88a7f12015-09-01 20:35:42 +0000907ModuleFile *
908ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
909 using namespace llvm::support;
910 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
911 return Reader.getLocalModuleFile(F, ModuleFileID);
912}
913
Guy Benyei11169dd2012-12-18 14:30:41 +0000914std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000915ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000916 using namespace llvm::support;
917 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
918 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000919 return std::make_pair(KeyLen, DataLen);
920}
921
Richard Smitha06c7e62015-08-26 23:55:49 +0000922ASTDeclContextNameLookupTrait::internal_key_type
923ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000924 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000925
Richard Smitha06c7e62015-08-26 23:55:49 +0000926 auto Kind = (DeclarationName::NameKind)*d++;
927 uint64_t Data;
928 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000929 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000930 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000931 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000932 break;
933 case DeclarationName::ObjCZeroArgSelector:
934 case DeclarationName::ObjCOneArgSelector:
935 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000936 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000937 (uint64_t)Reader.getLocalSelector(
938 F, endian::readNext<uint32_t, little, unaligned>(
939 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000940 break;
941 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000942 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +0000943 break;
944 case DeclarationName::CXXLiteralOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000945 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000946 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000947 break;
948 case DeclarationName::CXXConstructorName:
949 case DeclarationName::CXXDestructorName:
950 case DeclarationName::CXXConversionFunctionName:
951 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +0000952 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000953 break;
954 }
955
Richard Smitha06c7e62015-08-26 23:55:49 +0000956 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000957}
958
Richard Smithd88a7f12015-09-01 20:35:42 +0000959void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
960 const unsigned char *d,
961 unsigned DataLen,
962 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000963 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +0000964 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
965 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
966 Val.insert(Reader.getGlobalDeclID(F, LocalID));
967 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000968}
969
Richard Smith0f4e2c42015-08-06 04:23:48 +0000970bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
971 BitstreamCursor &Cursor,
972 uint64_t Offset,
973 DeclContext *DC) {
974 assert(Offset != 0);
975
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +0000977 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000978
Richard Smith0f4e2c42015-08-06 04:23:48 +0000979 RecordData Record;
980 StringRef Blob;
981 unsigned Code = Cursor.ReadCode();
982 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
983 if (RecCode != DECL_CONTEXT_LEXICAL) {
984 Error("Expected lexical block");
985 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000986 }
987
Richard Smith82f8fcd2015-08-06 22:07:25 +0000988 assert(!isa<TranslationUnitDecl>(DC) &&
989 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +0000990 // If we are handling a C++ class template instantiation, we can see multiple
991 // lexical updates for the same record. It's important that we select only one
992 // of them, so that field numbering works properly. Just pick the first one we
993 // see.
994 auto &Lex = LexicalDecls[DC];
995 if (!Lex.first) {
996 Lex = std::make_pair(
997 &M, llvm::makeArrayRef(
998 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
999 Blob.data()),
1000 Blob.size() / 4));
1001 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001002 DC->setHasExternalLexicalStorage(true);
1003 return false;
1004}
Guy Benyei11169dd2012-12-18 14:30:41 +00001005
Richard Smith0f4e2c42015-08-06 04:23:48 +00001006bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1007 BitstreamCursor &Cursor,
1008 uint64_t Offset,
1009 DeclID ID) {
1010 assert(Offset != 0);
1011
1012 SavedStreamPosition SavedPosition(Cursor);
1013 Cursor.JumpToBit(Offset);
1014
1015 RecordData Record;
1016 StringRef Blob;
1017 unsigned Code = Cursor.ReadCode();
1018 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1019 if (RecCode != DECL_CONTEXT_VISIBLE) {
1020 Error("Expected visible lookup table block");
1021 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001022 }
1023
Richard Smith0f4e2c42015-08-06 04:23:48 +00001024 // We can't safely determine the primary context yet, so delay attaching the
1025 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001026 auto *Data = (const unsigned char*)Blob.data();
1027 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001028 return false;
1029}
1030
1031void ASTReader::Error(StringRef Msg) {
1032 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001033 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1034 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001035 Diag(diag::note_module_cache_path)
1036 << PP.getHeaderSearchInfo().getModuleCachePath();
1037 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001038}
1039
1040void ASTReader::Error(unsigned DiagID,
1041 StringRef Arg1, StringRef Arg2) {
1042 if (Diags.isDiagnosticInFlight())
1043 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1044 else
1045 Diag(DiagID) << Arg1 << Arg2;
1046}
1047
1048//===----------------------------------------------------------------------===//
1049// Source Manager Deserialization
1050//===----------------------------------------------------------------------===//
1051
1052/// \brief Read the line table in the source manager block.
1053/// \returns true if there was an error.
1054bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001055 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001056 unsigned Idx = 0;
1057 LineTableInfo &LineTable = SourceMgr.getLineTable();
1058
1059 // Parse the file names
1060 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001061 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001062 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001063 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001064 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1065 }
Richard Smith63078492015-09-01 07:41:55 +00001066 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001067
1068 // Parse the line entries
1069 std::vector<LineEntry> Entries;
1070 while (Idx < Record.size()) {
1071 int FID = Record[Idx++];
1072 assert(FID >= 0 && "Serialized line entries for non-local file.");
1073 // Remap FileID from 1-based old view.
1074 FID += F.SLocEntryBaseID - 1;
1075
1076 // Extract the line entries
1077 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001078 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001079 Entries.clear();
1080 Entries.reserve(NumEntries);
1081 for (unsigned I = 0; I != NumEntries; ++I) {
1082 unsigned FileOffset = Record[Idx++];
1083 unsigned LineNo = Record[Idx++];
1084 int FilenameID = FileIDs[Record[Idx++]];
1085 SrcMgr::CharacteristicKind FileKind
1086 = (SrcMgr::CharacteristicKind)Record[Idx++];
1087 unsigned IncludeOffset = Record[Idx++];
1088 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1089 FileKind, IncludeOffset));
1090 }
1091 LineTable.AddEntry(FileID::get(FID), Entries);
1092 }
1093
1094 return false;
1095}
1096
1097/// \brief Read a source manager block
1098bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1099 using namespace SrcMgr;
1100
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001101 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001102
1103 // Set the source-location entry cursor to the current position in
1104 // the stream. This cursor will be used to read the contents of the
1105 // source manager block initially, and then lazily read
1106 // source-location entries as needed.
1107 SLocEntryCursor = F.Stream;
1108
1109 // The stream itself is going to skip over the source manager block.
1110 if (F.Stream.SkipBlock()) {
1111 Error("malformed block record in AST file");
1112 return true;
1113 }
1114
1115 // Enter the source manager block.
1116 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1117 Error("malformed source manager block record in AST file");
1118 return true;
1119 }
1120
1121 RecordData Record;
1122 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001123 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1124
1125 switch (E.Kind) {
1126 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1127 case llvm::BitstreamEntry::Error:
1128 Error("malformed block record in AST file");
1129 return true;
1130 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001131 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001132 case llvm::BitstreamEntry::Record:
1133 // The interesting case.
1134 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001135 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001136
Guy Benyei11169dd2012-12-18 14:30:41 +00001137 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001138 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001139 StringRef Blob;
1140 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001141 default: // Default behavior: ignore.
1142 break;
1143
1144 case SM_SLOC_FILE_ENTRY:
1145 case SM_SLOC_BUFFER_ENTRY:
1146 case SM_SLOC_EXPANSION_ENTRY:
1147 // Once we hit one of the source location entries, we're done.
1148 return false;
1149 }
1150 }
1151}
1152
1153/// \brief If a header file is not found at the path that we expect it to be
1154/// and the PCH file was moved from its original location, try to resolve the
1155/// file by assuming that header+PCH were moved together and the header is in
1156/// the same place relative to the PCH.
1157static std::string
1158resolveFileRelativeToOriginalDir(const std::string &Filename,
1159 const std::string &OriginalDir,
1160 const std::string &CurrDir) {
1161 assert(OriginalDir != CurrDir &&
1162 "No point trying to resolve the file if the PCH dir didn't change");
1163 using namespace llvm::sys;
1164 SmallString<128> filePath(Filename);
1165 fs::make_absolute(filePath);
1166 assert(path::is_absolute(OriginalDir));
1167 SmallString<128> currPCHPath(CurrDir);
1168
1169 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1170 fileDirE = path::end(path::parent_path(filePath));
1171 path::const_iterator origDirI = path::begin(OriginalDir),
1172 origDirE = path::end(OriginalDir);
1173 // Skip the common path components from filePath and OriginalDir.
1174 while (fileDirI != fileDirE && origDirI != origDirE &&
1175 *fileDirI == *origDirI) {
1176 ++fileDirI;
1177 ++origDirI;
1178 }
1179 for (; origDirI != origDirE; ++origDirI)
1180 path::append(currPCHPath, "..");
1181 path::append(currPCHPath, fileDirI, fileDirE);
1182 path::append(currPCHPath, path::filename(Filename));
1183 return currPCHPath.str();
1184}
1185
1186bool ASTReader::ReadSLocEntry(int ID) {
1187 if (ID == 0)
1188 return false;
1189
1190 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1191 Error("source location entry ID out-of-range for AST file");
1192 return true;
1193 }
1194
1195 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1196 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001197 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001198 unsigned BaseOffset = F->SLocEntryBaseOffset;
1199
1200 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001201 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1202 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001203 Error("incorrectly-formatted source location entry in AST file");
1204 return true;
1205 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001206
Guy Benyei11169dd2012-12-18 14:30:41 +00001207 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001208 StringRef Blob;
1209 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001210 default:
1211 Error("incorrectly-formatted source location entry in AST file");
1212 return true;
1213
1214 case SM_SLOC_FILE_ENTRY: {
1215 // We will detect whether a file changed and return 'Failure' for it, but
1216 // we will also try to fail gracefully by setting up the SLocEntry.
1217 unsigned InputID = Record[4];
1218 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001219 const FileEntry *File = IF.getFile();
1220 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001221
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001222 // Note that we only check if a File was returned. If it was out-of-date
1223 // we have complained but we will continue creating a FileID to recover
1224 // gracefully.
1225 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001226 return true;
1227
1228 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1229 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1230 // This is the module's main file.
1231 IncludeLoc = getImportLocation(F);
1232 }
1233 SrcMgr::CharacteristicKind
1234 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1235 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1236 ID, BaseOffset + Record[0]);
1237 SrcMgr::FileInfo &FileInfo =
1238 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1239 FileInfo.NumCreatedFIDs = Record[5];
1240 if (Record[3])
1241 FileInfo.setHasLineDirectives();
1242
1243 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1244 unsigned NumFileDecls = Record[7];
1245 if (NumFileDecls) {
1246 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1247 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1248 NumFileDecls));
1249 }
1250
1251 const SrcMgr::ContentCache *ContentCache
1252 = SourceMgr.getOrCreateContentCache(File,
1253 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1254 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1255 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1256 unsigned Code = SLocEntryCursor.ReadCode();
1257 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001258 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001259
1260 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1261 Error("AST record has invalid code");
1262 return true;
1263 }
1264
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001265 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001266 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001267 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001268 }
1269
1270 break;
1271 }
1272
1273 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001274 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001275 unsigned Offset = Record[0];
1276 SrcMgr::CharacteristicKind
1277 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1278 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001279 if (IncludeLoc.isInvalid() &&
1280 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001281 IncludeLoc = getImportLocation(F);
1282 }
1283 unsigned Code = SLocEntryCursor.ReadCode();
1284 Record.clear();
1285 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001286 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001287
1288 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1289 Error("AST record has invalid code");
1290 return true;
1291 }
1292
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001293 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1294 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001295 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001296 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001297 break;
1298 }
1299
1300 case SM_SLOC_EXPANSION_ENTRY: {
1301 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1302 SourceMgr.createExpansionLoc(SpellingLoc,
1303 ReadSourceLocation(*F, Record[2]),
1304 ReadSourceLocation(*F, Record[3]),
1305 Record[4],
1306 ID,
1307 BaseOffset + Record[0]);
1308 break;
1309 }
1310 }
1311
1312 return false;
1313}
1314
1315std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1316 if (ID == 0)
1317 return std::make_pair(SourceLocation(), "");
1318
1319 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1320 Error("source location entry ID out-of-range for AST file");
1321 return std::make_pair(SourceLocation(), "");
1322 }
1323
1324 // Find which module file this entry lands in.
1325 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001326 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001327 return std::make_pair(SourceLocation(), "");
1328
1329 // FIXME: Can we map this down to a particular submodule? That would be
1330 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001331 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001332}
1333
1334/// \brief Find the location where the module F is imported.
1335SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1336 if (F->ImportLoc.isValid())
1337 return F->ImportLoc;
1338
1339 // Otherwise we have a PCH. It's considered to be "imported" at the first
1340 // location of its includer.
1341 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001342 // Main file is the importer.
1343 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1344 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001345 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001346 return F->ImportedBy[0]->FirstLoc;
1347}
1348
1349/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1350/// specified cursor. Read the abbreviations that are at the top of the block
1351/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001352bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001353 if (Cursor.EnterSubBlock(BlockID))
1354 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001355
1356 while (true) {
1357 uint64_t Offset = Cursor.GetCurrentBitNo();
1358 unsigned Code = Cursor.ReadCode();
1359
1360 // We expect all abbrevs to be at the start of the block.
1361 if (Code != llvm::bitc::DEFINE_ABBREV) {
1362 Cursor.JumpToBit(Offset);
1363 return false;
1364 }
1365 Cursor.ReadAbbrevRecord();
1366 }
1367}
1368
Richard Smithe40f2ba2013-08-07 21:41:30 +00001369Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001370 unsigned &Idx) {
1371 Token Tok;
1372 Tok.startToken();
1373 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1374 Tok.setLength(Record[Idx++]);
1375 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1376 Tok.setIdentifierInfo(II);
1377 Tok.setKind((tok::TokenKind)Record[Idx++]);
1378 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1379 return Tok;
1380}
1381
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001382MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001383 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001384
1385 // Keep track of where we are in the stream, then jump back there
1386 // after reading this macro.
1387 SavedStreamPosition SavedPosition(Stream);
1388
1389 Stream.JumpToBit(Offset);
1390 RecordData Record;
1391 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001392 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001393
Guy Benyei11169dd2012-12-18 14:30:41 +00001394 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001395 // Advance to the next record, but if we get to the end of the block, don't
1396 // pop it (removing all the abbreviations from the cursor) since we want to
1397 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001398 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001399 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1400
1401 switch (Entry.Kind) {
1402 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1403 case llvm::BitstreamEntry::Error:
1404 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001405 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001406 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001407 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001408 case llvm::BitstreamEntry::Record:
1409 // The interesting case.
1410 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001411 }
1412
1413 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001414 Record.clear();
1415 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001416 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001418 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001419 case PP_MACRO_DIRECTIVE_HISTORY:
1420 return Macro;
1421
Guy Benyei11169dd2012-12-18 14:30:41 +00001422 case PP_MACRO_OBJECT_LIKE:
1423 case PP_MACRO_FUNCTION_LIKE: {
1424 // If we already have a macro, that means that we've hit the end
1425 // of the definition of the macro we were looking for. We're
1426 // done.
1427 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001428 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001429
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001430 unsigned NextIndex = 1; // Skip identifier ID.
1431 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001432 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001433 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001434 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001435 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001436 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001437
Guy Benyei11169dd2012-12-18 14:30:41 +00001438 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1439 // Decode function-like macro info.
1440 bool isC99VarArgs = Record[NextIndex++];
1441 bool isGNUVarArgs = Record[NextIndex++];
1442 bool hasCommaPasting = Record[NextIndex++];
1443 MacroArgs.clear();
1444 unsigned NumArgs = Record[NextIndex++];
1445 for (unsigned i = 0; i != NumArgs; ++i)
1446 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1447
1448 // Install function-like macro info.
1449 MI->setIsFunctionLike();
1450 if (isC99VarArgs) MI->setIsC99Varargs();
1451 if (isGNUVarArgs) MI->setIsGNUVarargs();
1452 if (hasCommaPasting) MI->setHasCommaPasting();
1453 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1454 PP.getPreprocessorAllocator());
1455 }
1456
Guy Benyei11169dd2012-12-18 14:30:41 +00001457 // Remember that we saw this macro last so that we add the tokens that
1458 // form its body to it.
1459 Macro = MI;
1460
1461 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1462 Record[NextIndex]) {
1463 // We have a macro definition. Register the association
1464 PreprocessedEntityID
1465 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1466 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001467 PreprocessingRecord::PPEntityID PPID =
1468 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1469 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1470 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001471 if (PPDef)
1472 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001473 }
1474
1475 ++NumMacrosRead;
1476 break;
1477 }
1478
1479 case PP_TOKEN: {
1480 // If we see a TOKEN before a PP_MACRO_*, then the file is
1481 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001482 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001483
John McCallf413f5e2013-05-03 00:10:13 +00001484 unsigned Idx = 0;
1485 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001486 Macro->AddTokenToBody(Tok);
1487 break;
1488 }
1489 }
1490 }
1491}
1492
1493PreprocessedEntityID
1494ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1495 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1496 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1497 assert(I != M.PreprocessedEntityRemap.end()
1498 && "Invalid index into preprocessed entity index remap");
1499
1500 return LocalID + I->second;
1501}
1502
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001503unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1504 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001505}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001506
Guy Benyei11169dd2012-12-18 14:30:41 +00001507HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001508HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001509 internal_key_type ikey = {FE->getSize(),
1510 M.HasTimestamps ? FE->getModificationTime() : 0,
1511 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001512 return ikey;
1513}
Guy Benyei11169dd2012-12-18 14:30:41 +00001514
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001515bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001516 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 return false;
1518
Richard Smith7ed1bc92014-12-05 22:42:13 +00001519 if (llvm::sys::path::is_absolute(a.Filename) &&
1520 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001521 return true;
1522
Guy Benyei11169dd2012-12-18 14:30:41 +00001523 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001524 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001525 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1526 if (!Key.Imported)
1527 return FileMgr.getFile(Key.Filename);
1528
1529 std::string Resolved = Key.Filename;
1530 Reader.ResolveImportedPath(M, Resolved);
1531 return FileMgr.getFile(Resolved);
1532 };
1533
1534 const FileEntry *FEA = GetFile(a);
1535 const FileEntry *FEB = GetFile(b);
1536 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001537}
1538
1539std::pair<unsigned, unsigned>
1540HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001541 using namespace llvm::support;
1542 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001543 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001544 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001545}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001546
1547HeaderFileInfoTrait::internal_key_type
1548HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001549 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001550 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001551 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1552 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001553 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001554 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001555 return ikey;
1556}
1557
Guy Benyei11169dd2012-12-18 14:30:41 +00001558HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001559HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001560 unsigned DataLen) {
1561 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001562 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001563 HeaderFileInfo HFI;
1564 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001565 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1566 HFI.isImport |= (Flags >> 4) & 0x01;
1567 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1568 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001569 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001570 // FIXME: Find a better way to handle this. Maybe just store a
1571 // "has been included" flag?
1572 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1573 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001574 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1575 M, endian::readNext<uint32_t, little, unaligned>(d));
1576 if (unsigned FrameworkOffset =
1577 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001578 // The framework offset is 1 greater than the actual offset,
1579 // since 0 is used as an indicator for "no framework name".
1580 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1581 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1582 }
Richard Smith386bb072015-08-18 23:42:23 +00001583
1584 assert((End - d) % 4 == 0 &&
1585 "Wrong data length in HeaderFileInfo deserialization");
1586 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001587 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001588 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1589 LocalSMID >>= 2;
1590
1591 // This header is part of a module. Associate it with the module to enable
1592 // implicit module import.
1593 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1594 Module *Mod = Reader.getSubmodule(GlobalSMID);
1595 FileManager &FileMgr = Reader.getFileManager();
1596 ModuleMap &ModMap =
1597 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1598
1599 std::string Filename = key.Filename;
1600 if (key.Imported)
1601 Reader.ResolveImportedPath(M, Filename);
1602 // FIXME: This is not always the right filename-as-written, but we're not
1603 // going to use this information to rebuild the module, so it doesn't make
1604 // a lot of difference.
1605 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001606 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1607 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001608 }
1609
Guy Benyei11169dd2012-12-18 14:30:41 +00001610 // This HeaderFileInfo was externally loaded.
1611 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001612 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001613 return HFI;
1614}
1615
Richard Smithd7329392015-04-21 21:46:32 +00001616void ASTReader::addPendingMacro(IdentifierInfo *II,
1617 ModuleFile *M,
1618 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001619 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1620 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001621}
1622
1623void ASTReader::ReadDefinedMacros() {
1624 // Note that we are loading defined macros.
1625 Deserializing Macros(this);
1626
Pete Cooper57d3f142015-07-30 17:22:52 +00001627 for (auto &I : llvm::reverse(ModuleMgr)) {
1628 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001629
1630 // If there was no preprocessor block, skip this file.
1631 if (!MacroCursor.getBitStreamReader())
1632 continue;
1633
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001634 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001635 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001636
1637 RecordData Record;
1638 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001639 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1640
1641 switch (E.Kind) {
1642 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1643 case llvm::BitstreamEntry::Error:
1644 Error("malformed block record in AST file");
1645 return;
1646 case llvm::BitstreamEntry::EndBlock:
1647 goto NextCursor;
1648
1649 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001650 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001651 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001652 default: // Default behavior: ignore.
1653 break;
1654
1655 case PP_MACRO_OBJECT_LIKE:
1656 case PP_MACRO_FUNCTION_LIKE:
Pete Cooper57d3f142015-07-30 17:22:52 +00001657 getLocalIdentifier(*I, Record[0]);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001658 break;
1659
1660 case PP_TOKEN:
1661 // Ignore tokens.
1662 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001663 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001664 break;
1665 }
1666 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001667 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001668 }
1669}
1670
1671namespace {
1672 /// \brief Visitor class used to look up identifirs in an AST file.
1673 class IdentifierLookupVisitor {
1674 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001675 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001676 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001677 unsigned &NumIdentifierLookups;
1678 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001679 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001680
Guy Benyei11169dd2012-12-18 14:30:41 +00001681 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001682 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1683 unsigned &NumIdentifierLookups,
1684 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001685 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1686 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001687 NumIdentifierLookups(NumIdentifierLookups),
1688 NumIdentifierLookupHits(NumIdentifierLookupHits),
1689 Found()
1690 {
1691 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001692
1693 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001694 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001695 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001696 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001697
Guy Benyei11169dd2012-12-18 14:30:41 +00001698 ASTIdentifierLookupTable *IdTable
1699 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1700 if (!IdTable)
1701 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001702
1703 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001704 Found);
1705 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001706 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001707 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001708 if (Pos == IdTable->end())
1709 return false;
1710
1711 // Dereferencing the iterator has the effect of building the
1712 // IdentifierInfo node and populating it with the various
1713 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001714 ++NumIdentifierLookupHits;
1715 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001716 return true;
1717 }
1718
1719 // \brief Retrieve the identifier info found within the module
1720 // files.
1721 IdentifierInfo *getIdentifierInfo() const { return Found; }
1722 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001723}
Guy Benyei11169dd2012-12-18 14:30:41 +00001724
1725void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1726 // Note that we are loading an identifier.
1727 Deserializing AnIdentifier(this);
1728
1729 unsigned PriorGeneration = 0;
1730 if (getContext().getLangOpts().Modules)
1731 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001732
1733 // If there is a global index, look there first to determine which modules
1734 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001735 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001736 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001737 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001738 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1739 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001740 }
1741 }
1742
Douglas Gregor7211ac12013-01-25 23:32:03 +00001743 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001744 NumIdentifierLookups,
1745 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001746 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001747 markIdentifierUpToDate(&II);
1748}
1749
1750void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1751 if (!II)
1752 return;
1753
1754 II->setOutOfDate(false);
1755
1756 // Update the generation for this identifier.
1757 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001758 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001759}
1760
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001761void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1762 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001763 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001764
1765 BitstreamCursor &Cursor = M.MacroCursor;
1766 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001767 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001768
Richard Smith713369b2015-04-23 20:40:50 +00001769 struct ModuleMacroRecord {
1770 SubmoduleID SubModID;
1771 MacroInfo *MI;
1772 SmallVector<SubmoduleID, 8> Overrides;
1773 };
1774 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001775
Richard Smithd7329392015-04-21 21:46:32 +00001776 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1777 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1778 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001779 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001780 while (true) {
1781 llvm::BitstreamEntry Entry =
1782 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1783 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1784 Error("malformed block record in AST file");
1785 return;
1786 }
1787
1788 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001789 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001790 case PP_MACRO_DIRECTIVE_HISTORY:
1791 break;
1792
1793 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001794 ModuleMacros.push_back(ModuleMacroRecord());
1795 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001796 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1797 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001798 for (int I = 2, N = Record.size(); I != N; ++I)
1799 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001800 continue;
1801 }
1802
1803 default:
1804 Error("malformed block record in AST file");
1805 return;
1806 }
1807
1808 // We found the macro directive history; that's the last record
1809 // for this macro.
1810 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001811 }
1812
Richard Smithd7329392015-04-21 21:46:32 +00001813 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001814 {
1815 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001816 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001817 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001818 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001819 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001820 Module *Mod = getSubmodule(ModID);
1821 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001822 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001823 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001824 }
1825
1826 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001827 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001828 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001829 }
1830 }
1831
1832 // Don't read the directive history for a module; we don't have anywhere
1833 // to put it.
1834 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1835 return;
1836
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001837 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001838 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001839 unsigned Idx = 0, N = Record.size();
1840 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001841 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001842 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001843 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1844 switch (K) {
1845 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001846 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001847 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001848 break;
1849 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001850 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001851 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001852 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001853 }
1854 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001855 bool isPublic = Record[Idx++];
1856 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1857 break;
1858 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001859
1860 if (!Latest)
1861 Latest = MD;
1862 if (Earliest)
1863 Earliest->setPrevious(MD);
1864 Earliest = MD;
1865 }
1866
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001867 if (Latest)
1868 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001869}
1870
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001871ASTReader::InputFileInfo
1872ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001873 // Go find this input file.
1874 BitstreamCursor &Cursor = F.InputFilesCursor;
1875 SavedStreamPosition SavedPosition(Cursor);
1876 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1877
1878 unsigned Code = Cursor.ReadCode();
1879 RecordData Record;
1880 StringRef Blob;
1881
1882 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1883 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1884 "invalid record type for input file");
1885 (void)Result;
1886
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001887 std::string Filename;
1888 off_t StoredSize;
1889 time_t StoredTime;
1890 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001891
Ben Langmuir198c1682014-03-07 07:27:49 +00001892 assert(Record[0] == ID && "Bogus stored ID or offset");
1893 StoredSize = static_cast<off_t>(Record[1]);
1894 StoredTime = static_cast<time_t>(Record[2]);
1895 Overridden = static_cast<bool>(Record[3]);
1896 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001897 ResolveImportedPath(F, Filename);
1898
Hans Wennborg73945142014-03-14 17:45:06 +00001899 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1900 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001901}
1902
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001903InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001904 // If this ID is bogus, just return an empty input file.
1905 if (ID == 0 || ID > F.InputFilesLoaded.size())
1906 return InputFile();
1907
1908 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001909 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001910 return F.InputFilesLoaded[ID-1];
1911
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001912 if (F.InputFilesLoaded[ID-1].isNotFound())
1913 return InputFile();
1914
Guy Benyei11169dd2012-12-18 14:30:41 +00001915 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001916 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001917 SavedStreamPosition SavedPosition(Cursor);
1918 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1919
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001920 InputFileInfo FI = readInputFileInfo(F, ID);
1921 off_t StoredSize = FI.StoredSize;
1922 time_t StoredTime = FI.StoredTime;
1923 bool Overridden = FI.Overridden;
1924 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001925
Ben Langmuir198c1682014-03-07 07:27:49 +00001926 const FileEntry *File
1927 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1928 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1929
1930 // If we didn't find the file, resolve it relative to the
1931 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001932 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001933 F.OriginalDir != CurrentDir) {
1934 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1935 F.OriginalDir,
1936 CurrentDir);
1937 if (!Resolved.empty())
1938 File = FileMgr.getFile(Resolved);
1939 }
1940
1941 // For an overridden file, create a virtual file with the stored
1942 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001943 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001944 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1945 }
1946
Craig Toppera13603a2014-05-22 05:54:18 +00001947 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001948 if (Complain) {
1949 std::string ErrorStr = "could not find file '";
1950 ErrorStr += Filename;
1951 ErrorStr += "' referenced by AST file";
1952 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001953 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001954 // Record that we didn't find the file.
1955 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1956 return InputFile();
1957 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001958
Ben Langmuir198c1682014-03-07 07:27:49 +00001959 // Check if there was a request to override the contents of the file
1960 // that was part of the precompiled header. Overridding such a file
1961 // can lead to problems when lexing using the source locations from the
1962 // PCH.
1963 SourceManager &SM = getSourceManager();
1964 if (!Overridden && SM.isFileOverridden(File)) {
1965 if (Complain)
1966 Error(diag::err_fe_pch_file_overridden, Filename);
1967 // After emitting the diagnostic, recover by disabling the override so
1968 // that the original file will be used.
1969 SM.disableFileContentsOverride(File);
1970 // The FileEntry is a virtual file entry with the size of the contents
1971 // that would override the original contents. Set it to the original's
1972 // size/time.
1973 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1974 StoredSize, StoredTime);
1975 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001976
Ben Langmuir198c1682014-03-07 07:27:49 +00001977 bool IsOutOfDate = false;
1978
1979 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001980 if (!Overridden && //
1981 (StoredSize != File->getSize() ||
1982#if defined(LLVM_ON_WIN32)
1983 false
1984#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001985 // In our regression testing, the Windows file system seems to
1986 // have inconsistent modification times that sometimes
1987 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001988 //
Richard Smithe75ee0f2015-08-17 07:13:32 +00001989 // FIXME: This probably also breaks HeaderFileInfo lookups on Windows.
1990 (StoredTime && StoredTime != File->getModificationTime() &&
1991 !DisableValidation)
Guy Benyei11169dd2012-12-18 14:30:41 +00001992#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001993 )) {
1994 if (Complain) {
1995 // Build a list of the PCH imports that got us here (in reverse).
1996 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1997 while (ImportStack.back()->ImportedBy.size() > 0)
1998 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001999
Ben Langmuir198c1682014-03-07 07:27:49 +00002000 // The top-level PCH is stale.
2001 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2002 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002003
Ben Langmuir198c1682014-03-07 07:27:49 +00002004 // Print the import stack.
2005 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2006 Diag(diag::note_pch_required_by)
2007 << Filename << ImportStack[0]->FileName;
2008 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002009 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002010 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002011 }
2012
Ben Langmuir198c1682014-03-07 07:27:49 +00002013 if (!Diags.isDiagnosticInFlight())
2014 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002015 }
2016
Ben Langmuir198c1682014-03-07 07:27:49 +00002017 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002018 }
2019
Ben Langmuir198c1682014-03-07 07:27:49 +00002020 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2021
2022 // Note that we've loaded this input file.
2023 F.InputFilesLoaded[ID-1] = IF;
2024 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002025}
2026
Richard Smith7ed1bc92014-12-05 22:42:13 +00002027/// \brief If we are loading a relocatable PCH or module file, and the filename
2028/// is not an absolute path, add the system or module root to the beginning of
2029/// the file name.
2030void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2031 // Resolve relative to the base directory, if we have one.
2032 if (!M.BaseDirectory.empty())
2033 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002034}
2035
Richard Smith7ed1bc92014-12-05 22:42:13 +00002036void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002037 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2038 return;
2039
Richard Smith7ed1bc92014-12-05 22:42:13 +00002040 SmallString<128> Buffer;
2041 llvm::sys::path::append(Buffer, Prefix, Filename);
2042 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002043}
2044
Richard Smith0f99d6a2015-08-09 08:48:41 +00002045static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2046 switch (ARR) {
2047 case ASTReader::Failure: return true;
2048 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2049 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2050 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2051 case ASTReader::ConfigurationMismatch:
2052 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2053 case ASTReader::HadErrors: return true;
2054 case ASTReader::Success: return false;
2055 }
2056
2057 llvm_unreachable("unknown ASTReadResult");
2058}
2059
Richard Smith0516b182015-09-08 19:40:14 +00002060ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2061 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2062 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2063 std::string &SuggestedPredefines) {
2064 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2065 return Failure;
2066
2067 // Read all of the records in the options block.
2068 RecordData Record;
2069 ASTReadResult Result = Success;
2070 while (1) {
2071 llvm::BitstreamEntry Entry = Stream.advance();
2072
2073 switch (Entry.Kind) {
2074 case llvm::BitstreamEntry::Error:
2075 case llvm::BitstreamEntry::SubBlock:
2076 return Failure;
2077
2078 case llvm::BitstreamEntry::EndBlock:
2079 return Result;
2080
2081 case llvm::BitstreamEntry::Record:
2082 // The interesting case.
2083 break;
2084 }
2085
2086 // Read and process a record.
2087 Record.clear();
2088 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2089 case LANGUAGE_OPTIONS: {
2090 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2091 if (ParseLanguageOptions(Record, Complain, Listener,
2092 AllowCompatibleConfigurationMismatch))
2093 Result = ConfigurationMismatch;
2094 break;
2095 }
2096
2097 case TARGET_OPTIONS: {
2098 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2099 if (ParseTargetOptions(Record, Complain, Listener,
2100 AllowCompatibleConfigurationMismatch))
2101 Result = ConfigurationMismatch;
2102 break;
2103 }
2104
2105 case DIAGNOSTIC_OPTIONS: {
2106 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2107 if (!AllowCompatibleConfigurationMismatch &&
2108 ParseDiagnosticOptions(Record, Complain, Listener))
2109 return OutOfDate;
2110 break;
2111 }
2112
2113 case FILE_SYSTEM_OPTIONS: {
2114 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2115 if (!AllowCompatibleConfigurationMismatch &&
2116 ParseFileSystemOptions(Record, Complain, Listener))
2117 Result = ConfigurationMismatch;
2118 break;
2119 }
2120
2121 case HEADER_SEARCH_OPTIONS: {
2122 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2123 if (!AllowCompatibleConfigurationMismatch &&
2124 ParseHeaderSearchOptions(Record, Complain, Listener))
2125 Result = ConfigurationMismatch;
2126 break;
2127 }
2128
2129 case PREPROCESSOR_OPTIONS:
2130 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2131 if (!AllowCompatibleConfigurationMismatch &&
2132 ParsePreprocessorOptions(Record, Complain, Listener,
2133 SuggestedPredefines))
2134 Result = ConfigurationMismatch;
2135 break;
2136 }
2137 }
2138}
2139
Guy Benyei11169dd2012-12-18 14:30:41 +00002140ASTReader::ASTReadResult
2141ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002142 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002143 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002144 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002145 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002146
2147 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2148 Error("malformed block record in AST file");
2149 return Failure;
2150 }
2151
2152 // Read all of the records and blocks in the control block.
2153 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002154 unsigned NumInputs = 0;
2155 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002156 while (1) {
2157 llvm::BitstreamEntry Entry = Stream.advance();
2158
2159 switch (Entry.Kind) {
2160 case llvm::BitstreamEntry::Error:
2161 Error("malformed block record in AST file");
2162 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002163 case llvm::BitstreamEntry::EndBlock: {
2164 // Validate input files.
2165 const HeaderSearchOptions &HSOpts =
2166 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002167
Richard Smitha1825302014-10-23 22:18:29 +00002168 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002169 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2170 // loaded module files, ignore missing inputs.
2171 if (!DisableValidation && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002172 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002173
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002174 // If we are reading a module, we will create a verification timestamp,
2175 // so we verify all input files. Otherwise, verify only user input
2176 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002177
2178 unsigned N = NumUserInputs;
2179 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002180 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002181 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002182 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002183 N = NumInputs;
2184
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002185 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002186 InputFile IF = getInputFile(F, I+1, Complain);
2187 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002188 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002189 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002190 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002191
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002192 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002193 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002194
Ben Langmuircb69b572014-03-07 06:40:32 +00002195 if (Listener && Listener->needsInputFileVisitation()) {
2196 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2197 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002198 for (unsigned I = 0; I < N; ++I) {
2199 bool IsSystem = I >= NumUserInputs;
2200 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002201 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2202 F.Kind == MK_ExplicitModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002203 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002204 }
2205
Guy Benyei11169dd2012-12-18 14:30:41 +00002206 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002207 }
2208
Chris Lattnere7b154b2013-01-19 21:39:22 +00002209 case llvm::BitstreamEntry::SubBlock:
2210 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002211 case INPUT_FILES_BLOCK_ID:
2212 F.InputFilesCursor = Stream;
2213 if (Stream.SkipBlock() || // Skip with the main cursor
2214 // Read the abbreviations
2215 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2216 Error("malformed block record in AST file");
2217 return Failure;
2218 }
2219 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002220
2221 case OPTIONS_BLOCK_ID:
2222 // If we're reading the first module for this group, check its options
2223 // are compatible with ours. For modules it imports, no further checking
2224 // is required, because we checked them when we built it.
2225 if (Listener && !ImportedBy) {
2226 // Should we allow the configuration of the module file to differ from
2227 // the configuration of the current translation unit in a compatible
2228 // way?
2229 //
2230 // FIXME: Allow this for files explicitly specified with -include-pch.
2231 bool AllowCompatibleConfigurationMismatch =
2232 F.Kind == MK_ExplicitModule;
2233
2234 auto Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2235 AllowCompatibleConfigurationMismatch,
2236 *Listener, SuggestedPredefines);
2237 if (Result == Failure) {
2238 Error("malformed block record in AST file");
2239 return Result;
2240 }
2241
2242 if (!DisableValidation && Result != Success &&
2243 (Result != ConfigurationMismatch || !AllowConfigurationMismatch))
2244 return Result;
2245 } else if (Stream.SkipBlock()) {
2246 Error("malformed block record in AST file");
2247 return Failure;
2248 }
2249 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002250
Guy Benyei11169dd2012-12-18 14:30:41 +00002251 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002252 if (Stream.SkipBlock()) {
2253 Error("malformed block record in AST file");
2254 return Failure;
2255 }
2256 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002257 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002258
2259 case llvm::BitstreamEntry::Record:
2260 // The interesting case.
2261 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002262 }
2263
2264 // Read and process a record.
2265 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002266 StringRef Blob;
2267 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002268 case METADATA: {
2269 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2270 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002271 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2272 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002273 return VersionMismatch;
2274 }
2275
Richard Smithe75ee0f2015-08-17 07:13:32 +00002276 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002277 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2278 Diag(diag::err_pch_with_compiler_errors);
2279 return HadErrors;
2280 }
2281
2282 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002283 // Relative paths in a relocatable PCH are relative to our sysroot.
2284 if (F.RelocatablePCH)
2285 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002286
Richard Smithe75ee0f2015-08-17 07:13:32 +00002287 F.HasTimestamps = Record[5];
2288
Guy Benyei11169dd2012-12-18 14:30:41 +00002289 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002290 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002291 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2292 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002293 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002294 return VersionMismatch;
2295 }
2296 break;
2297 }
2298
Ben Langmuir487ea142014-10-23 18:05:36 +00002299 case SIGNATURE:
2300 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2301 F.Signature = Record[0];
2302 break;
2303
Guy Benyei11169dd2012-12-18 14:30:41 +00002304 case IMPORTS: {
2305 // Load each of the imported PCH files.
2306 unsigned Idx = 0, N = Record.size();
2307 while (Idx < N) {
2308 // Read information about the AST file.
2309 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2310 // The import location will be the local one for now; we will adjust
2311 // all import locations of module imports after the global source
2312 // location info are setup.
2313 SourceLocation ImportLoc =
2314 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002315 off_t StoredSize = (off_t)Record[Idx++];
2316 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002317 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002318 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002319
Richard Smith0f99d6a2015-08-09 08:48:41 +00002320 // If our client can't cope with us being out of date, we can't cope with
2321 // our dependency being missing.
2322 unsigned Capabilities = ClientLoadCapabilities;
2323 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2324 Capabilities &= ~ARR_Missing;
2325
Guy Benyei11169dd2012-12-18 14:30:41 +00002326 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002327 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2328 Loaded, StoredSize, StoredModTime,
2329 StoredSignature, Capabilities);
2330
2331 // If we diagnosed a problem, produce a backtrace.
2332 if (isDiagnosedResult(Result, Capabilities))
2333 Diag(diag::note_module_file_imported_by)
2334 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2335
2336 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002337 case Failure: return Failure;
2338 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002339 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002340 case OutOfDate: return OutOfDate;
2341 case VersionMismatch: return VersionMismatch;
2342 case ConfigurationMismatch: return ConfigurationMismatch;
2343 case HadErrors: return HadErrors;
2344 case Success: break;
2345 }
2346 }
2347 break;
2348 }
2349
Guy Benyei11169dd2012-12-18 14:30:41 +00002350 case ORIGINAL_FILE:
2351 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002352 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002354 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002355 break;
2356
2357 case ORIGINAL_FILE_ID:
2358 F.OriginalSourceFileID = FileID::get(Record[0]);
2359 break;
2360
2361 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002362 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002363 break;
2364
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002365 case MODULE_NAME:
2366 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002367 if (Listener)
2368 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002369 break;
2370
Richard Smith223d3f22014-12-06 03:21:08 +00002371 case MODULE_DIRECTORY: {
2372 assert(!F.ModuleName.empty() &&
2373 "MODULE_DIRECTORY found before MODULE_NAME");
2374 // If we've already loaded a module map file covering this module, we may
2375 // have a better path for it (relative to the current build).
2376 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2377 if (M && M->Directory) {
2378 // If we're implicitly loading a module, the base directory can't
2379 // change between the build and use.
2380 if (F.Kind != MK_ExplicitModule) {
2381 const DirectoryEntry *BuildDir =
2382 PP.getFileManager().getDirectory(Blob);
2383 if (!BuildDir || BuildDir != M->Directory) {
2384 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2385 Diag(diag::err_imported_module_relocated)
2386 << F.ModuleName << Blob << M->Directory->getName();
2387 return OutOfDate;
2388 }
2389 }
2390 F.BaseDirectory = M->Directory->getName();
2391 } else {
2392 F.BaseDirectory = Blob;
2393 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002394 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002395 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002396
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002397 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002398 if (ASTReadResult Result =
2399 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2400 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002401 break;
2402
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002403 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002404 NumInputs = Record[0];
2405 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002406 F.InputFileOffsets =
2407 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002408 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002409 break;
2410 }
2411 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002412}
2413
Ben Langmuir2c9af442014-04-10 17:57:43 +00002414ASTReader::ASTReadResult
2415ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002416 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002417
2418 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2419 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002420 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002421 }
2422
2423 // Read all of the records and blocks for the AST file.
2424 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002425 while (1) {
2426 llvm::BitstreamEntry Entry = Stream.advance();
2427
2428 switch (Entry.Kind) {
2429 case llvm::BitstreamEntry::Error:
2430 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002431 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002432 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002433 // Outside of C++, we do not store a lookup map for the translation unit.
2434 // Instead, mark it as needing a lookup map to be built if this module
2435 // contains any declarations lexically within it (which it always does!).
2436 // This usually has no cost, since we very rarely need the lookup map for
2437 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002438 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002439 if (DC->hasExternalLexicalStorage() &&
2440 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002442
Ben Langmuir2c9af442014-04-10 17:57:43 +00002443 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002444 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002445 case llvm::BitstreamEntry::SubBlock:
2446 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002447 case DECLTYPES_BLOCK_ID:
2448 // We lazily load the decls block, but we want to set up the
2449 // DeclsCursor cursor to point into it. Clone our current bitcode
2450 // cursor to it, enter the block and read the abbrevs in that block.
2451 // With the main cursor, we just skip over it.
2452 F.DeclsCursor = Stream;
2453 if (Stream.SkipBlock() || // Skip with the main cursor.
2454 // Read the abbrevs.
2455 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2456 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002457 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002458 }
2459 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002460
Guy Benyei11169dd2012-12-18 14:30:41 +00002461 case PREPROCESSOR_BLOCK_ID:
2462 F.MacroCursor = Stream;
2463 if (!PP.getExternalSource())
2464 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002465
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 if (Stream.SkipBlock() ||
2467 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2468 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002469 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002470 }
2471 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2472 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002473
Guy Benyei11169dd2012-12-18 14:30:41 +00002474 case PREPROCESSOR_DETAIL_BLOCK_ID:
2475 F.PreprocessorDetailCursor = Stream;
2476 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002477 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002478 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002479 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002480 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002481 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002482 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002483 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2484
Guy Benyei11169dd2012-12-18 14:30:41 +00002485 if (!PP.getPreprocessingRecord())
2486 PP.createPreprocessingRecord();
2487 if (!PP.getPreprocessingRecord()->getExternalSource())
2488 PP.getPreprocessingRecord()->SetExternalSource(*this);
2489 break;
2490
2491 case SOURCE_MANAGER_BLOCK_ID:
2492 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002493 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002494 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002495
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002497 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2498 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002500
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002502 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 if (Stream.SkipBlock() ||
2504 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2505 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002506 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002507 }
2508 CommentsCursors.push_back(std::make_pair(C, &F));
2509 break;
2510 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002511
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002513 if (Stream.SkipBlock()) {
2514 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002515 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002516 }
2517 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 }
2519 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002520
2521 case llvm::BitstreamEntry::Record:
2522 // The interesting case.
2523 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002524 }
2525
2526 // Read and process a record.
2527 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002528 StringRef Blob;
2529 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002530 default: // Default behavior: ignore.
2531 break;
2532
2533 case TYPE_OFFSET: {
2534 if (F.LocalNumTypes != 0) {
2535 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002536 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002537 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002538 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 F.LocalNumTypes = Record[0];
2540 unsigned LocalBaseTypeIndex = Record[1];
2541 F.BaseTypeIndex = getTotalNumTypes();
2542
2543 if (F.LocalNumTypes > 0) {
2544 // Introduce the global -> local mapping for types within this module.
2545 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2546
2547 // Introduce the local -> global mapping for types within this module.
2548 F.TypeRemap.insertOrReplace(
2549 std::make_pair(LocalBaseTypeIndex,
2550 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002551
2552 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002553 }
2554 break;
2555 }
2556
2557 case DECL_OFFSET: {
2558 if (F.LocalNumDecls != 0) {
2559 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002560 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002562 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002563 F.LocalNumDecls = Record[0];
2564 unsigned LocalBaseDeclID = Record[1];
2565 F.BaseDeclID = getTotalNumDecls();
2566
2567 if (F.LocalNumDecls > 0) {
2568 // Introduce the global -> local mapping for declarations within this
2569 // module.
2570 GlobalDeclMap.insert(
2571 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2572
2573 // Introduce the local -> global mapping for declarations within this
2574 // module.
2575 F.DeclRemap.insertOrReplace(
2576 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2577
2578 // Introduce the global -> local mapping for declarations within this
2579 // module.
2580 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002581
Ben Langmuir52ca6782014-10-20 16:27:32 +00002582 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2583 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 break;
2585 }
2586
2587 case TU_UPDATE_LEXICAL: {
2588 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002589 LexicalContents Contents(
2590 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2591 Blob.data()),
2592 static_cast<unsigned int>(Blob.size() / 4));
2593 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 TU->setHasExternalLexicalStorage(true);
2595 break;
2596 }
2597
2598 case UPDATE_VISIBLE: {
2599 unsigned Idx = 0;
2600 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002601 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002602 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002603 // If we've already loaded the decl, perform the updates when we finish
2604 // loading this block.
2605 if (Decl *D = GetExistingDecl(ID))
2606 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002607 break;
2608 }
2609
2610 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002611 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002613 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2614 (const unsigned char *)F.IdentifierTableData + Record[0],
2615 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2616 (const unsigned char *)F.IdentifierTableData,
2617 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002618
2619 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2620 }
2621 break;
2622
2623 case IDENTIFIER_OFFSET: {
2624 if (F.LocalNumIdentifiers != 0) {
2625 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002626 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002627 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002628 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002629 F.LocalNumIdentifiers = Record[0];
2630 unsigned LocalBaseIdentifierID = Record[1];
2631 F.BaseIdentifierID = getTotalNumIdentifiers();
2632
2633 if (F.LocalNumIdentifiers > 0) {
2634 // Introduce the global -> local mapping for identifiers within this
2635 // module.
2636 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2637 &F));
2638
2639 // Introduce the local -> global mapping for identifiers within this
2640 // module.
2641 F.IdentifierRemap.insertOrReplace(
2642 std::make_pair(LocalBaseIdentifierID,
2643 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002644
Ben Langmuir52ca6782014-10-20 16:27:32 +00002645 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2646 + F.LocalNumIdentifiers);
2647 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002648 break;
2649 }
2650
Richard Smith33e0f7e2015-07-22 02:08:40 +00002651 case INTERESTING_IDENTIFIERS:
2652 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2653 break;
2654
Ben Langmuir332aafe2014-01-31 01:06:56 +00002655 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002656 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2657 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002658 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002659 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 break;
2661
2662 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002663 if (SpecialTypes.empty()) {
2664 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2665 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2666 break;
2667 }
2668
2669 if (SpecialTypes.size() != Record.size()) {
2670 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002671 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002672 }
2673
2674 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2675 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2676 if (!SpecialTypes[I])
2677 SpecialTypes[I] = ID;
2678 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2679 // merge step?
2680 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002681 break;
2682
2683 case STATISTICS:
2684 TotalNumStatements += Record[0];
2685 TotalNumMacros += Record[1];
2686 TotalLexicalDeclContexts += Record[2];
2687 TotalVisibleDeclContexts += Record[3];
2688 break;
2689
2690 case UNUSED_FILESCOPED_DECLS:
2691 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2692 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2693 break;
2694
2695 case DELEGATING_CTORS:
2696 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2697 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2698 break;
2699
2700 case WEAK_UNDECLARED_IDENTIFIERS:
2701 if (Record.size() % 4 != 0) {
2702 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002703 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 }
2705
2706 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2707 // files. This isn't the way to do it :)
2708 WeakUndeclaredIdentifiers.clear();
2709
2710 // Translate the weak, undeclared identifiers into global IDs.
2711 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2712 WeakUndeclaredIdentifiers.push_back(
2713 getGlobalIdentifierID(F, Record[I++]));
2714 WeakUndeclaredIdentifiers.push_back(
2715 getGlobalIdentifierID(F, Record[I++]));
2716 WeakUndeclaredIdentifiers.push_back(
2717 ReadSourceLocation(F, Record, I).getRawEncoding());
2718 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2719 }
2720 break;
2721
Guy Benyei11169dd2012-12-18 14:30:41 +00002722 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002723 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002724 F.LocalNumSelectors = Record[0];
2725 unsigned LocalBaseSelectorID = Record[1];
2726 F.BaseSelectorID = getTotalNumSelectors();
2727
2728 if (F.LocalNumSelectors > 0) {
2729 // Introduce the global -> local mapping for selectors within this
2730 // module.
2731 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2732
2733 // Introduce the local -> global mapping for selectors within this
2734 // module.
2735 F.SelectorRemap.insertOrReplace(
2736 std::make_pair(LocalBaseSelectorID,
2737 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002738
2739 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 }
2741 break;
2742 }
2743
2744 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002745 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002746 if (Record[0])
2747 F.SelectorLookupTable
2748 = ASTSelectorLookupTable::Create(
2749 F.SelectorLookupTableData + Record[0],
2750 F.SelectorLookupTableData,
2751 ASTSelectorLookupTrait(*this, F));
2752 TotalNumMethodPoolEntries += Record[1];
2753 break;
2754
2755 case REFERENCED_SELECTOR_POOL:
2756 if (!Record.empty()) {
2757 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2758 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2759 Record[Idx++]));
2760 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2761 getRawEncoding());
2762 }
2763 }
2764 break;
2765
2766 case PP_COUNTER_VALUE:
2767 if (!Record.empty() && Listener)
2768 Listener->ReadCounter(F, Record[0]);
2769 break;
2770
2771 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002772 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002773 F.NumFileSortedDecls = Record[0];
2774 break;
2775
2776 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002777 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002778 F.LocalNumSLocEntries = Record[0];
2779 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002780 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002781 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002782 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002783 if (!F.SLocEntryBaseID) {
2784 Error("ran out of source locations");
2785 break;
2786 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002787 // Make our entry in the range map. BaseID is negative and growing, so
2788 // we invert it. Because we invert it, though, we need the other end of
2789 // the range.
2790 unsigned RangeStart =
2791 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2792 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2793 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2794
2795 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2796 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2797 GlobalSLocOffsetMap.insert(
2798 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2799 - SLocSpaceSize,&F));
2800
2801 // Initialize the remapping table.
2802 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002803 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002804 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002805 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002806 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2807
2808 TotalNumSLocEntries += F.LocalNumSLocEntries;
2809 break;
2810 }
2811
2812 case MODULE_OFFSET_MAP: {
2813 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002814 const unsigned char *Data = (const unsigned char*)Blob.data();
2815 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002816
2817 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2818 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2819 F.SLocRemap.insert(std::make_pair(0U, 0));
2820 F.SLocRemap.insert(std::make_pair(2U, 1));
2821 }
2822
Guy Benyei11169dd2012-12-18 14:30:41 +00002823 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002824 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2825 RemapBuilder;
2826 RemapBuilder SLocRemap(F.SLocRemap);
2827 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2828 RemapBuilder MacroRemap(F.MacroRemap);
2829 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2830 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2831 RemapBuilder SelectorRemap(F.SelectorRemap);
2832 RemapBuilder DeclRemap(F.DeclRemap);
2833 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002834
Richard Smithd8879c82015-08-24 21:59:32 +00002835 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002836 using namespace llvm::support;
2837 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002838 StringRef Name = StringRef((const char*)Data, Len);
2839 Data += Len;
2840 ModuleFile *OM = ModuleMgr.lookup(Name);
2841 if (!OM) {
2842 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002843 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002844 }
2845
Justin Bogner57ba0b22014-03-28 22:03:24 +00002846 uint32_t SLocOffset =
2847 endian::readNext<uint32_t, little, unaligned>(Data);
2848 uint32_t IdentifierIDOffset =
2849 endian::readNext<uint32_t, little, unaligned>(Data);
2850 uint32_t MacroIDOffset =
2851 endian::readNext<uint32_t, little, unaligned>(Data);
2852 uint32_t PreprocessedEntityIDOffset =
2853 endian::readNext<uint32_t, little, unaligned>(Data);
2854 uint32_t SubmoduleIDOffset =
2855 endian::readNext<uint32_t, little, unaligned>(Data);
2856 uint32_t SelectorIDOffset =
2857 endian::readNext<uint32_t, little, unaligned>(Data);
2858 uint32_t DeclIDOffset =
2859 endian::readNext<uint32_t, little, unaligned>(Data);
2860 uint32_t TypeIndexOffset =
2861 endian::readNext<uint32_t, little, unaligned>(Data);
2862
Ben Langmuir785180e2014-10-20 16:27:30 +00002863 uint32_t None = std::numeric_limits<uint32_t>::max();
2864
2865 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2866 RemapBuilder &Remap) {
2867 if (Offset != None)
2868 Remap.insert(std::make_pair(Offset,
2869 static_cast<int>(BaseOffset - Offset)));
2870 };
2871 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2872 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2873 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2874 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2875 PreprocessedEntityRemap);
2876 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2877 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2878 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2879 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002880
2881 // Global -> local mappings.
2882 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2883 }
2884 break;
2885 }
2886
2887 case SOURCE_MANAGER_LINE_TABLE:
2888 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002889 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002890 break;
2891
2892 case SOURCE_LOCATION_PRELOADS: {
2893 // Need to transform from the local view (1-based IDs) to the global view,
2894 // which is based off F.SLocEntryBaseID.
2895 if (!F.PreloadSLocEntries.empty()) {
2896 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002897 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002898 }
2899
2900 F.PreloadSLocEntries.swap(Record);
2901 break;
2902 }
2903
2904 case EXT_VECTOR_DECLS:
2905 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2906 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2907 break;
2908
2909 case VTABLE_USES:
2910 if (Record.size() % 3 != 0) {
2911 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002912 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002913 }
2914
2915 // Later tables overwrite earlier ones.
2916 // FIXME: Modules will have some trouble with this. This is clearly not
2917 // the right way to do this.
2918 VTableUses.clear();
2919
2920 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2921 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2922 VTableUses.push_back(
2923 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2924 VTableUses.push_back(Record[Idx++]);
2925 }
2926 break;
2927
Guy Benyei11169dd2012-12-18 14:30:41 +00002928 case PENDING_IMPLICIT_INSTANTIATIONS:
2929 if (PendingInstantiations.size() % 2 != 0) {
2930 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002931 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002932 }
2933
2934 if (Record.size() % 2 != 0) {
2935 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002936 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002937 }
2938
2939 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2940 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2941 PendingInstantiations.push_back(
2942 ReadSourceLocation(F, Record, I).getRawEncoding());
2943 }
2944 break;
2945
2946 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002947 if (Record.size() != 2) {
2948 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002949 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002950 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002951 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2952 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2953 break;
2954
2955 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002956 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2957 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2958 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002959
2960 unsigned LocalBasePreprocessedEntityID = Record[0];
2961
2962 unsigned StartingID;
2963 if (!PP.getPreprocessingRecord())
2964 PP.createPreprocessingRecord();
2965 if (!PP.getPreprocessingRecord()->getExternalSource())
2966 PP.getPreprocessingRecord()->SetExternalSource(*this);
2967 StartingID
2968 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002969 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002970 F.BasePreprocessedEntityID = StartingID;
2971
2972 if (F.NumPreprocessedEntities > 0) {
2973 // Introduce the global -> local mapping for preprocessed entities in
2974 // this module.
2975 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2976
2977 // Introduce the local -> global mapping for preprocessed entities in
2978 // this module.
2979 F.PreprocessedEntityRemap.insertOrReplace(
2980 std::make_pair(LocalBasePreprocessedEntityID,
2981 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2982 }
2983
2984 break;
2985 }
2986
2987 case DECL_UPDATE_OFFSETS: {
2988 if (Record.size() % 2 != 0) {
2989 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002990 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002991 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002992 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2993 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2994 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2995
2996 // If we've already loaded the decl, perform the updates when we finish
2997 // loading this block.
2998 if (Decl *D = GetExistingDecl(ID))
2999 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3000 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003001 break;
3002 }
3003
3004 case DECL_REPLACEMENTS: {
3005 if (Record.size() % 3 != 0) {
3006 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003007 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003008 }
3009 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3010 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3011 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3012 break;
3013 }
3014
3015 case OBJC_CATEGORIES_MAP: {
3016 if (F.LocalNumObjCCategoriesInMap != 0) {
3017 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003018 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003019 }
3020
3021 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003022 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003023 break;
3024 }
3025
3026 case OBJC_CATEGORIES:
3027 F.ObjCCategories.swap(Record);
3028 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003029
Guy Benyei11169dd2012-12-18 14:30:41 +00003030 case CXX_BASE_SPECIFIER_OFFSETS: {
3031 if (F.LocalNumCXXBaseSpecifiers != 0) {
3032 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003033 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003034 }
Richard Smithc2bb8182015-03-24 06:36:48 +00003035
Guy Benyei11169dd2012-12-18 14:30:41 +00003036 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003037 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00003038 break;
3039 }
3040
3041 case CXX_CTOR_INITIALIZERS_OFFSETS: {
3042 if (F.LocalNumCXXCtorInitializers != 0) {
3043 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
3044 return Failure;
3045 }
3046
3047 F.LocalNumCXXCtorInitializers = Record[0];
3048 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003049 break;
3050 }
3051
3052 case DIAG_PRAGMA_MAPPINGS:
3053 if (F.PragmaDiagMappings.empty())
3054 F.PragmaDiagMappings.swap(Record);
3055 else
3056 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3057 Record.begin(), Record.end());
3058 break;
3059
3060 case CUDA_SPECIAL_DECL_REFS:
3061 // Later tables overwrite earlier ones.
3062 // FIXME: Modules will have trouble with this.
3063 CUDASpecialDeclRefs.clear();
3064 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3065 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3066 break;
3067
3068 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003069 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003070 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003071 if (Record[0]) {
3072 F.HeaderFileInfoTable
3073 = HeaderFileInfoLookupTable::Create(
3074 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3075 (const unsigned char *)F.HeaderFileInfoTableData,
3076 HeaderFileInfoTrait(*this, F,
3077 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003078 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003079
3080 PP.getHeaderSearchInfo().SetExternalSource(this);
3081 if (!PP.getHeaderSearchInfo().getExternalLookup())
3082 PP.getHeaderSearchInfo().SetExternalLookup(this);
3083 }
3084 break;
3085 }
3086
3087 case FP_PRAGMA_OPTIONS:
3088 // Later tables overwrite earlier ones.
3089 FPPragmaOptions.swap(Record);
3090 break;
3091
3092 case OPENCL_EXTENSIONS:
3093 // Later tables overwrite earlier ones.
3094 OpenCLExtensions.swap(Record);
3095 break;
3096
3097 case TENTATIVE_DEFINITIONS:
3098 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3099 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3100 break;
3101
3102 case KNOWN_NAMESPACES:
3103 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3104 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3105 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003106
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003107 case UNDEFINED_BUT_USED:
3108 if (UndefinedButUsed.size() % 2 != 0) {
3109 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003110 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003111 }
3112
3113 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003114 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003115 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003116 }
3117 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003118 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3119 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003120 ReadSourceLocation(F, Record, I).getRawEncoding());
3121 }
3122 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003123 case DELETE_EXPRS_TO_ANALYZE:
3124 for (unsigned I = 0, N = Record.size(); I != N;) {
3125 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3126 const uint64_t Count = Record[I++];
3127 DelayedDeleteExprs.push_back(Count);
3128 for (uint64_t C = 0; C < Count; ++C) {
3129 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3130 bool IsArrayForm = Record[I++] == 1;
3131 DelayedDeleteExprs.push_back(IsArrayForm);
3132 }
3133 }
3134 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003135
Guy Benyei11169dd2012-12-18 14:30:41 +00003136 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003137 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003138 // If we aren't loading a module (which has its own exports), make
3139 // all of the imported modules visible.
3140 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003141 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3142 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3143 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3144 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003145 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 }
3147 }
3148 break;
3149 }
3150
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 case MACRO_OFFSET: {
3152 if (F.LocalNumMacros != 0) {
3153 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003154 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003155 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003156 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003157 F.LocalNumMacros = Record[0];
3158 unsigned LocalBaseMacroID = Record[1];
3159 F.BaseMacroID = getTotalNumMacros();
3160
3161 if (F.LocalNumMacros > 0) {
3162 // Introduce the global -> local mapping for macros within this module.
3163 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3164
3165 // Introduce the local -> global mapping for macros within this module.
3166 F.MacroRemap.insertOrReplace(
3167 std::make_pair(LocalBaseMacroID,
3168 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003169
3170 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003171 }
3172 break;
3173 }
3174
Richard Smithe40f2ba2013-08-07 21:41:30 +00003175 case LATE_PARSED_TEMPLATE: {
3176 LateParsedTemplates.append(Record.begin(), Record.end());
3177 break;
3178 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003179
3180 case OPTIMIZE_PRAGMA_OPTIONS:
3181 if (Record.size() != 1) {
3182 Error("invalid pragma optimize record");
3183 return Failure;
3184 }
3185 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3186 break;
Nico Weber72889432014-09-06 01:25:55 +00003187
3188 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3189 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3190 UnusedLocalTypedefNameCandidates.push_back(
3191 getGlobalDeclID(F, Record[I]));
3192 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003193 }
3194 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003195}
3196
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003197ASTReader::ASTReadResult
3198ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3199 const ModuleFile *ImportedBy,
3200 unsigned ClientLoadCapabilities) {
3201 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003202 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003203
Richard Smithe842a472014-10-22 02:05:46 +00003204 if (F.Kind == MK_ExplicitModule) {
3205 // For an explicitly-loaded module, we don't care whether the original
3206 // module map file exists or matches.
3207 return Success;
3208 }
3209
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003210 // Try to resolve ModuleName in the current header search context and
3211 // verify that it is found in the same module map file as we saved. If the
3212 // top-level AST file is a main file, skip this check because there is no
3213 // usable header search context.
3214 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003215 "MODULE_NAME should come before MODULE_MAP_FILE");
3216 if (F.Kind == MK_ImplicitModule &&
3217 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3218 // An implicitly-loaded module file should have its module listed in some
3219 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003220 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003221 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3222 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3223 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003224 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003225 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3226 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3227 // This module was defined by an imported (explicit) module.
3228 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3229 << ASTFE->getName();
3230 else
3231 // This module was built with a different module map.
3232 Diag(diag::err_imported_module_not_found)
3233 << F.ModuleName << F.FileName << ImportedBy->FileName
3234 << F.ModuleMapPath;
3235 }
3236 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003237 }
3238
Richard Smithe842a472014-10-22 02:05:46 +00003239 assert(M->Name == F.ModuleName && "found module with different name");
3240
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003241 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003242 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003243 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3244 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003245 assert(ImportedBy && "top-level import should be verified");
3246 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3247 Diag(diag::err_imported_module_modmap_changed)
3248 << F.ModuleName << ImportedBy->FileName
3249 << ModMap->getName() << F.ModuleMapPath;
3250 return OutOfDate;
3251 }
3252
3253 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3254 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3255 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003256 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003257 const FileEntry *F =
3258 FileMgr.getFile(Filename, false, false);
3259 if (F == nullptr) {
3260 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3261 Error("could not find file '" + Filename +"' referenced by AST file");
3262 return OutOfDate;
3263 }
3264 AdditionalStoredMaps.insert(F);
3265 }
3266
3267 // Check any additional module map files (e.g. module.private.modulemap)
3268 // that are not in the pcm.
3269 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3270 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3271 // Remove files that match
3272 // Note: SmallPtrSet::erase is really remove
3273 if (!AdditionalStoredMaps.erase(ModMap)) {
3274 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3275 Diag(diag::err_module_different_modmap)
3276 << F.ModuleName << /*new*/0 << ModMap->getName();
3277 return OutOfDate;
3278 }
3279 }
3280 }
3281
3282 // Check any additional module map files that are in the pcm, but not
3283 // found in header search. Cases that match are already removed.
3284 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3285 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3286 Diag(diag::err_module_different_modmap)
3287 << F.ModuleName << /*not new*/1 << ModMap->getName();
3288 return OutOfDate;
3289 }
3290 }
3291
3292 if (Listener)
3293 Listener->ReadModuleMapFile(F.ModuleMapPath);
3294 return Success;
3295}
3296
3297
Douglas Gregorc1489562013-02-12 23:36:21 +00003298/// \brief Move the given method to the back of the global list of methods.
3299static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3300 // Find the entry for this selector in the method pool.
3301 Sema::GlobalMethodPool::iterator Known
3302 = S.MethodPool.find(Method->getSelector());
3303 if (Known == S.MethodPool.end())
3304 return;
3305
3306 // Retrieve the appropriate method list.
3307 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3308 : Known->second.second;
3309 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003310 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003311 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003312 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003313 Found = true;
3314 } else {
3315 // Keep searching.
3316 continue;
3317 }
3318 }
3319
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003320 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003321 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003322 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003323 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003324 }
3325}
3326
Richard Smithde711422015-04-23 21:20:19 +00003327void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003328 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003329 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003330 bool wasHidden = D->Hidden;
3331 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003332
Richard Smith49f906a2014-03-01 00:08:04 +00003333 if (wasHidden && SemaObj) {
3334 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3335 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003336 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003337 }
3338 }
3339}
3340
Richard Smith49f906a2014-03-01 00:08:04 +00003341void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003342 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003343 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003344 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003345 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003346 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003347 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003348 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003349
3350 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003351 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003352 // there is nothing more to do.
3353 continue;
3354 }
Richard Smith49f906a2014-03-01 00:08:04 +00003355
Guy Benyei11169dd2012-12-18 14:30:41 +00003356 if (!Mod->isAvailable()) {
3357 // Modules that aren't available cannot be made visible.
3358 continue;
3359 }
3360
3361 // Update the module's name visibility.
3362 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003363
Guy Benyei11169dd2012-12-18 14:30:41 +00003364 // If we've already deserialized any names from this module,
3365 // mark them as visible.
3366 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3367 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003368 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003369 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003370 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003371 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3372 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003373 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003374
Guy Benyei11169dd2012-12-18 14:30:41 +00003375 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003376 SmallVector<Module *, 16> Exports;
3377 Mod->getExportedModules(Exports);
3378 for (SmallVectorImpl<Module *>::iterator
3379 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3380 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003381 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003382 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003383 }
3384 }
3385}
3386
Douglas Gregore060e572013-01-25 01:03:03 +00003387bool ASTReader::loadGlobalIndex() {
3388 if (GlobalIndex)
3389 return false;
3390
3391 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3392 !Context.getLangOpts().Modules)
3393 return true;
3394
3395 // Try to load the global index.
3396 TriedLoadingGlobalIndex = true;
3397 StringRef ModuleCachePath
3398 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3399 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003400 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003401 if (!Result.first)
3402 return true;
3403
3404 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003405 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003406 return false;
3407}
3408
3409bool ASTReader::isGlobalIndexUnavailable() const {
3410 return Context.getLangOpts().Modules && UseGlobalIndex &&
3411 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3412}
3413
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003414static void updateModuleTimestamp(ModuleFile &MF) {
3415 // Overwrite the timestamp file contents so that file's mtime changes.
3416 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003417 std::error_code EC;
3418 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3419 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003420 return;
3421 OS << "Timestamp file\n";
3422}
3423
Guy Benyei11169dd2012-12-18 14:30:41 +00003424ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3425 ModuleKind Type,
3426 SourceLocation ImportLoc,
3427 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003428 llvm::SaveAndRestore<SourceLocation>
3429 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3430
Richard Smithd1c46742014-04-30 02:24:17 +00003431 // Defer any pending actions until we get to the end of reading the AST file.
3432 Deserializing AnASTFile(this);
3433
Guy Benyei11169dd2012-12-18 14:30:41 +00003434 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003435 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003436
3437 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003438 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003439 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003440 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003441 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003442 ClientLoadCapabilities)) {
3443 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003444 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003445 case OutOfDate:
3446 case VersionMismatch:
3447 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003448 case HadErrors: {
3449 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3450 for (const ImportedModule &IM : Loaded)
3451 LoadedSet.insert(IM.Mod);
3452
Douglas Gregor7029ce12013-03-19 00:28:20 +00003453 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003454 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003455 Context.getLangOpts().Modules
3456 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003457 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003458
3459 // If we find that any modules are unusable, the global index is going
3460 // to be out-of-date. Just remove it.
3461 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003462 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003463 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003464 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003465 case Success:
3466 break;
3467 }
3468
3469 // Here comes stuff that we only do once the entire chain is loaded.
3470
3471 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003472 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3473 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003474 M != MEnd; ++M) {
3475 ModuleFile &F = *M->Mod;
3476
3477 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003478 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3479 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003480
3481 // Once read, set the ModuleFile bit base offset and update the size in
3482 // bits of all files we've seen.
3483 F.GlobalBitOffset = TotalModulesSizeInBits;
3484 TotalModulesSizeInBits += F.SizeInBits;
3485 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3486
3487 // Preload SLocEntries.
3488 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3489 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3490 // Load it through the SourceManager and don't call ReadSLocEntry()
3491 // directly because the entry may have already been loaded in which case
3492 // calling ReadSLocEntry() directly would trigger an assertion in
3493 // SourceManager.
3494 SourceMgr.getLoadedSLocEntryByID(Index);
3495 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003496
3497 // Preload all the pending interesting identifiers by marking them out of
3498 // date.
3499 for (auto Offset : F.PreloadIdentifierOffsets) {
3500 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3501 F.IdentifierTableData + Offset);
3502
3503 ASTIdentifierLookupTrait Trait(*this, F);
3504 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3505 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003506 auto &II = PP.getIdentifierTable().getOwn(Key);
3507 II.setOutOfDate(true);
3508
3509 // Mark this identifier as being from an AST file so that we can track
3510 // whether we need to serialize it.
3511 if (!II.isFromAST()) {
3512 II.setIsFromAST();
3513 if (isInterestingIdentifier(*this, II, F.isModule()))
3514 II.setChangedSinceDeserialization();
3515 }
3516
3517 // Associate the ID with the identifier so that the writer can reuse it.
3518 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3519 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003520 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003521 }
3522
Douglas Gregor603cd862013-03-22 18:50:14 +00003523 // Setup the import locations and notify the module manager that we've
3524 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003525 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3526 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003527 M != MEnd; ++M) {
3528 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003529
3530 ModuleMgr.moduleFileAccepted(&F);
3531
3532 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003533 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003534 if (!M->ImportedBy)
3535 F.ImportLoc = M->ImportLoc;
3536 else
3537 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3538 M->ImportLoc.getRawEncoding());
3539 }
3540
Richard Smith33e0f7e2015-07-22 02:08:40 +00003541 if (!Context.getLangOpts().CPlusPlus ||
3542 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3543 // Mark all of the identifiers in the identifier table as being out of date,
3544 // so that various accessors know to check the loaded modules when the
3545 // identifier is used.
3546 //
3547 // For C++ modules, we don't need information on many identifiers (just
3548 // those that provide macros or are poisoned), so we mark all of
3549 // the interesting ones via PreloadIdentifierOffsets.
3550 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3551 IdEnd = PP.getIdentifierTable().end();
3552 Id != IdEnd; ++Id)
3553 Id->second->setOutOfDate(true);
3554 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003555
3556 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003557 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3558 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003559 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3560 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003561
3562 switch (Unresolved.Kind) {
3563 case UnresolvedModuleRef::Conflict:
3564 if (ResolvedMod) {
3565 Module::Conflict Conflict;
3566 Conflict.Other = ResolvedMod;
3567 Conflict.Message = Unresolved.String.str();
3568 Unresolved.Mod->Conflicts.push_back(Conflict);
3569 }
3570 continue;
3571
3572 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003573 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003574 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003575 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003576
Douglas Gregorfb912652013-03-20 21:10:35 +00003577 case UnresolvedModuleRef::Export:
3578 if (ResolvedMod || Unresolved.IsWildcard)
3579 Unresolved.Mod->Exports.push_back(
3580 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3581 continue;
3582 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003583 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003584 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003585
3586 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3587 // Might be unnecessary as use declarations are only used to build the
3588 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003589
3590 InitializeContext();
3591
Richard Smith3d8e97e2013-10-18 06:54:39 +00003592 if (SemaObj)
3593 UpdateSema();
3594
Guy Benyei11169dd2012-12-18 14:30:41 +00003595 if (DeserializationListener)
3596 DeserializationListener->ReaderInitialized(this);
3597
3598 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3599 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3600 PrimaryModule.OriginalSourceFileID
3601 = FileID::get(PrimaryModule.SLocEntryBaseID
3602 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3603
3604 // If this AST file is a precompiled preamble, then set the
3605 // preamble file ID of the source manager to the file source file
3606 // from which the preamble was built.
3607 if (Type == MK_Preamble) {
3608 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3609 } else if (Type == MK_MainFile) {
3610 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3611 }
3612 }
3613
3614 // For any Objective-C class definitions we have already loaded, make sure
3615 // that we load any additional categories.
3616 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3617 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3618 ObjCClassesLoaded[I],
3619 PreviousGeneration);
3620 }
Douglas Gregore060e572013-01-25 01:03:03 +00003621
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003622 if (PP.getHeaderSearchInfo()
3623 .getHeaderSearchOpts()
3624 .ModulesValidateOncePerBuildSession) {
3625 // Now we are certain that the module and all modules it depends on are
3626 // up to date. Create or update timestamp files for modules that are
3627 // located in the module cache (not for PCH files that could be anywhere
3628 // in the filesystem).
3629 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3630 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003631 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003632 updateModuleTimestamp(*M.Mod);
3633 }
3634 }
3635 }
3636
Guy Benyei11169dd2012-12-18 14:30:41 +00003637 return Success;
3638}
3639
Ben Langmuir487ea142014-10-23 18:05:36 +00003640static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3641
Ben Langmuir70a1b812015-03-24 04:43:52 +00003642/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3643static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3644 return Stream.Read(8) == 'C' &&
3645 Stream.Read(8) == 'P' &&
3646 Stream.Read(8) == 'C' &&
3647 Stream.Read(8) == 'H';
3648}
3649
Richard Smith0f99d6a2015-08-09 08:48:41 +00003650static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3651 switch (Kind) {
3652 case MK_PCH:
3653 return 0; // PCH
3654 case MK_ImplicitModule:
3655 case MK_ExplicitModule:
3656 return 1; // module
3657 case MK_MainFile:
3658 case MK_Preamble:
3659 return 2; // main source file
3660 }
3661 llvm_unreachable("unknown module kind");
3662}
3663
Guy Benyei11169dd2012-12-18 14:30:41 +00003664ASTReader::ASTReadResult
3665ASTReader::ReadASTCore(StringRef FileName,
3666 ModuleKind Type,
3667 SourceLocation ImportLoc,
3668 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003669 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003670 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003671 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003672 unsigned ClientLoadCapabilities) {
3673 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003674 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003675 ModuleManager::AddModuleResult AddResult
3676 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003677 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003678 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003679 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003680
Douglas Gregor7029ce12013-03-19 00:28:20 +00003681 switch (AddResult) {
3682 case ModuleManager::AlreadyLoaded:
3683 return Success;
3684
3685 case ModuleManager::NewlyLoaded:
3686 // Load module file below.
3687 break;
3688
3689 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003690 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003691 // it.
3692 if (ClientLoadCapabilities & ARR_Missing)
3693 return Missing;
3694
3695 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003696 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3697 << FileName << ErrorStr.empty()
3698 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003699 return Failure;
3700
3701 case ModuleManager::OutOfDate:
3702 // We couldn't load the module file because it is out-of-date. If the
3703 // client can handle out-of-date, return it.
3704 if (ClientLoadCapabilities & ARR_OutOfDate)
3705 return OutOfDate;
3706
3707 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003708 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3709 << FileName << ErrorStr.empty()
3710 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003711 return Failure;
3712 }
3713
Douglas Gregor7029ce12013-03-19 00:28:20 +00003714 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003715
3716 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3717 // module?
3718 if (FileName != "-") {
3719 CurrentDir = llvm::sys::path::parent_path(FileName);
3720 if (CurrentDir.empty()) CurrentDir = ".";
3721 }
3722
3723 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003724 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003725 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003726 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003727 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3728
Guy Benyei11169dd2012-12-18 14:30:41 +00003729 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003730 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003731 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3732 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003733 return Failure;
3734 }
3735
3736 // This is used for compatibility with older PCH formats.
3737 bool HaveReadControlBlock = false;
3738
Chris Lattnerefa77172013-01-20 00:00:22 +00003739 while (1) {
3740 llvm::BitstreamEntry Entry = Stream.advance();
3741
3742 switch (Entry.Kind) {
3743 case llvm::BitstreamEntry::Error:
3744 case llvm::BitstreamEntry::EndBlock:
3745 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003746 Error("invalid record at top-level of AST file");
3747 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003748
3749 case llvm::BitstreamEntry::SubBlock:
3750 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003751 }
3752
Chris Lattnerefa77172013-01-20 00:00:22 +00003753 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003754 case CONTROL_BLOCK_ID:
3755 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003756 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003757 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003758 // Check that we didn't try to load a non-module AST file as a module.
3759 //
3760 // FIXME: Should we also perform the converse check? Loading a module as
3761 // a PCH file sort of works, but it's a bit wonky.
3762 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule) &&
3763 F.ModuleName.empty()) {
3764 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3765 if (Result != OutOfDate ||
3766 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3767 Diag(diag::err_module_file_not_module) << FileName;
3768 return Result;
3769 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003770 break;
3771
3772 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003773 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003774 case OutOfDate: return OutOfDate;
3775 case VersionMismatch: return VersionMismatch;
3776 case ConfigurationMismatch: return ConfigurationMismatch;
3777 case HadErrors: return HadErrors;
3778 }
3779 break;
Richard Smithf8c32552015-09-02 17:45:54 +00003780
Guy Benyei11169dd2012-12-18 14:30:41 +00003781 case AST_BLOCK_ID:
3782 if (!HaveReadControlBlock) {
3783 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003784 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003785 return VersionMismatch;
3786 }
3787
3788 // Record that we've loaded this module.
3789 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3790 return Success;
3791
3792 default:
3793 if (Stream.SkipBlock()) {
3794 Error("malformed block record in AST file");
3795 return Failure;
3796 }
3797 break;
3798 }
3799 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003800}
3801
Richard Smitha7e2cc62015-05-01 01:53:09 +00003802void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003803 // If there's a listener, notify them that we "read" the translation unit.
3804 if (DeserializationListener)
3805 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3806 Context.getTranslationUnitDecl());
3807
Guy Benyei11169dd2012-12-18 14:30:41 +00003808 // FIXME: Find a better way to deal with collisions between these
3809 // built-in types. Right now, we just ignore the problem.
3810
3811 // Load the special types.
3812 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3813 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3814 if (!Context.CFConstantStringTypeDecl)
3815 Context.setCFConstantStringType(GetType(String));
3816 }
3817
3818 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3819 QualType FileType = GetType(File);
3820 if (FileType.isNull()) {
3821 Error("FILE type is NULL");
3822 return;
3823 }
3824
3825 if (!Context.FILEDecl) {
3826 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3827 Context.setFILEDecl(Typedef->getDecl());
3828 else {
3829 const TagType *Tag = FileType->getAs<TagType>();
3830 if (!Tag) {
3831 Error("Invalid FILE type in AST file");
3832 return;
3833 }
3834 Context.setFILEDecl(Tag->getDecl());
3835 }
3836 }
3837 }
3838
3839 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3840 QualType Jmp_bufType = GetType(Jmp_buf);
3841 if (Jmp_bufType.isNull()) {
3842 Error("jmp_buf type is NULL");
3843 return;
3844 }
3845
3846 if (!Context.jmp_bufDecl) {
3847 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3848 Context.setjmp_bufDecl(Typedef->getDecl());
3849 else {
3850 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3851 if (!Tag) {
3852 Error("Invalid jmp_buf type in AST file");
3853 return;
3854 }
3855 Context.setjmp_bufDecl(Tag->getDecl());
3856 }
3857 }
3858 }
3859
3860 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3861 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3862 if (Sigjmp_bufType.isNull()) {
3863 Error("sigjmp_buf type is NULL");
3864 return;
3865 }
3866
3867 if (!Context.sigjmp_bufDecl) {
3868 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3869 Context.setsigjmp_bufDecl(Typedef->getDecl());
3870 else {
3871 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3872 assert(Tag && "Invalid sigjmp_buf type in AST file");
3873 Context.setsigjmp_bufDecl(Tag->getDecl());
3874 }
3875 }
3876 }
3877
3878 if (unsigned ObjCIdRedef
3879 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3880 if (Context.ObjCIdRedefinitionType.isNull())
3881 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3882 }
3883
3884 if (unsigned ObjCClassRedef
3885 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3886 if (Context.ObjCClassRedefinitionType.isNull())
3887 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3888 }
3889
3890 if (unsigned ObjCSelRedef
3891 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3892 if (Context.ObjCSelRedefinitionType.isNull())
3893 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3894 }
3895
3896 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3897 QualType Ucontext_tType = GetType(Ucontext_t);
3898 if (Ucontext_tType.isNull()) {
3899 Error("ucontext_t type is NULL");
3900 return;
3901 }
3902
3903 if (!Context.ucontext_tDecl) {
3904 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3905 Context.setucontext_tDecl(Typedef->getDecl());
3906 else {
3907 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3908 assert(Tag && "Invalid ucontext_t type in AST file");
3909 Context.setucontext_tDecl(Tag->getDecl());
3910 }
3911 }
3912 }
3913 }
3914
3915 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3916
3917 // If there were any CUDA special declarations, deserialize them.
3918 if (!CUDASpecialDeclRefs.empty()) {
3919 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3920 Context.setcudaConfigureCallDecl(
3921 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3922 }
Richard Smith56be7542014-03-21 00:33:59 +00003923
Guy Benyei11169dd2012-12-18 14:30:41 +00003924 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003925 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003926 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003927 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003928 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003929 /*ImportLoc=*/Import.ImportLoc);
3930 PP.makeModuleVisible(Imported, Import.ImportLoc);
3931 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003932 }
3933 ImportedModules.clear();
3934}
3935
3936void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003937 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003938}
3939
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003940/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3941/// cursor into the start of the given block ID, returning false on success and
3942/// true on failure.
3943static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003944 while (1) {
3945 llvm::BitstreamEntry Entry = Cursor.advance();
3946 switch (Entry.Kind) {
3947 case llvm::BitstreamEntry::Error:
3948 case llvm::BitstreamEntry::EndBlock:
3949 return true;
3950
3951 case llvm::BitstreamEntry::Record:
3952 // Ignore top-level records.
3953 Cursor.skipRecord(Entry.ID);
3954 break;
3955
3956 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003957 if (Entry.ID == BlockID) {
3958 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003959 return true;
3960 // Found it!
3961 return false;
3962 }
3963
3964 if (Cursor.SkipBlock())
3965 return true;
3966 }
3967 }
3968}
3969
Ben Langmuir70a1b812015-03-24 04:43:52 +00003970/// \brief Reads and return the signature record from \p StreamFile's control
3971/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003972static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3973 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003974 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003975 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003976
3977 // Scan for the CONTROL_BLOCK_ID block.
3978 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3979 return 0;
3980
3981 // Scan for SIGNATURE inside the control block.
3982 ASTReader::RecordData Record;
3983 while (1) {
3984 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3985 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3986 Entry.Kind != llvm::BitstreamEntry::Record)
3987 return 0;
3988
3989 Record.clear();
3990 StringRef Blob;
3991 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3992 return Record[0];
3993 }
3994}
3995
Guy Benyei11169dd2012-12-18 14:30:41 +00003996/// \brief Retrieve the name of the original source file name
3997/// directly from the AST file, without actually loading the AST
3998/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003999std::string ASTReader::getOriginalSourceFile(
4000 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004001 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004002 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004003 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004004 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004005 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4006 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004007 return std::string();
4008 }
4009
4010 // Initialize the stream
4011 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004012 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004013 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004014
4015 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004016 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004017 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4018 return std::string();
4019 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004020
Chris Lattnere7b154b2013-01-19 21:39:22 +00004021 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004022 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004023 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4024 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004025 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004026
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004027 // Scan for ORIGINAL_FILE inside the control block.
4028 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004029 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004030 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004031 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4032 return std::string();
4033
4034 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4035 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4036 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004037 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004038
Guy Benyei11169dd2012-12-18 14:30:41 +00004039 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004040 StringRef Blob;
4041 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4042 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004043 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004044}
4045
4046namespace {
4047 class SimplePCHValidator : public ASTReaderListener {
4048 const LangOptions &ExistingLangOpts;
4049 const TargetOptions &ExistingTargetOpts;
4050 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004051 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004052 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004053
Guy Benyei11169dd2012-12-18 14:30:41 +00004054 public:
4055 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4056 const TargetOptions &ExistingTargetOpts,
4057 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004058 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004059 FileManager &FileMgr)
4060 : ExistingLangOpts(ExistingLangOpts),
4061 ExistingTargetOpts(ExistingTargetOpts),
4062 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004063 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004064 FileMgr(FileMgr)
4065 {
4066 }
4067
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004068 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4069 bool AllowCompatibleDifferences) override {
4070 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4071 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004072 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004073 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4074 bool AllowCompatibleDifferences) override {
4075 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4076 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004077 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004078 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4079 StringRef SpecificModuleCachePath,
4080 bool Complain) override {
4081 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4082 ExistingModuleCachePath,
4083 nullptr, ExistingLangOpts);
4084 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004085 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4086 bool Complain,
4087 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004088 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004089 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004090 }
4091 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004092}
Guy Benyei11169dd2012-12-18 14:30:41 +00004093
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004094bool ASTReader::readASTFileControlBlock(
4095 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004096 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004097 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004098 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004099 // FIXME: This allows use of the VFS; we do not allow use of the
4100 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004101 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004102 if (!Buffer) {
4103 return true;
4104 }
4105
4106 // Initialize the stream
4107 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004108 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004109 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004110
4111 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004112 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004113 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004114
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004115 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004116 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004117 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004118
4119 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004120 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004121 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004122 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004123
Guy Benyei11169dd2012-12-18 14:30:41 +00004124 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004125 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004126 while (1) {
Richard Smith0516b182015-09-08 19:40:14 +00004127 llvm::BitstreamEntry Entry = Stream.advance();
4128
4129 switch (Entry.Kind) {
4130 case llvm::BitstreamEntry::SubBlock: {
4131 switch (Entry.ID) {
4132 case OPTIONS_BLOCK_ID: {
4133 std::string IgnoredSuggestedPredefines;
4134 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4135 /*AllowCompatibleConfigurationMismatch*/ false,
4136 Listener, IgnoredSuggestedPredefines) != Success)
4137 return true;
4138 break;
4139 }
4140
4141 case INPUT_FILES_BLOCK_ID:
4142 InputFilesCursor = Stream;
4143 if (Stream.SkipBlock() ||
4144 (NeedsInputFiles &&
4145 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4146 return true;
4147 break;
4148
4149 default:
4150 if (Stream.SkipBlock())
4151 return true;
4152 break;
4153 }
4154
4155 continue;
4156 }
4157
4158 case llvm::BitstreamEntry::EndBlock:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004159 return false;
Richard Smith0516b182015-09-08 19:40:14 +00004160
4161 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004162 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004163
4164 case llvm::BitstreamEntry::Record:
4165 break;
4166 }
4167
Guy Benyei11169dd2012-12-18 14:30:41 +00004168 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004169 StringRef Blob;
4170 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004171 switch ((ControlRecordTypes)RecCode) {
4172 case METADATA: {
4173 if (Record[0] != VERSION_MAJOR)
4174 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004175
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004176 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004177 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004178
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004179 break;
4180 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004181 case MODULE_NAME:
4182 Listener.ReadModuleName(Blob);
4183 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004184 case MODULE_DIRECTORY:
4185 ModuleDir = Blob;
4186 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004187 case MODULE_MAP_FILE: {
4188 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004189 auto Path = ReadString(Record, Idx);
4190 ResolveImportedPath(Path, ModuleDir);
4191 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004192 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004193 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004194 case INPUT_FILE_OFFSETS: {
4195 if (!NeedsInputFiles)
4196 break;
4197
4198 unsigned NumInputFiles = Record[0];
4199 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004200 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004201 for (unsigned I = 0; I != NumInputFiles; ++I) {
4202 // Go find this input file.
4203 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004204
4205 if (isSystemFile && !NeedsSystemInputFiles)
4206 break; // the rest are system input files
4207
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004208 BitstreamCursor &Cursor = InputFilesCursor;
4209 SavedStreamPosition SavedPosition(Cursor);
4210 Cursor.JumpToBit(InputFileOffs[I]);
4211
4212 unsigned Code = Cursor.ReadCode();
4213 RecordData Record;
4214 StringRef Blob;
4215 bool shouldContinue = false;
4216 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4217 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004218 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004219 std::string Filename = Blob;
4220 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004221 shouldContinue = Listener.visitInputFile(
4222 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004223 break;
4224 }
4225 if (!shouldContinue)
4226 break;
4227 }
4228 break;
4229 }
4230
Richard Smithd4b230b2014-10-27 23:01:16 +00004231 case IMPORTS: {
4232 if (!NeedsImports)
4233 break;
4234
4235 unsigned Idx = 0, N = Record.size();
4236 while (Idx < N) {
4237 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004238 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004239 std::string Filename = ReadString(Record, Idx);
4240 ResolveImportedPath(Filename, ModuleDir);
4241 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004242 }
4243 break;
4244 }
4245
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004246 default:
4247 // No other validation to perform.
4248 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004249 }
4250 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004251}
4252
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004253bool ASTReader::isAcceptableASTFile(
4254 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004255 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004256 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4257 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004258 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4259 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004260 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004261 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004262}
4263
Ben Langmuir2c9af442014-04-10 17:57:43 +00004264ASTReader::ASTReadResult
4265ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004266 // Enter the submodule block.
4267 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4268 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004269 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004270 }
4271
4272 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4273 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004274 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004275 RecordData Record;
4276 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004277 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4278
4279 switch (Entry.Kind) {
4280 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4281 case llvm::BitstreamEntry::Error:
4282 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004283 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004284 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004285 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004286 case llvm::BitstreamEntry::Record:
4287 // The interesting case.
4288 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004289 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004290
Guy Benyei11169dd2012-12-18 14:30:41 +00004291 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004292 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004293 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004294 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4295
4296 if ((Kind == SUBMODULE_METADATA) != First) {
4297 Error("submodule metadata record should be at beginning of block");
4298 return Failure;
4299 }
4300 First = false;
4301
4302 // Submodule information is only valid if we have a current module.
4303 // FIXME: Should we error on these cases?
4304 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4305 Kind != SUBMODULE_DEFINITION)
4306 continue;
4307
4308 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004309 default: // Default behavior: ignore.
4310 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004311
Richard Smith03478d92014-10-23 22:12:14 +00004312 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004313 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004314 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004315 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004316 }
Richard Smith03478d92014-10-23 22:12:14 +00004317
Chris Lattner0e6c9402013-01-20 02:38:54 +00004318 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004319 unsigned Idx = 0;
4320 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4321 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4322 bool IsFramework = Record[Idx++];
4323 bool IsExplicit = Record[Idx++];
4324 bool IsSystem = Record[Idx++];
4325 bool IsExternC = Record[Idx++];
4326 bool InferSubmodules = Record[Idx++];
4327 bool InferExplicitSubmodules = Record[Idx++];
4328 bool InferExportWildcard = Record[Idx++];
4329 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004330
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004331 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004332 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004333 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004334
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 // Retrieve this (sub)module from the module map, creating it if
4336 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004337 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004338 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004339
4340 // FIXME: set the definition loc for CurrentModule, or call
4341 // ModMap.setInferredModuleAllowedBy()
4342
Guy Benyei11169dd2012-12-18 14:30:41 +00004343 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4344 if (GlobalIndex >= SubmodulesLoaded.size() ||
4345 SubmodulesLoaded[GlobalIndex]) {
4346 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004347 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004348 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004349
Douglas Gregor7029ce12013-03-19 00:28:20 +00004350 if (!ParentModule) {
4351 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4352 if (CurFile != F.File) {
4353 if (!Diags.isDiagnosticInFlight()) {
4354 Diag(diag::err_module_file_conflict)
4355 << CurrentModule->getTopLevelModuleName()
4356 << CurFile->getName()
4357 << F.File->getName();
4358 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004359 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004360 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004361 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004362
4363 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004364 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004365
Adrian Prantl15bcf702015-06-30 17:39:43 +00004366 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 CurrentModule->IsFromModuleFile = true;
4368 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004369 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004370 CurrentModule->InferSubmodules = InferSubmodules;
4371 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4372 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004373 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004374 if (DeserializationListener)
4375 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4376
4377 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004378
Douglas Gregorfb912652013-03-20 21:10:35 +00004379 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004380 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004381 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004382 CurrentModule->UnresolvedConflicts.clear();
4383 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004384 break;
4385 }
4386
4387 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004388 std::string Filename = Blob;
4389 ResolveImportedPath(F, Filename);
4390 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004391 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004392 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4393 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004394 // This can be a spurious difference caused by changing the VFS to
4395 // point to a different copy of the file, and it is too late to
4396 // to rebuild safely.
4397 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4398 // after input file validation only real problems would remain and we
4399 // could just error. For now, assume it's okay.
4400 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004401 }
4402 }
4403 break;
4404 }
4405
Richard Smith202210b2014-10-24 20:23:01 +00004406 case SUBMODULE_HEADER:
4407 case SUBMODULE_EXCLUDED_HEADER:
4408 case SUBMODULE_PRIVATE_HEADER:
4409 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004410 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4411 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004412 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004413
Richard Smith202210b2014-10-24 20:23:01 +00004414 case SUBMODULE_TEXTUAL_HEADER:
4415 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4416 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4417 // them here.
4418 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004419
Guy Benyei11169dd2012-12-18 14:30:41 +00004420 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004421 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004422 break;
4423 }
4424
4425 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004426 std::string Dirname = Blob;
4427 ResolveImportedPath(F, Dirname);
4428 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004429 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004430 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4431 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004432 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4433 Error("mismatched umbrella directories in submodule");
4434 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 }
4436 }
4437 break;
4438 }
4439
4440 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 F.BaseSubmoduleID = getTotalNumSubmodules();
4442 F.LocalNumSubmodules = Record[0];
4443 unsigned LocalBaseSubmoduleID = Record[1];
4444 if (F.LocalNumSubmodules > 0) {
4445 // Introduce the global -> local mapping for submodules within this
4446 // module.
4447 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4448
4449 // Introduce the local -> global mapping for submodules within this
4450 // module.
4451 F.SubmoduleRemap.insertOrReplace(
4452 std::make_pair(LocalBaseSubmoduleID,
4453 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004454
Ben Langmuir52ca6782014-10-20 16:27:32 +00004455 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4456 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004457 break;
4458 }
4459
4460 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004461 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004462 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004463 Unresolved.File = &F;
4464 Unresolved.Mod = CurrentModule;
4465 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004466 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004467 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004468 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 }
4470 break;
4471 }
4472
4473 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004474 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004475 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004476 Unresolved.File = &F;
4477 Unresolved.Mod = CurrentModule;
4478 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004479 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004480 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004481 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004482 }
4483
4484 // Once we've loaded the set of exports, there's no reason to keep
4485 // the parsed, unresolved exports around.
4486 CurrentModule->UnresolvedExports.clear();
4487 break;
4488 }
4489 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004490 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004491 Context.getTargetInfo());
4492 break;
4493 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004494
4495 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004496 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004497 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004498 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004499
4500 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004501 CurrentModule->ConfigMacros.push_back(Blob.str());
4502 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004503
4504 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004505 UnresolvedModuleRef Unresolved;
4506 Unresolved.File = &F;
4507 Unresolved.Mod = CurrentModule;
4508 Unresolved.ID = Record[0];
4509 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4510 Unresolved.IsWildcard = false;
4511 Unresolved.String = Blob;
4512 UnresolvedModuleRefs.push_back(Unresolved);
4513 break;
4514 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 }
4516 }
4517}
4518
4519/// \brief Parse the record that corresponds to a LangOptions data
4520/// structure.
4521///
4522/// This routine parses the language options from the AST file and then gives
4523/// them to the AST listener if one is set.
4524///
4525/// \returns true if the listener deems the file unacceptable, false otherwise.
4526bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4527 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004528 ASTReaderListener &Listener,
4529 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004530 LangOptions LangOpts;
4531 unsigned Idx = 0;
4532#define LANGOPT(Name, Bits, Default, Description) \
4533 LangOpts.Name = Record[Idx++];
4534#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4535 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4536#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004537#define SANITIZER(NAME, ID) \
4538 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004539#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004540
Ben Langmuircd98cb72015-06-23 18:20:18 +00004541 for (unsigned N = Record[Idx++]; N; --N)
4542 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4543
Guy Benyei11169dd2012-12-18 14:30:41 +00004544 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4545 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4546 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004547
Ben Langmuird4a667a2015-06-23 18:20:23 +00004548 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004549
4550 // Comment options.
4551 for (unsigned N = Record[Idx++]; N; --N) {
4552 LangOpts.CommentOpts.BlockCommandNames.push_back(
4553 ReadString(Record, Idx));
4554 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004555 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004556
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004557 return Listener.ReadLanguageOptions(LangOpts, Complain,
4558 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004559}
4560
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004561bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4562 ASTReaderListener &Listener,
4563 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 unsigned Idx = 0;
4565 TargetOptions TargetOpts;
4566 TargetOpts.Triple = ReadString(Record, Idx);
4567 TargetOpts.CPU = ReadString(Record, Idx);
4568 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004569 for (unsigned N = Record[Idx++]; N; --N) {
4570 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4571 }
4572 for (unsigned N = Record[Idx++]; N; --N) {
4573 TargetOpts.Features.push_back(ReadString(Record, Idx));
4574 }
4575
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004576 return Listener.ReadTargetOptions(TargetOpts, Complain,
4577 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004578}
4579
4580bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4581 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004582 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004583 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004584#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004585#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004586 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004587#include "clang/Basic/DiagnosticOptions.def"
4588
Richard Smith3be1cb22014-08-07 00:24:21 +00004589 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004590 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004591 for (unsigned N = Record[Idx++]; N; --N)
4592 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004593
4594 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4595}
4596
4597bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4598 ASTReaderListener &Listener) {
4599 FileSystemOptions FSOpts;
4600 unsigned Idx = 0;
4601 FSOpts.WorkingDir = ReadString(Record, Idx);
4602 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4603}
4604
4605bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4606 bool Complain,
4607 ASTReaderListener &Listener) {
4608 HeaderSearchOptions HSOpts;
4609 unsigned Idx = 0;
4610 HSOpts.Sysroot = ReadString(Record, Idx);
4611
4612 // Include entries.
4613 for (unsigned N = Record[Idx++]; N; --N) {
4614 std::string Path = ReadString(Record, Idx);
4615 frontend::IncludeDirGroup Group
4616 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 bool IsFramework = Record[Idx++];
4618 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004619 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4620 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 }
4622
4623 // System header prefixes.
4624 for (unsigned N = Record[Idx++]; N; --N) {
4625 std::string Prefix = ReadString(Record, Idx);
4626 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004627 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004628 }
4629
4630 HSOpts.ResourceDir = ReadString(Record, Idx);
4631 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004632 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 HSOpts.DisableModuleHash = Record[Idx++];
4634 HSOpts.UseBuiltinIncludes = Record[Idx++];
4635 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4636 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4637 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004638 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004639
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004640 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4641 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004642}
4643
4644bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4645 bool Complain,
4646 ASTReaderListener &Listener,
4647 std::string &SuggestedPredefines) {
4648 PreprocessorOptions PPOpts;
4649 unsigned Idx = 0;
4650
4651 // Macro definitions/undefs
4652 for (unsigned N = Record[Idx++]; N; --N) {
4653 std::string Macro = ReadString(Record, Idx);
4654 bool IsUndef = Record[Idx++];
4655 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4656 }
4657
4658 // Includes
4659 for (unsigned N = Record[Idx++]; N; --N) {
4660 PPOpts.Includes.push_back(ReadString(Record, Idx));
4661 }
4662
4663 // Macro Includes
4664 for (unsigned N = Record[Idx++]; N; --N) {
4665 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4666 }
4667
4668 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004669 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004670 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4671 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4672 PPOpts.ObjCXXARCStandardLibrary =
4673 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4674 SuggestedPredefines.clear();
4675 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4676 SuggestedPredefines);
4677}
4678
4679std::pair<ModuleFile *, unsigned>
4680ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4681 GlobalPreprocessedEntityMapType::iterator
4682 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4683 assert(I != GlobalPreprocessedEntityMap.end() &&
4684 "Corrupted global preprocessed entity map");
4685 ModuleFile *M = I->second;
4686 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4687 return std::make_pair(M, LocalIndex);
4688}
4689
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004690llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004691ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4692 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4693 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4694 Mod.NumPreprocessedEntities);
4695
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004696 return llvm::make_range(PreprocessingRecord::iterator(),
4697 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004698}
4699
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004700llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004701ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004702 return llvm::make_range(
4703 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4704 ModuleDeclIterator(this, &Mod,
4705 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004706}
4707
4708PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4709 PreprocessedEntityID PPID = Index+1;
4710 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4711 ModuleFile &M = *PPInfo.first;
4712 unsigned LocalIndex = PPInfo.second;
4713 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4714
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 if (!PP.getPreprocessingRecord()) {
4716 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004717 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004718 }
4719
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004720 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4721 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4722
4723 llvm::BitstreamEntry Entry =
4724 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4725 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004726 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004727
Guy Benyei11169dd2012-12-18 14:30:41 +00004728 // Read the record.
4729 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4730 ReadSourceLocation(M, PPOffs.End));
4731 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004732 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004733 RecordData Record;
4734 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004735 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4736 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 switch (RecType) {
4738 case PPD_MACRO_EXPANSION: {
4739 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004740 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004741 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004742 if (isBuiltin)
4743 Name = getLocalIdentifier(M, Record[1]);
4744 else {
Richard Smith66a81862015-05-04 02:25:31 +00004745 PreprocessedEntityID GlobalID =
4746 getGlobalPreprocessedEntityID(M, Record[1]);
4747 Def = cast<MacroDefinitionRecord>(
4748 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004749 }
4750
4751 MacroExpansion *ME;
4752 if (isBuiltin)
4753 ME = new (PPRec) MacroExpansion(Name, Range);
4754 else
4755 ME = new (PPRec) MacroExpansion(Def, Range);
4756
4757 return ME;
4758 }
4759
4760 case PPD_MACRO_DEFINITION: {
4761 // Decode the identifier info and then check again; if the macro is
4762 // still defined and associated with the identifier,
4763 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004764 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004765
4766 if (DeserializationListener)
4767 DeserializationListener->MacroDefinitionRead(PPID, MD);
4768
4769 return MD;
4770 }
4771
4772 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004773 const char *FullFileNameStart = Blob.data() + Record[0];
4774 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004775 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004776 if (!FullFileName.empty())
4777 File = PP.getFileManager().getFile(FullFileName);
4778
4779 // FIXME: Stable encoding
4780 InclusionDirective::InclusionKind Kind
4781 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4782 InclusionDirective *ID
4783 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004784 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004785 Record[1], Record[3],
4786 File,
4787 Range);
4788 return ID;
4789 }
4790 }
4791
4792 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4793}
4794
4795/// \brief \arg SLocMapI points at a chunk of a module that contains no
4796/// preprocessed entities or the entities it contains are not the ones we are
4797/// looking for. Find the next module that contains entities and return the ID
4798/// of the first entry.
4799PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4800 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4801 ++SLocMapI;
4802 for (GlobalSLocOffsetMapType::const_iterator
4803 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4804 ModuleFile &M = *SLocMapI->second;
4805 if (M.NumPreprocessedEntities)
4806 return M.BasePreprocessedEntityID;
4807 }
4808
4809 return getTotalNumPreprocessedEntities();
4810}
4811
4812namespace {
4813
4814template <unsigned PPEntityOffset::*PPLoc>
4815struct PPEntityComp {
4816 const ASTReader &Reader;
4817 ModuleFile &M;
4818
4819 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4820
4821 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4822 SourceLocation LHS = getLoc(L);
4823 SourceLocation RHS = getLoc(R);
4824 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4825 }
4826
4827 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4828 SourceLocation LHS = getLoc(L);
4829 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4830 }
4831
4832 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4833 SourceLocation RHS = getLoc(R);
4834 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4835 }
4836
4837 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4838 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4839 }
4840};
4841
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004842}
Guy Benyei11169dd2012-12-18 14:30:41 +00004843
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004844PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4845 bool EndsAfter) const {
4846 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004847 return getTotalNumPreprocessedEntities();
4848
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004849 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4850 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004851 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4852 "Corrupted global sloc offset map");
4853
4854 if (SLocMapI->second->NumPreprocessedEntities == 0)
4855 return findNextPreprocessedEntity(SLocMapI);
4856
4857 ModuleFile &M = *SLocMapI->second;
4858 typedef const PPEntityOffset *pp_iterator;
4859 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4860 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4861
4862 size_t Count = M.NumPreprocessedEntities;
4863 size_t Half;
4864 pp_iterator First = pp_begin;
4865 pp_iterator PPI;
4866
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004867 if (EndsAfter) {
4868 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4869 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4870 } else {
4871 // Do a binary search manually instead of using std::lower_bound because
4872 // The end locations of entities may be unordered (when a macro expansion
4873 // is inside another macro argument), but for this case it is not important
4874 // whether we get the first macro expansion or its containing macro.
4875 while (Count > 0) {
4876 Half = Count / 2;
4877 PPI = First;
4878 std::advance(PPI, Half);
4879 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4880 Loc)) {
4881 First = PPI;
4882 ++First;
4883 Count = Count - Half - 1;
4884 } else
4885 Count = Half;
4886 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004887 }
4888
4889 if (PPI == pp_end)
4890 return findNextPreprocessedEntity(SLocMapI);
4891
4892 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4893}
4894
Guy Benyei11169dd2012-12-18 14:30:41 +00004895/// \brief Returns a pair of [Begin, End) indices of preallocated
4896/// preprocessed entities that \arg Range encompasses.
4897std::pair<unsigned, unsigned>
4898 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4899 if (Range.isInvalid())
4900 return std::make_pair(0,0);
4901 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4902
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004903 PreprocessedEntityID BeginID =
4904 findPreprocessedEntity(Range.getBegin(), false);
4905 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004906 return std::make_pair(BeginID, EndID);
4907}
4908
4909/// \brief Optionally returns true or false if the preallocated preprocessed
4910/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004911Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004912 FileID FID) {
4913 if (FID.isInvalid())
4914 return false;
4915
4916 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4917 ModuleFile &M = *PPInfo.first;
4918 unsigned LocalIndex = PPInfo.second;
4919 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4920
4921 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4922 if (Loc.isInvalid())
4923 return false;
4924
4925 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4926 return true;
4927 else
4928 return false;
4929}
4930
4931namespace {
4932 /// \brief Visitor used to search for information about a header file.
4933 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004934 const FileEntry *FE;
4935
David Blaikie05785d12013-02-20 22:23:23 +00004936 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004937
4938 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004939 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4940 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004941
4942 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004943 HeaderFileInfoLookupTable *Table
4944 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4945 if (!Table)
4946 return false;
4947
4948 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00004949 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004950 if (Pos == Table->end())
4951 return false;
4952
Richard Smithbdf2d932015-07-30 03:37:16 +00004953 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00004954 return true;
4955 }
4956
David Blaikie05785d12013-02-20 22:23:23 +00004957 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004958 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004959}
Guy Benyei11169dd2012-12-18 14:30:41 +00004960
4961HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004962 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004963 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004964 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004965 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004966
4967 return HeaderFileInfo();
4968}
4969
4970void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4971 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004972 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004973 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4974 ModuleFile &F = *(*I);
4975 unsigned Idx = 0;
4976 DiagStates.clear();
4977 assert(!Diag.DiagStates.empty());
4978 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4979 while (Idx < F.PragmaDiagMappings.size()) {
4980 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4981 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4982 if (DiagStateID != 0) {
4983 Diag.DiagStatePoints.push_back(
4984 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4985 FullSourceLoc(Loc, SourceMgr)));
4986 continue;
4987 }
4988
4989 assert(DiagStateID == 0);
4990 // A new DiagState was created here.
4991 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4992 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4993 DiagStates.push_back(NewState);
4994 Diag.DiagStatePoints.push_back(
4995 DiagnosticsEngine::DiagStatePoint(NewState,
4996 FullSourceLoc(Loc, SourceMgr)));
4997 while (1) {
4998 assert(Idx < F.PragmaDiagMappings.size() &&
4999 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5000 if (Idx >= F.PragmaDiagMappings.size()) {
5001 break; // Something is messed up but at least avoid infinite loop in
5002 // release build.
5003 }
5004 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5005 if (DiagID == (unsigned)-1) {
5006 break; // no more diag/map pairs for this location.
5007 }
Alp Tokerc726c362014-06-10 09:31:37 +00005008 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5009 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5010 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005011 }
5012 }
5013 }
5014}
5015
5016/// \brief Get the correct cursor and offset for loading a type.
5017ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5018 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5019 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5020 ModuleFile *M = I->second;
5021 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5022}
5023
5024/// \brief Read and return the type with the given index..
5025///
5026/// The index is the type ID, shifted and minus the number of predefs. This
5027/// routine actually reads the record corresponding to the type at the given
5028/// location. It is a helper routine for GetType, which deals with reading type
5029/// IDs.
5030QualType ASTReader::readTypeRecord(unsigned Index) {
5031 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005032 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005033
5034 // Keep track of where we are in the stream, then jump back there
5035 // after reading this type.
5036 SavedStreamPosition SavedPosition(DeclsCursor);
5037
5038 ReadingKindTracker ReadingKind(Read_Type, *this);
5039
5040 // Note that we are loading a type record.
5041 Deserializing AType(this);
5042
5043 unsigned Idx = 0;
5044 DeclsCursor.JumpToBit(Loc.Offset);
5045 RecordData Record;
5046 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005047 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005048 case TYPE_EXT_QUAL: {
5049 if (Record.size() != 2) {
5050 Error("Incorrect encoding of extended qualifier type");
5051 return QualType();
5052 }
5053 QualType Base = readType(*Loc.F, Record, Idx);
5054 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5055 return Context.getQualifiedType(Base, Quals);
5056 }
5057
5058 case TYPE_COMPLEX: {
5059 if (Record.size() != 1) {
5060 Error("Incorrect encoding of complex type");
5061 return QualType();
5062 }
5063 QualType ElemType = readType(*Loc.F, Record, Idx);
5064 return Context.getComplexType(ElemType);
5065 }
5066
5067 case TYPE_POINTER: {
5068 if (Record.size() != 1) {
5069 Error("Incorrect encoding of pointer type");
5070 return QualType();
5071 }
5072 QualType PointeeType = readType(*Loc.F, Record, Idx);
5073 return Context.getPointerType(PointeeType);
5074 }
5075
Reid Kleckner8a365022013-06-24 17:51:48 +00005076 case TYPE_DECAYED: {
5077 if (Record.size() != 1) {
5078 Error("Incorrect encoding of decayed type");
5079 return QualType();
5080 }
5081 QualType OriginalType = readType(*Loc.F, Record, Idx);
5082 QualType DT = Context.getAdjustedParameterType(OriginalType);
5083 if (!isa<DecayedType>(DT))
5084 Error("Decayed type does not decay");
5085 return DT;
5086 }
5087
Reid Kleckner0503a872013-12-05 01:23:43 +00005088 case TYPE_ADJUSTED: {
5089 if (Record.size() != 2) {
5090 Error("Incorrect encoding of adjusted type");
5091 return QualType();
5092 }
5093 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5094 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5095 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5096 }
5097
Guy Benyei11169dd2012-12-18 14:30:41 +00005098 case TYPE_BLOCK_POINTER: {
5099 if (Record.size() != 1) {
5100 Error("Incorrect encoding of block pointer type");
5101 return QualType();
5102 }
5103 QualType PointeeType = readType(*Loc.F, Record, Idx);
5104 return Context.getBlockPointerType(PointeeType);
5105 }
5106
5107 case TYPE_LVALUE_REFERENCE: {
5108 if (Record.size() != 2) {
5109 Error("Incorrect encoding of lvalue reference type");
5110 return QualType();
5111 }
5112 QualType PointeeType = readType(*Loc.F, Record, Idx);
5113 return Context.getLValueReferenceType(PointeeType, Record[1]);
5114 }
5115
5116 case TYPE_RVALUE_REFERENCE: {
5117 if (Record.size() != 1) {
5118 Error("Incorrect encoding of rvalue reference type");
5119 return QualType();
5120 }
5121 QualType PointeeType = readType(*Loc.F, Record, Idx);
5122 return Context.getRValueReferenceType(PointeeType);
5123 }
5124
5125 case TYPE_MEMBER_POINTER: {
5126 if (Record.size() != 2) {
5127 Error("Incorrect encoding of member pointer type");
5128 return QualType();
5129 }
5130 QualType PointeeType = readType(*Loc.F, Record, Idx);
5131 QualType ClassType = readType(*Loc.F, Record, Idx);
5132 if (PointeeType.isNull() || ClassType.isNull())
5133 return QualType();
5134
5135 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5136 }
5137
5138 case TYPE_CONSTANT_ARRAY: {
5139 QualType ElementType = readType(*Loc.F, Record, Idx);
5140 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5141 unsigned IndexTypeQuals = Record[2];
5142 unsigned Idx = 3;
5143 llvm::APInt Size = ReadAPInt(Record, Idx);
5144 return Context.getConstantArrayType(ElementType, Size,
5145 ASM, IndexTypeQuals);
5146 }
5147
5148 case TYPE_INCOMPLETE_ARRAY: {
5149 QualType ElementType = readType(*Loc.F, Record, Idx);
5150 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5151 unsigned IndexTypeQuals = Record[2];
5152 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5153 }
5154
5155 case TYPE_VARIABLE_ARRAY: {
5156 QualType ElementType = readType(*Loc.F, Record, Idx);
5157 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5158 unsigned IndexTypeQuals = Record[2];
5159 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5160 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5161 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5162 ASM, IndexTypeQuals,
5163 SourceRange(LBLoc, RBLoc));
5164 }
5165
5166 case TYPE_VECTOR: {
5167 if (Record.size() != 3) {
5168 Error("incorrect encoding of vector type in AST file");
5169 return QualType();
5170 }
5171
5172 QualType ElementType = readType(*Loc.F, Record, Idx);
5173 unsigned NumElements = Record[1];
5174 unsigned VecKind = Record[2];
5175 return Context.getVectorType(ElementType, NumElements,
5176 (VectorType::VectorKind)VecKind);
5177 }
5178
5179 case TYPE_EXT_VECTOR: {
5180 if (Record.size() != 3) {
5181 Error("incorrect encoding of extended vector type in AST file");
5182 return QualType();
5183 }
5184
5185 QualType ElementType = readType(*Loc.F, Record, Idx);
5186 unsigned NumElements = Record[1];
5187 return Context.getExtVectorType(ElementType, NumElements);
5188 }
5189
5190 case TYPE_FUNCTION_NO_PROTO: {
5191 if (Record.size() != 6) {
5192 Error("incorrect encoding of no-proto function type");
5193 return QualType();
5194 }
5195 QualType ResultType = readType(*Loc.F, Record, Idx);
5196 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5197 (CallingConv)Record[4], Record[5]);
5198 return Context.getFunctionNoProtoType(ResultType, Info);
5199 }
5200
5201 case TYPE_FUNCTION_PROTO: {
5202 QualType ResultType = readType(*Loc.F, Record, Idx);
5203
5204 FunctionProtoType::ExtProtoInfo EPI;
5205 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5206 /*hasregparm*/ Record[2],
5207 /*regparm*/ Record[3],
5208 static_cast<CallingConv>(Record[4]),
5209 /*produces*/ Record[5]);
5210
5211 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005212
5213 EPI.Variadic = Record[Idx++];
5214 EPI.HasTrailingReturn = Record[Idx++];
5215 EPI.TypeQuals = Record[Idx++];
5216 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005217 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005218 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005219
5220 unsigned NumParams = Record[Idx++];
5221 SmallVector<QualType, 16> ParamTypes;
5222 for (unsigned I = 0; I != NumParams; ++I)
5223 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5224
Jordan Rose5c382722013-03-08 21:51:21 +00005225 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005226 }
5227
5228 case TYPE_UNRESOLVED_USING: {
5229 unsigned Idx = 0;
5230 return Context.getTypeDeclType(
5231 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5232 }
5233
5234 case TYPE_TYPEDEF: {
5235 if (Record.size() != 2) {
5236 Error("incorrect encoding of typedef type");
5237 return QualType();
5238 }
5239 unsigned Idx = 0;
5240 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5241 QualType Canonical = readType(*Loc.F, Record, Idx);
5242 if (!Canonical.isNull())
5243 Canonical = Context.getCanonicalType(Canonical);
5244 return Context.getTypedefType(Decl, Canonical);
5245 }
5246
5247 case TYPE_TYPEOF_EXPR:
5248 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5249
5250 case TYPE_TYPEOF: {
5251 if (Record.size() != 1) {
5252 Error("incorrect encoding of typeof(type) in AST file");
5253 return QualType();
5254 }
5255 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5256 return Context.getTypeOfType(UnderlyingType);
5257 }
5258
5259 case TYPE_DECLTYPE: {
5260 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5261 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5262 }
5263
5264 case TYPE_UNARY_TRANSFORM: {
5265 QualType BaseType = readType(*Loc.F, Record, Idx);
5266 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5267 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5268 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5269 }
5270
Richard Smith74aeef52013-04-26 16:15:35 +00005271 case TYPE_AUTO: {
5272 QualType Deduced = readType(*Loc.F, Record, Idx);
5273 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005274 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005275 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005276 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005277
5278 case TYPE_RECORD: {
5279 if (Record.size() != 2) {
5280 Error("incorrect encoding of record type");
5281 return QualType();
5282 }
5283 unsigned Idx = 0;
5284 bool IsDependent = Record[Idx++];
5285 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5286 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5287 QualType T = Context.getRecordType(RD);
5288 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5289 return T;
5290 }
5291
5292 case TYPE_ENUM: {
5293 if (Record.size() != 2) {
5294 Error("incorrect encoding of enum type");
5295 return QualType();
5296 }
5297 unsigned Idx = 0;
5298 bool IsDependent = Record[Idx++];
5299 QualType T
5300 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5301 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5302 return T;
5303 }
5304
5305 case TYPE_ATTRIBUTED: {
5306 if (Record.size() != 3) {
5307 Error("incorrect encoding of attributed type");
5308 return QualType();
5309 }
5310 QualType modifiedType = readType(*Loc.F, Record, Idx);
5311 QualType equivalentType = readType(*Loc.F, Record, Idx);
5312 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5313 return Context.getAttributedType(kind, modifiedType, equivalentType);
5314 }
5315
5316 case TYPE_PAREN: {
5317 if (Record.size() != 1) {
5318 Error("incorrect encoding of paren type");
5319 return QualType();
5320 }
5321 QualType InnerType = readType(*Loc.F, Record, Idx);
5322 return Context.getParenType(InnerType);
5323 }
5324
5325 case TYPE_PACK_EXPANSION: {
5326 if (Record.size() != 2) {
5327 Error("incorrect encoding of pack expansion type");
5328 return QualType();
5329 }
5330 QualType Pattern = readType(*Loc.F, Record, Idx);
5331 if (Pattern.isNull())
5332 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005333 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005334 if (Record[1])
5335 NumExpansions = Record[1] - 1;
5336 return Context.getPackExpansionType(Pattern, NumExpansions);
5337 }
5338
5339 case TYPE_ELABORATED: {
5340 unsigned Idx = 0;
5341 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5342 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5343 QualType NamedType = readType(*Loc.F, Record, Idx);
5344 return Context.getElaboratedType(Keyword, NNS, NamedType);
5345 }
5346
5347 case TYPE_OBJC_INTERFACE: {
5348 unsigned Idx = 0;
5349 ObjCInterfaceDecl *ItfD
5350 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5351 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5352 }
5353
5354 case TYPE_OBJC_OBJECT: {
5355 unsigned Idx = 0;
5356 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005357 unsigned NumTypeArgs = Record[Idx++];
5358 SmallVector<QualType, 4> TypeArgs;
5359 for (unsigned I = 0; I != NumTypeArgs; ++I)
5360 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005361 unsigned NumProtos = Record[Idx++];
5362 SmallVector<ObjCProtocolDecl*, 4> Protos;
5363 for (unsigned I = 0; I != NumProtos; ++I)
5364 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005365 bool IsKindOf = Record[Idx++];
5366 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005367 }
5368
5369 case TYPE_OBJC_OBJECT_POINTER: {
5370 unsigned Idx = 0;
5371 QualType Pointee = readType(*Loc.F, Record, Idx);
5372 return Context.getObjCObjectPointerType(Pointee);
5373 }
5374
5375 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5376 unsigned Idx = 0;
5377 QualType Parm = readType(*Loc.F, Record, Idx);
5378 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005379 return Context.getSubstTemplateTypeParmType(
5380 cast<TemplateTypeParmType>(Parm),
5381 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005382 }
5383
5384 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5385 unsigned Idx = 0;
5386 QualType Parm = readType(*Loc.F, Record, Idx);
5387 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5388 return Context.getSubstTemplateTypeParmPackType(
5389 cast<TemplateTypeParmType>(Parm),
5390 ArgPack);
5391 }
5392
5393 case TYPE_INJECTED_CLASS_NAME: {
5394 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5395 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5396 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5397 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005398 const Type *T = nullptr;
5399 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5400 if (const Type *Existing = DI->getTypeForDecl()) {
5401 T = Existing;
5402 break;
5403 }
5404 }
5405 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005406 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005407 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5408 DI->setTypeForDecl(T);
5409 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005410 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005411 }
5412
5413 case TYPE_TEMPLATE_TYPE_PARM: {
5414 unsigned Idx = 0;
5415 unsigned Depth = Record[Idx++];
5416 unsigned Index = Record[Idx++];
5417 bool Pack = Record[Idx++];
5418 TemplateTypeParmDecl *D
5419 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5420 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5421 }
5422
5423 case TYPE_DEPENDENT_NAME: {
5424 unsigned Idx = 0;
5425 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5426 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005427 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005428 QualType Canon = readType(*Loc.F, Record, Idx);
5429 if (!Canon.isNull())
5430 Canon = Context.getCanonicalType(Canon);
5431 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5432 }
5433
5434 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5435 unsigned Idx = 0;
5436 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5437 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005438 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005439 unsigned NumArgs = Record[Idx++];
5440 SmallVector<TemplateArgument, 8> Args;
5441 Args.reserve(NumArgs);
5442 while (NumArgs--)
5443 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5444 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5445 Args.size(), Args.data());
5446 }
5447
5448 case TYPE_DEPENDENT_SIZED_ARRAY: {
5449 unsigned Idx = 0;
5450
5451 // ArrayType
5452 QualType ElementType = readType(*Loc.F, Record, Idx);
5453 ArrayType::ArraySizeModifier ASM
5454 = (ArrayType::ArraySizeModifier)Record[Idx++];
5455 unsigned IndexTypeQuals = Record[Idx++];
5456
5457 // DependentSizedArrayType
5458 Expr *NumElts = ReadExpr(*Loc.F);
5459 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5460
5461 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5462 IndexTypeQuals, Brackets);
5463 }
5464
5465 case TYPE_TEMPLATE_SPECIALIZATION: {
5466 unsigned Idx = 0;
5467 bool IsDependent = Record[Idx++];
5468 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5469 SmallVector<TemplateArgument, 8> Args;
5470 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5471 QualType Underlying = readType(*Loc.F, Record, Idx);
5472 QualType T;
5473 if (Underlying.isNull())
5474 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5475 Args.size());
5476 else
5477 T = Context.getTemplateSpecializationType(Name, Args.data(),
5478 Args.size(), Underlying);
5479 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5480 return T;
5481 }
5482
5483 case TYPE_ATOMIC: {
5484 if (Record.size() != 1) {
5485 Error("Incorrect encoding of atomic type");
5486 return QualType();
5487 }
5488 QualType ValueType = readType(*Loc.F, Record, Idx);
5489 return Context.getAtomicType(ValueType);
5490 }
5491 }
5492 llvm_unreachable("Invalid TypeCode!");
5493}
5494
Richard Smith564417a2014-03-20 21:47:22 +00005495void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5496 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005497 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005498 const RecordData &Record, unsigned &Idx) {
5499 ExceptionSpecificationType EST =
5500 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005501 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005502 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005503 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005504 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005505 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005506 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005507 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005508 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005509 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5510 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005511 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005512 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005513 }
5514}
5515
Guy Benyei11169dd2012-12-18 14:30:41 +00005516class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5517 ASTReader &Reader;
5518 ModuleFile &F;
5519 const ASTReader::RecordData &Record;
5520 unsigned &Idx;
5521
5522 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5523 unsigned &I) {
5524 return Reader.ReadSourceLocation(F, R, I);
5525 }
5526
5527 template<typename T>
5528 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5529 return Reader.ReadDeclAs<T>(F, Record, Idx);
5530 }
5531
5532public:
5533 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5534 const ASTReader::RecordData &Record, unsigned &Idx)
5535 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5536 { }
5537
5538 // We want compile-time assurance that we've enumerated all of
5539 // these, so unfortunately we have to declare them first, then
5540 // define them out-of-line.
5541#define ABSTRACT_TYPELOC(CLASS, PARENT)
5542#define TYPELOC(CLASS, PARENT) \
5543 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5544#include "clang/AST/TypeLocNodes.def"
5545
5546 void VisitFunctionTypeLoc(FunctionTypeLoc);
5547 void VisitArrayTypeLoc(ArrayTypeLoc);
5548};
5549
5550void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5551 // nothing to do
5552}
5553void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5554 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5555 if (TL.needsExtraLocalData()) {
5556 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5557 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5558 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5559 TL.setModeAttr(Record[Idx++]);
5560 }
5561}
5562void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5563 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5564}
5565void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5566 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5567}
Reid Kleckner8a365022013-06-24 17:51:48 +00005568void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5569 // nothing to do
5570}
Reid Kleckner0503a872013-12-05 01:23:43 +00005571void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5572 // nothing to do
5573}
Guy Benyei11169dd2012-12-18 14:30:41 +00005574void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5575 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5576}
5577void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5578 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5579}
5580void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5581 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5582}
5583void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5584 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5585 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5586}
5587void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5588 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5589 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5590 if (Record[Idx++])
5591 TL.setSizeExpr(Reader.ReadExpr(F));
5592 else
Craig Toppera13603a2014-05-22 05:54:18 +00005593 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005594}
5595void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5596 VisitArrayTypeLoc(TL);
5597}
5598void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5599 VisitArrayTypeLoc(TL);
5600}
5601void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5602 VisitArrayTypeLoc(TL);
5603}
5604void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5605 DependentSizedArrayTypeLoc TL) {
5606 VisitArrayTypeLoc(TL);
5607}
5608void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5609 DependentSizedExtVectorTypeLoc TL) {
5610 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5611}
5612void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5613 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5614}
5615void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5616 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5617}
5618void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5619 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5620 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5621 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5622 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005623 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5624 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005625 }
5626}
5627void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5628 VisitFunctionTypeLoc(TL);
5629}
5630void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5631 VisitFunctionTypeLoc(TL);
5632}
5633void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5634 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5635}
5636void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5637 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5638}
5639void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5640 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5641 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5642 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5643}
5644void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5645 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5646 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5647 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5648 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5649}
5650void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5651 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5652}
5653void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5654 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5655 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5656 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5657 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5658}
5659void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5660 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5661}
5662void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5663 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5664}
5665void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5666 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5667}
5668void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5669 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5670 if (TL.hasAttrOperand()) {
5671 SourceRange range;
5672 range.setBegin(ReadSourceLocation(Record, Idx));
5673 range.setEnd(ReadSourceLocation(Record, Idx));
5674 TL.setAttrOperandParensRange(range);
5675 }
5676 if (TL.hasAttrExprOperand()) {
5677 if (Record[Idx++])
5678 TL.setAttrExprOperand(Reader.ReadExpr(F));
5679 else
Craig Toppera13603a2014-05-22 05:54:18 +00005680 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005681 } else if (TL.hasAttrEnumOperand())
5682 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5683}
5684void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5685 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5686}
5687void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5688 SubstTemplateTypeParmTypeLoc TL) {
5689 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5690}
5691void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5692 SubstTemplateTypeParmPackTypeLoc TL) {
5693 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5694}
5695void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5696 TemplateSpecializationTypeLoc TL) {
5697 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5698 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5699 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5700 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5701 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5702 TL.setArgLocInfo(i,
5703 Reader.GetTemplateArgumentLocInfo(F,
5704 TL.getTypePtr()->getArg(i).getKind(),
5705 Record, Idx));
5706}
5707void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5708 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5709 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5710}
5711void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5712 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5713 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5714}
5715void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5716 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5717}
5718void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5719 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5720 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5721 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5722}
5723void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5724 DependentTemplateSpecializationTypeLoc TL) {
5725 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5726 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5727 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5728 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5729 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5730 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5731 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5732 TL.setArgLocInfo(I,
5733 Reader.GetTemplateArgumentLocInfo(F,
5734 TL.getTypePtr()->getArg(I).getKind(),
5735 Record, Idx));
5736}
5737void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5738 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5739}
5740void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5741 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5742}
5743void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5744 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005745 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5746 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5747 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5748 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5749 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5750 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005751 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5752 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5753}
5754void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5755 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5756}
5757void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5758 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5759 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5760 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5761}
5762
5763TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5764 const RecordData &Record,
5765 unsigned &Idx) {
5766 QualType InfoTy = readType(F, Record, Idx);
5767 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005768 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005769
5770 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5771 TypeLocReader TLR(*this, F, Record, Idx);
5772 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5773 TLR.Visit(TL);
5774 return TInfo;
5775}
5776
5777QualType ASTReader::GetType(TypeID ID) {
5778 unsigned FastQuals = ID & Qualifiers::FastMask;
5779 unsigned Index = ID >> Qualifiers::FastWidth;
5780
5781 if (Index < NUM_PREDEF_TYPE_IDS) {
5782 QualType T;
5783 switch ((PredefinedTypeIDs)Index) {
5784 case PREDEF_TYPE_NULL_ID: return QualType();
5785 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5786 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5787
5788 case PREDEF_TYPE_CHAR_U_ID:
5789 case PREDEF_TYPE_CHAR_S_ID:
5790 // FIXME: Check that the signedness of CharTy is correct!
5791 T = Context.CharTy;
5792 break;
5793
5794 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5795 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5796 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5797 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5798 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5799 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5800 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5801 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5802 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5803 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5804 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5805 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5806 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5807 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5808 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5809 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5810 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5811 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5812 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5813 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5814 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5815 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5816 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5817 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5818 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5819 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5820 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5821 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005822 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5823 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5824 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5825 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5826 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00005827 case PREDEF_TYPE_IMAGE2D_DEP_ID:
5828 T = Context.OCLImage2dDepthTy;
5829 break;
5830 case PREDEF_TYPE_IMAGE2D_ARR_DEP_ID:
5831 T = Context.OCLImage2dArrayDepthTy;
5832 break;
5833 case PREDEF_TYPE_IMAGE2D_MSAA_ID:
5834 T = Context.OCLImage2dMSAATy;
5835 break;
5836 case PREDEF_TYPE_IMAGE2D_ARR_MSAA_ID:
5837 T = Context.OCLImage2dArrayMSAATy;
5838 break;
5839 case PREDEF_TYPE_IMAGE2D_MSAA_DEP_ID:
5840 T = Context.OCLImage2dMSAADepthTy;
5841 break;
5842 case PREDEF_TYPE_IMAGE2D_ARR_MSAA_DEPTH_ID:
5843 T = Context.OCLImage2dArrayMSAADepthTy;
5844 break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005845 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005846 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005847 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00005848 case PREDEF_TYPE_CLK_EVENT_ID:
5849 T = Context.OCLClkEventTy;
5850 break;
5851 case PREDEF_TYPE_QUEUE_ID:
5852 T = Context.OCLQueueTy;
5853 break;
5854 case PREDEF_TYPE_NDRANGE_ID:
5855 T = Context.OCLNDRangeTy;
5856 break;
5857 case PREDEF_TYPE_RESERVE_ID_ID:
5858 T = Context.OCLReserveIDTy;
5859 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005860 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5861
5862 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5863 T = Context.getAutoRRefDeductType();
5864 break;
5865
5866 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5867 T = Context.ARCUnbridgedCastTy;
5868 break;
5869
Guy Benyei11169dd2012-12-18 14:30:41 +00005870 case PREDEF_TYPE_BUILTIN_FN:
5871 T = Context.BuiltinFnTy;
5872 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005873
5874 case PREDEF_TYPE_OMP_ARRAY_SECTION:
5875 T = Context.OMPArraySectionTy;
5876 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005877 }
5878
5879 assert(!T.isNull() && "Unknown predefined type");
5880 return T.withFastQualifiers(FastQuals);
5881 }
5882
5883 Index -= NUM_PREDEF_TYPE_IDS;
5884 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5885 if (TypesLoaded[Index].isNull()) {
5886 TypesLoaded[Index] = readTypeRecord(Index);
5887 if (TypesLoaded[Index].isNull())
5888 return QualType();
5889
5890 TypesLoaded[Index]->setFromAST();
5891 if (DeserializationListener)
5892 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5893 TypesLoaded[Index]);
5894 }
5895
5896 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5897}
5898
5899QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5900 return GetType(getGlobalTypeID(F, LocalID));
5901}
5902
5903serialization::TypeID
5904ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5905 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5906 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5907
5908 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5909 return LocalID;
5910
5911 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5912 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5913 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5914
5915 unsigned GlobalIndex = LocalIndex + I->second;
5916 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5917}
5918
5919TemplateArgumentLocInfo
5920ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5921 TemplateArgument::ArgKind Kind,
5922 const RecordData &Record,
5923 unsigned &Index) {
5924 switch (Kind) {
5925 case TemplateArgument::Expression:
5926 return ReadExpr(F);
5927 case TemplateArgument::Type:
5928 return GetTypeSourceInfo(F, Record, Index);
5929 case TemplateArgument::Template: {
5930 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5931 Index);
5932 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5933 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5934 SourceLocation());
5935 }
5936 case TemplateArgument::TemplateExpansion: {
5937 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5938 Index);
5939 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5940 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5941 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5942 EllipsisLoc);
5943 }
5944 case TemplateArgument::Null:
5945 case TemplateArgument::Integral:
5946 case TemplateArgument::Declaration:
5947 case TemplateArgument::NullPtr:
5948 case TemplateArgument::Pack:
5949 // FIXME: Is this right?
5950 return TemplateArgumentLocInfo();
5951 }
5952 llvm_unreachable("unexpected template argument loc");
5953}
5954
5955TemplateArgumentLoc
5956ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5957 const RecordData &Record, unsigned &Index) {
5958 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5959
5960 if (Arg.getKind() == TemplateArgument::Expression) {
5961 if (Record[Index++]) // bool InfoHasSameExpr.
5962 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5963 }
5964 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5965 Record, Index));
5966}
5967
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005968const ASTTemplateArgumentListInfo*
5969ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5970 const RecordData &Record,
5971 unsigned &Index) {
5972 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5973 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5974 unsigned NumArgsAsWritten = Record[Index++];
5975 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5976 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5977 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5978 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5979}
5980
Guy Benyei11169dd2012-12-18 14:30:41 +00005981Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5982 return GetDecl(ID);
5983}
5984
Richard Smith50895422015-01-31 03:04:55 +00005985template<typename TemplateSpecializationDecl>
5986static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5987 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5988 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5989}
5990
Richard Smith053f6c62014-05-16 23:01:30 +00005991void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005992 if (NumCurrentElementsDeserializing) {
5993 // We arrange to not care about the complete redeclaration chain while we're
5994 // deserializing. Just remember that the AST has marked this one as complete
5995 // but that it's not actually complete yet, so we know we still need to
5996 // complete it later.
5997 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5998 return;
5999 }
6000
Richard Smith053f6c62014-05-16 23:01:30 +00006001 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6002
Richard Smith053f6c62014-05-16 23:01:30 +00006003 // If this is a named declaration, complete it by looking it up
6004 // within its context.
6005 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006006 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006007 // all mergeable entities within it.
6008 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6009 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6010 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006011 if (!getContext().getLangOpts().CPlusPlus &&
6012 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006013 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006014 // the identifier instead. (For C++ modules, we don't store decls
6015 // in the serialized identifier table, so we do the lookup in the TU.)
6016 auto *II = Name.getAsIdentifierInfo();
6017 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006018 if (II->isOutOfDate())
6019 updateOutOfDateIdentifier(*II);
6020 } else
6021 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006022 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006023 // Find all declarations of this kind from the relevant context.
6024 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6025 auto *DC = cast<DeclContext>(DCDecl);
6026 SmallVector<Decl*, 8> Decls;
6027 FindExternalLexicalDecls(
6028 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6029 }
Richard Smith053f6c62014-05-16 23:01:30 +00006030 }
6031 }
Richard Smith50895422015-01-31 03:04:55 +00006032
6033 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6034 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6035 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6036 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6037 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6038 if (auto *Template = FD->getPrimaryTemplate())
6039 Template->LoadLazySpecializations();
6040 }
Richard Smith053f6c62014-05-16 23:01:30 +00006041}
6042
Richard Smithc2bb8182015-03-24 06:36:48 +00006043uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
6044 const RecordData &Record,
6045 unsigned &Idx) {
6046 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
6047 Error("malformed AST file: missing C++ ctor initializers");
6048 return 0;
6049 }
6050
6051 unsigned LocalID = Record[Idx++];
6052 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6053}
6054
6055CXXCtorInitializer **
6056ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6057 RecordLocation Loc = getLocalBitOffset(Offset);
6058 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6059 SavedStreamPosition SavedPosition(Cursor);
6060 Cursor.JumpToBit(Loc.Offset);
6061 ReadingKindTracker ReadingKind(Read_Decl, *this);
6062
6063 RecordData Record;
6064 unsigned Code = Cursor.ReadCode();
6065 unsigned RecCode = Cursor.readRecord(Code, Record);
6066 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6067 Error("malformed AST file: missing C++ ctor initializers");
6068 return nullptr;
6069 }
6070
6071 unsigned Idx = 0;
6072 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6073}
6074
Richard Smithcd45dbc2014-04-19 03:48:30 +00006075uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6076 const RecordData &Record,
6077 unsigned &Idx) {
6078 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6079 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006080 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006081 }
6082
Guy Benyei11169dd2012-12-18 14:30:41 +00006083 unsigned LocalID = Record[Idx++];
6084 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6085}
6086
6087CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6088 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006089 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006090 SavedStreamPosition SavedPosition(Cursor);
6091 Cursor.JumpToBit(Loc.Offset);
6092 ReadingKindTracker ReadingKind(Read_Decl, *this);
6093 RecordData Record;
6094 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006095 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006096 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006097 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006098 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006099 }
6100
6101 unsigned Idx = 0;
6102 unsigned NumBases = Record[Idx++];
6103 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6104 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6105 for (unsigned I = 0; I != NumBases; ++I)
6106 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6107 return Bases;
6108}
6109
6110serialization::DeclID
6111ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6112 if (LocalID < NUM_PREDEF_DECL_IDS)
6113 return LocalID;
6114
6115 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6116 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6117 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6118
6119 return LocalID + I->second;
6120}
6121
6122bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6123 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006124 // Predefined decls aren't from any module.
6125 if (ID < NUM_PREDEF_DECL_IDS)
6126 return false;
6127
Richard Smithbcda1a92015-07-12 23:51:20 +00006128 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6129 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006130}
6131
Douglas Gregor9f782892013-01-21 15:25:38 +00006132ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006133 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006134 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006135 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6136 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6137 return I->second;
6138}
6139
6140SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6141 if (ID < NUM_PREDEF_DECL_IDS)
6142 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006143
Guy Benyei11169dd2012-12-18 14:30:41 +00006144 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6145
6146 if (Index > DeclsLoaded.size()) {
6147 Error("declaration ID out-of-range for AST file");
6148 return SourceLocation();
6149 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006150
Guy Benyei11169dd2012-12-18 14:30:41 +00006151 if (Decl *D = DeclsLoaded[Index])
6152 return D->getLocation();
6153
6154 unsigned RawLocation = 0;
6155 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6156 return ReadSourceLocation(*Rec.F, RawLocation);
6157}
6158
Richard Smithfe620d22015-03-05 23:24:12 +00006159static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6160 switch (ID) {
6161 case PREDEF_DECL_NULL_ID:
6162 return nullptr;
6163
6164 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6165 return Context.getTranslationUnitDecl();
6166
6167 case PREDEF_DECL_OBJC_ID_ID:
6168 return Context.getObjCIdDecl();
6169
6170 case PREDEF_DECL_OBJC_SEL_ID:
6171 return Context.getObjCSelDecl();
6172
6173 case PREDEF_DECL_OBJC_CLASS_ID:
6174 return Context.getObjCClassDecl();
6175
6176 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6177 return Context.getObjCProtocolDecl();
6178
6179 case PREDEF_DECL_INT_128_ID:
6180 return Context.getInt128Decl();
6181
6182 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6183 return Context.getUInt128Decl();
6184
6185 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6186 return Context.getObjCInstanceTypeDecl();
6187
6188 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6189 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006190
Richard Smith9b88a4c2015-07-27 05:40:23 +00006191 case PREDEF_DECL_VA_LIST_TAG:
6192 return Context.getVaListTagDecl();
6193
Richard Smithf19e1272015-03-07 00:04:49 +00006194 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6195 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006196 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006197 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006198}
6199
Richard Smithcd45dbc2014-04-19 03:48:30 +00006200Decl *ASTReader::GetExistingDecl(DeclID ID) {
6201 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006202 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6203 if (D) {
6204 // Track that we have merged the declaration with ID \p ID into the
6205 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006206 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006207 if (Merged.empty())
6208 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006209 }
Richard Smithfe620d22015-03-05 23:24:12 +00006210 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006211 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006212
Guy Benyei11169dd2012-12-18 14:30:41 +00006213 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6214
6215 if (Index >= DeclsLoaded.size()) {
6216 assert(0 && "declaration ID out-of-range for AST file");
6217 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006218 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006219 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006220
6221 return DeclsLoaded[Index];
6222}
6223
6224Decl *ASTReader::GetDecl(DeclID ID) {
6225 if (ID < NUM_PREDEF_DECL_IDS)
6226 return GetExistingDecl(ID);
6227
6228 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6229
6230 if (Index >= DeclsLoaded.size()) {
6231 assert(0 && "declaration ID out-of-range for AST file");
6232 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006233 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006234 }
6235
Guy Benyei11169dd2012-12-18 14:30:41 +00006236 if (!DeclsLoaded[Index]) {
6237 ReadDeclRecord(ID);
6238 if (DeserializationListener)
6239 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6240 }
6241
6242 return DeclsLoaded[Index];
6243}
6244
6245DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6246 DeclID GlobalID) {
6247 if (GlobalID < NUM_PREDEF_DECL_IDS)
6248 return GlobalID;
6249
6250 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6251 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6252 ModuleFile *Owner = I->second;
6253
6254 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6255 = M.GlobalToLocalDeclIDs.find(Owner);
6256 if (Pos == M.GlobalToLocalDeclIDs.end())
6257 return 0;
6258
6259 return GlobalID - Owner->BaseDeclID + Pos->second;
6260}
6261
6262serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6263 const RecordData &Record,
6264 unsigned &Idx) {
6265 if (Idx >= Record.size()) {
6266 Error("Corrupted AST file");
6267 return 0;
6268 }
6269
6270 return getGlobalDeclID(F, Record[Idx++]);
6271}
6272
6273/// \brief Resolve the offset of a statement into a statement.
6274///
6275/// This operation will read a new statement from the external
6276/// source each time it is called, and is meant to be used via a
6277/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6278Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6279 // Switch case IDs are per Decl.
6280 ClearSwitchCaseIDs();
6281
6282 // Offset here is a global offset across the entire chain.
6283 RecordLocation Loc = getLocalBitOffset(Offset);
6284 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6285 return ReadStmtFromStream(*Loc.F);
6286}
6287
Richard Smith3cb15722015-08-05 22:41:45 +00006288void ASTReader::FindExternalLexicalDecls(
6289 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6290 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006291 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6292
Richard Smith9ccdd932015-08-06 22:14:12 +00006293 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006294 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6295 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6296 auto K = (Decl::Kind)+LexicalDecls[I];
6297 if (!IsKindWeWant(K))
6298 continue;
6299
6300 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6301
6302 // Don't add predefined declarations to the lexical context more
6303 // than once.
6304 if (ID < NUM_PREDEF_DECL_IDS) {
6305 if (PredefsVisited[ID])
6306 continue;
6307
6308 PredefsVisited[ID] = true;
6309 }
6310
6311 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006312 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006313 if (!DC->isDeclInLexicalTraversal(D))
6314 Decls.push_back(D);
6315 }
6316 }
6317 };
6318
6319 if (isa<TranslationUnitDecl>(DC)) {
6320 for (auto Lexical : TULexicalDecls)
6321 Visit(Lexical.first, Lexical.second);
6322 } else {
6323 auto I = LexicalDecls.find(DC);
6324 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006325 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006326 }
6327
Guy Benyei11169dd2012-12-18 14:30:41 +00006328 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006329}
6330
6331namespace {
6332
6333class DeclIDComp {
6334 ASTReader &Reader;
6335 ModuleFile &Mod;
6336
6337public:
6338 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6339
6340 bool operator()(LocalDeclID L, LocalDeclID R) const {
6341 SourceLocation LHS = getLocation(L);
6342 SourceLocation RHS = getLocation(R);
6343 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6344 }
6345
6346 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6347 SourceLocation RHS = getLocation(R);
6348 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6349 }
6350
6351 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6352 SourceLocation LHS = getLocation(L);
6353 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6354 }
6355
6356 SourceLocation getLocation(LocalDeclID ID) const {
6357 return Reader.getSourceManager().getFileLoc(
6358 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6359 }
6360};
6361
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006362}
Guy Benyei11169dd2012-12-18 14:30:41 +00006363
6364void ASTReader::FindFileRegionDecls(FileID File,
6365 unsigned Offset, unsigned Length,
6366 SmallVectorImpl<Decl *> &Decls) {
6367 SourceManager &SM = getSourceManager();
6368
6369 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6370 if (I == FileDeclIDs.end())
6371 return;
6372
6373 FileDeclsInfo &DInfo = I->second;
6374 if (DInfo.Decls.empty())
6375 return;
6376
6377 SourceLocation
6378 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6379 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6380
6381 DeclIDComp DIDComp(*this, *DInfo.Mod);
6382 ArrayRef<serialization::LocalDeclID>::iterator
6383 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6384 BeginLoc, DIDComp);
6385 if (BeginIt != DInfo.Decls.begin())
6386 --BeginIt;
6387
6388 // If we are pointing at a top-level decl inside an objc container, we need
6389 // to backtrack until we find it otherwise we will fail to report that the
6390 // region overlaps with an objc container.
6391 while (BeginIt != DInfo.Decls.begin() &&
6392 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6393 ->isTopLevelDeclInObjCContainer())
6394 --BeginIt;
6395
6396 ArrayRef<serialization::LocalDeclID>::iterator
6397 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6398 EndLoc, DIDComp);
6399 if (EndIt != DInfo.Decls.end())
6400 ++EndIt;
6401
6402 for (ArrayRef<serialization::LocalDeclID>::iterator
6403 DIt = BeginIt; DIt != EndIt; ++DIt)
6404 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6405}
6406
Richard Smith9ce12e32013-02-07 03:30:24 +00006407bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006408ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6409 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006410 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006411 "DeclContext has no visible decls in storage");
6412 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006413 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006414
Richard Smithd88a7f12015-09-01 20:35:42 +00006415 auto It = Lookups.find(DC);
6416 if (It == Lookups.end())
6417 return false;
6418
Richard Smith8c913ec2014-08-14 02:21:01 +00006419 Deserializing LookupResults(this);
6420
Richard Smithd88a7f12015-09-01 20:35:42 +00006421 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006422 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006423 for (DeclID ID : It->second.Table.find(Name)) {
6424 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6425 if (ND->getDeclName() == Name)
6426 Decls.push_back(ND);
6427 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006428
Guy Benyei11169dd2012-12-18 14:30:41 +00006429 ++NumVisibleDeclContextsRead;
6430 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006431 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006432}
6433
Guy Benyei11169dd2012-12-18 14:30:41 +00006434void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6435 if (!DC->hasExternalVisibleStorage())
6436 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006437
6438 auto It = Lookups.find(DC);
6439 assert(It != Lookups.end() &&
6440 "have external visible storage but no lookup tables");
6441
Craig Topper79be4cd2013-07-05 04:33:53 +00006442 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006443
Richard Smithd88a7f12015-09-01 20:35:42 +00006444 for (DeclID ID : It->second.Table.findAll()) {
6445 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6446 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006447 }
6448
Guy Benyei11169dd2012-12-18 14:30:41 +00006449 ++NumVisibleDeclContextsRead;
6450
Craig Topper79be4cd2013-07-05 04:33:53 +00006451 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006452 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6453 }
6454 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6455}
6456
Richard Smithd88a7f12015-09-01 20:35:42 +00006457const serialization::reader::DeclContextLookupTable *
6458ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6459 auto I = Lookups.find(Primary);
6460 return I == Lookups.end() ? nullptr : &I->second;
6461}
6462
Guy Benyei11169dd2012-12-18 14:30:41 +00006463/// \brief Under non-PCH compilation the consumer receives the objc methods
6464/// before receiving the implementation, and codegen depends on this.
6465/// We simulate this by deserializing and passing to consumer the methods of the
6466/// implementation before passing the deserialized implementation decl.
6467static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6468 ASTConsumer *Consumer) {
6469 assert(ImplD && Consumer);
6470
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006471 for (auto *I : ImplD->methods())
6472 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006473
6474 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6475}
6476
6477void ASTReader::PassInterestingDeclsToConsumer() {
6478 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006479
6480 if (PassingDeclsToConsumer)
6481 return;
6482
6483 // Guard variable to avoid recursively redoing the process of passing
6484 // decls to consumer.
6485 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6486 true);
6487
Richard Smith9e2341d2015-03-23 03:25:59 +00006488 // Ensure that we've loaded all potentially-interesting declarations
6489 // that need to be eagerly loaded.
6490 for (auto ID : EagerlyDeserializedDecls)
6491 GetDecl(ID);
6492 EagerlyDeserializedDecls.clear();
6493
Guy Benyei11169dd2012-12-18 14:30:41 +00006494 while (!InterestingDecls.empty()) {
6495 Decl *D = InterestingDecls.front();
6496 InterestingDecls.pop_front();
6497
6498 PassInterestingDeclToConsumer(D);
6499 }
6500}
6501
6502void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6503 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6504 PassObjCImplDeclToConsumer(ImplD, Consumer);
6505 else
6506 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6507}
6508
6509void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6510 this->Consumer = Consumer;
6511
Richard Smith9e2341d2015-03-23 03:25:59 +00006512 if (Consumer)
6513 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006514
6515 if (DeserializationListener)
6516 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006517}
6518
6519void ASTReader::PrintStats() {
6520 std::fprintf(stderr, "*** AST File Statistics:\n");
6521
6522 unsigned NumTypesLoaded
6523 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6524 QualType());
6525 unsigned NumDeclsLoaded
6526 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006527 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006528 unsigned NumIdentifiersLoaded
6529 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6530 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006531 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006532 unsigned NumMacrosLoaded
6533 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6534 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006535 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006536 unsigned NumSelectorsLoaded
6537 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6538 SelectorsLoaded.end(),
6539 Selector());
6540
6541 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6542 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6543 NumSLocEntriesRead, TotalNumSLocEntries,
6544 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6545 if (!TypesLoaded.empty())
6546 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6547 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6548 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6549 if (!DeclsLoaded.empty())
6550 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6551 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6552 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6553 if (!IdentifiersLoaded.empty())
6554 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6555 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6556 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6557 if (!MacrosLoaded.empty())
6558 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6559 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6560 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6561 if (!SelectorsLoaded.empty())
6562 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6563 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6564 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6565 if (TotalNumStatements)
6566 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6567 NumStatementsRead, TotalNumStatements,
6568 ((float)NumStatementsRead/TotalNumStatements * 100));
6569 if (TotalNumMacros)
6570 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6571 NumMacrosRead, TotalNumMacros,
6572 ((float)NumMacrosRead/TotalNumMacros * 100));
6573 if (TotalLexicalDeclContexts)
6574 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6575 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6576 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6577 * 100));
6578 if (TotalVisibleDeclContexts)
6579 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6580 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6581 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6582 * 100));
6583 if (TotalNumMethodPoolEntries) {
6584 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6585 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6586 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6587 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006588 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006589 if (NumMethodPoolLookups) {
6590 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6591 NumMethodPoolHits, NumMethodPoolLookups,
6592 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6593 }
6594 if (NumMethodPoolTableLookups) {
6595 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6596 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6597 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6598 * 100.0));
6599 }
6600
Douglas Gregor00a50f72013-01-25 00:38:33 +00006601 if (NumIdentifierLookupHits) {
6602 std::fprintf(stderr,
6603 " %u / %u identifier table lookups succeeded (%f%%)\n",
6604 NumIdentifierLookupHits, NumIdentifierLookups,
6605 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6606 }
6607
Douglas Gregore060e572013-01-25 01:03:03 +00006608 if (GlobalIndex) {
6609 std::fprintf(stderr, "\n");
6610 GlobalIndex->printStats();
6611 }
6612
Guy Benyei11169dd2012-12-18 14:30:41 +00006613 std::fprintf(stderr, "\n");
6614 dump();
6615 std::fprintf(stderr, "\n");
6616}
6617
6618template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6619static void
6620dumpModuleIDMap(StringRef Name,
6621 const ContinuousRangeMap<Key, ModuleFile *,
6622 InitialCapacity> &Map) {
6623 if (Map.begin() == Map.end())
6624 return;
6625
6626 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6627 llvm::errs() << Name << ":\n";
6628 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6629 I != IEnd; ++I) {
6630 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6631 << "\n";
6632 }
6633}
6634
6635void ASTReader::dump() {
6636 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6637 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6638 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6639 dumpModuleIDMap("Global type map", GlobalTypeMap);
6640 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6641 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6642 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6643 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6644 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6645 dumpModuleIDMap("Global preprocessed entity map",
6646 GlobalPreprocessedEntityMap);
6647
6648 llvm::errs() << "\n*** PCH/Modules Loaded:";
6649 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6650 MEnd = ModuleMgr.end();
6651 M != MEnd; ++M)
6652 (*M)->dump();
6653}
6654
6655/// Return the amount of memory used by memory buffers, breaking down
6656/// by heap-backed versus mmap'ed memory.
6657void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6658 for (ModuleConstIterator I = ModuleMgr.begin(),
6659 E = ModuleMgr.end(); I != E; ++I) {
6660 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6661 size_t bytes = buf->getBufferSize();
6662 switch (buf->getBufferKind()) {
6663 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6664 sizes.malloc_bytes += bytes;
6665 break;
6666 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6667 sizes.mmap_bytes += bytes;
6668 break;
6669 }
6670 }
6671 }
6672}
6673
6674void ASTReader::InitializeSema(Sema &S) {
6675 SemaObj = &S;
6676 S.addExternalSource(this);
6677
6678 // Makes sure any declarations that were deserialized "too early"
6679 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006680 for (uint64_t ID : PreloadedDeclIDs) {
6681 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6682 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006683 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006684 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006685
Richard Smith3d8e97e2013-10-18 06:54:39 +00006686 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006687 if (!FPPragmaOptions.empty()) {
6688 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6689 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6690 }
6691
Richard Smith3d8e97e2013-10-18 06:54:39 +00006692 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006693 if (!OpenCLExtensions.empty()) {
6694 unsigned I = 0;
6695#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6696#include "clang/Basic/OpenCLExtensions.def"
6697
6698 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6699 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006700
6701 UpdateSema();
6702}
6703
6704void ASTReader::UpdateSema() {
6705 assert(SemaObj && "no Sema to update");
6706
6707 // Load the offsets of the declarations that Sema references.
6708 // They will be lazily deserialized when needed.
6709 if (!SemaDeclRefs.empty()) {
6710 assert(SemaDeclRefs.size() % 2 == 0);
6711 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6712 if (!SemaObj->StdNamespace)
6713 SemaObj->StdNamespace = SemaDeclRefs[I];
6714 if (!SemaObj->StdBadAlloc)
6715 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6716 }
6717 SemaDeclRefs.clear();
6718 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006719
6720 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6721 // encountered the pragma in the source.
6722 if(OptimizeOffPragmaLocation.isValid())
6723 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006724}
6725
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006726IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006727 // Note that we are loading an identifier.
6728 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006729
Douglas Gregor7211ac12013-01-25 23:32:03 +00006730 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006731 NumIdentifierLookups,
6732 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006733
6734 // We don't need to do identifier table lookups in C++ modules (we preload
6735 // all interesting declarations, and don't need to use the scope for name
6736 // lookups). Perform the lookup in PCH files, though, since we don't build
6737 // a complete initial identifier table if we're carrying on from a PCH.
6738 if (Context.getLangOpts().CPlusPlus) {
6739 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006740 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006741 break;
6742 } else {
6743 // If there is a global index, look there first to determine which modules
6744 // provably do not have any results for this identifier.
6745 GlobalModuleIndex::HitSet Hits;
6746 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6747 if (!loadGlobalIndex()) {
6748 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6749 HitsPtr = &Hits;
6750 }
6751 }
6752
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006753 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006754 }
6755
Guy Benyei11169dd2012-12-18 14:30:41 +00006756 IdentifierInfo *II = Visitor.getIdentifierInfo();
6757 markIdentifierUpToDate(II);
6758 return II;
6759}
6760
6761namespace clang {
6762 /// \brief An identifier-lookup iterator that enumerates all of the
6763 /// identifiers stored within a set of AST files.
6764 class ASTIdentifierIterator : public IdentifierIterator {
6765 /// \brief The AST reader whose identifiers are being enumerated.
6766 const ASTReader &Reader;
6767
6768 /// \brief The current index into the chain of AST files stored in
6769 /// the AST reader.
6770 unsigned Index;
6771
6772 /// \brief The current position within the identifier lookup table
6773 /// of the current AST file.
6774 ASTIdentifierLookupTable::key_iterator Current;
6775
6776 /// \brief The end position within the identifier lookup table of
6777 /// the current AST file.
6778 ASTIdentifierLookupTable::key_iterator End;
6779
6780 public:
6781 explicit ASTIdentifierIterator(const ASTReader &Reader);
6782
Craig Topper3e89dfe2014-03-13 02:13:41 +00006783 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006784 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006785}
Guy Benyei11169dd2012-12-18 14:30:41 +00006786
6787ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6788 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6789 ASTIdentifierLookupTable *IdTable
6790 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6791 Current = IdTable->key_begin();
6792 End = IdTable->key_end();
6793}
6794
6795StringRef ASTIdentifierIterator::Next() {
6796 while (Current == End) {
6797 // If we have exhausted all of our AST files, we're done.
6798 if (Index == 0)
6799 return StringRef();
6800
6801 --Index;
6802 ASTIdentifierLookupTable *IdTable
6803 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6804 IdentifierLookupTable;
6805 Current = IdTable->key_begin();
6806 End = IdTable->key_end();
6807 }
6808
6809 // We have any identifiers remaining in the current AST file; return
6810 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006811 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006812 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006813 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006814}
6815
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006816IdentifierIterator *ASTReader::getIdentifiers() {
6817 if (!loadGlobalIndex())
6818 return GlobalIndex->createIdentifierIterator();
6819
Guy Benyei11169dd2012-12-18 14:30:41 +00006820 return new ASTIdentifierIterator(*this);
6821}
6822
6823namespace clang { namespace serialization {
6824 class ReadMethodPoolVisitor {
6825 ASTReader &Reader;
6826 Selector Sel;
6827 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006828 unsigned InstanceBits;
6829 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006830 bool InstanceHasMoreThanOneDecl;
6831 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006832 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6833 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006834
6835 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006836 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006837 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006838 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006839 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6840 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006841
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006842 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006843 if (!M.SelectorLookupTable)
6844 return false;
6845
6846 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00006847 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00006848 return true;
6849
Richard Smithbdf2d932015-07-30 03:37:16 +00006850 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006851 ASTSelectorLookupTable *PoolTable
6852 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00006853 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00006854 if (Pos == PoolTable->end())
6855 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006856
Richard Smithbdf2d932015-07-30 03:37:16 +00006857 ++Reader.NumMethodPoolTableHits;
6858 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006859 // FIXME: Not quite happy with the statistics here. We probably should
6860 // disable this tracking when called via LoadSelector.
6861 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00006862 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006863 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00006864 if (Reader.DeserializationListener)
6865 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006866
Richard Smithbdf2d932015-07-30 03:37:16 +00006867 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6868 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6869 InstanceBits = Data.InstanceBits;
6870 FactoryBits = Data.FactoryBits;
6871 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6872 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006873 return true;
6874 }
6875
6876 /// \brief Retrieve the instance methods found by this visitor.
6877 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6878 return InstanceMethods;
6879 }
6880
6881 /// \brief Retrieve the instance methods found by this visitor.
6882 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6883 return FactoryMethods;
6884 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006885
6886 unsigned getInstanceBits() const { return InstanceBits; }
6887 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006888 bool instanceHasMoreThanOneDecl() const {
6889 return InstanceHasMoreThanOneDecl;
6890 }
6891 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006892 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006893} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00006894
6895/// \brief Add the given set of methods to the method list.
6896static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6897 ObjCMethodList &List) {
6898 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6899 S.addMethodToGlobalList(&List, Methods[I]);
6900 }
6901}
6902
6903void ASTReader::ReadMethodPool(Selector Sel) {
6904 // Get the selector generation and update it to the current generation.
6905 unsigned &Generation = SelectorGeneration[Sel];
6906 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00006907 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00006908
6909 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006910 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006911 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006912 ModuleMgr.visit(Visitor);
6913
Guy Benyei11169dd2012-12-18 14:30:41 +00006914 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006915 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006916 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006917
6918 ++NumMethodPoolHits;
6919
Guy Benyei11169dd2012-12-18 14:30:41 +00006920 if (!getSema())
6921 return;
6922
6923 Sema &S = *getSema();
6924 Sema::GlobalMethodPool::iterator Pos
6925 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00006926
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006927 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00006928 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006929 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00006930 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00006931
6932 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
6933 // when building a module we keep every method individually and may need to
6934 // update hasMoreThanOneDecl as we add the methods.
6935 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6936 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00006937}
6938
6939void ASTReader::ReadKnownNamespaces(
6940 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6941 Namespaces.clear();
6942
6943 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6944 if (NamespaceDecl *Namespace
6945 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6946 Namespaces.push_back(Namespace);
6947 }
6948}
6949
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006950void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00006951 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006952 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6953 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00006954 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006955 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00006956 Undefined.insert(std::make_pair(D, Loc));
6957 }
6958}
Nick Lewycky8334af82013-01-26 00:35:08 +00006959
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00006960void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
6961 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
6962 Exprs) {
6963 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
6964 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
6965 uint64_t Count = DelayedDeleteExprs[Idx++];
6966 for (uint64_t C = 0; C < Count; ++C) {
6967 SourceLocation DeleteLoc =
6968 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
6969 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
6970 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
6971 }
6972 }
6973}
6974
Guy Benyei11169dd2012-12-18 14:30:41 +00006975void ASTReader::ReadTentativeDefinitions(
6976 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6977 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6978 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6979 if (Var)
6980 TentativeDefs.push_back(Var);
6981 }
6982 TentativeDefinitions.clear();
6983}
6984
6985void ASTReader::ReadUnusedFileScopedDecls(
6986 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6987 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6988 DeclaratorDecl *D
6989 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6990 if (D)
6991 Decls.push_back(D);
6992 }
6993 UnusedFileScopedDecls.clear();
6994}
6995
6996void ASTReader::ReadDelegatingConstructors(
6997 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6998 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6999 CXXConstructorDecl *D
7000 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7001 if (D)
7002 Decls.push_back(D);
7003 }
7004 DelegatingCtorDecls.clear();
7005}
7006
7007void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7008 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7009 TypedefNameDecl *D
7010 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7011 if (D)
7012 Decls.push_back(D);
7013 }
7014 ExtVectorDecls.clear();
7015}
7016
Nico Weber72889432014-09-06 01:25:55 +00007017void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7018 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7019 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7020 ++I) {
7021 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7022 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7023 if (D)
7024 Decls.insert(D);
7025 }
7026 UnusedLocalTypedefNameCandidates.clear();
7027}
7028
Guy Benyei11169dd2012-12-18 14:30:41 +00007029void ASTReader::ReadReferencedSelectors(
7030 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7031 if (ReferencedSelectorsData.empty())
7032 return;
7033
7034 // If there are @selector references added them to its pool. This is for
7035 // implementation of -Wselector.
7036 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7037 unsigned I = 0;
7038 while (I < DataSize) {
7039 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7040 SourceLocation SelLoc
7041 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7042 Sels.push_back(std::make_pair(Sel, SelLoc));
7043 }
7044 ReferencedSelectorsData.clear();
7045}
7046
7047void ASTReader::ReadWeakUndeclaredIdentifiers(
7048 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7049 if (WeakUndeclaredIdentifiers.empty())
7050 return;
7051
7052 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7053 IdentifierInfo *WeakId
7054 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7055 IdentifierInfo *AliasId
7056 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7057 SourceLocation Loc
7058 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7059 bool Used = WeakUndeclaredIdentifiers[I++];
7060 WeakInfo WI(AliasId, Loc);
7061 WI.setUsed(Used);
7062 WeakIDs.push_back(std::make_pair(WeakId, WI));
7063 }
7064 WeakUndeclaredIdentifiers.clear();
7065}
7066
7067void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7068 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7069 ExternalVTableUse VT;
7070 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7071 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7072 VT.DefinitionRequired = VTableUses[Idx++];
7073 VTables.push_back(VT);
7074 }
7075
7076 VTableUses.clear();
7077}
7078
7079void ASTReader::ReadPendingInstantiations(
7080 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7081 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7082 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7083 SourceLocation Loc
7084 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7085
7086 Pending.push_back(std::make_pair(D, Loc));
7087 }
7088 PendingInstantiations.clear();
7089}
7090
Richard Smithe40f2ba2013-08-07 21:41:30 +00007091void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007092 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007093 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7094 /* In loop */) {
7095 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7096
7097 LateParsedTemplate *LT = new LateParsedTemplate;
7098 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7099
7100 ModuleFile *F = getOwningModuleFile(LT->D);
7101 assert(F && "No module");
7102
7103 unsigned TokN = LateParsedTemplates[Idx++];
7104 LT->Toks.reserve(TokN);
7105 for (unsigned T = 0; T < TokN; ++T)
7106 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7107
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007108 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007109 }
7110
7111 LateParsedTemplates.clear();
7112}
7113
Guy Benyei11169dd2012-12-18 14:30:41 +00007114void ASTReader::LoadSelector(Selector Sel) {
7115 // It would be complicated to avoid reading the methods anyway. So don't.
7116 ReadMethodPool(Sel);
7117}
7118
7119void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7120 assert(ID && "Non-zero identifier ID required");
7121 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7122 IdentifiersLoaded[ID - 1] = II;
7123 if (DeserializationListener)
7124 DeserializationListener->IdentifierRead(ID, II);
7125}
7126
7127/// \brief Set the globally-visible declarations associated with the given
7128/// identifier.
7129///
7130/// If the AST reader is currently in a state where the given declaration IDs
7131/// cannot safely be resolved, they are queued until it is safe to resolve
7132/// them.
7133///
7134/// \param II an IdentifierInfo that refers to one or more globally-visible
7135/// declarations.
7136///
7137/// \param DeclIDs the set of declaration IDs with the name @p II that are
7138/// visible at global scope.
7139///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007140/// \param Decls if non-null, this vector will be populated with the set of
7141/// deserialized declarations. These declarations will not be pushed into
7142/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007143void
7144ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7145 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007146 SmallVectorImpl<Decl *> *Decls) {
7147 if (NumCurrentElementsDeserializing && !Decls) {
7148 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007149 return;
7150 }
7151
7152 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007153 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007154 // Queue this declaration so that it will be added to the
7155 // translation unit scope and identifier's declaration chain
7156 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007157 PreloadedDeclIDs.push_back(DeclIDs[I]);
7158 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007159 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007160
7161 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7162
7163 // If we're simply supposed to record the declarations, do so now.
7164 if (Decls) {
7165 Decls->push_back(D);
7166 continue;
7167 }
7168
7169 // Introduce this declaration into the translation-unit scope
7170 // and add it to the declaration chain for this identifier, so
7171 // that (unqualified) name lookup will find it.
7172 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007173 }
7174}
7175
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007176IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007177 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007178 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007179
7180 if (IdentifiersLoaded.empty()) {
7181 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007182 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007183 }
7184
7185 ID -= 1;
7186 if (!IdentifiersLoaded[ID]) {
7187 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7188 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7189 ModuleFile *M = I->second;
7190 unsigned Index = ID - M->BaseIdentifierID;
7191 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7192
7193 // All of the strings in the AST file are preceded by a 16-bit length.
7194 // Extract that 16-bit length to avoid having to execute strlen().
7195 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7196 // unsigned integers. This is important to avoid integer overflow when
7197 // we cast them to 'unsigned'.
7198 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7199 unsigned StrLen = (((unsigned) StrLenPtr[0])
7200 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007201 IdentifiersLoaded[ID]
7202 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007203 if (DeserializationListener)
7204 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7205 }
7206
7207 return IdentifiersLoaded[ID];
7208}
7209
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007210IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7211 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007212}
7213
7214IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7215 if (LocalID < NUM_PREDEF_IDENT_IDS)
7216 return LocalID;
7217
7218 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7219 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7220 assert(I != M.IdentifierRemap.end()
7221 && "Invalid index into identifier index remap");
7222
7223 return LocalID + I->second;
7224}
7225
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007226MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007227 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007228 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007229
7230 if (MacrosLoaded.empty()) {
7231 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007232 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007233 }
7234
7235 ID -= NUM_PREDEF_MACRO_IDS;
7236 if (!MacrosLoaded[ID]) {
7237 GlobalMacroMapType::iterator I
7238 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7239 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7240 ModuleFile *M = I->second;
7241 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007242 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7243
7244 if (DeserializationListener)
7245 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7246 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007247 }
7248
7249 return MacrosLoaded[ID];
7250}
7251
7252MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7253 if (LocalID < NUM_PREDEF_MACRO_IDS)
7254 return LocalID;
7255
7256 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7257 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7258 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7259
7260 return LocalID + I->second;
7261}
7262
7263serialization::SubmoduleID
7264ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7265 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7266 return LocalID;
7267
7268 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7269 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7270 assert(I != M.SubmoduleRemap.end()
7271 && "Invalid index into submodule index remap");
7272
7273 return LocalID + I->second;
7274}
7275
7276Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7277 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7278 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007279 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007280 }
7281
7282 if (GlobalID > SubmodulesLoaded.size()) {
7283 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007284 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007285 }
7286
7287 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7288}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007289
7290Module *ASTReader::getModule(unsigned ID) {
7291 return getSubmodule(ID);
7292}
7293
Richard Smithd88a7f12015-09-01 20:35:42 +00007294ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7295 if (ID & 1) {
7296 // It's a module, look it up by submodule ID.
7297 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7298 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7299 } else {
7300 // It's a prefix (preamble, PCH, ...). Look it up by index.
7301 unsigned IndexFromEnd = ID >> 1;
7302 assert(IndexFromEnd && "got reference to unknown module file");
7303 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7304 }
7305}
7306
7307unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7308 if (!F)
7309 return 1;
7310
7311 // For a file representing a module, use the submodule ID of the top-level
7312 // module as the file ID. For any other kind of file, the number of such
7313 // files loaded beforehand will be the same on reload.
7314 // FIXME: Is this true even if we have an explicit module file and a PCH?
7315 if (F->isModule())
7316 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7317
7318 auto PCHModules = getModuleManager().pch_modules();
7319 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7320 assert(I != PCHModules.end() && "emitting reference to unknown file");
7321 return (I - PCHModules.end()) << 1;
7322}
7323
Adrian Prantl15bcf702015-06-30 17:39:43 +00007324ExternalASTSource::ASTSourceDescriptor
7325ASTReader::getSourceDescriptor(const Module &M) {
7326 StringRef Dir, Filename;
7327 if (M.Directory)
7328 Dir = M.Directory->getName();
7329 if (auto *File = M.getASTFile())
7330 Filename = File->getName();
7331 return ASTReader::ASTSourceDescriptor{
7332 M.getFullModuleName(), Dir, Filename,
7333 M.Signature
7334 };
7335}
7336
7337llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7338ASTReader::getSourceDescriptor(unsigned ID) {
7339 if (const Module *M = getSubmodule(ID))
7340 return getSourceDescriptor(*M);
7341
7342 // If there is only a single PCH, return it instead.
7343 // Chained PCH are not suported.
7344 if (ModuleMgr.size() == 1) {
7345 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7346 return ASTReader::ASTSourceDescriptor{
7347 MF.OriginalSourceFileName, MF.OriginalDir,
7348 MF.FileName,
7349 MF.Signature
7350 };
7351 }
7352 return None;
7353}
7354
Guy Benyei11169dd2012-12-18 14:30:41 +00007355Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7356 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7357}
7358
7359Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7360 if (ID == 0)
7361 return Selector();
7362
7363 if (ID > SelectorsLoaded.size()) {
7364 Error("selector ID out of range in AST file");
7365 return Selector();
7366 }
7367
Craig Toppera13603a2014-05-22 05:54:18 +00007368 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007369 // Load this selector from the selector table.
7370 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7371 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7372 ModuleFile &M = *I->second;
7373 ASTSelectorLookupTrait Trait(*this, M);
7374 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7375 SelectorsLoaded[ID - 1] =
7376 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7377 if (DeserializationListener)
7378 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7379 }
7380
7381 return SelectorsLoaded[ID - 1];
7382}
7383
7384Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7385 return DecodeSelector(ID);
7386}
7387
7388uint32_t ASTReader::GetNumExternalSelectors() {
7389 // ID 0 (the null selector) is considered an external selector.
7390 return getTotalNumSelectors() + 1;
7391}
7392
7393serialization::SelectorID
7394ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7395 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7396 return LocalID;
7397
7398 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7399 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7400 assert(I != M.SelectorRemap.end()
7401 && "Invalid index into selector index remap");
7402
7403 return LocalID + I->second;
7404}
7405
7406DeclarationName
7407ASTReader::ReadDeclarationName(ModuleFile &F,
7408 const RecordData &Record, unsigned &Idx) {
7409 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7410 switch (Kind) {
7411 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007412 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007413
7414 case DeclarationName::ObjCZeroArgSelector:
7415 case DeclarationName::ObjCOneArgSelector:
7416 case DeclarationName::ObjCMultiArgSelector:
7417 return DeclarationName(ReadSelector(F, Record, Idx));
7418
7419 case DeclarationName::CXXConstructorName:
7420 return Context.DeclarationNames.getCXXConstructorName(
7421 Context.getCanonicalType(readType(F, Record, Idx)));
7422
7423 case DeclarationName::CXXDestructorName:
7424 return Context.DeclarationNames.getCXXDestructorName(
7425 Context.getCanonicalType(readType(F, Record, Idx)));
7426
7427 case DeclarationName::CXXConversionFunctionName:
7428 return Context.DeclarationNames.getCXXConversionFunctionName(
7429 Context.getCanonicalType(readType(F, Record, Idx)));
7430
7431 case DeclarationName::CXXOperatorName:
7432 return Context.DeclarationNames.getCXXOperatorName(
7433 (OverloadedOperatorKind)Record[Idx++]);
7434
7435 case DeclarationName::CXXLiteralOperatorName:
7436 return Context.DeclarationNames.getCXXLiteralOperatorName(
7437 GetIdentifierInfo(F, Record, Idx));
7438
7439 case DeclarationName::CXXUsingDirective:
7440 return DeclarationName::getUsingDirectiveName();
7441 }
7442
7443 llvm_unreachable("Invalid NameKind!");
7444}
7445
7446void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7447 DeclarationNameLoc &DNLoc,
7448 DeclarationName Name,
7449 const RecordData &Record, unsigned &Idx) {
7450 switch (Name.getNameKind()) {
7451 case DeclarationName::CXXConstructorName:
7452 case DeclarationName::CXXDestructorName:
7453 case DeclarationName::CXXConversionFunctionName:
7454 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7455 break;
7456
7457 case DeclarationName::CXXOperatorName:
7458 DNLoc.CXXOperatorName.BeginOpNameLoc
7459 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7460 DNLoc.CXXOperatorName.EndOpNameLoc
7461 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7462 break;
7463
7464 case DeclarationName::CXXLiteralOperatorName:
7465 DNLoc.CXXLiteralOperatorName.OpNameLoc
7466 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7467 break;
7468
7469 case DeclarationName::Identifier:
7470 case DeclarationName::ObjCZeroArgSelector:
7471 case DeclarationName::ObjCOneArgSelector:
7472 case DeclarationName::ObjCMultiArgSelector:
7473 case DeclarationName::CXXUsingDirective:
7474 break;
7475 }
7476}
7477
7478void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7479 DeclarationNameInfo &NameInfo,
7480 const RecordData &Record, unsigned &Idx) {
7481 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7482 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7483 DeclarationNameLoc DNLoc;
7484 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7485 NameInfo.setInfo(DNLoc);
7486}
7487
7488void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7489 const RecordData &Record, unsigned &Idx) {
7490 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7491 unsigned NumTPLists = Record[Idx++];
7492 Info.NumTemplParamLists = NumTPLists;
7493 if (NumTPLists) {
7494 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7495 for (unsigned i=0; i != NumTPLists; ++i)
7496 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7497 }
7498}
7499
7500TemplateName
7501ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7502 unsigned &Idx) {
7503 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7504 switch (Kind) {
7505 case TemplateName::Template:
7506 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7507
7508 case TemplateName::OverloadedTemplate: {
7509 unsigned size = Record[Idx++];
7510 UnresolvedSet<8> Decls;
7511 while (size--)
7512 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7513
7514 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7515 }
7516
7517 case TemplateName::QualifiedTemplate: {
7518 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7519 bool hasTemplKeyword = Record[Idx++];
7520 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7521 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7522 }
7523
7524 case TemplateName::DependentTemplate: {
7525 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7526 if (Record[Idx++]) // isIdentifier
7527 return Context.getDependentTemplateName(NNS,
7528 GetIdentifierInfo(F, Record,
7529 Idx));
7530 return Context.getDependentTemplateName(NNS,
7531 (OverloadedOperatorKind)Record[Idx++]);
7532 }
7533
7534 case TemplateName::SubstTemplateTemplateParm: {
7535 TemplateTemplateParmDecl *param
7536 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7537 if (!param) return TemplateName();
7538 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7539 return Context.getSubstTemplateTemplateParm(param, replacement);
7540 }
7541
7542 case TemplateName::SubstTemplateTemplateParmPack: {
7543 TemplateTemplateParmDecl *Param
7544 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7545 if (!Param)
7546 return TemplateName();
7547
7548 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7549 if (ArgPack.getKind() != TemplateArgument::Pack)
7550 return TemplateName();
7551
7552 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7553 }
7554 }
7555
7556 llvm_unreachable("Unhandled template name kind!");
7557}
7558
Richard Smith2bb3c342015-08-09 01:05:31 +00007559TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7560 const RecordData &Record,
7561 unsigned &Idx,
7562 bool Canonicalize) {
7563 if (Canonicalize) {
7564 // The caller wants a canonical template argument. Sometimes the AST only
7565 // wants template arguments in canonical form (particularly as the template
7566 // argument lists of template specializations) so ensure we preserve that
7567 // canonical form across serialization.
7568 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7569 return Context.getCanonicalTemplateArgument(Arg);
7570 }
7571
Guy Benyei11169dd2012-12-18 14:30:41 +00007572 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7573 switch (Kind) {
7574 case TemplateArgument::Null:
7575 return TemplateArgument();
7576 case TemplateArgument::Type:
7577 return TemplateArgument(readType(F, Record, Idx));
7578 case TemplateArgument::Declaration: {
7579 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007580 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007581 }
7582 case TemplateArgument::NullPtr:
7583 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7584 case TemplateArgument::Integral: {
7585 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7586 QualType T = readType(F, Record, Idx);
7587 return TemplateArgument(Context, Value, T);
7588 }
7589 case TemplateArgument::Template:
7590 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7591 case TemplateArgument::TemplateExpansion: {
7592 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007593 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007594 if (unsigned NumExpansions = Record[Idx++])
7595 NumTemplateExpansions = NumExpansions - 1;
7596 return TemplateArgument(Name, NumTemplateExpansions);
7597 }
7598 case TemplateArgument::Expression:
7599 return TemplateArgument(ReadExpr(F));
7600 case TemplateArgument::Pack: {
7601 unsigned NumArgs = Record[Idx++];
7602 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7603 for (unsigned I = 0; I != NumArgs; ++I)
7604 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007605 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007606 }
7607 }
7608
7609 llvm_unreachable("Unhandled template argument kind!");
7610}
7611
7612TemplateParameterList *
7613ASTReader::ReadTemplateParameterList(ModuleFile &F,
7614 const RecordData &Record, unsigned &Idx) {
7615 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7616 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7617 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7618
7619 unsigned NumParams = Record[Idx++];
7620 SmallVector<NamedDecl *, 16> Params;
7621 Params.reserve(NumParams);
7622 while (NumParams--)
7623 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7624
7625 TemplateParameterList* TemplateParams =
7626 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7627 Params.data(), Params.size(), RAngleLoc);
7628 return TemplateParams;
7629}
7630
7631void
7632ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007633ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007634 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007635 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007636 unsigned NumTemplateArgs = Record[Idx++];
7637 TemplArgs.reserve(NumTemplateArgs);
7638 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007639 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007640}
7641
7642/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007643void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007644 const RecordData &Record, unsigned &Idx) {
7645 unsigned NumDecls = Record[Idx++];
7646 Set.reserve(Context, NumDecls);
7647 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007648 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007649 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007650 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007651 }
7652}
7653
7654CXXBaseSpecifier
7655ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7656 const RecordData &Record, unsigned &Idx) {
7657 bool isVirtual = static_cast<bool>(Record[Idx++]);
7658 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7659 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7660 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7661 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7662 SourceRange Range = ReadSourceRange(F, Record, Idx);
7663 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7664 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7665 EllipsisLoc);
7666 Result.setInheritConstructors(inheritConstructors);
7667 return Result;
7668}
7669
Richard Smithc2bb8182015-03-24 06:36:48 +00007670CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007671ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7672 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007673 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007674 assert(NumInitializers && "wrote ctor initializers but have no inits");
7675 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7676 for (unsigned i = 0; i != NumInitializers; ++i) {
7677 TypeSourceInfo *TInfo = nullptr;
7678 bool IsBaseVirtual = false;
7679 FieldDecl *Member = nullptr;
7680 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007681
Richard Smithc2bb8182015-03-24 06:36:48 +00007682 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7683 switch (Type) {
7684 case CTOR_INITIALIZER_BASE:
7685 TInfo = GetTypeSourceInfo(F, Record, Idx);
7686 IsBaseVirtual = Record[Idx++];
7687 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007688
Richard Smithc2bb8182015-03-24 06:36:48 +00007689 case CTOR_INITIALIZER_DELEGATING:
7690 TInfo = GetTypeSourceInfo(F, Record, Idx);
7691 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007692
Richard Smithc2bb8182015-03-24 06:36:48 +00007693 case CTOR_INITIALIZER_MEMBER:
7694 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7695 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007696
Richard Smithc2bb8182015-03-24 06:36:48 +00007697 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7698 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7699 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007700 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007701
7702 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7703 Expr *Init = ReadExpr(F);
7704 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7705 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7706 bool IsWritten = Record[Idx++];
7707 unsigned SourceOrderOrNumArrayIndices;
7708 SmallVector<VarDecl *, 8> Indices;
7709 if (IsWritten) {
7710 SourceOrderOrNumArrayIndices = Record[Idx++];
7711 } else {
7712 SourceOrderOrNumArrayIndices = Record[Idx++];
7713 Indices.reserve(SourceOrderOrNumArrayIndices);
7714 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7715 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7716 }
7717
7718 CXXCtorInitializer *BOMInit;
7719 if (Type == CTOR_INITIALIZER_BASE) {
7720 BOMInit = new (Context)
7721 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7722 RParenLoc, MemberOrEllipsisLoc);
7723 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7724 BOMInit = new (Context)
7725 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7726 } else if (IsWritten) {
7727 if (Member)
7728 BOMInit = new (Context) CXXCtorInitializer(
7729 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7730 else
7731 BOMInit = new (Context)
7732 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7733 LParenLoc, Init, RParenLoc);
7734 } else {
7735 if (IndirectMember) {
7736 assert(Indices.empty() && "Indirect field improperly initialized");
7737 BOMInit = new (Context)
7738 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7739 LParenLoc, Init, RParenLoc);
7740 } else {
7741 BOMInit = CXXCtorInitializer::Create(
7742 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7743 Indices.data(), Indices.size());
7744 }
7745 }
7746
7747 if (IsWritten)
7748 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7749 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007750 }
7751
Richard Smithc2bb8182015-03-24 06:36:48 +00007752 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007753}
7754
7755NestedNameSpecifier *
7756ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7757 const RecordData &Record, unsigned &Idx) {
7758 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007759 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007760 for (unsigned I = 0; I != N; ++I) {
7761 NestedNameSpecifier::SpecifierKind Kind
7762 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7763 switch (Kind) {
7764 case NestedNameSpecifier::Identifier: {
7765 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7766 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7767 break;
7768 }
7769
7770 case NestedNameSpecifier::Namespace: {
7771 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7772 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7773 break;
7774 }
7775
7776 case NestedNameSpecifier::NamespaceAlias: {
7777 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7778 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7779 break;
7780 }
7781
7782 case NestedNameSpecifier::TypeSpec:
7783 case NestedNameSpecifier::TypeSpecWithTemplate: {
7784 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7785 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007786 return nullptr;
7787
Guy Benyei11169dd2012-12-18 14:30:41 +00007788 bool Template = Record[Idx++];
7789 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7790 break;
7791 }
7792
7793 case NestedNameSpecifier::Global: {
7794 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7795 // No associated value, and there can't be a prefix.
7796 break;
7797 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007798
7799 case NestedNameSpecifier::Super: {
7800 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7801 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7802 break;
7803 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007804 }
7805 Prev = NNS;
7806 }
7807 return NNS;
7808}
7809
7810NestedNameSpecifierLoc
7811ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7812 unsigned &Idx) {
7813 unsigned N = Record[Idx++];
7814 NestedNameSpecifierLocBuilder Builder;
7815 for (unsigned I = 0; I != N; ++I) {
7816 NestedNameSpecifier::SpecifierKind Kind
7817 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7818 switch (Kind) {
7819 case NestedNameSpecifier::Identifier: {
7820 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7821 SourceRange Range = ReadSourceRange(F, Record, Idx);
7822 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7823 break;
7824 }
7825
7826 case NestedNameSpecifier::Namespace: {
7827 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7828 SourceRange Range = ReadSourceRange(F, Record, Idx);
7829 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7830 break;
7831 }
7832
7833 case NestedNameSpecifier::NamespaceAlias: {
7834 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7835 SourceRange Range = ReadSourceRange(F, Record, Idx);
7836 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7837 break;
7838 }
7839
7840 case NestedNameSpecifier::TypeSpec:
7841 case NestedNameSpecifier::TypeSpecWithTemplate: {
7842 bool Template = Record[Idx++];
7843 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7844 if (!T)
7845 return NestedNameSpecifierLoc();
7846 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7847
7848 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7849 Builder.Extend(Context,
7850 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7851 T->getTypeLoc(), ColonColonLoc);
7852 break;
7853 }
7854
7855 case NestedNameSpecifier::Global: {
7856 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7857 Builder.MakeGlobal(Context, ColonColonLoc);
7858 break;
7859 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007860
7861 case NestedNameSpecifier::Super: {
7862 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7863 SourceRange Range = ReadSourceRange(F, Record, Idx);
7864 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7865 break;
7866 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007867 }
7868 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007869
Guy Benyei11169dd2012-12-18 14:30:41 +00007870 return Builder.getWithLocInContext(Context);
7871}
7872
7873SourceRange
7874ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7875 unsigned &Idx) {
7876 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7877 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7878 return SourceRange(beg, end);
7879}
7880
7881/// \brief Read an integral value
7882llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7883 unsigned BitWidth = Record[Idx++];
7884 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7885 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7886 Idx += NumWords;
7887 return Result;
7888}
7889
7890/// \brief Read a signed integral value
7891llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7892 bool isUnsigned = Record[Idx++];
7893 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7894}
7895
7896/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007897llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7898 const llvm::fltSemantics &Sem,
7899 unsigned &Idx) {
7900 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007901}
7902
7903// \brief Read a string
7904std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7905 unsigned Len = Record[Idx++];
7906 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7907 Idx += Len;
7908 return Result;
7909}
7910
Richard Smith7ed1bc92014-12-05 22:42:13 +00007911std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7912 unsigned &Idx) {
7913 std::string Filename = ReadString(Record, Idx);
7914 ResolveImportedPath(F, Filename);
7915 return Filename;
7916}
7917
Guy Benyei11169dd2012-12-18 14:30:41 +00007918VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7919 unsigned &Idx) {
7920 unsigned Major = Record[Idx++];
7921 unsigned Minor = Record[Idx++];
7922 unsigned Subminor = Record[Idx++];
7923 if (Minor == 0)
7924 return VersionTuple(Major);
7925 if (Subminor == 0)
7926 return VersionTuple(Major, Minor - 1);
7927 return VersionTuple(Major, Minor - 1, Subminor - 1);
7928}
7929
7930CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7931 const RecordData &Record,
7932 unsigned &Idx) {
7933 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7934 return CXXTemporary::Create(Context, Decl);
7935}
7936
7937DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007938 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007939}
7940
7941DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7942 return Diags.Report(Loc, DiagID);
7943}
7944
7945/// \brief Retrieve the identifier table associated with the
7946/// preprocessor.
7947IdentifierTable &ASTReader::getIdentifierTable() {
7948 return PP.getIdentifierTable();
7949}
7950
7951/// \brief Record that the given ID maps to the given switch-case
7952/// statement.
7953void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007954 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007955 "Already have a SwitchCase with this ID");
7956 (*CurrSwitchCaseStmts)[ID] = SC;
7957}
7958
7959/// \brief Retrieve the switch-case statement with the given ID.
7960SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007961 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00007962 return (*CurrSwitchCaseStmts)[ID];
7963}
7964
7965void ASTReader::ClearSwitchCaseIDs() {
7966 CurrSwitchCaseStmts->clear();
7967}
7968
7969void ASTReader::ReadComments() {
7970 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007971 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007972 serialization::ModuleFile *> >::iterator
7973 I = CommentsCursors.begin(),
7974 E = CommentsCursors.end();
7975 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007976 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007977 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007978 serialization::ModuleFile &F = *I->second;
7979 SavedStreamPosition SavedPosition(Cursor);
7980
7981 RecordData Record;
7982 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007983 llvm::BitstreamEntry Entry =
7984 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007985
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007986 switch (Entry.Kind) {
7987 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7988 case llvm::BitstreamEntry::Error:
7989 Error("malformed block record in AST file");
7990 return;
7991 case llvm::BitstreamEntry::EndBlock:
7992 goto NextCursor;
7993 case llvm::BitstreamEntry::Record:
7994 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007995 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007996 }
7997
7998 // Read a record.
7999 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008000 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008001 case COMMENTS_RAW_COMMENT: {
8002 unsigned Idx = 0;
8003 SourceRange SR = ReadSourceRange(F, Record, Idx);
8004 RawComment::CommentKind Kind =
8005 (RawComment::CommentKind) Record[Idx++];
8006 bool IsTrailingComment = Record[Idx++];
8007 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008008 Comments.push_back(new (Context) RawComment(
8009 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8010 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008011 break;
8012 }
8013 }
8014 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008015 NextCursor:
8016 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008017 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008018}
8019
Richard Smithcd45dbc2014-04-19 03:48:30 +00008020std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8021 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008022 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008023 return M->getFullModuleName();
8024
8025 // Otherwise, use the name of the top-level module the decl is within.
8026 if (ModuleFile *M = getOwningModuleFile(D))
8027 return M->ModuleName;
8028
8029 // Not from a module.
8030 return "";
8031}
8032
Guy Benyei11169dd2012-12-18 14:30:41 +00008033void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008034 while (!PendingIdentifierInfos.empty() ||
8035 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008036 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008037 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008038 // If any identifiers with corresponding top-level declarations have
8039 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008040 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8041 TopLevelDeclsMap;
8042 TopLevelDeclsMap TopLevelDecls;
8043
Guy Benyei11169dd2012-12-18 14:30:41 +00008044 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008045 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008046 SmallVector<uint32_t, 4> DeclIDs =
8047 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008048 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008049
8050 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008051 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008052
Richard Smith851072e2014-05-19 20:59:20 +00008053 // For each decl chain that we wanted to complete while deserializing, mark
8054 // it as "still needs to be completed".
8055 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8056 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8057 }
8058 PendingIncompleteDeclChains.clear();
8059
Guy Benyei11169dd2012-12-18 14:30:41 +00008060 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008061 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008062 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008063 PendingDeclChains.clear();
8064
Douglas Gregor6168bd22013-02-18 15:53:43 +00008065 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008066 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8067 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008068 IdentifierInfo *II = TLD->first;
8069 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008070 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008071 }
8072 }
8073
Guy Benyei11169dd2012-12-18 14:30:41 +00008074 // Load any pending macro definitions.
8075 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008076 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8077 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8078 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8079 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008080 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008081 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008082 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008083 if (Info.M->Kind != MK_ImplicitModule &&
8084 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008085 resolvePendingMacro(II, Info);
8086 }
8087 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008088 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008089 ++IDIdx) {
8090 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008091 if (Info.M->Kind == MK_ImplicitModule ||
8092 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008093 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008094 }
8095 }
8096 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008097
8098 // Wire up the DeclContexts for Decls that we delayed setting until
8099 // recursive loading is completed.
8100 while (!PendingDeclContextInfos.empty()) {
8101 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8102 PendingDeclContextInfos.pop_front();
8103 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8104 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8105 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8106 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008107
Richard Smithd1c46742014-04-30 02:24:17 +00008108 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008109 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008110 auto Update = PendingUpdateRecords.pop_back_val();
8111 ReadingKindTracker ReadingKind(Read_Decl, *this);
8112 loadDeclUpdateRecords(Update.first, Update.second);
8113 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008114 }
Richard Smith8a639892015-01-24 01:07:20 +00008115
8116 // At this point, all update records for loaded decls are in place, so any
8117 // fake class definitions should have become real.
8118 assert(PendingFakeDefinitionData.empty() &&
8119 "faked up a class definition but never saw the real one");
8120
Guy Benyei11169dd2012-12-18 14:30:41 +00008121 // If we deserialized any C++ or Objective-C class definitions, any
8122 // Objective-C protocol definitions, or any redeclarable templates, make sure
8123 // that all redeclarations point to the definitions. Note that this can only
8124 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008125 for (Decl *D : PendingDefinitions) {
8126 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008127 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008128 // Make sure that the TagType points at the definition.
8129 const_cast<TagType*>(TagT)->decl = TD;
8130 }
Richard Smith8ce51082015-03-11 01:44:51 +00008131
Craig Topperc6914d02014-08-25 04:15:02 +00008132 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008133 for (auto *R = getMostRecentExistingDecl(RD); R;
8134 R = R->getPreviousDecl()) {
8135 assert((R == D) ==
8136 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008137 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008138 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008139 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008140 }
8141
8142 continue;
8143 }
Richard Smith8ce51082015-03-11 01:44:51 +00008144
Craig Topperc6914d02014-08-25 04:15:02 +00008145 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008146 // Make sure that the ObjCInterfaceType points at the definition.
8147 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8148 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008149
8150 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8151 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8152
Guy Benyei11169dd2012-12-18 14:30:41 +00008153 continue;
8154 }
Richard Smith8ce51082015-03-11 01:44:51 +00008155
Craig Topperc6914d02014-08-25 04:15:02 +00008156 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008157 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8158 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8159
Guy Benyei11169dd2012-12-18 14:30:41 +00008160 continue;
8161 }
Richard Smith8ce51082015-03-11 01:44:51 +00008162
Craig Topperc6914d02014-08-25 04:15:02 +00008163 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008164 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8165 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008166 }
8167 PendingDefinitions.clear();
8168
8169 // Load the bodies of any functions or methods we've encountered. We do
8170 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008171 // have been fully wired up (hasBody relies on this).
8172 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008173 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8174 PBEnd = PendingBodies.end();
8175 PB != PBEnd; ++PB) {
8176 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8177 // FIXME: Check for =delete/=default?
8178 // FIXME: Complain about ODR violations here?
8179 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8180 FD->setLazyBody(PB->second);
8181 continue;
8182 }
8183
8184 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8185 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8186 MD->setLazyBody(PB->second);
8187 }
8188 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008189
8190 // Do some cleanup.
8191 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8192 getContext().deduplicateMergedDefinitonsFor(ND);
8193 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008194}
8195
8196void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008197 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8198 return;
8199
Richard Smitha0ce9c42014-07-29 23:23:27 +00008200 // Trigger the import of the full definition of each class that had any
8201 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008202 // These updates may in turn find and diagnose some ODR failures, so take
8203 // ownership of the set first.
8204 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8205 PendingOdrMergeFailures.clear();
8206 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008207 Merge.first->buildLookup();
8208 Merge.first->decls_begin();
8209 Merge.first->bases_begin();
8210 Merge.first->vbases_begin();
8211 for (auto *RD : Merge.second) {
8212 RD->decls_begin();
8213 RD->bases_begin();
8214 RD->vbases_begin();
8215 }
8216 }
8217
8218 // For each declaration from a merged context, check that the canonical
8219 // definition of that context also contains a declaration of the same
8220 // entity.
8221 //
8222 // Caution: this loop does things that might invalidate iterators into
8223 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8224 while (!PendingOdrMergeChecks.empty()) {
8225 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8226
8227 // FIXME: Skip over implicit declarations for now. This matters for things
8228 // like implicitly-declared special member functions. This isn't entirely
8229 // correct; we can end up with multiple unmerged declarations of the same
8230 // implicit entity.
8231 if (D->isImplicit())
8232 continue;
8233
8234 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008235
8236 bool Found = false;
8237 const Decl *DCanon = D->getCanonicalDecl();
8238
Richard Smith01bdb7a2014-08-28 05:44:07 +00008239 for (auto RI : D->redecls()) {
8240 if (RI->getLexicalDeclContext() == CanonDef) {
8241 Found = true;
8242 break;
8243 }
8244 }
8245 if (Found)
8246 continue;
8247
Richard Smith0f4e2c42015-08-06 04:23:48 +00008248 // Quick check failed, time to do the slow thing. Note, we can't just
8249 // look up the name of D in CanonDef here, because the member that is
8250 // in CanonDef might not be found by name lookup (it might have been
8251 // replaced by a more recent declaration in the lookup table), and we
8252 // can't necessarily find it in the redeclaration chain because it might
8253 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008254 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008255 for (auto *CanonMember : CanonDef->decls()) {
8256 if (CanonMember->getCanonicalDecl() == DCanon) {
8257 // This can happen if the declaration is merely mergeable and not
8258 // actually redeclarable (we looked for redeclarations earlier).
8259 //
8260 // FIXME: We should be able to detect this more efficiently, without
8261 // pulling in all of the members of CanonDef.
8262 Found = true;
8263 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008264 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008265 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8266 if (ND->getDeclName() == D->getDeclName())
8267 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008268 }
8269
8270 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008271 // The AST doesn't like TagDecls becoming invalid after they've been
8272 // completed. We only really need to mark FieldDecls as invalid here.
8273 if (!isa<TagDecl>(D))
8274 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008275
8276 // Ensure we don't accidentally recursively enter deserialization while
8277 // we're producing our diagnostic.
8278 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008279
8280 std::string CanonDefModule =
8281 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8282 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8283 << D << getOwningModuleNameForDiagnostic(D)
8284 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8285
8286 if (Candidates.empty())
8287 Diag(cast<Decl>(CanonDef)->getLocation(),
8288 diag::note_module_odr_violation_no_possible_decls) << D;
8289 else {
8290 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8291 Diag(Candidates[I]->getLocation(),
8292 diag::note_module_odr_violation_possible_decl)
8293 << Candidates[I];
8294 }
8295
8296 DiagnosedOdrMergeFailures.insert(CanonDef);
8297 }
8298 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008299
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008300 if (OdrMergeFailures.empty())
8301 return;
8302
8303 // Ensure we don't accidentally recursively enter deserialization while
8304 // we're producing our diagnostics.
8305 Deserializing RecursionGuard(this);
8306
Richard Smithcd45dbc2014-04-19 03:48:30 +00008307 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008308 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008309 // If we've already pointed out a specific problem with this class, don't
8310 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008311 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008312 continue;
8313
8314 bool Diagnosed = false;
8315 for (auto *RD : Merge.second) {
8316 // Multiple different declarations got merged together; tell the user
8317 // where they came from.
8318 if (Merge.first != RD) {
8319 // FIXME: Walk the definition, figure out what's different,
8320 // and diagnose that.
8321 if (!Diagnosed) {
8322 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8323 Diag(Merge.first->getLocation(),
8324 diag::err_module_odr_violation_different_definitions)
8325 << Merge.first << Module.empty() << Module;
8326 Diagnosed = true;
8327 }
8328
8329 Diag(RD->getLocation(),
8330 diag::note_module_odr_violation_different_definitions)
8331 << getOwningModuleNameForDiagnostic(RD);
8332 }
8333 }
8334
8335 if (!Diagnosed) {
8336 // All definitions are updates to the same declaration. This happens if a
8337 // module instantiates the declaration of a class template specialization
8338 // and two or more other modules instantiate its definition.
8339 //
8340 // FIXME: Indicate which modules had instantiations of this definition.
8341 // FIXME: How can this even happen?
8342 Diag(Merge.first->getLocation(),
8343 diag::err_module_odr_violation_different_instantiations)
8344 << Merge.first;
8345 }
8346 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008347}
8348
Richard Smithce18a182015-07-14 00:26:00 +00008349void ASTReader::StartedDeserializing() {
8350 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8351 ReadTimer->startTimer();
8352}
8353
Guy Benyei11169dd2012-12-18 14:30:41 +00008354void ASTReader::FinishedDeserializing() {
8355 assert(NumCurrentElementsDeserializing &&
8356 "FinishedDeserializing not paired with StartedDeserializing");
8357 if (NumCurrentElementsDeserializing == 1) {
8358 // We decrease NumCurrentElementsDeserializing only after pending actions
8359 // are finished, to avoid recursively re-calling finishPendingActions().
8360 finishPendingActions();
8361 }
8362 --NumCurrentElementsDeserializing;
8363
Richard Smitha0ce9c42014-07-29 23:23:27 +00008364 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008365 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008366 while (!PendingExceptionSpecUpdates.empty()) {
8367 auto Updates = std::move(PendingExceptionSpecUpdates);
8368 PendingExceptionSpecUpdates.clear();
8369 for (auto Update : Updates) {
8370 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008371 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00008372 if (auto *Listener = Context.getASTMutationListener())
8373 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00008374 for (auto *Redecl : Update.second->redecls())
8375 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008376 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008377 }
8378
Richard Smithce18a182015-07-14 00:26:00 +00008379 if (ReadTimer)
8380 ReadTimer->stopTimer();
8381
Richard Smith0f4e2c42015-08-06 04:23:48 +00008382 diagnoseOdrViolations();
8383
Richard Smith04d05b52014-03-23 00:27:18 +00008384 // We are not in recursive loading, so it's safe to pass the "interesting"
8385 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008386 if (Consumer)
8387 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008388 }
8389}
8390
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008391void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008392 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8393 // Remove any fake results before adding any real ones.
8394 auto It = PendingFakeLookupResults.find(II);
8395 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008396 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008397 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008398 // FIXME: this works around module+PCH performance issue.
8399 // Rather than erase the result from the map, which is O(n), just clear
8400 // the vector of NamedDecls.
8401 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008402 }
8403 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008404
8405 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8406 SemaObj->TUScope->AddDecl(D);
8407 } else if (SemaObj->TUScope) {
8408 // Adding the decl to IdResolver may have failed because it was already in
8409 // (even though it was not added in scope). If it is already in, make sure
8410 // it gets in the scope as well.
8411 if (std::find(SemaObj->IdResolver.begin(Name),
8412 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8413 SemaObj->TUScope->AddDecl(D);
8414 }
8415}
8416
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008417ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008418 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008419 StringRef isysroot, bool DisableValidation,
8420 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008421 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Richard Smithce18a182015-07-14 00:26:00 +00008422 bool UseGlobalIndex,
8423 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008424 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008425 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008426 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008427 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008428 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008429 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008430 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008431 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8432 AllowConfigurationMismatch(AllowConfigurationMismatch),
8433 ValidateSystemInputs(ValidateSystemInputs),
8434 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008435 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8436 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8437 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8438 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008439 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8440 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8441 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8442 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8443 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8444 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008445 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008446 SourceMgr.setExternalSLocEntrySource(this);
8447}
8448
8449ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008450 if (OwnsDeserializationListener)
8451 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008452}