blob: c54f659f09f697caeb29b65eb93270b212974636 [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
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000167ASTReaderListener::~ASTReaderListener() {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000168
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();
Ben Langmuirb9ad4e62015-10-28 22:25:37 +0000783 bool IsModule = Reader.PP.getCurrentModule() != nullptr;
784 if (isInterestingIdentifier(Reader, *II, IsModule))
Richard Smith76c2f2c2015-07-17 20:09:43 +0000785 II->setChangedSinceDeserialization();
786 }
787 Reader.markIdentifierUpToDate(II);
788
Guy Benyei11169dd2012-12-18 14:30:41 +0000789 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
790 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000791 // For uninteresting identifiers, there's nothing else to do. Just notify
792 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000793 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000794 return II;
795 }
796
Justin Bogner57ba0b22014-03-28 22:03:24 +0000797 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
798 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000799 bool CPlusPlusOperatorKeyword = readBit(Bits);
800 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000801 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000802 bool Poisoned = readBit(Bits);
803 bool ExtensionToken = readBit(Bits);
804 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000805
806 assert(Bits == 0 && "Extra bits in the identifier?");
807 DataLen -= 8;
808
Guy Benyei11169dd2012-12-18 14:30:41 +0000809 // Set or check the various bits in the IdentifierInfo structure.
810 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000811 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000812 II->revertTokenIDToIdentifier();
813 if (!F.isModule())
814 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
815 else if (HasRevertedBuiltin && II->getBuiltinID()) {
816 II->revertBuiltin();
817 assert((II->hasRevertedBuiltin() ||
818 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
819 "Incorrect ObjC keyword or builtin ID");
820 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000821 assert(II->isExtensionToken() == ExtensionToken &&
822 "Incorrect extension token flag");
823 (void)ExtensionToken;
824 if (Poisoned)
825 II->setIsPoisoned(true);
826 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
827 "Incorrect C++ operator keyword flag");
828 (void)CPlusPlusOperatorKeyword;
829
830 // If this identifier is a macro, deserialize the macro
831 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000832 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000833 uint32_t MacroDirectivesOffset =
834 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000835 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000836
Richard Smithd7329392015-04-21 21:46:32 +0000837 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000838 }
839
840 Reader.SetIdentifierInfo(ID, II);
841
842 // Read all of the declarations visible at global scope with this
843 // name.
844 if (DataLen > 0) {
845 SmallVector<uint32_t, 4> DeclIDs;
846 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000847 DeclIDs.push_back(Reader.getGlobalDeclID(
848 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000849 Reader.SetGloballyVisibleDecls(II, DeclIDs);
850 }
851
852 return II;
853}
854
Richard Smitha06c7e62015-08-26 23:55:49 +0000855DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
856 : Kind(Name.getNameKind()) {
857 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000858 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000859 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000860 break;
861 case DeclarationName::ObjCZeroArgSelector:
862 case DeclarationName::ObjCOneArgSelector:
863 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000864 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000865 break;
866 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000867 Data = Name.getCXXOverloadedOperator();
868 break;
869 case DeclarationName::CXXLiteralOperatorName:
870 Data = (uint64_t)Name.getCXXLiteralIdentifier();
871 break;
872 case DeclarationName::CXXConstructorName:
873 case DeclarationName::CXXDestructorName:
874 case DeclarationName::CXXConversionFunctionName:
875 case DeclarationName::CXXUsingDirective:
876 Data = 0;
877 break;
878 }
879}
880
881unsigned DeclarationNameKey::getHash() const {
882 llvm::FoldingSetNodeID ID;
883 ID.AddInteger(Kind);
884
885 switch (Kind) {
886 case DeclarationName::Identifier:
887 case DeclarationName::CXXLiteralOperatorName:
888 ID.AddString(((IdentifierInfo*)Data)->getName());
889 break;
890 case DeclarationName::ObjCZeroArgSelector:
891 case DeclarationName::ObjCOneArgSelector:
892 case DeclarationName::ObjCMultiArgSelector:
893 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
894 break;
895 case DeclarationName::CXXOperatorName:
896 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000897 break;
898 case DeclarationName::CXXConstructorName:
899 case DeclarationName::CXXDestructorName:
900 case DeclarationName::CXXConversionFunctionName:
901 case DeclarationName::CXXUsingDirective:
902 break;
903 }
904
905 return ID.ComputeHash();
906}
907
Richard Smithd88a7f12015-09-01 20:35:42 +0000908ModuleFile *
909ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
910 using namespace llvm::support;
911 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
912 return Reader.getLocalModuleFile(F, ModuleFileID);
913}
914
Guy Benyei11169dd2012-12-18 14:30:41 +0000915std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000916ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000917 using namespace llvm::support;
918 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
919 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000920 return std::make_pair(KeyLen, DataLen);
921}
922
Richard Smitha06c7e62015-08-26 23:55:49 +0000923ASTDeclContextNameLookupTrait::internal_key_type
924ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000925 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000926
Richard Smitha06c7e62015-08-26 23:55:49 +0000927 auto Kind = (DeclarationName::NameKind)*d++;
928 uint64_t Data;
929 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000930 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000931 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000932 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000933 break;
934 case DeclarationName::ObjCZeroArgSelector:
935 case DeclarationName::ObjCOneArgSelector:
936 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000937 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000938 (uint64_t)Reader.getLocalSelector(
939 F, endian::readNext<uint32_t, little, unaligned>(
940 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000941 break;
942 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000943 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +0000944 break;
945 case DeclarationName::CXXLiteralOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000946 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000947 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000948 break;
949 case DeclarationName::CXXConstructorName:
950 case DeclarationName::CXXDestructorName:
951 case DeclarationName::CXXConversionFunctionName:
952 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +0000953 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000954 break;
955 }
956
Richard Smitha06c7e62015-08-26 23:55:49 +0000957 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000958}
959
Richard Smithd88a7f12015-09-01 20:35:42 +0000960void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
961 const unsigned char *d,
962 unsigned DataLen,
963 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000964 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +0000965 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
966 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
967 Val.insert(Reader.getGlobalDeclID(F, LocalID));
968 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000969}
970
Richard Smith0f4e2c42015-08-06 04:23:48 +0000971bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
972 BitstreamCursor &Cursor,
973 uint64_t Offset,
974 DeclContext *DC) {
975 assert(Offset != 0);
976
Guy Benyei11169dd2012-12-18 14:30:41 +0000977 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +0000978 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000979
Richard Smith0f4e2c42015-08-06 04:23:48 +0000980 RecordData Record;
981 StringRef Blob;
982 unsigned Code = Cursor.ReadCode();
983 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
984 if (RecCode != DECL_CONTEXT_LEXICAL) {
985 Error("Expected lexical block");
986 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000987 }
988
Richard Smith82f8fcd2015-08-06 22:07:25 +0000989 assert(!isa<TranslationUnitDecl>(DC) &&
990 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +0000991 // If we are handling a C++ class template instantiation, we can see multiple
992 // lexical updates for the same record. It's important that we select only one
993 // of them, so that field numbering works properly. Just pick the first one we
994 // see.
995 auto &Lex = LexicalDecls[DC];
996 if (!Lex.first) {
997 Lex = std::make_pair(
998 &M, llvm::makeArrayRef(
999 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1000 Blob.data()),
1001 Blob.size() / 4));
1002 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001003 DC->setHasExternalLexicalStorage(true);
1004 return false;
1005}
Guy Benyei11169dd2012-12-18 14:30:41 +00001006
Richard Smith0f4e2c42015-08-06 04:23:48 +00001007bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1008 BitstreamCursor &Cursor,
1009 uint64_t Offset,
1010 DeclID ID) {
1011 assert(Offset != 0);
1012
1013 SavedStreamPosition SavedPosition(Cursor);
1014 Cursor.JumpToBit(Offset);
1015
1016 RecordData Record;
1017 StringRef Blob;
1018 unsigned Code = Cursor.ReadCode();
1019 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1020 if (RecCode != DECL_CONTEXT_VISIBLE) {
1021 Error("Expected visible lookup table block");
1022 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 }
1024
Richard Smith0f4e2c42015-08-06 04:23:48 +00001025 // We can't safely determine the primary context yet, so delay attaching the
1026 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001027 auto *Data = (const unsigned char*)Blob.data();
1028 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001029 return false;
1030}
1031
1032void ASTReader::Error(StringRef Msg) {
1033 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001034 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1035 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001036 Diag(diag::note_module_cache_path)
1037 << PP.getHeaderSearchInfo().getModuleCachePath();
1038 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001039}
1040
1041void ASTReader::Error(unsigned DiagID,
1042 StringRef Arg1, StringRef Arg2) {
1043 if (Diags.isDiagnosticInFlight())
1044 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1045 else
1046 Diag(DiagID) << Arg1 << Arg2;
1047}
1048
1049//===----------------------------------------------------------------------===//
1050// Source Manager Deserialization
1051//===----------------------------------------------------------------------===//
1052
1053/// \brief Read the line table in the source manager block.
1054/// \returns true if there was an error.
1055bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001056 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001057 unsigned Idx = 0;
1058 LineTableInfo &LineTable = SourceMgr.getLineTable();
1059
1060 // Parse the file names
1061 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001062 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001063 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001064 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001065 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1066 }
Richard Smith63078492015-09-01 07:41:55 +00001067 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001068
1069 // Parse the line entries
1070 std::vector<LineEntry> Entries;
1071 while (Idx < Record.size()) {
1072 int FID = Record[Idx++];
1073 assert(FID >= 0 && "Serialized line entries for non-local file.");
1074 // Remap FileID from 1-based old view.
1075 FID += F.SLocEntryBaseID - 1;
1076
1077 // Extract the line entries
1078 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001079 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001080 Entries.clear();
1081 Entries.reserve(NumEntries);
1082 for (unsigned I = 0; I != NumEntries; ++I) {
1083 unsigned FileOffset = Record[Idx++];
1084 unsigned LineNo = Record[Idx++];
1085 int FilenameID = FileIDs[Record[Idx++]];
1086 SrcMgr::CharacteristicKind FileKind
1087 = (SrcMgr::CharacteristicKind)Record[Idx++];
1088 unsigned IncludeOffset = Record[Idx++];
1089 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1090 FileKind, IncludeOffset));
1091 }
1092 LineTable.AddEntry(FileID::get(FID), Entries);
1093 }
1094
1095 return false;
1096}
1097
1098/// \brief Read a source manager block
1099bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1100 using namespace SrcMgr;
1101
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001102 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001103
1104 // Set the source-location entry cursor to the current position in
1105 // the stream. This cursor will be used to read the contents of the
1106 // source manager block initially, and then lazily read
1107 // source-location entries as needed.
1108 SLocEntryCursor = F.Stream;
1109
1110 // The stream itself is going to skip over the source manager block.
1111 if (F.Stream.SkipBlock()) {
1112 Error("malformed block record in AST file");
1113 return true;
1114 }
1115
1116 // Enter the source manager block.
1117 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1118 Error("malformed source manager block record in AST file");
1119 return true;
1120 }
1121
1122 RecordData Record;
1123 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001124 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1125
1126 switch (E.Kind) {
1127 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1128 case llvm::BitstreamEntry::Error:
1129 Error("malformed block record in AST file");
1130 return true;
1131 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001132 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001133 case llvm::BitstreamEntry::Record:
1134 // The interesting case.
1135 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001136 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001137
Guy Benyei11169dd2012-12-18 14:30:41 +00001138 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001139 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001140 StringRef Blob;
1141 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001142 default: // Default behavior: ignore.
1143 break;
1144
1145 case SM_SLOC_FILE_ENTRY:
1146 case SM_SLOC_BUFFER_ENTRY:
1147 case SM_SLOC_EXPANSION_ENTRY:
1148 // Once we hit one of the source location entries, we're done.
1149 return false;
1150 }
1151 }
1152}
1153
1154/// \brief If a header file is not found at the path that we expect it to be
1155/// and the PCH file was moved from its original location, try to resolve the
1156/// file by assuming that header+PCH were moved together and the header is in
1157/// the same place relative to the PCH.
1158static std::string
1159resolveFileRelativeToOriginalDir(const std::string &Filename,
1160 const std::string &OriginalDir,
1161 const std::string &CurrDir) {
1162 assert(OriginalDir != CurrDir &&
1163 "No point trying to resolve the file if the PCH dir didn't change");
1164 using namespace llvm::sys;
1165 SmallString<128> filePath(Filename);
1166 fs::make_absolute(filePath);
1167 assert(path::is_absolute(OriginalDir));
1168 SmallString<128> currPCHPath(CurrDir);
1169
1170 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1171 fileDirE = path::end(path::parent_path(filePath));
1172 path::const_iterator origDirI = path::begin(OriginalDir),
1173 origDirE = path::end(OriginalDir);
1174 // Skip the common path components from filePath and OriginalDir.
1175 while (fileDirI != fileDirE && origDirI != origDirE &&
1176 *fileDirI == *origDirI) {
1177 ++fileDirI;
1178 ++origDirI;
1179 }
1180 for (; origDirI != origDirE; ++origDirI)
1181 path::append(currPCHPath, "..");
1182 path::append(currPCHPath, fileDirI, fileDirE);
1183 path::append(currPCHPath, path::filename(Filename));
1184 return currPCHPath.str();
1185}
1186
1187bool ASTReader::ReadSLocEntry(int ID) {
1188 if (ID == 0)
1189 return false;
1190
1191 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1192 Error("source location entry ID out-of-range for AST file");
1193 return true;
1194 }
1195
1196 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1197 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001198 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001199 unsigned BaseOffset = F->SLocEntryBaseOffset;
1200
1201 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001202 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1203 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001204 Error("incorrectly-formatted source location entry in AST file");
1205 return true;
1206 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001207
Guy Benyei11169dd2012-12-18 14:30:41 +00001208 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001209 StringRef Blob;
1210 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001211 default:
1212 Error("incorrectly-formatted source location entry in AST file");
1213 return true;
1214
1215 case SM_SLOC_FILE_ENTRY: {
1216 // We will detect whether a file changed and return 'Failure' for it, but
1217 // we will also try to fail gracefully by setting up the SLocEntry.
1218 unsigned InputID = Record[4];
1219 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001220 const FileEntry *File = IF.getFile();
1221 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001222
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001223 // Note that we only check if a File was returned. If it was out-of-date
1224 // we have complained but we will continue creating a FileID to recover
1225 // gracefully.
1226 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001227 return true;
1228
1229 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1230 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1231 // This is the module's main file.
1232 IncludeLoc = getImportLocation(F);
1233 }
1234 SrcMgr::CharacteristicKind
1235 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1236 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1237 ID, BaseOffset + Record[0]);
1238 SrcMgr::FileInfo &FileInfo =
1239 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1240 FileInfo.NumCreatedFIDs = Record[5];
1241 if (Record[3])
1242 FileInfo.setHasLineDirectives();
1243
1244 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1245 unsigned NumFileDecls = Record[7];
1246 if (NumFileDecls) {
1247 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1248 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1249 NumFileDecls));
1250 }
1251
1252 const SrcMgr::ContentCache *ContentCache
1253 = SourceMgr.getOrCreateContentCache(File,
1254 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1255 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1256 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1257 unsigned Code = SLocEntryCursor.ReadCode();
1258 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001259 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001260
1261 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1262 Error("AST record has invalid code");
1263 return true;
1264 }
1265
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001266 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001267 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001268 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001269 }
1270
1271 break;
1272 }
1273
1274 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001275 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001276 unsigned Offset = Record[0];
1277 SrcMgr::CharacteristicKind
1278 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1279 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001280 if (IncludeLoc.isInvalid() &&
1281 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001282 IncludeLoc = getImportLocation(F);
1283 }
1284 unsigned Code = SLocEntryCursor.ReadCode();
1285 Record.clear();
1286 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001287 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001288
1289 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1290 Error("AST record has invalid code");
1291 return true;
1292 }
1293
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001294 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1295 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001296 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001297 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001298 break;
1299 }
1300
1301 case SM_SLOC_EXPANSION_ENTRY: {
1302 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1303 SourceMgr.createExpansionLoc(SpellingLoc,
1304 ReadSourceLocation(*F, Record[2]),
1305 ReadSourceLocation(*F, Record[3]),
1306 Record[4],
1307 ID,
1308 BaseOffset + Record[0]);
1309 break;
1310 }
1311 }
1312
1313 return false;
1314}
1315
1316std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1317 if (ID == 0)
1318 return std::make_pair(SourceLocation(), "");
1319
1320 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1321 Error("source location entry ID out-of-range for AST file");
1322 return std::make_pair(SourceLocation(), "");
1323 }
1324
1325 // Find which module file this entry lands in.
1326 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001327 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001328 return std::make_pair(SourceLocation(), "");
1329
1330 // FIXME: Can we map this down to a particular submodule? That would be
1331 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001332 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001333}
1334
1335/// \brief Find the location where the module F is imported.
1336SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1337 if (F->ImportLoc.isValid())
1338 return F->ImportLoc;
1339
1340 // Otherwise we have a PCH. It's considered to be "imported" at the first
1341 // location of its includer.
1342 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001343 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001344 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001345 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001346 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001347 return F->ImportedBy[0]->FirstLoc;
1348}
1349
1350/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1351/// specified cursor. Read the abbreviations that are at the top of the block
1352/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001353bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001354 if (Cursor.EnterSubBlock(BlockID))
1355 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001356
1357 while (true) {
1358 uint64_t Offset = Cursor.GetCurrentBitNo();
1359 unsigned Code = Cursor.ReadCode();
1360
1361 // We expect all abbrevs to be at the start of the block.
1362 if (Code != llvm::bitc::DEFINE_ABBREV) {
1363 Cursor.JumpToBit(Offset);
1364 return false;
1365 }
1366 Cursor.ReadAbbrevRecord();
1367 }
1368}
1369
Richard Smithe40f2ba2013-08-07 21:41:30 +00001370Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001371 unsigned &Idx) {
1372 Token Tok;
1373 Tok.startToken();
1374 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1375 Tok.setLength(Record[Idx++]);
1376 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1377 Tok.setIdentifierInfo(II);
1378 Tok.setKind((tok::TokenKind)Record[Idx++]);
1379 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1380 return Tok;
1381}
1382
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001383MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001384 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001385
1386 // Keep track of where we are in the stream, then jump back there
1387 // after reading this macro.
1388 SavedStreamPosition SavedPosition(Stream);
1389
1390 Stream.JumpToBit(Offset);
1391 RecordData Record;
1392 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001393 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001394
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001396 // Advance to the next record, but if we get to the end of the block, don't
1397 // pop it (removing all the abbreviations from the cursor) since we want to
1398 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001399 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001400 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1401
1402 switch (Entry.Kind) {
1403 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1404 case llvm::BitstreamEntry::Error:
1405 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001406 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001407 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001408 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001409 case llvm::BitstreamEntry::Record:
1410 // The interesting case.
1411 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001412 }
1413
1414 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001415 Record.clear();
1416 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001417 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001418 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001419 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001420 case PP_MACRO_DIRECTIVE_HISTORY:
1421 return Macro;
1422
Guy Benyei11169dd2012-12-18 14:30:41 +00001423 case PP_MACRO_OBJECT_LIKE:
1424 case PP_MACRO_FUNCTION_LIKE: {
1425 // If we already have a macro, that means that we've hit the end
1426 // of the definition of the macro we were looking for. We're
1427 // done.
1428 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001429 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001430
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001431 unsigned NextIndex = 1; // Skip identifier ID.
1432 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001433 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001434 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001435 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001436 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001437 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001438
Guy Benyei11169dd2012-12-18 14:30:41 +00001439 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1440 // Decode function-like macro info.
1441 bool isC99VarArgs = Record[NextIndex++];
1442 bool isGNUVarArgs = Record[NextIndex++];
1443 bool hasCommaPasting = Record[NextIndex++];
1444 MacroArgs.clear();
1445 unsigned NumArgs = Record[NextIndex++];
1446 for (unsigned i = 0; i != NumArgs; ++i)
1447 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1448
1449 // Install function-like macro info.
1450 MI->setIsFunctionLike();
1451 if (isC99VarArgs) MI->setIsC99Varargs();
1452 if (isGNUVarArgs) MI->setIsGNUVarargs();
1453 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001454 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001455 }
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;
Richard Smith68142212015-10-13 01:26:26 +00001951 ErrorStr += "' referenced by AST file '";
1952 ErrorStr += F.FileName;
1953 ErrorStr += "'";
Ben Langmuir198c1682014-03-07 07:27:49 +00001954 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001955 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001956 // Record that we didn't find the file.
1957 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1958 return InputFile();
1959 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001960
Ben Langmuir198c1682014-03-07 07:27:49 +00001961 // Check if there was a request to override the contents of the file
1962 // that was part of the precompiled header. Overridding such a file
1963 // can lead to problems when lexing using the source locations from the
1964 // PCH.
1965 SourceManager &SM = getSourceManager();
1966 if (!Overridden && SM.isFileOverridden(File)) {
1967 if (Complain)
1968 Error(diag::err_fe_pch_file_overridden, Filename);
1969 // After emitting the diagnostic, recover by disabling the override so
1970 // that the original file will be used.
1971 SM.disableFileContentsOverride(File);
1972 // The FileEntry is a virtual file entry with the size of the contents
1973 // that would override the original contents. Set it to the original's
1974 // size/time.
1975 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1976 StoredSize, StoredTime);
1977 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001978
Ben Langmuir198c1682014-03-07 07:27:49 +00001979 bool IsOutOfDate = false;
1980
1981 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001982 if (!Overridden && //
1983 (StoredSize != File->getSize() ||
1984#if defined(LLVM_ON_WIN32)
1985 false
1986#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001987 // In our regression testing, the Windows file system seems to
1988 // have inconsistent modification times that sometimes
1989 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001990 //
Richard Smithe75ee0f2015-08-17 07:13:32 +00001991 // FIXME: This probably also breaks HeaderFileInfo lookups on Windows.
1992 (StoredTime && StoredTime != File->getModificationTime() &&
1993 !DisableValidation)
Guy Benyei11169dd2012-12-18 14:30:41 +00001994#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001995 )) {
1996 if (Complain) {
1997 // Build a list of the PCH imports that got us here (in reverse).
1998 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1999 while (ImportStack.back()->ImportedBy.size() > 0)
2000 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002001
Ben Langmuir198c1682014-03-07 07:27:49 +00002002 // The top-level PCH is stale.
2003 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2004 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002005
Ben Langmuir198c1682014-03-07 07:27:49 +00002006 // Print the import stack.
2007 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2008 Diag(diag::note_pch_required_by)
2009 << Filename << ImportStack[0]->FileName;
2010 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002011 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002012 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002013 }
2014
Ben Langmuir198c1682014-03-07 07:27:49 +00002015 if (!Diags.isDiagnosticInFlight())
2016 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002017 }
2018
Ben Langmuir198c1682014-03-07 07:27:49 +00002019 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002020 }
2021
Ben Langmuir198c1682014-03-07 07:27:49 +00002022 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2023
2024 // Note that we've loaded this input file.
2025 F.InputFilesLoaded[ID-1] = IF;
2026 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002027}
2028
Richard Smith7ed1bc92014-12-05 22:42:13 +00002029/// \brief If we are loading a relocatable PCH or module file, and the filename
2030/// is not an absolute path, add the system or module root to the beginning of
2031/// the file name.
2032void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2033 // Resolve relative to the base directory, if we have one.
2034 if (!M.BaseDirectory.empty())
2035 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002036}
2037
Richard Smith7ed1bc92014-12-05 22:42:13 +00002038void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002039 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2040 return;
2041
Richard Smith7ed1bc92014-12-05 22:42:13 +00002042 SmallString<128> Buffer;
2043 llvm::sys::path::append(Buffer, Prefix, Filename);
2044 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002045}
2046
Richard Smith0f99d6a2015-08-09 08:48:41 +00002047static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2048 switch (ARR) {
2049 case ASTReader::Failure: return true;
2050 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2051 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2052 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2053 case ASTReader::ConfigurationMismatch:
2054 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2055 case ASTReader::HadErrors: return true;
2056 case ASTReader::Success: return false;
2057 }
2058
2059 llvm_unreachable("unknown ASTReadResult");
2060}
2061
Richard Smith0516b182015-09-08 19:40:14 +00002062ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2063 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2064 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2065 std::string &SuggestedPredefines) {
2066 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2067 return Failure;
2068
2069 // Read all of the records in the options block.
2070 RecordData Record;
2071 ASTReadResult Result = Success;
2072 while (1) {
2073 llvm::BitstreamEntry Entry = Stream.advance();
2074
2075 switch (Entry.Kind) {
2076 case llvm::BitstreamEntry::Error:
2077 case llvm::BitstreamEntry::SubBlock:
2078 return Failure;
2079
2080 case llvm::BitstreamEntry::EndBlock:
2081 return Result;
2082
2083 case llvm::BitstreamEntry::Record:
2084 // The interesting case.
2085 break;
2086 }
2087
2088 // Read and process a record.
2089 Record.clear();
2090 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2091 case LANGUAGE_OPTIONS: {
2092 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2093 if (ParseLanguageOptions(Record, Complain, Listener,
2094 AllowCompatibleConfigurationMismatch))
2095 Result = ConfigurationMismatch;
2096 break;
2097 }
2098
2099 case TARGET_OPTIONS: {
2100 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2101 if (ParseTargetOptions(Record, Complain, Listener,
2102 AllowCompatibleConfigurationMismatch))
2103 Result = ConfigurationMismatch;
2104 break;
2105 }
2106
2107 case DIAGNOSTIC_OPTIONS: {
2108 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2109 if (!AllowCompatibleConfigurationMismatch &&
2110 ParseDiagnosticOptions(Record, Complain, Listener))
2111 return OutOfDate;
2112 break;
2113 }
2114
2115 case FILE_SYSTEM_OPTIONS: {
2116 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2117 if (!AllowCompatibleConfigurationMismatch &&
2118 ParseFileSystemOptions(Record, Complain, Listener))
2119 Result = ConfigurationMismatch;
2120 break;
2121 }
2122
2123 case HEADER_SEARCH_OPTIONS: {
2124 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2125 if (!AllowCompatibleConfigurationMismatch &&
2126 ParseHeaderSearchOptions(Record, Complain, Listener))
2127 Result = ConfigurationMismatch;
2128 break;
2129 }
2130
2131 case PREPROCESSOR_OPTIONS:
2132 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2133 if (!AllowCompatibleConfigurationMismatch &&
2134 ParsePreprocessorOptions(Record, Complain, Listener,
2135 SuggestedPredefines))
2136 Result = ConfigurationMismatch;
2137 break;
2138 }
2139 }
2140}
2141
Guy Benyei11169dd2012-12-18 14:30:41 +00002142ASTReader::ASTReadResult
2143ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002144 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002145 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002146 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002147 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002148
2149 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2150 Error("malformed block record in AST file");
2151 return Failure;
2152 }
2153
2154 // Read all of the records and blocks in the control block.
2155 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002156 unsigned NumInputs = 0;
2157 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002158 while (1) {
2159 llvm::BitstreamEntry Entry = Stream.advance();
2160
2161 switch (Entry.Kind) {
2162 case llvm::BitstreamEntry::Error:
2163 Error("malformed block record in AST file");
2164 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002165 case llvm::BitstreamEntry::EndBlock: {
2166 // Validate input files.
2167 const HeaderSearchOptions &HSOpts =
2168 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002169
Richard Smitha1825302014-10-23 22:18:29 +00002170 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002171 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2172 // loaded module files, ignore missing inputs.
2173 if (!DisableValidation && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002174 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002175
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002176 // If we are reading a module, we will create a verification timestamp,
2177 // so we verify all input files. Otherwise, verify only user input
2178 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002179
2180 unsigned N = NumUserInputs;
2181 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002182 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002183 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002184 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002185 N = NumInputs;
2186
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002187 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002188 InputFile IF = getInputFile(F, I+1, Complain);
2189 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002190 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002191 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002192 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002193
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002194 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002195 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002196
Ben Langmuircb69b572014-03-07 06:40:32 +00002197 if (Listener && Listener->needsInputFileVisitation()) {
2198 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2199 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002200 for (unsigned I = 0; I < N; ++I) {
2201 bool IsSystem = I >= NumUserInputs;
2202 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002203 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2204 F.Kind == MK_ExplicitModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002205 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002206 }
2207
Guy Benyei11169dd2012-12-18 14:30:41 +00002208 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002209 }
2210
Chris Lattnere7b154b2013-01-19 21:39:22 +00002211 case llvm::BitstreamEntry::SubBlock:
2212 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002213 case INPUT_FILES_BLOCK_ID:
2214 F.InputFilesCursor = Stream;
2215 if (Stream.SkipBlock() || // Skip with the main cursor
2216 // Read the abbreviations
2217 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2218 Error("malformed block record in AST file");
2219 return Failure;
2220 }
2221 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002222
2223 case OPTIONS_BLOCK_ID:
2224 // If we're reading the first module for this group, check its options
2225 // are compatible with ours. For modules it imports, no further checking
2226 // is required, because we checked them when we built it.
2227 if (Listener && !ImportedBy) {
2228 // Should we allow the configuration of the module file to differ from
2229 // the configuration of the current translation unit in a compatible
2230 // way?
2231 //
2232 // FIXME: Allow this for files explicitly specified with -include-pch.
2233 bool AllowCompatibleConfigurationMismatch =
2234 F.Kind == MK_ExplicitModule;
2235
2236 auto Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2237 AllowCompatibleConfigurationMismatch,
2238 *Listener, SuggestedPredefines);
2239 if (Result == Failure) {
2240 Error("malformed block record in AST file");
2241 return Result;
2242 }
2243
2244 if (!DisableValidation && Result != Success &&
2245 (Result != ConfigurationMismatch || !AllowConfigurationMismatch))
2246 return Result;
2247 } else if (Stream.SkipBlock()) {
2248 Error("malformed block record in AST file");
2249 return Failure;
2250 }
2251 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002252
Guy Benyei11169dd2012-12-18 14:30:41 +00002253 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002254 if (Stream.SkipBlock()) {
2255 Error("malformed block record in AST file");
2256 return Failure;
2257 }
2258 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002259 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002260
2261 case llvm::BitstreamEntry::Record:
2262 // The interesting case.
2263 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002264 }
2265
2266 // Read and process a record.
2267 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002268 StringRef Blob;
2269 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002270 case METADATA: {
2271 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2272 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002273 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2274 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002275 return VersionMismatch;
2276 }
2277
Richard Smithe75ee0f2015-08-17 07:13:32 +00002278 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002279 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2280 Diag(diag::err_pch_with_compiler_errors);
2281 return HadErrors;
2282 }
2283
2284 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002285 // Relative paths in a relocatable PCH are relative to our sysroot.
2286 if (F.RelocatablePCH)
2287 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002288
Richard Smithe75ee0f2015-08-17 07:13:32 +00002289 F.HasTimestamps = Record[5];
2290
Guy Benyei11169dd2012-12-18 14:30:41 +00002291 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002292 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002293 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2294 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002295 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002296 return VersionMismatch;
2297 }
2298 break;
2299 }
2300
Ben Langmuir487ea142014-10-23 18:05:36 +00002301 case SIGNATURE:
2302 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2303 F.Signature = Record[0];
2304 break;
2305
Guy Benyei11169dd2012-12-18 14:30:41 +00002306 case IMPORTS: {
2307 // Load each of the imported PCH files.
2308 unsigned Idx = 0, N = Record.size();
2309 while (Idx < N) {
2310 // Read information about the AST file.
2311 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2312 // The import location will be the local one for now; we will adjust
2313 // all import locations of module imports after the global source
2314 // location info are setup.
2315 SourceLocation ImportLoc =
2316 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002317 off_t StoredSize = (off_t)Record[Idx++];
2318 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002319 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002320 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002321
Richard Smith0f99d6a2015-08-09 08:48:41 +00002322 // If our client can't cope with us being out of date, we can't cope with
2323 // our dependency being missing.
2324 unsigned Capabilities = ClientLoadCapabilities;
2325 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2326 Capabilities &= ~ARR_Missing;
2327
Guy Benyei11169dd2012-12-18 14:30:41 +00002328 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002329 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2330 Loaded, StoredSize, StoredModTime,
2331 StoredSignature, Capabilities);
2332
2333 // If we diagnosed a problem, produce a backtrace.
2334 if (isDiagnosedResult(Result, Capabilities))
2335 Diag(diag::note_module_file_imported_by)
2336 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2337
2338 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002339 case Failure: return Failure;
2340 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002341 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002342 case OutOfDate: return OutOfDate;
2343 case VersionMismatch: return VersionMismatch;
2344 case ConfigurationMismatch: return ConfigurationMismatch;
2345 case HadErrors: return HadErrors;
2346 case Success: break;
2347 }
2348 }
2349 break;
2350 }
2351
Guy Benyei11169dd2012-12-18 14:30:41 +00002352 case ORIGINAL_FILE:
2353 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002354 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002355 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002356 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002357 break;
2358
2359 case ORIGINAL_FILE_ID:
2360 F.OriginalSourceFileID = FileID::get(Record[0]);
2361 break;
2362
2363 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002364 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002365 break;
2366
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002367 case MODULE_NAME:
2368 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002369 if (Listener)
2370 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002371 break;
2372
Richard Smith223d3f22014-12-06 03:21:08 +00002373 case MODULE_DIRECTORY: {
2374 assert(!F.ModuleName.empty() &&
2375 "MODULE_DIRECTORY found before MODULE_NAME");
2376 // If we've already loaded a module map file covering this module, we may
2377 // have a better path for it (relative to the current build).
2378 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2379 if (M && M->Directory) {
2380 // If we're implicitly loading a module, the base directory can't
2381 // change between the build and use.
2382 if (F.Kind != MK_ExplicitModule) {
2383 const DirectoryEntry *BuildDir =
2384 PP.getFileManager().getDirectory(Blob);
2385 if (!BuildDir || BuildDir != M->Directory) {
2386 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2387 Diag(diag::err_imported_module_relocated)
2388 << F.ModuleName << Blob << M->Directory->getName();
2389 return OutOfDate;
2390 }
2391 }
2392 F.BaseDirectory = M->Directory->getName();
2393 } else {
2394 F.BaseDirectory = Blob;
2395 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002396 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002397 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002398
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002399 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002400 if (ASTReadResult Result =
2401 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2402 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002403 break;
2404
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002405 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002406 NumInputs = Record[0];
2407 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002408 F.InputFileOffsets =
2409 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002410 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 break;
2412 }
2413 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002414}
2415
Ben Langmuir2c9af442014-04-10 17:57:43 +00002416ASTReader::ASTReadResult
2417ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002418 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002419
2420 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2421 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002422 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002423 }
2424
2425 // Read all of the records and blocks for the AST file.
2426 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002427 while (1) {
2428 llvm::BitstreamEntry Entry = Stream.advance();
2429
2430 switch (Entry.Kind) {
2431 case llvm::BitstreamEntry::Error:
2432 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002433 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002434 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002435 // Outside of C++, we do not store a lookup map for the translation unit.
2436 // Instead, mark it as needing a lookup map to be built if this module
2437 // contains any declarations lexically within it (which it always does!).
2438 // This usually has no cost, since we very rarely need the lookup map for
2439 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002440 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002441 if (DC->hasExternalLexicalStorage() &&
2442 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002443 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002444
Ben Langmuir2c9af442014-04-10 17:57:43 +00002445 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002446 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002447 case llvm::BitstreamEntry::SubBlock:
2448 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002449 case DECLTYPES_BLOCK_ID:
2450 // We lazily load the decls block, but we want to set up the
2451 // DeclsCursor cursor to point into it. Clone our current bitcode
2452 // cursor to it, enter the block and read the abbrevs in that block.
2453 // With the main cursor, we just skip over it.
2454 F.DeclsCursor = Stream;
2455 if (Stream.SkipBlock() || // Skip with the main cursor.
2456 // Read the abbrevs.
2457 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2458 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002459 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002460 }
2461 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002462
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 case PREPROCESSOR_BLOCK_ID:
2464 F.MacroCursor = Stream;
2465 if (!PP.getExternalSource())
2466 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002467
Guy Benyei11169dd2012-12-18 14:30:41 +00002468 if (Stream.SkipBlock() ||
2469 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2470 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002471 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 }
2473 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2474 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002475
Guy Benyei11169dd2012-12-18 14:30:41 +00002476 case PREPROCESSOR_DETAIL_BLOCK_ID:
2477 F.PreprocessorDetailCursor = Stream;
2478 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002479 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002481 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002482 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002483 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002484 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002485 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2486
Guy Benyei11169dd2012-12-18 14:30:41 +00002487 if (!PP.getPreprocessingRecord())
2488 PP.createPreprocessingRecord();
2489 if (!PP.getPreprocessingRecord()->getExternalSource())
2490 PP.getPreprocessingRecord()->SetExternalSource(*this);
2491 break;
2492
2493 case SOURCE_MANAGER_BLOCK_ID:
2494 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002495 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002497
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002499 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2500 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002502
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002504 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002505 if (Stream.SkipBlock() ||
2506 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2507 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002508 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 }
2510 CommentsCursors.push_back(std::make_pair(C, &F));
2511 break;
2512 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002513
Guy Benyei11169dd2012-12-18 14:30:41 +00002514 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002515 if (Stream.SkipBlock()) {
2516 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002517 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002518 }
2519 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002520 }
2521 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002522
2523 case llvm::BitstreamEntry::Record:
2524 // The interesting case.
2525 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 }
2527
2528 // Read and process a record.
2529 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002530 StringRef Blob;
2531 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 default: // Default behavior: ignore.
2533 break;
2534
2535 case TYPE_OFFSET: {
2536 if (F.LocalNumTypes != 0) {
2537 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002538 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002540 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002541 F.LocalNumTypes = Record[0];
2542 unsigned LocalBaseTypeIndex = Record[1];
2543 F.BaseTypeIndex = getTotalNumTypes();
2544
2545 if (F.LocalNumTypes > 0) {
2546 // Introduce the global -> local mapping for types within this module.
2547 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2548
2549 // Introduce the local -> global mapping for types within this module.
2550 F.TypeRemap.insertOrReplace(
2551 std::make_pair(LocalBaseTypeIndex,
2552 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002553
2554 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 }
2556 break;
2557 }
2558
2559 case DECL_OFFSET: {
2560 if (F.LocalNumDecls != 0) {
2561 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002562 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002563 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002564 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 F.LocalNumDecls = Record[0];
2566 unsigned LocalBaseDeclID = Record[1];
2567 F.BaseDeclID = getTotalNumDecls();
2568
2569 if (F.LocalNumDecls > 0) {
2570 // Introduce the global -> local mapping for declarations within this
2571 // module.
2572 GlobalDeclMap.insert(
2573 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2574
2575 // Introduce the local -> global mapping for declarations within this
2576 // module.
2577 F.DeclRemap.insertOrReplace(
2578 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2579
2580 // Introduce the global -> local mapping for declarations within this
2581 // module.
2582 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002583
Ben Langmuir52ca6782014-10-20 16:27:32 +00002584 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2585 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 break;
2587 }
2588
2589 case TU_UPDATE_LEXICAL: {
2590 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002591 LexicalContents Contents(
2592 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2593 Blob.data()),
2594 static_cast<unsigned int>(Blob.size() / 4));
2595 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002596 TU->setHasExternalLexicalStorage(true);
2597 break;
2598 }
2599
2600 case UPDATE_VISIBLE: {
2601 unsigned Idx = 0;
2602 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002603 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002604 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002605 // If we've already loaded the decl, perform the updates when we finish
2606 // loading this block.
2607 if (Decl *D = GetExistingDecl(ID))
2608 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 break;
2610 }
2611
2612 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002613 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002615 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2616 (const unsigned char *)F.IdentifierTableData + Record[0],
2617 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2618 (const unsigned char *)F.IdentifierTableData,
2619 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002620
2621 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2622 }
2623 break;
2624
2625 case IDENTIFIER_OFFSET: {
2626 if (F.LocalNumIdentifiers != 0) {
2627 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002628 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002629 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002630 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 F.LocalNumIdentifiers = Record[0];
2632 unsigned LocalBaseIdentifierID = Record[1];
2633 F.BaseIdentifierID = getTotalNumIdentifiers();
2634
2635 if (F.LocalNumIdentifiers > 0) {
2636 // Introduce the global -> local mapping for identifiers within this
2637 // module.
2638 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2639 &F));
2640
2641 // Introduce the local -> global mapping for identifiers within this
2642 // module.
2643 F.IdentifierRemap.insertOrReplace(
2644 std::make_pair(LocalBaseIdentifierID,
2645 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002646
Ben Langmuir52ca6782014-10-20 16:27:32 +00002647 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2648 + F.LocalNumIdentifiers);
2649 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002650 break;
2651 }
2652
Richard Smith33e0f7e2015-07-22 02:08:40 +00002653 case INTERESTING_IDENTIFIERS:
2654 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2655 break;
2656
Ben Langmuir332aafe2014-01-31 01:06:56 +00002657 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002658 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2659 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002661 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002662 break;
2663
2664 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002665 if (SpecialTypes.empty()) {
2666 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2667 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2668 break;
2669 }
2670
2671 if (SpecialTypes.size() != Record.size()) {
2672 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002673 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002674 }
2675
2676 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2677 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2678 if (!SpecialTypes[I])
2679 SpecialTypes[I] = ID;
2680 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2681 // merge step?
2682 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002683 break;
2684
2685 case STATISTICS:
2686 TotalNumStatements += Record[0];
2687 TotalNumMacros += Record[1];
2688 TotalLexicalDeclContexts += Record[2];
2689 TotalVisibleDeclContexts += Record[3];
2690 break;
2691
2692 case UNUSED_FILESCOPED_DECLS:
2693 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2694 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2695 break;
2696
2697 case DELEGATING_CTORS:
2698 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2699 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2700 break;
2701
2702 case WEAK_UNDECLARED_IDENTIFIERS:
2703 if (Record.size() % 4 != 0) {
2704 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002705 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002706 }
2707
2708 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2709 // files. This isn't the way to do it :)
2710 WeakUndeclaredIdentifiers.clear();
2711
2712 // Translate the weak, undeclared identifiers into global IDs.
2713 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2714 WeakUndeclaredIdentifiers.push_back(
2715 getGlobalIdentifierID(F, Record[I++]));
2716 WeakUndeclaredIdentifiers.push_back(
2717 getGlobalIdentifierID(F, Record[I++]));
2718 WeakUndeclaredIdentifiers.push_back(
2719 ReadSourceLocation(F, Record, I).getRawEncoding());
2720 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2721 }
2722 break;
2723
Guy Benyei11169dd2012-12-18 14:30:41 +00002724 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002725 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002726 F.LocalNumSelectors = Record[0];
2727 unsigned LocalBaseSelectorID = Record[1];
2728 F.BaseSelectorID = getTotalNumSelectors();
2729
2730 if (F.LocalNumSelectors > 0) {
2731 // Introduce the global -> local mapping for selectors within this
2732 // module.
2733 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2734
2735 // Introduce the local -> global mapping for selectors within this
2736 // module.
2737 F.SelectorRemap.insertOrReplace(
2738 std::make_pair(LocalBaseSelectorID,
2739 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002740
2741 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 }
2743 break;
2744 }
2745
2746 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002747 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 if (Record[0])
2749 F.SelectorLookupTable
2750 = ASTSelectorLookupTable::Create(
2751 F.SelectorLookupTableData + Record[0],
2752 F.SelectorLookupTableData,
2753 ASTSelectorLookupTrait(*this, F));
2754 TotalNumMethodPoolEntries += Record[1];
2755 break;
2756
2757 case REFERENCED_SELECTOR_POOL:
2758 if (!Record.empty()) {
2759 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2760 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2761 Record[Idx++]));
2762 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2763 getRawEncoding());
2764 }
2765 }
2766 break;
2767
2768 case PP_COUNTER_VALUE:
2769 if (!Record.empty() && Listener)
2770 Listener->ReadCounter(F, Record[0]);
2771 break;
2772
2773 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002774 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002775 F.NumFileSortedDecls = Record[0];
2776 break;
2777
2778 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002779 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002780 F.LocalNumSLocEntries = Record[0];
2781 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002782 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002783 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002784 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002785 if (!F.SLocEntryBaseID) {
2786 Error("ran out of source locations");
2787 break;
2788 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002789 // Make our entry in the range map. BaseID is negative and growing, so
2790 // we invert it. Because we invert it, though, we need the other end of
2791 // the range.
2792 unsigned RangeStart =
2793 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2794 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2795 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2796
2797 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2798 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2799 GlobalSLocOffsetMap.insert(
2800 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2801 - SLocSpaceSize,&F));
2802
2803 // Initialize the remapping table.
2804 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002805 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002806 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002807 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002808 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2809
2810 TotalNumSLocEntries += F.LocalNumSLocEntries;
2811 break;
2812 }
2813
2814 case MODULE_OFFSET_MAP: {
2815 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002816 const unsigned char *Data = (const unsigned char*)Blob.data();
2817 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002818
2819 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2820 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2821 F.SLocRemap.insert(std::make_pair(0U, 0));
2822 F.SLocRemap.insert(std::make_pair(2U, 1));
2823 }
2824
Guy Benyei11169dd2012-12-18 14:30:41 +00002825 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002826 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2827 RemapBuilder;
2828 RemapBuilder SLocRemap(F.SLocRemap);
2829 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2830 RemapBuilder MacroRemap(F.MacroRemap);
2831 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2832 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2833 RemapBuilder SelectorRemap(F.SelectorRemap);
2834 RemapBuilder DeclRemap(F.DeclRemap);
2835 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002836
Richard Smithd8879c82015-08-24 21:59:32 +00002837 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002838 using namespace llvm::support;
2839 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002840 StringRef Name = StringRef((const char*)Data, Len);
2841 Data += Len;
2842 ModuleFile *OM = ModuleMgr.lookup(Name);
2843 if (!OM) {
2844 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002845 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002846 }
2847
Justin Bogner57ba0b22014-03-28 22:03:24 +00002848 uint32_t SLocOffset =
2849 endian::readNext<uint32_t, little, unaligned>(Data);
2850 uint32_t IdentifierIDOffset =
2851 endian::readNext<uint32_t, little, unaligned>(Data);
2852 uint32_t MacroIDOffset =
2853 endian::readNext<uint32_t, little, unaligned>(Data);
2854 uint32_t PreprocessedEntityIDOffset =
2855 endian::readNext<uint32_t, little, unaligned>(Data);
2856 uint32_t SubmoduleIDOffset =
2857 endian::readNext<uint32_t, little, unaligned>(Data);
2858 uint32_t SelectorIDOffset =
2859 endian::readNext<uint32_t, little, unaligned>(Data);
2860 uint32_t DeclIDOffset =
2861 endian::readNext<uint32_t, little, unaligned>(Data);
2862 uint32_t TypeIndexOffset =
2863 endian::readNext<uint32_t, little, unaligned>(Data);
2864
Ben Langmuir785180e2014-10-20 16:27:30 +00002865 uint32_t None = std::numeric_limits<uint32_t>::max();
2866
2867 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2868 RemapBuilder &Remap) {
2869 if (Offset != None)
2870 Remap.insert(std::make_pair(Offset,
2871 static_cast<int>(BaseOffset - Offset)));
2872 };
2873 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2874 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2875 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2876 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2877 PreprocessedEntityRemap);
2878 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2879 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2880 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2881 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002882
2883 // Global -> local mappings.
2884 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2885 }
2886 break;
2887 }
2888
2889 case SOURCE_MANAGER_LINE_TABLE:
2890 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002891 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002892 break;
2893
2894 case SOURCE_LOCATION_PRELOADS: {
2895 // Need to transform from the local view (1-based IDs) to the global view,
2896 // which is based off F.SLocEntryBaseID.
2897 if (!F.PreloadSLocEntries.empty()) {
2898 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002899 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002900 }
2901
2902 F.PreloadSLocEntries.swap(Record);
2903 break;
2904 }
2905
2906 case EXT_VECTOR_DECLS:
2907 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2908 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2909 break;
2910
2911 case VTABLE_USES:
2912 if (Record.size() % 3 != 0) {
2913 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002914 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002915 }
2916
2917 // Later tables overwrite earlier ones.
2918 // FIXME: Modules will have some trouble with this. This is clearly not
2919 // the right way to do this.
2920 VTableUses.clear();
2921
2922 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2923 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2924 VTableUses.push_back(
2925 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2926 VTableUses.push_back(Record[Idx++]);
2927 }
2928 break;
2929
Guy Benyei11169dd2012-12-18 14:30:41 +00002930 case PENDING_IMPLICIT_INSTANTIATIONS:
2931 if (PendingInstantiations.size() % 2 != 0) {
2932 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002933 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002934 }
2935
2936 if (Record.size() % 2 != 0) {
2937 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002938 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002939 }
2940
2941 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2942 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2943 PendingInstantiations.push_back(
2944 ReadSourceLocation(F, Record, I).getRawEncoding());
2945 }
2946 break;
2947
2948 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002949 if (Record.size() != 2) {
2950 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002951 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002952 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002953 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2954 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2955 break;
2956
2957 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002958 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2959 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2960 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002961
2962 unsigned LocalBasePreprocessedEntityID = Record[0];
2963
2964 unsigned StartingID;
2965 if (!PP.getPreprocessingRecord())
2966 PP.createPreprocessingRecord();
2967 if (!PP.getPreprocessingRecord()->getExternalSource())
2968 PP.getPreprocessingRecord()->SetExternalSource(*this);
2969 StartingID
2970 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002971 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002972 F.BasePreprocessedEntityID = StartingID;
2973
2974 if (F.NumPreprocessedEntities > 0) {
2975 // Introduce the global -> local mapping for preprocessed entities in
2976 // this module.
2977 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2978
2979 // Introduce the local -> global mapping for preprocessed entities in
2980 // this module.
2981 F.PreprocessedEntityRemap.insertOrReplace(
2982 std::make_pair(LocalBasePreprocessedEntityID,
2983 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2984 }
2985
2986 break;
2987 }
2988
2989 case DECL_UPDATE_OFFSETS: {
2990 if (Record.size() % 2 != 0) {
2991 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002992 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002993 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002994 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2995 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2996 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2997
2998 // If we've already loaded the decl, perform the updates when we finish
2999 // loading this block.
3000 if (Decl *D = GetExistingDecl(ID))
3001 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3002 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003003 break;
3004 }
3005
3006 case DECL_REPLACEMENTS: {
3007 if (Record.size() % 3 != 0) {
3008 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003009 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003010 }
3011 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3012 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3013 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3014 break;
3015 }
3016
3017 case OBJC_CATEGORIES_MAP: {
3018 if (F.LocalNumObjCCategoriesInMap != 0) {
3019 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003020 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003021 }
3022
3023 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003024 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003025 break;
3026 }
3027
3028 case OBJC_CATEGORIES:
3029 F.ObjCCategories.swap(Record);
3030 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003031
Guy Benyei11169dd2012-12-18 14:30:41 +00003032 case CXX_BASE_SPECIFIER_OFFSETS: {
3033 if (F.LocalNumCXXBaseSpecifiers != 0) {
3034 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003035 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003036 }
Richard Smithc2bb8182015-03-24 06:36:48 +00003037
Guy Benyei11169dd2012-12-18 14:30:41 +00003038 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003039 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00003040 break;
3041 }
3042
3043 case CXX_CTOR_INITIALIZERS_OFFSETS: {
3044 if (F.LocalNumCXXCtorInitializers != 0) {
3045 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
3046 return Failure;
3047 }
3048
3049 F.LocalNumCXXCtorInitializers = Record[0];
3050 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003051 break;
3052 }
3053
3054 case DIAG_PRAGMA_MAPPINGS:
3055 if (F.PragmaDiagMappings.empty())
3056 F.PragmaDiagMappings.swap(Record);
3057 else
3058 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3059 Record.begin(), Record.end());
3060 break;
3061
3062 case CUDA_SPECIAL_DECL_REFS:
3063 // Later tables overwrite earlier ones.
3064 // FIXME: Modules will have trouble with this.
3065 CUDASpecialDeclRefs.clear();
3066 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3067 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3068 break;
3069
3070 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003071 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003072 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003073 if (Record[0]) {
3074 F.HeaderFileInfoTable
3075 = HeaderFileInfoLookupTable::Create(
3076 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3077 (const unsigned char *)F.HeaderFileInfoTableData,
3078 HeaderFileInfoTrait(*this, F,
3079 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003080 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003081
3082 PP.getHeaderSearchInfo().SetExternalSource(this);
3083 if (!PP.getHeaderSearchInfo().getExternalLookup())
3084 PP.getHeaderSearchInfo().SetExternalLookup(this);
3085 }
3086 break;
3087 }
3088
3089 case FP_PRAGMA_OPTIONS:
3090 // Later tables overwrite earlier ones.
3091 FPPragmaOptions.swap(Record);
3092 break;
3093
3094 case OPENCL_EXTENSIONS:
3095 // Later tables overwrite earlier ones.
3096 OpenCLExtensions.swap(Record);
3097 break;
3098
3099 case TENTATIVE_DEFINITIONS:
3100 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3101 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3102 break;
3103
3104 case KNOWN_NAMESPACES:
3105 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3106 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3107 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003108
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003109 case UNDEFINED_BUT_USED:
3110 if (UndefinedButUsed.size() % 2 != 0) {
3111 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003112 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003113 }
3114
3115 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003116 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003117 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003118 }
3119 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003120 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3121 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003122 ReadSourceLocation(F, Record, I).getRawEncoding());
3123 }
3124 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003125 case DELETE_EXPRS_TO_ANALYZE:
3126 for (unsigned I = 0, N = Record.size(); I != N;) {
3127 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3128 const uint64_t Count = Record[I++];
3129 DelayedDeleteExprs.push_back(Count);
3130 for (uint64_t C = 0; C < Count; ++C) {
3131 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3132 bool IsArrayForm = Record[I++] == 1;
3133 DelayedDeleteExprs.push_back(IsArrayForm);
3134 }
3135 }
3136 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003137
Guy Benyei11169dd2012-12-18 14:30:41 +00003138 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003139 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003140 // If we aren't loading a module (which has its own exports), make
3141 // all of the imported modules visible.
3142 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003143 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3144 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3145 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3146 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003147 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003148 }
3149 }
3150 break;
3151 }
3152
Guy Benyei11169dd2012-12-18 14:30:41 +00003153 case MACRO_OFFSET: {
3154 if (F.LocalNumMacros != 0) {
3155 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003156 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003157 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003158 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003159 F.LocalNumMacros = Record[0];
3160 unsigned LocalBaseMacroID = Record[1];
3161 F.BaseMacroID = getTotalNumMacros();
3162
3163 if (F.LocalNumMacros > 0) {
3164 // Introduce the global -> local mapping for macros within this module.
3165 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3166
3167 // Introduce the local -> global mapping for macros within this module.
3168 F.MacroRemap.insertOrReplace(
3169 std::make_pair(LocalBaseMacroID,
3170 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003171
3172 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003173 }
3174 break;
3175 }
3176
Richard Smithe40f2ba2013-08-07 21:41:30 +00003177 case LATE_PARSED_TEMPLATE: {
3178 LateParsedTemplates.append(Record.begin(), Record.end());
3179 break;
3180 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003181
3182 case OPTIMIZE_PRAGMA_OPTIONS:
3183 if (Record.size() != 1) {
3184 Error("invalid pragma optimize record");
3185 return Failure;
3186 }
3187 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3188 break;
Nico Weber72889432014-09-06 01:25:55 +00003189
3190 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3191 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3192 UnusedLocalTypedefNameCandidates.push_back(
3193 getGlobalDeclID(F, Record[I]));
3194 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003195 }
3196 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003197}
3198
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003199ASTReader::ASTReadResult
3200ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3201 const ModuleFile *ImportedBy,
3202 unsigned ClientLoadCapabilities) {
3203 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003204 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003205
Richard Smithe842a472014-10-22 02:05:46 +00003206 if (F.Kind == MK_ExplicitModule) {
3207 // For an explicitly-loaded module, we don't care whether the original
3208 // module map file exists or matches.
3209 return Success;
3210 }
3211
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003212 // Try to resolve ModuleName in the current header search context and
3213 // verify that it is found in the same module map file as we saved. If the
3214 // top-level AST file is a main file, skip this check because there is no
3215 // usable header search context.
3216 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003217 "MODULE_NAME should come before MODULE_MAP_FILE");
3218 if (F.Kind == MK_ImplicitModule &&
3219 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3220 // An implicitly-loaded module file should have its module listed in some
3221 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003222 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003223 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3224 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3225 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003226 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003227 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3228 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3229 // This module was defined by an imported (explicit) module.
3230 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3231 << ASTFE->getName();
3232 else
3233 // This module was built with a different module map.
3234 Diag(diag::err_imported_module_not_found)
3235 << F.ModuleName << F.FileName << ImportedBy->FileName
3236 << F.ModuleMapPath;
3237 }
3238 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003239 }
3240
Richard Smithe842a472014-10-22 02:05:46 +00003241 assert(M->Name == F.ModuleName && "found module with different name");
3242
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003243 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003244 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003245 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3246 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003247 assert(ImportedBy && "top-level import should be verified");
3248 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3249 Diag(diag::err_imported_module_modmap_changed)
3250 << F.ModuleName << ImportedBy->FileName
3251 << ModMap->getName() << F.ModuleMapPath;
3252 return OutOfDate;
3253 }
3254
3255 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3256 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3257 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003258 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003259 const FileEntry *F =
3260 FileMgr.getFile(Filename, false, false);
3261 if (F == nullptr) {
3262 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3263 Error("could not find file '" + Filename +"' referenced by AST file");
3264 return OutOfDate;
3265 }
3266 AdditionalStoredMaps.insert(F);
3267 }
3268
3269 // Check any additional module map files (e.g. module.private.modulemap)
3270 // that are not in the pcm.
3271 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3272 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3273 // Remove files that match
3274 // Note: SmallPtrSet::erase is really remove
3275 if (!AdditionalStoredMaps.erase(ModMap)) {
3276 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3277 Diag(diag::err_module_different_modmap)
3278 << F.ModuleName << /*new*/0 << ModMap->getName();
3279 return OutOfDate;
3280 }
3281 }
3282 }
3283
3284 // Check any additional module map files that are in the pcm, but not
3285 // found in header search. Cases that match are already removed.
3286 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3287 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3288 Diag(diag::err_module_different_modmap)
3289 << F.ModuleName << /*not new*/1 << ModMap->getName();
3290 return OutOfDate;
3291 }
3292 }
3293
3294 if (Listener)
3295 Listener->ReadModuleMapFile(F.ModuleMapPath);
3296 return Success;
3297}
3298
3299
Douglas Gregorc1489562013-02-12 23:36:21 +00003300/// \brief Move the given method to the back of the global list of methods.
3301static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3302 // Find the entry for this selector in the method pool.
3303 Sema::GlobalMethodPool::iterator Known
3304 = S.MethodPool.find(Method->getSelector());
3305 if (Known == S.MethodPool.end())
3306 return;
3307
3308 // Retrieve the appropriate method list.
3309 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3310 : Known->second.second;
3311 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003312 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003313 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003314 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003315 Found = true;
3316 } else {
3317 // Keep searching.
3318 continue;
3319 }
3320 }
3321
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003322 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003323 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003324 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003325 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003326 }
3327}
3328
Richard Smithde711422015-04-23 21:20:19 +00003329void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003330 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003331 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003332 bool wasHidden = D->Hidden;
3333 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003334
Richard Smith49f906a2014-03-01 00:08:04 +00003335 if (wasHidden && SemaObj) {
3336 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3337 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003338 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003339 }
3340 }
3341}
3342
Richard Smith49f906a2014-03-01 00:08:04 +00003343void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003344 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003345 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003346 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003347 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003348 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003349 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003350 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003351
3352 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003353 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003354 // there is nothing more to do.
3355 continue;
3356 }
Richard Smith49f906a2014-03-01 00:08:04 +00003357
Guy Benyei11169dd2012-12-18 14:30:41 +00003358 if (!Mod->isAvailable()) {
3359 // Modules that aren't available cannot be made visible.
3360 continue;
3361 }
3362
3363 // Update the module's name visibility.
3364 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003365
Guy Benyei11169dd2012-12-18 14:30:41 +00003366 // If we've already deserialized any names from this module,
3367 // mark them as visible.
3368 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3369 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003370 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003371 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003372 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003373 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3374 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003375 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003376
Guy Benyei11169dd2012-12-18 14:30:41 +00003377 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003378 SmallVector<Module *, 16> Exports;
3379 Mod->getExportedModules(Exports);
3380 for (SmallVectorImpl<Module *>::iterator
3381 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3382 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003383 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003384 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003385 }
3386 }
3387}
3388
Douglas Gregore060e572013-01-25 01:03:03 +00003389bool ASTReader::loadGlobalIndex() {
3390 if (GlobalIndex)
3391 return false;
3392
3393 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3394 !Context.getLangOpts().Modules)
3395 return true;
3396
3397 // Try to load the global index.
3398 TriedLoadingGlobalIndex = true;
3399 StringRef ModuleCachePath
3400 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3401 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003402 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003403 if (!Result.first)
3404 return true;
3405
3406 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003407 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003408 return false;
3409}
3410
3411bool ASTReader::isGlobalIndexUnavailable() const {
3412 return Context.getLangOpts().Modules && UseGlobalIndex &&
3413 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3414}
3415
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003416static void updateModuleTimestamp(ModuleFile &MF) {
3417 // Overwrite the timestamp file contents so that file's mtime changes.
3418 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003419 std::error_code EC;
3420 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3421 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003422 return;
3423 OS << "Timestamp file\n";
3424}
3425
Guy Benyei11169dd2012-12-18 14:30:41 +00003426ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3427 ModuleKind Type,
3428 SourceLocation ImportLoc,
3429 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003430 llvm::SaveAndRestore<SourceLocation>
3431 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3432
Richard Smithd1c46742014-04-30 02:24:17 +00003433 // Defer any pending actions until we get to the end of reading the AST file.
3434 Deserializing AnASTFile(this);
3435
Guy Benyei11169dd2012-12-18 14:30:41 +00003436 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003437 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003438
3439 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003440 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003441 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003442 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003443 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003444 ClientLoadCapabilities)) {
3445 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003446 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003447 case OutOfDate:
3448 case VersionMismatch:
3449 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003450 case HadErrors: {
3451 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3452 for (const ImportedModule &IM : Loaded)
3453 LoadedSet.insert(IM.Mod);
3454
Douglas Gregor7029ce12013-03-19 00:28:20 +00003455 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003456 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003457 Context.getLangOpts().Modules
3458 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003459 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003460
3461 // If we find that any modules are unusable, the global index is going
3462 // to be out-of-date. Just remove it.
3463 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003464 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003465 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003466 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003467 case Success:
3468 break;
3469 }
3470
3471 // Here comes stuff that we only do once the entire chain is loaded.
3472
3473 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003474 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3475 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003476 M != MEnd; ++M) {
3477 ModuleFile &F = *M->Mod;
3478
3479 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003480 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3481 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003482
3483 // Once read, set the ModuleFile bit base offset and update the size in
3484 // bits of all files we've seen.
3485 F.GlobalBitOffset = TotalModulesSizeInBits;
3486 TotalModulesSizeInBits += F.SizeInBits;
3487 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3488
3489 // Preload SLocEntries.
3490 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3491 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3492 // Load it through the SourceManager and don't call ReadSLocEntry()
3493 // directly because the entry may have already been loaded in which case
3494 // calling ReadSLocEntry() directly would trigger an assertion in
3495 // SourceManager.
3496 SourceMgr.getLoadedSLocEntryByID(Index);
3497 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003498
3499 // Preload all the pending interesting identifiers by marking them out of
3500 // date.
3501 for (auto Offset : F.PreloadIdentifierOffsets) {
3502 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3503 F.IdentifierTableData + Offset);
3504
3505 ASTIdentifierLookupTrait Trait(*this, F);
3506 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3507 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003508 auto &II = PP.getIdentifierTable().getOwn(Key);
3509 II.setOutOfDate(true);
3510
3511 // Mark this identifier as being from an AST file so that we can track
3512 // whether we need to serialize it.
3513 if (!II.isFromAST()) {
3514 II.setIsFromAST();
Ben Langmuirb9ad4e62015-10-28 22:25:37 +00003515 bool IsModule = PP.getCurrentModule() != nullptr;
3516 if (isInterestingIdentifier(*this, II, IsModule))
Richard Smith79bf9202015-08-24 03:33:22 +00003517 II.setChangedSinceDeserialization();
3518 }
3519
3520 // Associate the ID with the identifier so that the writer can reuse it.
3521 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3522 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003523 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003524 }
3525
Douglas Gregor603cd862013-03-22 18:50:14 +00003526 // Setup the import locations and notify the module manager that we've
3527 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003528 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3529 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003530 M != MEnd; ++M) {
3531 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003532
3533 ModuleMgr.moduleFileAccepted(&F);
3534
3535 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003536 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003537 if (!M->ImportedBy)
3538 F.ImportLoc = M->ImportLoc;
3539 else
3540 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3541 M->ImportLoc.getRawEncoding());
3542 }
3543
Richard Smith33e0f7e2015-07-22 02:08:40 +00003544 if (!Context.getLangOpts().CPlusPlus ||
3545 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3546 // Mark all of the identifiers in the identifier table as being out of date,
3547 // so that various accessors know to check the loaded modules when the
3548 // identifier is used.
3549 //
3550 // For C++ modules, we don't need information on many identifiers (just
3551 // those that provide macros or are poisoned), so we mark all of
3552 // the interesting ones via PreloadIdentifierOffsets.
3553 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3554 IdEnd = PP.getIdentifierTable().end();
3555 Id != IdEnd; ++Id)
3556 Id->second->setOutOfDate(true);
3557 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003558
3559 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003560 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3561 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003562 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3563 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003564
3565 switch (Unresolved.Kind) {
3566 case UnresolvedModuleRef::Conflict:
3567 if (ResolvedMod) {
3568 Module::Conflict Conflict;
3569 Conflict.Other = ResolvedMod;
3570 Conflict.Message = Unresolved.String.str();
3571 Unresolved.Mod->Conflicts.push_back(Conflict);
3572 }
3573 continue;
3574
3575 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003576 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003577 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003578 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003579
Douglas Gregorfb912652013-03-20 21:10:35 +00003580 case UnresolvedModuleRef::Export:
3581 if (ResolvedMod || Unresolved.IsWildcard)
3582 Unresolved.Mod->Exports.push_back(
3583 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3584 continue;
3585 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003586 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003587 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003588
3589 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3590 // Might be unnecessary as use declarations are only used to build the
3591 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003592
3593 InitializeContext();
3594
Richard Smith3d8e97e2013-10-18 06:54:39 +00003595 if (SemaObj)
3596 UpdateSema();
3597
Guy Benyei11169dd2012-12-18 14:30:41 +00003598 if (DeserializationListener)
3599 DeserializationListener->ReaderInitialized(this);
3600
3601 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003602 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003603 PrimaryModule.OriginalSourceFileID
3604 = FileID::get(PrimaryModule.SLocEntryBaseID
3605 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3606
3607 // If this AST file is a precompiled preamble, then set the
3608 // preamble file ID of the source manager to the file source file
3609 // from which the preamble was built.
3610 if (Type == MK_Preamble) {
3611 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3612 } else if (Type == MK_MainFile) {
3613 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3614 }
3615 }
3616
3617 // For any Objective-C class definitions we have already loaded, make sure
3618 // that we load any additional categories.
3619 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3620 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3621 ObjCClassesLoaded[I],
3622 PreviousGeneration);
3623 }
Douglas Gregore060e572013-01-25 01:03:03 +00003624
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003625 if (PP.getHeaderSearchInfo()
3626 .getHeaderSearchOpts()
3627 .ModulesValidateOncePerBuildSession) {
3628 // Now we are certain that the module and all modules it depends on are
3629 // up to date. Create or update timestamp files for modules that are
3630 // located in the module cache (not for PCH files that could be anywhere
3631 // in the filesystem).
3632 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3633 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003634 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003635 updateModuleTimestamp(*M.Mod);
3636 }
3637 }
3638 }
3639
Guy Benyei11169dd2012-12-18 14:30:41 +00003640 return Success;
3641}
3642
Ben Langmuir487ea142014-10-23 18:05:36 +00003643static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3644
Ben Langmuir70a1b812015-03-24 04:43:52 +00003645/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3646static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3647 return Stream.Read(8) == 'C' &&
3648 Stream.Read(8) == 'P' &&
3649 Stream.Read(8) == 'C' &&
3650 Stream.Read(8) == 'H';
3651}
3652
Richard Smith0f99d6a2015-08-09 08:48:41 +00003653static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3654 switch (Kind) {
3655 case MK_PCH:
3656 return 0; // PCH
3657 case MK_ImplicitModule:
3658 case MK_ExplicitModule:
3659 return 1; // module
3660 case MK_MainFile:
3661 case MK_Preamble:
3662 return 2; // main source file
3663 }
3664 llvm_unreachable("unknown module kind");
3665}
3666
Guy Benyei11169dd2012-12-18 14:30:41 +00003667ASTReader::ASTReadResult
3668ASTReader::ReadASTCore(StringRef FileName,
3669 ModuleKind Type,
3670 SourceLocation ImportLoc,
3671 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003672 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003673 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003674 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003675 unsigned ClientLoadCapabilities) {
3676 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003677 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003678 ModuleManager::AddModuleResult AddResult
3679 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003680 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003681 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003682 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003683
Douglas Gregor7029ce12013-03-19 00:28:20 +00003684 switch (AddResult) {
3685 case ModuleManager::AlreadyLoaded:
3686 return Success;
3687
3688 case ModuleManager::NewlyLoaded:
3689 // Load module file below.
3690 break;
3691
3692 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003693 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003694 // it.
3695 if (ClientLoadCapabilities & ARR_Missing)
3696 return Missing;
3697
3698 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003699 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3700 << FileName << ErrorStr.empty()
3701 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003702 return Failure;
3703
3704 case ModuleManager::OutOfDate:
3705 // We couldn't load the module file because it is out-of-date. If the
3706 // client can handle out-of-date, return it.
3707 if (ClientLoadCapabilities & ARR_OutOfDate)
3708 return OutOfDate;
3709
3710 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003711 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3712 << FileName << ErrorStr.empty()
3713 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003714 return Failure;
3715 }
3716
Douglas Gregor7029ce12013-03-19 00:28:20 +00003717 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003718
3719 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3720 // module?
3721 if (FileName != "-") {
3722 CurrentDir = llvm::sys::path::parent_path(FileName);
3723 if (CurrentDir.empty()) CurrentDir = ".";
3724 }
3725
3726 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003727 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003728 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003729 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003730 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3731
Guy Benyei11169dd2012-12-18 14:30:41 +00003732 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003733 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003734 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3735 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003736 return Failure;
3737 }
3738
3739 // This is used for compatibility with older PCH formats.
3740 bool HaveReadControlBlock = false;
3741
Chris Lattnerefa77172013-01-20 00:00:22 +00003742 while (1) {
3743 llvm::BitstreamEntry Entry = Stream.advance();
3744
3745 switch (Entry.Kind) {
3746 case llvm::BitstreamEntry::Error:
3747 case llvm::BitstreamEntry::EndBlock:
3748 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003749 Error("invalid record at top-level of AST file");
3750 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003751
3752 case llvm::BitstreamEntry::SubBlock:
3753 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003754 }
3755
Chris Lattnerefa77172013-01-20 00:00:22 +00003756 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003757 case CONTROL_BLOCK_ID:
3758 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003759 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003760 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003761 // Check that we didn't try to load a non-module AST file as a module.
3762 //
3763 // FIXME: Should we also perform the converse check? Loading a module as
3764 // a PCH file sort of works, but it's a bit wonky.
3765 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule) &&
3766 F.ModuleName.empty()) {
3767 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3768 if (Result != OutOfDate ||
3769 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3770 Diag(diag::err_module_file_not_module) << FileName;
3771 return Result;
3772 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003773 break;
3774
3775 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003776 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003777 case OutOfDate: return OutOfDate;
3778 case VersionMismatch: return VersionMismatch;
3779 case ConfigurationMismatch: return ConfigurationMismatch;
3780 case HadErrors: return HadErrors;
3781 }
3782 break;
Richard Smithf8c32552015-09-02 17:45:54 +00003783
Guy Benyei11169dd2012-12-18 14:30:41 +00003784 case AST_BLOCK_ID:
3785 if (!HaveReadControlBlock) {
3786 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003787 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003788 return VersionMismatch;
3789 }
3790
3791 // Record that we've loaded this module.
3792 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3793 return Success;
3794
3795 default:
3796 if (Stream.SkipBlock()) {
3797 Error("malformed block record in AST file");
3798 return Failure;
3799 }
3800 break;
3801 }
3802 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003803}
3804
Richard Smitha7e2cc62015-05-01 01:53:09 +00003805void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003806 // If there's a listener, notify them that we "read" the translation unit.
3807 if (DeserializationListener)
3808 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3809 Context.getTranslationUnitDecl());
3810
Guy Benyei11169dd2012-12-18 14:30:41 +00003811 // FIXME: Find a better way to deal with collisions between these
3812 // built-in types. Right now, we just ignore the problem.
3813
3814 // Load the special types.
3815 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3816 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3817 if (!Context.CFConstantStringTypeDecl)
3818 Context.setCFConstantStringType(GetType(String));
3819 }
3820
3821 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3822 QualType FileType = GetType(File);
3823 if (FileType.isNull()) {
3824 Error("FILE type is NULL");
3825 return;
3826 }
3827
3828 if (!Context.FILEDecl) {
3829 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3830 Context.setFILEDecl(Typedef->getDecl());
3831 else {
3832 const TagType *Tag = FileType->getAs<TagType>();
3833 if (!Tag) {
3834 Error("Invalid FILE type in AST file");
3835 return;
3836 }
3837 Context.setFILEDecl(Tag->getDecl());
3838 }
3839 }
3840 }
3841
3842 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3843 QualType Jmp_bufType = GetType(Jmp_buf);
3844 if (Jmp_bufType.isNull()) {
3845 Error("jmp_buf type is NULL");
3846 return;
3847 }
3848
3849 if (!Context.jmp_bufDecl) {
3850 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3851 Context.setjmp_bufDecl(Typedef->getDecl());
3852 else {
3853 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3854 if (!Tag) {
3855 Error("Invalid jmp_buf type in AST file");
3856 return;
3857 }
3858 Context.setjmp_bufDecl(Tag->getDecl());
3859 }
3860 }
3861 }
3862
3863 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3864 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3865 if (Sigjmp_bufType.isNull()) {
3866 Error("sigjmp_buf type is NULL");
3867 return;
3868 }
3869
3870 if (!Context.sigjmp_bufDecl) {
3871 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3872 Context.setsigjmp_bufDecl(Typedef->getDecl());
3873 else {
3874 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3875 assert(Tag && "Invalid sigjmp_buf type in AST file");
3876 Context.setsigjmp_bufDecl(Tag->getDecl());
3877 }
3878 }
3879 }
3880
3881 if (unsigned ObjCIdRedef
3882 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3883 if (Context.ObjCIdRedefinitionType.isNull())
3884 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3885 }
3886
3887 if (unsigned ObjCClassRedef
3888 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3889 if (Context.ObjCClassRedefinitionType.isNull())
3890 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3891 }
3892
3893 if (unsigned ObjCSelRedef
3894 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3895 if (Context.ObjCSelRedefinitionType.isNull())
3896 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3897 }
3898
3899 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3900 QualType Ucontext_tType = GetType(Ucontext_t);
3901 if (Ucontext_tType.isNull()) {
3902 Error("ucontext_t type is NULL");
3903 return;
3904 }
3905
3906 if (!Context.ucontext_tDecl) {
3907 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3908 Context.setucontext_tDecl(Typedef->getDecl());
3909 else {
3910 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3911 assert(Tag && "Invalid ucontext_t type in AST file");
3912 Context.setucontext_tDecl(Tag->getDecl());
3913 }
3914 }
3915 }
3916 }
3917
3918 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3919
3920 // If there were any CUDA special declarations, deserialize them.
3921 if (!CUDASpecialDeclRefs.empty()) {
3922 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3923 Context.setcudaConfigureCallDecl(
3924 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3925 }
Richard Smith56be7542014-03-21 00:33:59 +00003926
Guy Benyei11169dd2012-12-18 14:30:41 +00003927 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003928 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003929 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003930 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003931 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003932 /*ImportLoc=*/Import.ImportLoc);
3933 PP.makeModuleVisible(Imported, Import.ImportLoc);
3934 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003935 }
3936 ImportedModules.clear();
3937}
3938
3939void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003940 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003941}
3942
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003943/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3944/// cursor into the start of the given block ID, returning false on success and
3945/// true on failure.
3946static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003947 while (1) {
3948 llvm::BitstreamEntry Entry = Cursor.advance();
3949 switch (Entry.Kind) {
3950 case llvm::BitstreamEntry::Error:
3951 case llvm::BitstreamEntry::EndBlock:
3952 return true;
3953
3954 case llvm::BitstreamEntry::Record:
3955 // Ignore top-level records.
3956 Cursor.skipRecord(Entry.ID);
3957 break;
3958
3959 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003960 if (Entry.ID == BlockID) {
3961 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003962 return true;
3963 // Found it!
3964 return false;
3965 }
3966
3967 if (Cursor.SkipBlock())
3968 return true;
3969 }
3970 }
3971}
3972
Ben Langmuir70a1b812015-03-24 04:43:52 +00003973/// \brief Reads and return the signature record from \p StreamFile's control
3974/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003975static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3976 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003977 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003978 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003979
3980 // Scan for the CONTROL_BLOCK_ID block.
3981 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3982 return 0;
3983
3984 // Scan for SIGNATURE inside the control block.
3985 ASTReader::RecordData Record;
3986 while (1) {
3987 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3988 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3989 Entry.Kind != llvm::BitstreamEntry::Record)
3990 return 0;
3991
3992 Record.clear();
3993 StringRef Blob;
3994 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3995 return Record[0];
3996 }
3997}
3998
Guy Benyei11169dd2012-12-18 14:30:41 +00003999/// \brief Retrieve the name of the original source file name
4000/// directly from the AST file, without actually loading the AST
4001/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004002std::string ASTReader::getOriginalSourceFile(
4003 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004004 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004005 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004006 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004007 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004008 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4009 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004010 return std::string();
4011 }
4012
4013 // Initialize the stream
4014 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004015 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004016 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004017
4018 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004019 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004020 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4021 return std::string();
4022 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004023
Chris Lattnere7b154b2013-01-19 21:39:22 +00004024 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004025 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004026 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4027 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004028 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004029
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004030 // Scan for ORIGINAL_FILE inside the control block.
4031 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004032 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004033 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004034 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4035 return std::string();
4036
4037 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4038 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4039 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004040 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004041
Guy Benyei11169dd2012-12-18 14:30:41 +00004042 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004043 StringRef Blob;
4044 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4045 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004047}
4048
4049namespace {
4050 class SimplePCHValidator : public ASTReaderListener {
4051 const LangOptions &ExistingLangOpts;
4052 const TargetOptions &ExistingTargetOpts;
4053 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004054 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004055 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004056
Guy Benyei11169dd2012-12-18 14:30:41 +00004057 public:
4058 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4059 const TargetOptions &ExistingTargetOpts,
4060 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004061 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004062 FileManager &FileMgr)
4063 : ExistingLangOpts(ExistingLangOpts),
4064 ExistingTargetOpts(ExistingTargetOpts),
4065 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004066 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004067 FileMgr(FileMgr)
4068 {
4069 }
4070
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004071 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4072 bool AllowCompatibleDifferences) override {
4073 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4074 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004075 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004076 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4077 bool AllowCompatibleDifferences) override {
4078 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4079 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004080 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004081 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4082 StringRef SpecificModuleCachePath,
4083 bool Complain) override {
4084 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4085 ExistingModuleCachePath,
4086 nullptr, ExistingLangOpts);
4087 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004088 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4089 bool Complain,
4090 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004091 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004092 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004093 }
4094 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004095}
Guy Benyei11169dd2012-12-18 14:30:41 +00004096
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004097bool ASTReader::readASTFileControlBlock(
4098 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004099 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004100 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004101 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004102 // FIXME: This allows use of the VFS; we do not allow use of the
4103 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004104 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004105 if (!Buffer) {
4106 return true;
4107 }
4108
4109 // Initialize the stream
4110 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004111 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004112 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004113
4114 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004115 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004116 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004117
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004118 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004119 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004120 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004121
4122 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004123 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004124 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004125 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004126
Guy Benyei11169dd2012-12-18 14:30:41 +00004127 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004128 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004129 while (1) {
Richard Smith0516b182015-09-08 19:40:14 +00004130 llvm::BitstreamEntry Entry = Stream.advance();
4131
4132 switch (Entry.Kind) {
4133 case llvm::BitstreamEntry::SubBlock: {
4134 switch (Entry.ID) {
4135 case OPTIONS_BLOCK_ID: {
4136 std::string IgnoredSuggestedPredefines;
4137 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4138 /*AllowCompatibleConfigurationMismatch*/ false,
4139 Listener, IgnoredSuggestedPredefines) != Success)
4140 return true;
4141 break;
4142 }
4143
4144 case INPUT_FILES_BLOCK_ID:
4145 InputFilesCursor = Stream;
4146 if (Stream.SkipBlock() ||
4147 (NeedsInputFiles &&
4148 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4149 return true;
4150 break;
4151
4152 default:
4153 if (Stream.SkipBlock())
4154 return true;
4155 break;
4156 }
4157
4158 continue;
4159 }
4160
4161 case llvm::BitstreamEntry::EndBlock:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004162 return false;
Richard Smith0516b182015-09-08 19:40:14 +00004163
4164 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004165 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004166
4167 case llvm::BitstreamEntry::Record:
4168 break;
4169 }
4170
Guy Benyei11169dd2012-12-18 14:30:41 +00004171 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004172 StringRef Blob;
4173 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004174 switch ((ControlRecordTypes)RecCode) {
4175 case METADATA: {
4176 if (Record[0] != VERSION_MAJOR)
4177 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004178
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004179 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004180 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004181
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004182 break;
4183 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004184 case MODULE_NAME:
4185 Listener.ReadModuleName(Blob);
4186 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004187 case MODULE_DIRECTORY:
4188 ModuleDir = Blob;
4189 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004190 case MODULE_MAP_FILE: {
4191 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004192 auto Path = ReadString(Record, Idx);
4193 ResolveImportedPath(Path, ModuleDir);
4194 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004195 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004196 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004197 case INPUT_FILE_OFFSETS: {
4198 if (!NeedsInputFiles)
4199 break;
4200
4201 unsigned NumInputFiles = Record[0];
4202 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004203 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004204 for (unsigned I = 0; I != NumInputFiles; ++I) {
4205 // Go find this input file.
4206 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004207
4208 if (isSystemFile && !NeedsSystemInputFiles)
4209 break; // the rest are system input files
4210
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004211 BitstreamCursor &Cursor = InputFilesCursor;
4212 SavedStreamPosition SavedPosition(Cursor);
4213 Cursor.JumpToBit(InputFileOffs[I]);
4214
4215 unsigned Code = Cursor.ReadCode();
4216 RecordData Record;
4217 StringRef Blob;
4218 bool shouldContinue = false;
4219 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4220 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004221 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004222 std::string Filename = Blob;
4223 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004224 shouldContinue = Listener.visitInputFile(
4225 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004226 break;
4227 }
4228 if (!shouldContinue)
4229 break;
4230 }
4231 break;
4232 }
4233
Richard Smithd4b230b2014-10-27 23:01:16 +00004234 case IMPORTS: {
4235 if (!NeedsImports)
4236 break;
4237
4238 unsigned Idx = 0, N = Record.size();
4239 while (Idx < N) {
4240 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004241 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004242 std::string Filename = ReadString(Record, Idx);
4243 ResolveImportedPath(Filename, ModuleDir);
4244 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004245 }
4246 break;
4247 }
4248
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004249 default:
4250 // No other validation to perform.
4251 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004252 }
4253 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004254}
4255
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004256bool ASTReader::isAcceptableASTFile(
4257 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004258 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004259 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4260 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004261 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4262 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004263 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004264 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004265}
4266
Ben Langmuir2c9af442014-04-10 17:57:43 +00004267ASTReader::ASTReadResult
4268ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 // Enter the submodule block.
4270 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4271 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004272 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004273 }
4274
4275 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4276 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004277 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004278 RecordData Record;
4279 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004280 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4281
4282 switch (Entry.Kind) {
4283 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4284 case llvm::BitstreamEntry::Error:
4285 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004286 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004287 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004288 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004289 case llvm::BitstreamEntry::Record:
4290 // The interesting case.
4291 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004292 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004293
Guy Benyei11169dd2012-12-18 14:30:41 +00004294 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004295 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004297 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4298
4299 if ((Kind == SUBMODULE_METADATA) != First) {
4300 Error("submodule metadata record should be at beginning of block");
4301 return Failure;
4302 }
4303 First = false;
4304
4305 // Submodule information is only valid if we have a current module.
4306 // FIXME: Should we error on these cases?
4307 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4308 Kind != SUBMODULE_DEFINITION)
4309 continue;
4310
4311 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 default: // Default behavior: ignore.
4313 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004314
Richard Smith03478d92014-10-23 22:12:14 +00004315 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004316 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004318 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004319 }
Richard Smith03478d92014-10-23 22:12:14 +00004320
Chris Lattner0e6c9402013-01-20 02:38:54 +00004321 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004322 unsigned Idx = 0;
4323 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4324 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4325 bool IsFramework = Record[Idx++];
4326 bool IsExplicit = Record[Idx++];
4327 bool IsSystem = Record[Idx++];
4328 bool IsExternC = Record[Idx++];
4329 bool InferSubmodules = Record[Idx++];
4330 bool InferExplicitSubmodules = Record[Idx++];
4331 bool InferExportWildcard = Record[Idx++];
4332 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004333
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004334 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004335 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004336 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004337
Guy Benyei11169dd2012-12-18 14:30:41 +00004338 // Retrieve this (sub)module from the module map, creating it if
4339 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004340 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004341 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004342
4343 // FIXME: set the definition loc for CurrentModule, or call
4344 // ModMap.setInferredModuleAllowedBy()
4345
Guy Benyei11169dd2012-12-18 14:30:41 +00004346 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4347 if (GlobalIndex >= SubmodulesLoaded.size() ||
4348 SubmodulesLoaded[GlobalIndex]) {
4349 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004350 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004351 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004352
Douglas Gregor7029ce12013-03-19 00:28:20 +00004353 if (!ParentModule) {
4354 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4355 if (CurFile != F.File) {
4356 if (!Diags.isDiagnosticInFlight()) {
4357 Diag(diag::err_module_file_conflict)
4358 << CurrentModule->getTopLevelModuleName()
4359 << CurFile->getName()
4360 << F.File->getName();
4361 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004362 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004363 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004364 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004365
4366 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004367 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004368
Adrian Prantl15bcf702015-06-30 17:39:43 +00004369 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004370 CurrentModule->IsFromModuleFile = true;
4371 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004372 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 CurrentModule->InferSubmodules = InferSubmodules;
4374 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4375 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004376 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004377 if (DeserializationListener)
4378 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4379
4380 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004381
Douglas Gregorfb912652013-03-20 21:10:35 +00004382 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004383 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004384 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004385 CurrentModule->UnresolvedConflicts.clear();
4386 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 break;
4388 }
4389
4390 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004391 std::string Filename = Blob;
4392 ResolveImportedPath(F, Filename);
4393 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004395 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4396 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004397 // This can be a spurious difference caused by changing the VFS to
4398 // point to a different copy of the file, and it is too late to
4399 // to rebuild safely.
4400 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4401 // after input file validation only real problems would remain and we
4402 // could just error. For now, assume it's okay.
4403 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 }
4405 }
4406 break;
4407 }
4408
Richard Smith202210b2014-10-24 20:23:01 +00004409 case SUBMODULE_HEADER:
4410 case SUBMODULE_EXCLUDED_HEADER:
4411 case SUBMODULE_PRIVATE_HEADER:
4412 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004413 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4414 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004415 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004416
Richard Smith202210b2014-10-24 20:23:01 +00004417 case SUBMODULE_TEXTUAL_HEADER:
4418 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4419 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4420 // them here.
4421 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004422
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004424 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004425 break;
4426 }
4427
4428 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004429 std::string Dirname = Blob;
4430 ResolveImportedPath(F, Dirname);
4431 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004432 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004433 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4434 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004435 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4436 Error("mismatched umbrella directories in submodule");
4437 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004438 }
4439 }
4440 break;
4441 }
4442
4443 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004444 F.BaseSubmoduleID = getTotalNumSubmodules();
4445 F.LocalNumSubmodules = Record[0];
4446 unsigned LocalBaseSubmoduleID = Record[1];
4447 if (F.LocalNumSubmodules > 0) {
4448 // Introduce the global -> local mapping for submodules within this
4449 // module.
4450 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4451
4452 // Introduce the local -> global mapping for submodules within this
4453 // module.
4454 F.SubmoduleRemap.insertOrReplace(
4455 std::make_pair(LocalBaseSubmoduleID,
4456 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004457
Ben Langmuir52ca6782014-10-20 16:27:32 +00004458 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4459 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 break;
4461 }
4462
4463 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004465 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 Unresolved.File = &F;
4467 Unresolved.Mod = CurrentModule;
4468 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004469 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004470 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004471 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004472 }
4473 break;
4474 }
4475
4476 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004478 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004479 Unresolved.File = &F;
4480 Unresolved.Mod = CurrentModule;
4481 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004482 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004484 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004485 }
4486
4487 // Once we've loaded the set of exports, there's no reason to keep
4488 // the parsed, unresolved exports around.
4489 CurrentModule->UnresolvedExports.clear();
4490 break;
4491 }
4492 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004493 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004494 Context.getTargetInfo());
4495 break;
4496 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004497
4498 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004499 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004500 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004501 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004502
4503 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004504 CurrentModule->ConfigMacros.push_back(Blob.str());
4505 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004506
4507 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004508 UnresolvedModuleRef Unresolved;
4509 Unresolved.File = &F;
4510 Unresolved.Mod = CurrentModule;
4511 Unresolved.ID = Record[0];
4512 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4513 Unresolved.IsWildcard = false;
4514 Unresolved.String = Blob;
4515 UnresolvedModuleRefs.push_back(Unresolved);
4516 break;
4517 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004518 }
4519 }
4520}
4521
4522/// \brief Parse the record that corresponds to a LangOptions data
4523/// structure.
4524///
4525/// This routine parses the language options from the AST file and then gives
4526/// them to the AST listener if one is set.
4527///
4528/// \returns true if the listener deems the file unacceptable, false otherwise.
4529bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4530 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004531 ASTReaderListener &Listener,
4532 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004533 LangOptions LangOpts;
4534 unsigned Idx = 0;
4535#define LANGOPT(Name, Bits, Default, Description) \
4536 LangOpts.Name = Record[Idx++];
4537#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4538 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4539#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004540#define SANITIZER(NAME, ID) \
4541 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004542#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004543
Ben Langmuircd98cb72015-06-23 18:20:18 +00004544 for (unsigned N = Record[Idx++]; N; --N)
4545 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4546
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4548 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4549 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004550
Ben Langmuird4a667a2015-06-23 18:20:23 +00004551 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004552
4553 // Comment options.
4554 for (unsigned N = Record[Idx++]; N; --N) {
4555 LangOpts.CommentOpts.BlockCommandNames.push_back(
4556 ReadString(Record, Idx));
4557 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004558 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004559
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004560 return Listener.ReadLanguageOptions(LangOpts, Complain,
4561 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004562}
4563
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004564bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4565 ASTReaderListener &Listener,
4566 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004567 unsigned Idx = 0;
4568 TargetOptions TargetOpts;
4569 TargetOpts.Triple = ReadString(Record, Idx);
4570 TargetOpts.CPU = ReadString(Record, Idx);
4571 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004572 for (unsigned N = Record[Idx++]; N; --N) {
4573 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4574 }
4575 for (unsigned N = Record[Idx++]; N; --N) {
4576 TargetOpts.Features.push_back(ReadString(Record, Idx));
4577 }
4578
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004579 return Listener.ReadTargetOptions(TargetOpts, Complain,
4580 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004581}
4582
4583bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4584 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004585 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004586 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004587#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004588#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004589 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004590#include "clang/Basic/DiagnosticOptions.def"
4591
Richard Smith3be1cb22014-08-07 00:24:21 +00004592 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004593 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004594 for (unsigned N = Record[Idx++]; N; --N)
4595 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004596
4597 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4598}
4599
4600bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4601 ASTReaderListener &Listener) {
4602 FileSystemOptions FSOpts;
4603 unsigned Idx = 0;
4604 FSOpts.WorkingDir = ReadString(Record, Idx);
4605 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4606}
4607
4608bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4609 bool Complain,
4610 ASTReaderListener &Listener) {
4611 HeaderSearchOptions HSOpts;
4612 unsigned Idx = 0;
4613 HSOpts.Sysroot = ReadString(Record, Idx);
4614
4615 // Include entries.
4616 for (unsigned N = Record[Idx++]; N; --N) {
4617 std::string Path = ReadString(Record, Idx);
4618 frontend::IncludeDirGroup Group
4619 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 bool IsFramework = Record[Idx++];
4621 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004622 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4623 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004624 }
4625
4626 // System header prefixes.
4627 for (unsigned N = Record[Idx++]; N; --N) {
4628 std::string Prefix = ReadString(Record, Idx);
4629 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004630 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004631 }
4632
4633 HSOpts.ResourceDir = ReadString(Record, Idx);
4634 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004635 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004636 HSOpts.DisableModuleHash = Record[Idx++];
4637 HSOpts.UseBuiltinIncludes = Record[Idx++];
4638 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4639 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4640 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004641 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004642
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004643 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4644 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004645}
4646
4647bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4648 bool Complain,
4649 ASTReaderListener &Listener,
4650 std::string &SuggestedPredefines) {
4651 PreprocessorOptions PPOpts;
4652 unsigned Idx = 0;
4653
4654 // Macro definitions/undefs
4655 for (unsigned N = Record[Idx++]; N; --N) {
4656 std::string Macro = ReadString(Record, Idx);
4657 bool IsUndef = Record[Idx++];
4658 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4659 }
4660
4661 // Includes
4662 for (unsigned N = Record[Idx++]; N; --N) {
4663 PPOpts.Includes.push_back(ReadString(Record, Idx));
4664 }
4665
4666 // Macro Includes
4667 for (unsigned N = Record[Idx++]; N; --N) {
4668 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4669 }
4670
4671 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004672 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004673 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4674 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4675 PPOpts.ObjCXXARCStandardLibrary =
4676 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4677 SuggestedPredefines.clear();
4678 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4679 SuggestedPredefines);
4680}
4681
4682std::pair<ModuleFile *, unsigned>
4683ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4684 GlobalPreprocessedEntityMapType::iterator
4685 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4686 assert(I != GlobalPreprocessedEntityMap.end() &&
4687 "Corrupted global preprocessed entity map");
4688 ModuleFile *M = I->second;
4689 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4690 return std::make_pair(M, LocalIndex);
4691}
4692
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004693llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004694ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4695 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4696 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4697 Mod.NumPreprocessedEntities);
4698
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004699 return llvm::make_range(PreprocessingRecord::iterator(),
4700 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004701}
4702
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004703llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004704ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004705 return llvm::make_range(
4706 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4707 ModuleDeclIterator(this, &Mod,
4708 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004709}
4710
4711PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4712 PreprocessedEntityID PPID = Index+1;
4713 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4714 ModuleFile &M = *PPInfo.first;
4715 unsigned LocalIndex = PPInfo.second;
4716 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4717
Guy Benyei11169dd2012-12-18 14:30:41 +00004718 if (!PP.getPreprocessingRecord()) {
4719 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004720 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004721 }
4722
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004723 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4724 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4725
4726 llvm::BitstreamEntry Entry =
4727 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4728 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004729 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004730
Guy Benyei11169dd2012-12-18 14:30:41 +00004731 // Read the record.
4732 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4733 ReadSourceLocation(M, PPOffs.End));
4734 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004735 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004736 RecordData Record;
4737 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004738 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4739 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004740 switch (RecType) {
4741 case PPD_MACRO_EXPANSION: {
4742 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004743 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004744 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004745 if (isBuiltin)
4746 Name = getLocalIdentifier(M, Record[1]);
4747 else {
Richard Smith66a81862015-05-04 02:25:31 +00004748 PreprocessedEntityID GlobalID =
4749 getGlobalPreprocessedEntityID(M, Record[1]);
4750 Def = cast<MacroDefinitionRecord>(
4751 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004752 }
4753
4754 MacroExpansion *ME;
4755 if (isBuiltin)
4756 ME = new (PPRec) MacroExpansion(Name, Range);
4757 else
4758 ME = new (PPRec) MacroExpansion(Def, Range);
4759
4760 return ME;
4761 }
4762
4763 case PPD_MACRO_DEFINITION: {
4764 // Decode the identifier info and then check again; if the macro is
4765 // still defined and associated with the identifier,
4766 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004767 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004768
4769 if (DeserializationListener)
4770 DeserializationListener->MacroDefinitionRead(PPID, MD);
4771
4772 return MD;
4773 }
4774
4775 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004776 const char *FullFileNameStart = Blob.data() + Record[0];
4777 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004778 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004779 if (!FullFileName.empty())
4780 File = PP.getFileManager().getFile(FullFileName);
4781
4782 // FIXME: Stable encoding
4783 InclusionDirective::InclusionKind Kind
4784 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4785 InclusionDirective *ID
4786 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004787 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004788 Record[1], Record[3],
4789 File,
4790 Range);
4791 return ID;
4792 }
4793 }
4794
4795 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4796}
4797
4798/// \brief \arg SLocMapI points at a chunk of a module that contains no
4799/// preprocessed entities or the entities it contains are not the ones we are
4800/// looking for. Find the next module that contains entities and return the ID
4801/// of the first entry.
4802PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4803 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4804 ++SLocMapI;
4805 for (GlobalSLocOffsetMapType::const_iterator
4806 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4807 ModuleFile &M = *SLocMapI->second;
4808 if (M.NumPreprocessedEntities)
4809 return M.BasePreprocessedEntityID;
4810 }
4811
4812 return getTotalNumPreprocessedEntities();
4813}
4814
4815namespace {
4816
4817template <unsigned PPEntityOffset::*PPLoc>
4818struct PPEntityComp {
4819 const ASTReader &Reader;
4820 ModuleFile &M;
4821
4822 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4823
4824 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4825 SourceLocation LHS = getLoc(L);
4826 SourceLocation RHS = getLoc(R);
4827 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4828 }
4829
4830 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4831 SourceLocation LHS = getLoc(L);
4832 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4833 }
4834
4835 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4836 SourceLocation RHS = getLoc(R);
4837 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4838 }
4839
4840 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4841 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4842 }
4843};
4844
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004845}
Guy Benyei11169dd2012-12-18 14:30:41 +00004846
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004847PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4848 bool EndsAfter) const {
4849 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004850 return getTotalNumPreprocessedEntities();
4851
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004852 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4853 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004854 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4855 "Corrupted global sloc offset map");
4856
4857 if (SLocMapI->second->NumPreprocessedEntities == 0)
4858 return findNextPreprocessedEntity(SLocMapI);
4859
4860 ModuleFile &M = *SLocMapI->second;
4861 typedef const PPEntityOffset *pp_iterator;
4862 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4863 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4864
4865 size_t Count = M.NumPreprocessedEntities;
4866 size_t Half;
4867 pp_iterator First = pp_begin;
4868 pp_iterator PPI;
4869
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004870 if (EndsAfter) {
4871 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4872 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4873 } else {
4874 // Do a binary search manually instead of using std::lower_bound because
4875 // The end locations of entities may be unordered (when a macro expansion
4876 // is inside another macro argument), but for this case it is not important
4877 // whether we get the first macro expansion or its containing macro.
4878 while (Count > 0) {
4879 Half = Count / 2;
4880 PPI = First;
4881 std::advance(PPI, Half);
4882 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4883 Loc)) {
4884 First = PPI;
4885 ++First;
4886 Count = Count - Half - 1;
4887 } else
4888 Count = Half;
4889 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004890 }
4891
4892 if (PPI == pp_end)
4893 return findNextPreprocessedEntity(SLocMapI);
4894
4895 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4896}
4897
Guy Benyei11169dd2012-12-18 14:30:41 +00004898/// \brief Returns a pair of [Begin, End) indices of preallocated
4899/// preprocessed entities that \arg Range encompasses.
4900std::pair<unsigned, unsigned>
4901 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4902 if (Range.isInvalid())
4903 return std::make_pair(0,0);
4904 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4905
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004906 PreprocessedEntityID BeginID =
4907 findPreprocessedEntity(Range.getBegin(), false);
4908 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004909 return std::make_pair(BeginID, EndID);
4910}
4911
4912/// \brief Optionally returns true or false if the preallocated preprocessed
4913/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004914Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 FileID FID) {
4916 if (FID.isInvalid())
4917 return false;
4918
4919 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4920 ModuleFile &M = *PPInfo.first;
4921 unsigned LocalIndex = PPInfo.second;
4922 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4923
4924 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4925 if (Loc.isInvalid())
4926 return false;
4927
4928 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4929 return true;
4930 else
4931 return false;
4932}
4933
4934namespace {
4935 /// \brief Visitor used to search for information about a header file.
4936 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004937 const FileEntry *FE;
4938
David Blaikie05785d12013-02-20 22:23:23 +00004939 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004940
4941 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004942 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4943 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004944
4945 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004946 HeaderFileInfoLookupTable *Table
4947 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4948 if (!Table)
4949 return false;
4950
4951 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00004952 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004953 if (Pos == Table->end())
4954 return false;
4955
Richard Smithbdf2d932015-07-30 03:37:16 +00004956 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00004957 return true;
4958 }
4959
David Blaikie05785d12013-02-20 22:23:23 +00004960 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004961 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004962}
Guy Benyei11169dd2012-12-18 14:30:41 +00004963
4964HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004965 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004966 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004967 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004968 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004969
4970 return HeaderFileInfo();
4971}
4972
4973void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4974 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004975 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004976 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4977 ModuleFile &F = *(*I);
4978 unsigned Idx = 0;
4979 DiagStates.clear();
4980 assert(!Diag.DiagStates.empty());
4981 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4982 while (Idx < F.PragmaDiagMappings.size()) {
4983 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4984 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4985 if (DiagStateID != 0) {
4986 Diag.DiagStatePoints.push_back(
4987 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4988 FullSourceLoc(Loc, SourceMgr)));
4989 continue;
4990 }
4991
4992 assert(DiagStateID == 0);
4993 // A new DiagState was created here.
4994 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4995 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4996 DiagStates.push_back(NewState);
4997 Diag.DiagStatePoints.push_back(
4998 DiagnosticsEngine::DiagStatePoint(NewState,
4999 FullSourceLoc(Loc, SourceMgr)));
5000 while (1) {
5001 assert(Idx < F.PragmaDiagMappings.size() &&
5002 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5003 if (Idx >= F.PragmaDiagMappings.size()) {
5004 break; // Something is messed up but at least avoid infinite loop in
5005 // release build.
5006 }
5007 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5008 if (DiagID == (unsigned)-1) {
5009 break; // no more diag/map pairs for this location.
5010 }
Alp Tokerc726c362014-06-10 09:31:37 +00005011 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5012 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5013 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005014 }
5015 }
5016 }
5017}
5018
5019/// \brief Get the correct cursor and offset for loading a type.
5020ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5021 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5022 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5023 ModuleFile *M = I->second;
5024 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5025}
5026
5027/// \brief Read and return the type with the given index..
5028///
5029/// The index is the type ID, shifted and minus the number of predefs. This
5030/// routine actually reads the record corresponding to the type at the given
5031/// location. It is a helper routine for GetType, which deals with reading type
5032/// IDs.
5033QualType ASTReader::readTypeRecord(unsigned Index) {
5034 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005035 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005036
5037 // Keep track of where we are in the stream, then jump back there
5038 // after reading this type.
5039 SavedStreamPosition SavedPosition(DeclsCursor);
5040
5041 ReadingKindTracker ReadingKind(Read_Type, *this);
5042
5043 // Note that we are loading a type record.
5044 Deserializing AType(this);
5045
5046 unsigned Idx = 0;
5047 DeclsCursor.JumpToBit(Loc.Offset);
5048 RecordData Record;
5049 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005050 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 case TYPE_EXT_QUAL: {
5052 if (Record.size() != 2) {
5053 Error("Incorrect encoding of extended qualifier type");
5054 return QualType();
5055 }
5056 QualType Base = readType(*Loc.F, Record, Idx);
5057 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5058 return Context.getQualifiedType(Base, Quals);
5059 }
5060
5061 case TYPE_COMPLEX: {
5062 if (Record.size() != 1) {
5063 Error("Incorrect encoding of complex type");
5064 return QualType();
5065 }
5066 QualType ElemType = readType(*Loc.F, Record, Idx);
5067 return Context.getComplexType(ElemType);
5068 }
5069
5070 case TYPE_POINTER: {
5071 if (Record.size() != 1) {
5072 Error("Incorrect encoding of pointer type");
5073 return QualType();
5074 }
5075 QualType PointeeType = readType(*Loc.F, Record, Idx);
5076 return Context.getPointerType(PointeeType);
5077 }
5078
Reid Kleckner8a365022013-06-24 17:51:48 +00005079 case TYPE_DECAYED: {
5080 if (Record.size() != 1) {
5081 Error("Incorrect encoding of decayed type");
5082 return QualType();
5083 }
5084 QualType OriginalType = readType(*Loc.F, Record, Idx);
5085 QualType DT = Context.getAdjustedParameterType(OriginalType);
5086 if (!isa<DecayedType>(DT))
5087 Error("Decayed type does not decay");
5088 return DT;
5089 }
5090
Reid Kleckner0503a872013-12-05 01:23:43 +00005091 case TYPE_ADJUSTED: {
5092 if (Record.size() != 2) {
5093 Error("Incorrect encoding of adjusted type");
5094 return QualType();
5095 }
5096 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5097 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5098 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5099 }
5100
Guy Benyei11169dd2012-12-18 14:30:41 +00005101 case TYPE_BLOCK_POINTER: {
5102 if (Record.size() != 1) {
5103 Error("Incorrect encoding of block pointer type");
5104 return QualType();
5105 }
5106 QualType PointeeType = readType(*Loc.F, Record, Idx);
5107 return Context.getBlockPointerType(PointeeType);
5108 }
5109
5110 case TYPE_LVALUE_REFERENCE: {
5111 if (Record.size() != 2) {
5112 Error("Incorrect encoding of lvalue reference type");
5113 return QualType();
5114 }
5115 QualType PointeeType = readType(*Loc.F, Record, Idx);
5116 return Context.getLValueReferenceType(PointeeType, Record[1]);
5117 }
5118
5119 case TYPE_RVALUE_REFERENCE: {
5120 if (Record.size() != 1) {
5121 Error("Incorrect encoding of rvalue reference type");
5122 return QualType();
5123 }
5124 QualType PointeeType = readType(*Loc.F, Record, Idx);
5125 return Context.getRValueReferenceType(PointeeType);
5126 }
5127
5128 case TYPE_MEMBER_POINTER: {
5129 if (Record.size() != 2) {
5130 Error("Incorrect encoding of member pointer type");
5131 return QualType();
5132 }
5133 QualType PointeeType = readType(*Loc.F, Record, Idx);
5134 QualType ClassType = readType(*Loc.F, Record, Idx);
5135 if (PointeeType.isNull() || ClassType.isNull())
5136 return QualType();
5137
5138 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5139 }
5140
5141 case TYPE_CONSTANT_ARRAY: {
5142 QualType ElementType = readType(*Loc.F, Record, Idx);
5143 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5144 unsigned IndexTypeQuals = Record[2];
5145 unsigned Idx = 3;
5146 llvm::APInt Size = ReadAPInt(Record, Idx);
5147 return Context.getConstantArrayType(ElementType, Size,
5148 ASM, IndexTypeQuals);
5149 }
5150
5151 case TYPE_INCOMPLETE_ARRAY: {
5152 QualType ElementType = readType(*Loc.F, Record, Idx);
5153 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5154 unsigned IndexTypeQuals = Record[2];
5155 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5156 }
5157
5158 case TYPE_VARIABLE_ARRAY: {
5159 QualType ElementType = readType(*Loc.F, Record, Idx);
5160 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5161 unsigned IndexTypeQuals = Record[2];
5162 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5163 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5164 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5165 ASM, IndexTypeQuals,
5166 SourceRange(LBLoc, RBLoc));
5167 }
5168
5169 case TYPE_VECTOR: {
5170 if (Record.size() != 3) {
5171 Error("incorrect encoding of vector type in AST file");
5172 return QualType();
5173 }
5174
5175 QualType ElementType = readType(*Loc.F, Record, Idx);
5176 unsigned NumElements = Record[1];
5177 unsigned VecKind = Record[2];
5178 return Context.getVectorType(ElementType, NumElements,
5179 (VectorType::VectorKind)VecKind);
5180 }
5181
5182 case TYPE_EXT_VECTOR: {
5183 if (Record.size() != 3) {
5184 Error("incorrect encoding of extended vector type in AST file");
5185 return QualType();
5186 }
5187
5188 QualType ElementType = readType(*Loc.F, Record, Idx);
5189 unsigned NumElements = Record[1];
5190 return Context.getExtVectorType(ElementType, NumElements);
5191 }
5192
5193 case TYPE_FUNCTION_NO_PROTO: {
5194 if (Record.size() != 6) {
5195 Error("incorrect encoding of no-proto function type");
5196 return QualType();
5197 }
5198 QualType ResultType = readType(*Loc.F, Record, Idx);
5199 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5200 (CallingConv)Record[4], Record[5]);
5201 return Context.getFunctionNoProtoType(ResultType, Info);
5202 }
5203
5204 case TYPE_FUNCTION_PROTO: {
5205 QualType ResultType = readType(*Loc.F, Record, Idx);
5206
5207 FunctionProtoType::ExtProtoInfo EPI;
5208 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5209 /*hasregparm*/ Record[2],
5210 /*regparm*/ Record[3],
5211 static_cast<CallingConv>(Record[4]),
5212 /*produces*/ Record[5]);
5213
5214 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005215
5216 EPI.Variadic = Record[Idx++];
5217 EPI.HasTrailingReturn = Record[Idx++];
5218 EPI.TypeQuals = Record[Idx++];
5219 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005220 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005221 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005222
5223 unsigned NumParams = Record[Idx++];
5224 SmallVector<QualType, 16> ParamTypes;
5225 for (unsigned I = 0; I != NumParams; ++I)
5226 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5227
Jordan Rose5c382722013-03-08 21:51:21 +00005228 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005229 }
5230
5231 case TYPE_UNRESOLVED_USING: {
5232 unsigned Idx = 0;
5233 return Context.getTypeDeclType(
5234 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5235 }
5236
5237 case TYPE_TYPEDEF: {
5238 if (Record.size() != 2) {
5239 Error("incorrect encoding of typedef type");
5240 return QualType();
5241 }
5242 unsigned Idx = 0;
5243 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5244 QualType Canonical = readType(*Loc.F, Record, Idx);
5245 if (!Canonical.isNull())
5246 Canonical = Context.getCanonicalType(Canonical);
5247 return Context.getTypedefType(Decl, Canonical);
5248 }
5249
5250 case TYPE_TYPEOF_EXPR:
5251 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5252
5253 case TYPE_TYPEOF: {
5254 if (Record.size() != 1) {
5255 Error("incorrect encoding of typeof(type) in AST file");
5256 return QualType();
5257 }
5258 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5259 return Context.getTypeOfType(UnderlyingType);
5260 }
5261
5262 case TYPE_DECLTYPE: {
5263 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5264 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5265 }
5266
5267 case TYPE_UNARY_TRANSFORM: {
5268 QualType BaseType = readType(*Loc.F, Record, Idx);
5269 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5270 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5271 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5272 }
5273
Richard Smith74aeef52013-04-26 16:15:35 +00005274 case TYPE_AUTO: {
5275 QualType Deduced = readType(*Loc.F, Record, Idx);
5276 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005277 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005278 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005279 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005280
5281 case TYPE_RECORD: {
5282 if (Record.size() != 2) {
5283 Error("incorrect encoding of record type");
5284 return QualType();
5285 }
5286 unsigned Idx = 0;
5287 bool IsDependent = Record[Idx++];
5288 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5289 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5290 QualType T = Context.getRecordType(RD);
5291 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5292 return T;
5293 }
5294
5295 case TYPE_ENUM: {
5296 if (Record.size() != 2) {
5297 Error("incorrect encoding of enum type");
5298 return QualType();
5299 }
5300 unsigned Idx = 0;
5301 bool IsDependent = Record[Idx++];
5302 QualType T
5303 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5304 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5305 return T;
5306 }
5307
5308 case TYPE_ATTRIBUTED: {
5309 if (Record.size() != 3) {
5310 Error("incorrect encoding of attributed type");
5311 return QualType();
5312 }
5313 QualType modifiedType = readType(*Loc.F, Record, Idx);
5314 QualType equivalentType = readType(*Loc.F, Record, Idx);
5315 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5316 return Context.getAttributedType(kind, modifiedType, equivalentType);
5317 }
5318
5319 case TYPE_PAREN: {
5320 if (Record.size() != 1) {
5321 Error("incorrect encoding of paren type");
5322 return QualType();
5323 }
5324 QualType InnerType = readType(*Loc.F, Record, Idx);
5325 return Context.getParenType(InnerType);
5326 }
5327
5328 case TYPE_PACK_EXPANSION: {
5329 if (Record.size() != 2) {
5330 Error("incorrect encoding of pack expansion type");
5331 return QualType();
5332 }
5333 QualType Pattern = readType(*Loc.F, Record, Idx);
5334 if (Pattern.isNull())
5335 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005336 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005337 if (Record[1])
5338 NumExpansions = Record[1] - 1;
5339 return Context.getPackExpansionType(Pattern, NumExpansions);
5340 }
5341
5342 case TYPE_ELABORATED: {
5343 unsigned Idx = 0;
5344 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5345 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5346 QualType NamedType = readType(*Loc.F, Record, Idx);
5347 return Context.getElaboratedType(Keyword, NNS, NamedType);
5348 }
5349
5350 case TYPE_OBJC_INTERFACE: {
5351 unsigned Idx = 0;
5352 ObjCInterfaceDecl *ItfD
5353 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5354 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5355 }
5356
5357 case TYPE_OBJC_OBJECT: {
5358 unsigned Idx = 0;
5359 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005360 unsigned NumTypeArgs = Record[Idx++];
5361 SmallVector<QualType, 4> TypeArgs;
5362 for (unsigned I = 0; I != NumTypeArgs; ++I)
5363 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005364 unsigned NumProtos = Record[Idx++];
5365 SmallVector<ObjCProtocolDecl*, 4> Protos;
5366 for (unsigned I = 0; I != NumProtos; ++I)
5367 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005368 bool IsKindOf = Record[Idx++];
5369 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005370 }
5371
5372 case TYPE_OBJC_OBJECT_POINTER: {
5373 unsigned Idx = 0;
5374 QualType Pointee = readType(*Loc.F, Record, Idx);
5375 return Context.getObjCObjectPointerType(Pointee);
5376 }
5377
5378 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5379 unsigned Idx = 0;
5380 QualType Parm = readType(*Loc.F, Record, Idx);
5381 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005382 return Context.getSubstTemplateTypeParmType(
5383 cast<TemplateTypeParmType>(Parm),
5384 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005385 }
5386
5387 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5388 unsigned Idx = 0;
5389 QualType Parm = readType(*Loc.F, Record, Idx);
5390 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5391 return Context.getSubstTemplateTypeParmPackType(
5392 cast<TemplateTypeParmType>(Parm),
5393 ArgPack);
5394 }
5395
5396 case TYPE_INJECTED_CLASS_NAME: {
5397 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5398 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5399 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5400 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005401 const Type *T = nullptr;
5402 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5403 if (const Type *Existing = DI->getTypeForDecl()) {
5404 T = Existing;
5405 break;
5406 }
5407 }
5408 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005409 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005410 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5411 DI->setTypeForDecl(T);
5412 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005413 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005414 }
5415
5416 case TYPE_TEMPLATE_TYPE_PARM: {
5417 unsigned Idx = 0;
5418 unsigned Depth = Record[Idx++];
5419 unsigned Index = Record[Idx++];
5420 bool Pack = Record[Idx++];
5421 TemplateTypeParmDecl *D
5422 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5423 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5424 }
5425
5426 case TYPE_DEPENDENT_NAME: {
5427 unsigned Idx = 0;
5428 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5429 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005430 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005431 QualType Canon = readType(*Loc.F, Record, Idx);
5432 if (!Canon.isNull())
5433 Canon = Context.getCanonicalType(Canon);
5434 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5435 }
5436
5437 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5438 unsigned Idx = 0;
5439 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5440 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005441 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005442 unsigned NumArgs = Record[Idx++];
5443 SmallVector<TemplateArgument, 8> Args;
5444 Args.reserve(NumArgs);
5445 while (NumArgs--)
5446 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5447 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5448 Args.size(), Args.data());
5449 }
5450
5451 case TYPE_DEPENDENT_SIZED_ARRAY: {
5452 unsigned Idx = 0;
5453
5454 // ArrayType
5455 QualType ElementType = readType(*Loc.F, Record, Idx);
5456 ArrayType::ArraySizeModifier ASM
5457 = (ArrayType::ArraySizeModifier)Record[Idx++];
5458 unsigned IndexTypeQuals = Record[Idx++];
5459
5460 // DependentSizedArrayType
5461 Expr *NumElts = ReadExpr(*Loc.F);
5462 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5463
5464 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5465 IndexTypeQuals, Brackets);
5466 }
5467
5468 case TYPE_TEMPLATE_SPECIALIZATION: {
5469 unsigned Idx = 0;
5470 bool IsDependent = Record[Idx++];
5471 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5472 SmallVector<TemplateArgument, 8> Args;
5473 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5474 QualType Underlying = readType(*Loc.F, Record, Idx);
5475 QualType T;
5476 if (Underlying.isNull())
5477 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5478 Args.size());
5479 else
5480 T = Context.getTemplateSpecializationType(Name, Args.data(),
5481 Args.size(), Underlying);
5482 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5483 return T;
5484 }
5485
5486 case TYPE_ATOMIC: {
5487 if (Record.size() != 1) {
5488 Error("Incorrect encoding of atomic type");
5489 return QualType();
5490 }
5491 QualType ValueType = readType(*Loc.F, Record, Idx);
5492 return Context.getAtomicType(ValueType);
5493 }
5494 }
5495 llvm_unreachable("Invalid TypeCode!");
5496}
5497
Richard Smith564417a2014-03-20 21:47:22 +00005498void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5499 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005500 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005501 const RecordData &Record, unsigned &Idx) {
5502 ExceptionSpecificationType EST =
5503 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005504 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005505 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005506 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005507 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005508 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005509 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005510 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005511 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005512 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5513 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005514 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005515 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005516 }
5517}
5518
Guy Benyei11169dd2012-12-18 14:30:41 +00005519class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5520 ASTReader &Reader;
5521 ModuleFile &F;
5522 const ASTReader::RecordData &Record;
5523 unsigned &Idx;
5524
5525 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5526 unsigned &I) {
5527 return Reader.ReadSourceLocation(F, R, I);
5528 }
5529
5530 template<typename T>
5531 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5532 return Reader.ReadDeclAs<T>(F, Record, Idx);
5533 }
5534
5535public:
5536 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5537 const ASTReader::RecordData &Record, unsigned &Idx)
5538 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5539 { }
5540
5541 // We want compile-time assurance that we've enumerated all of
5542 // these, so unfortunately we have to declare them first, then
5543 // define them out-of-line.
5544#define ABSTRACT_TYPELOC(CLASS, PARENT)
5545#define TYPELOC(CLASS, PARENT) \
5546 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5547#include "clang/AST/TypeLocNodes.def"
5548
5549 void VisitFunctionTypeLoc(FunctionTypeLoc);
5550 void VisitArrayTypeLoc(ArrayTypeLoc);
5551};
5552
5553void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5554 // nothing to do
5555}
5556void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5557 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5558 if (TL.needsExtraLocalData()) {
5559 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5560 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5561 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5562 TL.setModeAttr(Record[Idx++]);
5563 }
5564}
5565void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5566 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5567}
5568void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5569 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5570}
Reid Kleckner8a365022013-06-24 17:51:48 +00005571void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5572 // nothing to do
5573}
Reid Kleckner0503a872013-12-05 01:23:43 +00005574void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5575 // nothing to do
5576}
Guy Benyei11169dd2012-12-18 14:30:41 +00005577void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5578 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5579}
5580void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5581 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5582}
5583void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5584 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5585}
5586void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5587 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5588 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5589}
5590void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5591 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5592 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5593 if (Record[Idx++])
5594 TL.setSizeExpr(Reader.ReadExpr(F));
5595 else
Craig Toppera13603a2014-05-22 05:54:18 +00005596 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005597}
5598void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5599 VisitArrayTypeLoc(TL);
5600}
5601void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5602 VisitArrayTypeLoc(TL);
5603}
5604void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5605 VisitArrayTypeLoc(TL);
5606}
5607void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5608 DependentSizedArrayTypeLoc TL) {
5609 VisitArrayTypeLoc(TL);
5610}
5611void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5612 DependentSizedExtVectorTypeLoc TL) {
5613 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5614}
5615void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5616 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5617}
5618void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5619 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5620}
5621void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5622 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5623 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5624 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5625 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005626 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5627 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005628 }
5629}
5630void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5631 VisitFunctionTypeLoc(TL);
5632}
5633void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5634 VisitFunctionTypeLoc(TL);
5635}
5636void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5637 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5638}
5639void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5640 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5641}
5642void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5643 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5644 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5645 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5646}
5647void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5648 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5649 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5650 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5651 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5652}
5653void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5654 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5655}
5656void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5657 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5658 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5659 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5660 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5661}
5662void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5663 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5664}
5665void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5666 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5667}
5668void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5669 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5670}
5671void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5672 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5673 if (TL.hasAttrOperand()) {
5674 SourceRange range;
5675 range.setBegin(ReadSourceLocation(Record, Idx));
5676 range.setEnd(ReadSourceLocation(Record, Idx));
5677 TL.setAttrOperandParensRange(range);
5678 }
5679 if (TL.hasAttrExprOperand()) {
5680 if (Record[Idx++])
5681 TL.setAttrExprOperand(Reader.ReadExpr(F));
5682 else
Craig Toppera13603a2014-05-22 05:54:18 +00005683 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005684 } else if (TL.hasAttrEnumOperand())
5685 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5686}
5687void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5688 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5689}
5690void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5691 SubstTemplateTypeParmTypeLoc TL) {
5692 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5693}
5694void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5695 SubstTemplateTypeParmPackTypeLoc TL) {
5696 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5697}
5698void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5699 TemplateSpecializationTypeLoc TL) {
5700 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5701 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5702 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5703 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5704 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5705 TL.setArgLocInfo(i,
5706 Reader.GetTemplateArgumentLocInfo(F,
5707 TL.getTypePtr()->getArg(i).getKind(),
5708 Record, Idx));
5709}
5710void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5711 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5712 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5713}
5714void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5715 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5716 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5717}
5718void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5719 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5720}
5721void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5722 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5723 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5724 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5725}
5726void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5727 DependentTemplateSpecializationTypeLoc TL) {
5728 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5729 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5730 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5731 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5732 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5733 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5734 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5735 TL.setArgLocInfo(I,
5736 Reader.GetTemplateArgumentLocInfo(F,
5737 TL.getTypePtr()->getArg(I).getKind(),
5738 Record, Idx));
5739}
5740void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5741 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5742}
5743void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5744 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5745}
5746void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5747 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005748 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5749 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5750 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5751 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5752 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5753 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005754 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5755 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5756}
5757void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5758 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5759}
5760void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5761 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5762 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5763 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5764}
5765
5766TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5767 const RecordData &Record,
5768 unsigned &Idx) {
5769 QualType InfoTy = readType(F, Record, Idx);
5770 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005771 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005772
5773 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5774 TypeLocReader TLR(*this, F, Record, Idx);
5775 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5776 TLR.Visit(TL);
5777 return TInfo;
5778}
5779
5780QualType ASTReader::GetType(TypeID ID) {
5781 unsigned FastQuals = ID & Qualifiers::FastMask;
5782 unsigned Index = ID >> Qualifiers::FastWidth;
5783
5784 if (Index < NUM_PREDEF_TYPE_IDS) {
5785 QualType T;
5786 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00005787 case PREDEF_TYPE_NULL_ID:
5788 return QualType();
5789 case PREDEF_TYPE_VOID_ID:
5790 T = Context.VoidTy;
5791 break;
5792 case PREDEF_TYPE_BOOL_ID:
5793 T = Context.BoolTy;
5794 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005795
5796 case PREDEF_TYPE_CHAR_U_ID:
5797 case PREDEF_TYPE_CHAR_S_ID:
5798 // FIXME: Check that the signedness of CharTy is correct!
5799 T = Context.CharTy;
5800 break;
5801
Alexey Baderbdf7c842015-09-15 12:18:29 +00005802 case PREDEF_TYPE_UCHAR_ID:
5803 T = Context.UnsignedCharTy;
5804 break;
5805 case PREDEF_TYPE_USHORT_ID:
5806 T = Context.UnsignedShortTy;
5807 break;
5808 case PREDEF_TYPE_UINT_ID:
5809 T = Context.UnsignedIntTy;
5810 break;
5811 case PREDEF_TYPE_ULONG_ID:
5812 T = Context.UnsignedLongTy;
5813 break;
5814 case PREDEF_TYPE_ULONGLONG_ID:
5815 T = Context.UnsignedLongLongTy;
5816 break;
5817 case PREDEF_TYPE_UINT128_ID:
5818 T = Context.UnsignedInt128Ty;
5819 break;
5820 case PREDEF_TYPE_SCHAR_ID:
5821 T = Context.SignedCharTy;
5822 break;
5823 case PREDEF_TYPE_WCHAR_ID:
5824 T = Context.WCharTy;
5825 break;
5826 case PREDEF_TYPE_SHORT_ID:
5827 T = Context.ShortTy;
5828 break;
5829 case PREDEF_TYPE_INT_ID:
5830 T = Context.IntTy;
5831 break;
5832 case PREDEF_TYPE_LONG_ID:
5833 T = Context.LongTy;
5834 break;
5835 case PREDEF_TYPE_LONGLONG_ID:
5836 T = Context.LongLongTy;
5837 break;
5838 case PREDEF_TYPE_INT128_ID:
5839 T = Context.Int128Ty;
5840 break;
5841 case PREDEF_TYPE_HALF_ID:
5842 T = Context.HalfTy;
5843 break;
5844 case PREDEF_TYPE_FLOAT_ID:
5845 T = Context.FloatTy;
5846 break;
5847 case PREDEF_TYPE_DOUBLE_ID:
5848 T = Context.DoubleTy;
5849 break;
5850 case PREDEF_TYPE_LONGDOUBLE_ID:
5851 T = Context.LongDoubleTy;
5852 break;
5853 case PREDEF_TYPE_OVERLOAD_ID:
5854 T = Context.OverloadTy;
5855 break;
5856 case PREDEF_TYPE_BOUND_MEMBER:
5857 T = Context.BoundMemberTy;
5858 break;
5859 case PREDEF_TYPE_PSEUDO_OBJECT:
5860 T = Context.PseudoObjectTy;
5861 break;
5862 case PREDEF_TYPE_DEPENDENT_ID:
5863 T = Context.DependentTy;
5864 break;
5865 case PREDEF_TYPE_UNKNOWN_ANY:
5866 T = Context.UnknownAnyTy;
5867 break;
5868 case PREDEF_TYPE_NULLPTR_ID:
5869 T = Context.NullPtrTy;
5870 break;
5871 case PREDEF_TYPE_CHAR16_ID:
5872 T = Context.Char16Ty;
5873 break;
5874 case PREDEF_TYPE_CHAR32_ID:
5875 T = Context.Char32Ty;
5876 break;
5877 case PREDEF_TYPE_OBJC_ID:
5878 T = Context.ObjCBuiltinIdTy;
5879 break;
5880 case PREDEF_TYPE_OBJC_CLASS:
5881 T = Context.ObjCBuiltinClassTy;
5882 break;
5883 case PREDEF_TYPE_OBJC_SEL:
5884 T = Context.ObjCBuiltinSelTy;
5885 break;
5886 case PREDEF_TYPE_IMAGE1D_ID:
5887 T = Context.OCLImage1dTy;
5888 break;
5889 case PREDEF_TYPE_IMAGE1D_ARR_ID:
5890 T = Context.OCLImage1dArrayTy;
5891 break;
5892 case PREDEF_TYPE_IMAGE1D_BUFF_ID:
5893 T = Context.OCLImage1dBufferTy;
5894 break;
5895 case PREDEF_TYPE_IMAGE2D_ID:
5896 T = Context.OCLImage2dTy;
5897 break;
5898 case PREDEF_TYPE_IMAGE2D_ARR_ID:
5899 T = Context.OCLImage2dArrayTy;
5900 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00005901 case PREDEF_TYPE_IMAGE2D_DEP_ID:
5902 T = Context.OCLImage2dDepthTy;
5903 break;
5904 case PREDEF_TYPE_IMAGE2D_ARR_DEP_ID:
5905 T = Context.OCLImage2dArrayDepthTy;
5906 break;
5907 case PREDEF_TYPE_IMAGE2D_MSAA_ID:
5908 T = Context.OCLImage2dMSAATy;
5909 break;
5910 case PREDEF_TYPE_IMAGE2D_ARR_MSAA_ID:
5911 T = Context.OCLImage2dArrayMSAATy;
5912 break;
5913 case PREDEF_TYPE_IMAGE2D_MSAA_DEP_ID:
5914 T = Context.OCLImage2dMSAADepthTy;
5915 break;
5916 case PREDEF_TYPE_IMAGE2D_ARR_MSAA_DEPTH_ID:
5917 T = Context.OCLImage2dArrayMSAADepthTy;
5918 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00005919 case PREDEF_TYPE_IMAGE3D_ID:
5920 T = Context.OCLImage3dTy;
5921 break;
5922 case PREDEF_TYPE_SAMPLER_ID:
5923 T = Context.OCLSamplerTy;
5924 break;
5925 case PREDEF_TYPE_EVENT_ID:
5926 T = Context.OCLEventTy;
5927 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00005928 case PREDEF_TYPE_CLK_EVENT_ID:
5929 T = Context.OCLClkEventTy;
5930 break;
5931 case PREDEF_TYPE_QUEUE_ID:
5932 T = Context.OCLQueueTy;
5933 break;
5934 case PREDEF_TYPE_NDRANGE_ID:
5935 T = Context.OCLNDRangeTy;
5936 break;
5937 case PREDEF_TYPE_RESERVE_ID_ID:
5938 T = Context.OCLReserveIDTy;
5939 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00005940 case PREDEF_TYPE_AUTO_DEDUCT:
5941 T = Context.getAutoDeductType();
5942 break;
5943
5944 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5945 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005946 break;
5947
5948 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5949 T = Context.ARCUnbridgedCastTy;
5950 break;
5951
Guy Benyei11169dd2012-12-18 14:30:41 +00005952 case PREDEF_TYPE_BUILTIN_FN:
5953 T = Context.BuiltinFnTy;
5954 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005955
5956 case PREDEF_TYPE_OMP_ARRAY_SECTION:
5957 T = Context.OMPArraySectionTy;
5958 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005959 }
5960
5961 assert(!T.isNull() && "Unknown predefined type");
5962 return T.withFastQualifiers(FastQuals);
5963 }
5964
5965 Index -= NUM_PREDEF_TYPE_IDS;
5966 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5967 if (TypesLoaded[Index].isNull()) {
5968 TypesLoaded[Index] = readTypeRecord(Index);
5969 if (TypesLoaded[Index].isNull())
5970 return QualType();
5971
5972 TypesLoaded[Index]->setFromAST();
5973 if (DeserializationListener)
5974 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5975 TypesLoaded[Index]);
5976 }
5977
5978 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5979}
5980
5981QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5982 return GetType(getGlobalTypeID(F, LocalID));
5983}
5984
5985serialization::TypeID
5986ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5987 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5988 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5989
5990 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5991 return LocalID;
5992
5993 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5994 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5995 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5996
5997 unsigned GlobalIndex = LocalIndex + I->second;
5998 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5999}
6000
6001TemplateArgumentLocInfo
6002ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6003 TemplateArgument::ArgKind Kind,
6004 const RecordData &Record,
6005 unsigned &Index) {
6006 switch (Kind) {
6007 case TemplateArgument::Expression:
6008 return ReadExpr(F);
6009 case TemplateArgument::Type:
6010 return GetTypeSourceInfo(F, Record, Index);
6011 case TemplateArgument::Template: {
6012 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6013 Index);
6014 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6015 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6016 SourceLocation());
6017 }
6018 case TemplateArgument::TemplateExpansion: {
6019 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6020 Index);
6021 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6022 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6023 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6024 EllipsisLoc);
6025 }
6026 case TemplateArgument::Null:
6027 case TemplateArgument::Integral:
6028 case TemplateArgument::Declaration:
6029 case TemplateArgument::NullPtr:
6030 case TemplateArgument::Pack:
6031 // FIXME: Is this right?
6032 return TemplateArgumentLocInfo();
6033 }
6034 llvm_unreachable("unexpected template argument loc");
6035}
6036
6037TemplateArgumentLoc
6038ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6039 const RecordData &Record, unsigned &Index) {
6040 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6041
6042 if (Arg.getKind() == TemplateArgument::Expression) {
6043 if (Record[Index++]) // bool InfoHasSameExpr.
6044 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6045 }
6046 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6047 Record, Index));
6048}
6049
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006050const ASTTemplateArgumentListInfo*
6051ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6052 const RecordData &Record,
6053 unsigned &Index) {
6054 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6055 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6056 unsigned NumArgsAsWritten = Record[Index++];
6057 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6058 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6059 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6060 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6061}
6062
Guy Benyei11169dd2012-12-18 14:30:41 +00006063Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6064 return GetDecl(ID);
6065}
6066
Richard Smith50895422015-01-31 03:04:55 +00006067template<typename TemplateSpecializationDecl>
6068static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6069 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6070 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6071}
6072
Richard Smith053f6c62014-05-16 23:01:30 +00006073void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006074 if (NumCurrentElementsDeserializing) {
6075 // We arrange to not care about the complete redeclaration chain while we're
6076 // deserializing. Just remember that the AST has marked this one as complete
6077 // but that it's not actually complete yet, so we know we still need to
6078 // complete it later.
6079 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6080 return;
6081 }
6082
Richard Smith053f6c62014-05-16 23:01:30 +00006083 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6084
Richard Smith053f6c62014-05-16 23:01:30 +00006085 // If this is a named declaration, complete it by looking it up
6086 // within its context.
6087 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006088 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006089 // all mergeable entities within it.
6090 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6091 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6092 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006093 if (!getContext().getLangOpts().CPlusPlus &&
6094 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006095 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006096 // the identifier instead. (For C++ modules, we don't store decls
6097 // in the serialized identifier table, so we do the lookup in the TU.)
6098 auto *II = Name.getAsIdentifierInfo();
6099 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006100 if (II->isOutOfDate())
6101 updateOutOfDateIdentifier(*II);
6102 } else
6103 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006104 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006105 // Find all declarations of this kind from the relevant context.
6106 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6107 auto *DC = cast<DeclContext>(DCDecl);
6108 SmallVector<Decl*, 8> Decls;
6109 FindExternalLexicalDecls(
6110 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6111 }
Richard Smith053f6c62014-05-16 23:01:30 +00006112 }
6113 }
Richard Smith50895422015-01-31 03:04:55 +00006114
6115 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6116 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6117 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6118 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6119 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6120 if (auto *Template = FD->getPrimaryTemplate())
6121 Template->LoadLazySpecializations();
6122 }
Richard Smith053f6c62014-05-16 23:01:30 +00006123}
6124
Richard Smithc2bb8182015-03-24 06:36:48 +00006125uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
6126 const RecordData &Record,
6127 unsigned &Idx) {
6128 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
6129 Error("malformed AST file: missing C++ ctor initializers");
6130 return 0;
6131 }
6132
6133 unsigned LocalID = Record[Idx++];
6134 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6135}
6136
6137CXXCtorInitializer **
6138ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6139 RecordLocation Loc = getLocalBitOffset(Offset);
6140 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6141 SavedStreamPosition SavedPosition(Cursor);
6142 Cursor.JumpToBit(Loc.Offset);
6143 ReadingKindTracker ReadingKind(Read_Decl, *this);
6144
6145 RecordData Record;
6146 unsigned Code = Cursor.ReadCode();
6147 unsigned RecCode = Cursor.readRecord(Code, Record);
6148 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6149 Error("malformed AST file: missing C++ ctor initializers");
6150 return nullptr;
6151 }
6152
6153 unsigned Idx = 0;
6154 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6155}
6156
Richard Smithcd45dbc2014-04-19 03:48:30 +00006157uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6158 const RecordData &Record,
6159 unsigned &Idx) {
6160 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6161 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006162 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006163 }
6164
Guy Benyei11169dd2012-12-18 14:30:41 +00006165 unsigned LocalID = Record[Idx++];
6166 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6167}
6168
6169CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6170 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006171 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006172 SavedStreamPosition SavedPosition(Cursor);
6173 Cursor.JumpToBit(Loc.Offset);
6174 ReadingKindTracker ReadingKind(Read_Decl, *this);
6175 RecordData Record;
6176 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006177 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006178 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006179 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006180 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006181 }
6182
6183 unsigned Idx = 0;
6184 unsigned NumBases = Record[Idx++];
6185 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6186 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6187 for (unsigned I = 0; I != NumBases; ++I)
6188 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6189 return Bases;
6190}
6191
6192serialization::DeclID
6193ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6194 if (LocalID < NUM_PREDEF_DECL_IDS)
6195 return LocalID;
6196
6197 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6198 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6199 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6200
6201 return LocalID + I->second;
6202}
6203
6204bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6205 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006206 // Predefined decls aren't from any module.
6207 if (ID < NUM_PREDEF_DECL_IDS)
6208 return false;
6209
Richard Smithbcda1a92015-07-12 23:51:20 +00006210 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6211 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006212}
6213
Douglas Gregor9f782892013-01-21 15:25:38 +00006214ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006215 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006216 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006217 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6218 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6219 return I->second;
6220}
6221
6222SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6223 if (ID < NUM_PREDEF_DECL_IDS)
6224 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006225
Guy Benyei11169dd2012-12-18 14:30:41 +00006226 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6227
6228 if (Index > DeclsLoaded.size()) {
6229 Error("declaration ID out-of-range for AST file");
6230 return SourceLocation();
6231 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006232
Guy Benyei11169dd2012-12-18 14:30:41 +00006233 if (Decl *D = DeclsLoaded[Index])
6234 return D->getLocation();
6235
6236 unsigned RawLocation = 0;
6237 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6238 return ReadSourceLocation(*Rec.F, RawLocation);
6239}
6240
Richard Smithfe620d22015-03-05 23:24:12 +00006241static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6242 switch (ID) {
6243 case PREDEF_DECL_NULL_ID:
6244 return nullptr;
6245
6246 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6247 return Context.getTranslationUnitDecl();
6248
6249 case PREDEF_DECL_OBJC_ID_ID:
6250 return Context.getObjCIdDecl();
6251
6252 case PREDEF_DECL_OBJC_SEL_ID:
6253 return Context.getObjCSelDecl();
6254
6255 case PREDEF_DECL_OBJC_CLASS_ID:
6256 return Context.getObjCClassDecl();
6257
6258 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6259 return Context.getObjCProtocolDecl();
6260
6261 case PREDEF_DECL_INT_128_ID:
6262 return Context.getInt128Decl();
6263
6264 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6265 return Context.getUInt128Decl();
6266
6267 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6268 return Context.getObjCInstanceTypeDecl();
6269
6270 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6271 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006272
Richard Smith9b88a4c2015-07-27 05:40:23 +00006273 case PREDEF_DECL_VA_LIST_TAG:
6274 return Context.getVaListTagDecl();
6275
Charles Davisc7d5c942015-09-17 20:55:33 +00006276 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6277 return Context.getBuiltinMSVaListDecl();
6278
Richard Smithf19e1272015-03-07 00:04:49 +00006279 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6280 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006281 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006282 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006283}
6284
Richard Smithcd45dbc2014-04-19 03:48:30 +00006285Decl *ASTReader::GetExistingDecl(DeclID ID) {
6286 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006287 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6288 if (D) {
6289 // Track that we have merged the declaration with ID \p ID into the
6290 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006291 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006292 if (Merged.empty())
6293 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006294 }
Richard Smithfe620d22015-03-05 23:24:12 +00006295 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006296 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006297
Guy Benyei11169dd2012-12-18 14:30:41 +00006298 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6299
6300 if (Index >= DeclsLoaded.size()) {
6301 assert(0 && "declaration ID out-of-range for AST file");
6302 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006303 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006304 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006305
6306 return DeclsLoaded[Index];
6307}
6308
6309Decl *ASTReader::GetDecl(DeclID ID) {
6310 if (ID < NUM_PREDEF_DECL_IDS)
6311 return GetExistingDecl(ID);
6312
6313 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6314
6315 if (Index >= DeclsLoaded.size()) {
6316 assert(0 && "declaration ID out-of-range for AST file");
6317 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006318 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006319 }
6320
Guy Benyei11169dd2012-12-18 14:30:41 +00006321 if (!DeclsLoaded[Index]) {
6322 ReadDeclRecord(ID);
6323 if (DeserializationListener)
6324 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6325 }
6326
6327 return DeclsLoaded[Index];
6328}
6329
6330DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6331 DeclID GlobalID) {
6332 if (GlobalID < NUM_PREDEF_DECL_IDS)
6333 return GlobalID;
6334
6335 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6336 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6337 ModuleFile *Owner = I->second;
6338
6339 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6340 = M.GlobalToLocalDeclIDs.find(Owner);
6341 if (Pos == M.GlobalToLocalDeclIDs.end())
6342 return 0;
6343
6344 return GlobalID - Owner->BaseDeclID + Pos->second;
6345}
6346
6347serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6348 const RecordData &Record,
6349 unsigned &Idx) {
6350 if (Idx >= Record.size()) {
6351 Error("Corrupted AST file");
6352 return 0;
6353 }
6354
6355 return getGlobalDeclID(F, Record[Idx++]);
6356}
6357
6358/// \brief Resolve the offset of a statement into a statement.
6359///
6360/// This operation will read a new statement from the external
6361/// source each time it is called, and is meant to be used via a
6362/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6363Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6364 // Switch case IDs are per Decl.
6365 ClearSwitchCaseIDs();
6366
6367 // Offset here is a global offset across the entire chain.
6368 RecordLocation Loc = getLocalBitOffset(Offset);
6369 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6370 return ReadStmtFromStream(*Loc.F);
6371}
6372
Richard Smith3cb15722015-08-05 22:41:45 +00006373void ASTReader::FindExternalLexicalDecls(
6374 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6375 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006376 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6377
Richard Smith9ccdd932015-08-06 22:14:12 +00006378 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006379 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6380 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6381 auto K = (Decl::Kind)+LexicalDecls[I];
6382 if (!IsKindWeWant(K))
6383 continue;
6384
6385 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6386
6387 // Don't add predefined declarations to the lexical context more
6388 // than once.
6389 if (ID < NUM_PREDEF_DECL_IDS) {
6390 if (PredefsVisited[ID])
6391 continue;
6392
6393 PredefsVisited[ID] = true;
6394 }
6395
6396 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006397 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006398 if (!DC->isDeclInLexicalTraversal(D))
6399 Decls.push_back(D);
6400 }
6401 }
6402 };
6403
6404 if (isa<TranslationUnitDecl>(DC)) {
6405 for (auto Lexical : TULexicalDecls)
6406 Visit(Lexical.first, Lexical.second);
6407 } else {
6408 auto I = LexicalDecls.find(DC);
6409 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006410 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006411 }
6412
Guy Benyei11169dd2012-12-18 14:30:41 +00006413 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006414}
6415
6416namespace {
6417
6418class DeclIDComp {
6419 ASTReader &Reader;
6420 ModuleFile &Mod;
6421
6422public:
6423 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6424
6425 bool operator()(LocalDeclID L, LocalDeclID R) const {
6426 SourceLocation LHS = getLocation(L);
6427 SourceLocation RHS = getLocation(R);
6428 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6429 }
6430
6431 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6432 SourceLocation RHS = getLocation(R);
6433 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6434 }
6435
6436 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6437 SourceLocation LHS = getLocation(L);
6438 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6439 }
6440
6441 SourceLocation getLocation(LocalDeclID ID) const {
6442 return Reader.getSourceManager().getFileLoc(
6443 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6444 }
6445};
6446
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006447}
Guy Benyei11169dd2012-12-18 14:30:41 +00006448
6449void ASTReader::FindFileRegionDecls(FileID File,
6450 unsigned Offset, unsigned Length,
6451 SmallVectorImpl<Decl *> &Decls) {
6452 SourceManager &SM = getSourceManager();
6453
6454 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6455 if (I == FileDeclIDs.end())
6456 return;
6457
6458 FileDeclsInfo &DInfo = I->second;
6459 if (DInfo.Decls.empty())
6460 return;
6461
6462 SourceLocation
6463 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6464 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6465
6466 DeclIDComp DIDComp(*this, *DInfo.Mod);
6467 ArrayRef<serialization::LocalDeclID>::iterator
6468 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6469 BeginLoc, DIDComp);
6470 if (BeginIt != DInfo.Decls.begin())
6471 --BeginIt;
6472
6473 // If we are pointing at a top-level decl inside an objc container, we need
6474 // to backtrack until we find it otherwise we will fail to report that the
6475 // region overlaps with an objc container.
6476 while (BeginIt != DInfo.Decls.begin() &&
6477 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6478 ->isTopLevelDeclInObjCContainer())
6479 --BeginIt;
6480
6481 ArrayRef<serialization::LocalDeclID>::iterator
6482 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6483 EndLoc, DIDComp);
6484 if (EndIt != DInfo.Decls.end())
6485 ++EndIt;
6486
6487 for (ArrayRef<serialization::LocalDeclID>::iterator
6488 DIt = BeginIt; DIt != EndIt; ++DIt)
6489 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6490}
6491
Richard Smith9ce12e32013-02-07 03:30:24 +00006492bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006493ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6494 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006495 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006496 "DeclContext has no visible decls in storage");
6497 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006498 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006499
Richard Smithd88a7f12015-09-01 20:35:42 +00006500 auto It = Lookups.find(DC);
6501 if (It == Lookups.end())
6502 return false;
6503
Richard Smith8c913ec2014-08-14 02:21:01 +00006504 Deserializing LookupResults(this);
6505
Richard Smithd88a7f12015-09-01 20:35:42 +00006506 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006507 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006508 for (DeclID ID : It->second.Table.find(Name)) {
6509 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6510 if (ND->getDeclName() == Name)
6511 Decls.push_back(ND);
6512 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006513
Guy Benyei11169dd2012-12-18 14:30:41 +00006514 ++NumVisibleDeclContextsRead;
6515 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006516 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006517}
6518
Guy Benyei11169dd2012-12-18 14:30:41 +00006519void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6520 if (!DC->hasExternalVisibleStorage())
6521 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006522
6523 auto It = Lookups.find(DC);
6524 assert(It != Lookups.end() &&
6525 "have external visible storage but no lookup tables");
6526
Craig Topper79be4cd2013-07-05 04:33:53 +00006527 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006528
Richard Smithd88a7f12015-09-01 20:35:42 +00006529 for (DeclID ID : It->second.Table.findAll()) {
6530 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6531 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006532 }
6533
Guy Benyei11169dd2012-12-18 14:30:41 +00006534 ++NumVisibleDeclContextsRead;
6535
Craig Topper79be4cd2013-07-05 04:33:53 +00006536 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006537 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6538 }
6539 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6540}
6541
Richard Smithd88a7f12015-09-01 20:35:42 +00006542const serialization::reader::DeclContextLookupTable *
6543ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6544 auto I = Lookups.find(Primary);
6545 return I == Lookups.end() ? nullptr : &I->second;
6546}
6547
Guy Benyei11169dd2012-12-18 14:30:41 +00006548/// \brief Under non-PCH compilation the consumer receives the objc methods
6549/// before receiving the implementation, and codegen depends on this.
6550/// We simulate this by deserializing and passing to consumer the methods of the
6551/// implementation before passing the deserialized implementation decl.
6552static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6553 ASTConsumer *Consumer) {
6554 assert(ImplD && Consumer);
6555
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006556 for (auto *I : ImplD->methods())
6557 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006558
6559 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6560}
6561
6562void ASTReader::PassInterestingDeclsToConsumer() {
6563 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006564
6565 if (PassingDeclsToConsumer)
6566 return;
6567
6568 // Guard variable to avoid recursively redoing the process of passing
6569 // decls to consumer.
6570 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6571 true);
6572
Richard Smith9e2341d2015-03-23 03:25:59 +00006573 // Ensure that we've loaded all potentially-interesting declarations
6574 // that need to be eagerly loaded.
6575 for (auto ID : EagerlyDeserializedDecls)
6576 GetDecl(ID);
6577 EagerlyDeserializedDecls.clear();
6578
Guy Benyei11169dd2012-12-18 14:30:41 +00006579 while (!InterestingDecls.empty()) {
6580 Decl *D = InterestingDecls.front();
6581 InterestingDecls.pop_front();
6582
6583 PassInterestingDeclToConsumer(D);
6584 }
6585}
6586
6587void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6588 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6589 PassObjCImplDeclToConsumer(ImplD, Consumer);
6590 else
6591 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6592}
6593
6594void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6595 this->Consumer = Consumer;
6596
Richard Smith9e2341d2015-03-23 03:25:59 +00006597 if (Consumer)
6598 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006599
6600 if (DeserializationListener)
6601 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006602}
6603
6604void ASTReader::PrintStats() {
6605 std::fprintf(stderr, "*** AST File Statistics:\n");
6606
6607 unsigned NumTypesLoaded
6608 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6609 QualType());
6610 unsigned NumDeclsLoaded
6611 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006612 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006613 unsigned NumIdentifiersLoaded
6614 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6615 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006616 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006617 unsigned NumMacrosLoaded
6618 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6619 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006620 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006621 unsigned NumSelectorsLoaded
6622 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6623 SelectorsLoaded.end(),
6624 Selector());
6625
6626 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6627 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6628 NumSLocEntriesRead, TotalNumSLocEntries,
6629 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6630 if (!TypesLoaded.empty())
6631 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6632 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6633 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6634 if (!DeclsLoaded.empty())
6635 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6636 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6637 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6638 if (!IdentifiersLoaded.empty())
6639 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6640 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6641 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6642 if (!MacrosLoaded.empty())
6643 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6644 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6645 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6646 if (!SelectorsLoaded.empty())
6647 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6648 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6649 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6650 if (TotalNumStatements)
6651 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6652 NumStatementsRead, TotalNumStatements,
6653 ((float)NumStatementsRead/TotalNumStatements * 100));
6654 if (TotalNumMacros)
6655 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6656 NumMacrosRead, TotalNumMacros,
6657 ((float)NumMacrosRead/TotalNumMacros * 100));
6658 if (TotalLexicalDeclContexts)
6659 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6660 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6661 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6662 * 100));
6663 if (TotalVisibleDeclContexts)
6664 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6665 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6666 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6667 * 100));
6668 if (TotalNumMethodPoolEntries) {
6669 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6670 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6671 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6672 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006673 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006674 if (NumMethodPoolLookups) {
6675 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6676 NumMethodPoolHits, NumMethodPoolLookups,
6677 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6678 }
6679 if (NumMethodPoolTableLookups) {
6680 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6681 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6682 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6683 * 100.0));
6684 }
6685
Douglas Gregor00a50f72013-01-25 00:38:33 +00006686 if (NumIdentifierLookupHits) {
6687 std::fprintf(stderr,
6688 " %u / %u identifier table lookups succeeded (%f%%)\n",
6689 NumIdentifierLookupHits, NumIdentifierLookups,
6690 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6691 }
6692
Douglas Gregore060e572013-01-25 01:03:03 +00006693 if (GlobalIndex) {
6694 std::fprintf(stderr, "\n");
6695 GlobalIndex->printStats();
6696 }
6697
Guy Benyei11169dd2012-12-18 14:30:41 +00006698 std::fprintf(stderr, "\n");
6699 dump();
6700 std::fprintf(stderr, "\n");
6701}
6702
6703template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6704static void
6705dumpModuleIDMap(StringRef Name,
6706 const ContinuousRangeMap<Key, ModuleFile *,
6707 InitialCapacity> &Map) {
6708 if (Map.begin() == Map.end())
6709 return;
6710
6711 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6712 llvm::errs() << Name << ":\n";
6713 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6714 I != IEnd; ++I) {
6715 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6716 << "\n";
6717 }
6718}
6719
6720void ASTReader::dump() {
6721 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6722 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6723 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6724 dumpModuleIDMap("Global type map", GlobalTypeMap);
6725 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6726 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6727 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6728 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6729 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6730 dumpModuleIDMap("Global preprocessed entity map",
6731 GlobalPreprocessedEntityMap);
6732
6733 llvm::errs() << "\n*** PCH/Modules Loaded:";
6734 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6735 MEnd = ModuleMgr.end();
6736 M != MEnd; ++M)
6737 (*M)->dump();
6738}
6739
6740/// Return the amount of memory used by memory buffers, breaking down
6741/// by heap-backed versus mmap'ed memory.
6742void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6743 for (ModuleConstIterator I = ModuleMgr.begin(),
6744 E = ModuleMgr.end(); I != E; ++I) {
6745 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6746 size_t bytes = buf->getBufferSize();
6747 switch (buf->getBufferKind()) {
6748 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6749 sizes.malloc_bytes += bytes;
6750 break;
6751 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6752 sizes.mmap_bytes += bytes;
6753 break;
6754 }
6755 }
6756 }
6757}
6758
6759void ASTReader::InitializeSema(Sema &S) {
6760 SemaObj = &S;
6761 S.addExternalSource(this);
6762
6763 // Makes sure any declarations that were deserialized "too early"
6764 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006765 for (uint64_t ID : PreloadedDeclIDs) {
6766 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6767 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006768 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006769 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006770
Richard Smith3d8e97e2013-10-18 06:54:39 +00006771 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006772 if (!FPPragmaOptions.empty()) {
6773 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6774 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6775 }
6776
Richard Smith3d8e97e2013-10-18 06:54:39 +00006777 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006778 if (!OpenCLExtensions.empty()) {
6779 unsigned I = 0;
6780#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6781#include "clang/Basic/OpenCLExtensions.def"
6782
6783 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6784 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006785
6786 UpdateSema();
6787}
6788
6789void ASTReader::UpdateSema() {
6790 assert(SemaObj && "no Sema to update");
6791
6792 // Load the offsets of the declarations that Sema references.
6793 // They will be lazily deserialized when needed.
6794 if (!SemaDeclRefs.empty()) {
6795 assert(SemaDeclRefs.size() % 2 == 0);
6796 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6797 if (!SemaObj->StdNamespace)
6798 SemaObj->StdNamespace = SemaDeclRefs[I];
6799 if (!SemaObj->StdBadAlloc)
6800 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6801 }
6802 SemaDeclRefs.clear();
6803 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006804
6805 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6806 // encountered the pragma in the source.
6807 if(OptimizeOffPragmaLocation.isValid())
6808 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006809}
6810
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006811IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006812 // Note that we are loading an identifier.
6813 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006814
Douglas Gregor7211ac12013-01-25 23:32:03 +00006815 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006816 NumIdentifierLookups,
6817 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006818
6819 // We don't need to do identifier table lookups in C++ modules (we preload
6820 // all interesting declarations, and don't need to use the scope for name
6821 // lookups). Perform the lookup in PCH files, though, since we don't build
6822 // a complete initial identifier table if we're carrying on from a PCH.
6823 if (Context.getLangOpts().CPlusPlus) {
6824 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006825 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006826 break;
6827 } else {
6828 // If there is a global index, look there first to determine which modules
6829 // provably do not have any results for this identifier.
6830 GlobalModuleIndex::HitSet Hits;
6831 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6832 if (!loadGlobalIndex()) {
6833 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6834 HitsPtr = &Hits;
6835 }
6836 }
6837
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006838 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006839 }
6840
Guy Benyei11169dd2012-12-18 14:30:41 +00006841 IdentifierInfo *II = Visitor.getIdentifierInfo();
6842 markIdentifierUpToDate(II);
6843 return II;
6844}
6845
6846namespace clang {
6847 /// \brief An identifier-lookup iterator that enumerates all of the
6848 /// identifiers stored within a set of AST files.
6849 class ASTIdentifierIterator : public IdentifierIterator {
6850 /// \brief The AST reader whose identifiers are being enumerated.
6851 const ASTReader &Reader;
6852
6853 /// \brief The current index into the chain of AST files stored in
6854 /// the AST reader.
6855 unsigned Index;
6856
6857 /// \brief The current position within the identifier lookup table
6858 /// of the current AST file.
6859 ASTIdentifierLookupTable::key_iterator Current;
6860
6861 /// \brief The end position within the identifier lookup table of
6862 /// the current AST file.
6863 ASTIdentifierLookupTable::key_iterator End;
6864
6865 public:
6866 explicit ASTIdentifierIterator(const ASTReader &Reader);
6867
Craig Topper3e89dfe2014-03-13 02:13:41 +00006868 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006869 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006870}
Guy Benyei11169dd2012-12-18 14:30:41 +00006871
6872ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6873 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6874 ASTIdentifierLookupTable *IdTable
6875 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6876 Current = IdTable->key_begin();
6877 End = IdTable->key_end();
6878}
6879
6880StringRef ASTIdentifierIterator::Next() {
6881 while (Current == End) {
6882 // If we have exhausted all of our AST files, we're done.
6883 if (Index == 0)
6884 return StringRef();
6885
6886 --Index;
6887 ASTIdentifierLookupTable *IdTable
6888 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6889 IdentifierLookupTable;
6890 Current = IdTable->key_begin();
6891 End = IdTable->key_end();
6892 }
6893
6894 // We have any identifiers remaining in the current AST file; return
6895 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006896 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006897 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006898 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006899}
6900
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006901IdentifierIterator *ASTReader::getIdentifiers() {
6902 if (!loadGlobalIndex())
6903 return GlobalIndex->createIdentifierIterator();
6904
Guy Benyei11169dd2012-12-18 14:30:41 +00006905 return new ASTIdentifierIterator(*this);
6906}
6907
6908namespace clang { namespace serialization {
6909 class ReadMethodPoolVisitor {
6910 ASTReader &Reader;
6911 Selector Sel;
6912 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006913 unsigned InstanceBits;
6914 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006915 bool InstanceHasMoreThanOneDecl;
6916 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006917 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6918 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006919
6920 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006921 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006922 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006923 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006924 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6925 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006926
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006927 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006928 if (!M.SelectorLookupTable)
6929 return false;
6930
6931 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00006932 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00006933 return true;
6934
Richard Smithbdf2d932015-07-30 03:37:16 +00006935 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006936 ASTSelectorLookupTable *PoolTable
6937 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00006938 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00006939 if (Pos == PoolTable->end())
6940 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006941
Richard Smithbdf2d932015-07-30 03:37:16 +00006942 ++Reader.NumMethodPoolTableHits;
6943 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006944 // FIXME: Not quite happy with the statistics here. We probably should
6945 // disable this tracking when called via LoadSelector.
6946 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00006947 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006948 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00006949 if (Reader.DeserializationListener)
6950 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006951
Richard Smithbdf2d932015-07-30 03:37:16 +00006952 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6953 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6954 InstanceBits = Data.InstanceBits;
6955 FactoryBits = Data.FactoryBits;
6956 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6957 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006958 return true;
6959 }
6960
6961 /// \brief Retrieve the instance methods found by this visitor.
6962 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6963 return InstanceMethods;
6964 }
6965
6966 /// \brief Retrieve the instance methods found by this visitor.
6967 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6968 return FactoryMethods;
6969 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006970
6971 unsigned getInstanceBits() const { return InstanceBits; }
6972 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006973 bool instanceHasMoreThanOneDecl() const {
6974 return InstanceHasMoreThanOneDecl;
6975 }
6976 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006977 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006978} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00006979
6980/// \brief Add the given set of methods to the method list.
6981static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6982 ObjCMethodList &List) {
6983 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6984 S.addMethodToGlobalList(&List, Methods[I]);
6985 }
6986}
6987
6988void ASTReader::ReadMethodPool(Selector Sel) {
6989 // Get the selector generation and update it to the current generation.
6990 unsigned &Generation = SelectorGeneration[Sel];
6991 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00006992 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00006993
6994 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006995 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006996 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006997 ModuleMgr.visit(Visitor);
6998
Guy Benyei11169dd2012-12-18 14:30:41 +00006999 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007000 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007001 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007002
7003 ++NumMethodPoolHits;
7004
Guy Benyei11169dd2012-12-18 14:30:41 +00007005 if (!getSema())
7006 return;
7007
7008 Sema &S = *getSema();
7009 Sema::GlobalMethodPool::iterator Pos
7010 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007011
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007012 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007013 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007014 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007015 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007016
7017 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7018 // when building a module we keep every method individually and may need to
7019 // update hasMoreThanOneDecl as we add the methods.
7020 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7021 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007022}
7023
7024void ASTReader::ReadKnownNamespaces(
7025 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7026 Namespaces.clear();
7027
7028 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7029 if (NamespaceDecl *Namespace
7030 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7031 Namespaces.push_back(Namespace);
7032 }
7033}
7034
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007035void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007036 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007037 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7038 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007039 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007040 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007041 Undefined.insert(std::make_pair(D, Loc));
7042 }
7043}
Nick Lewycky8334af82013-01-26 00:35:08 +00007044
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007045void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7046 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7047 Exprs) {
7048 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7049 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7050 uint64_t Count = DelayedDeleteExprs[Idx++];
7051 for (uint64_t C = 0; C < Count; ++C) {
7052 SourceLocation DeleteLoc =
7053 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7054 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7055 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7056 }
7057 }
7058}
7059
Guy Benyei11169dd2012-12-18 14:30:41 +00007060void ASTReader::ReadTentativeDefinitions(
7061 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7062 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7063 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7064 if (Var)
7065 TentativeDefs.push_back(Var);
7066 }
7067 TentativeDefinitions.clear();
7068}
7069
7070void ASTReader::ReadUnusedFileScopedDecls(
7071 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7072 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7073 DeclaratorDecl *D
7074 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7075 if (D)
7076 Decls.push_back(D);
7077 }
7078 UnusedFileScopedDecls.clear();
7079}
7080
7081void ASTReader::ReadDelegatingConstructors(
7082 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7083 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7084 CXXConstructorDecl *D
7085 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7086 if (D)
7087 Decls.push_back(D);
7088 }
7089 DelegatingCtorDecls.clear();
7090}
7091
7092void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7093 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7094 TypedefNameDecl *D
7095 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7096 if (D)
7097 Decls.push_back(D);
7098 }
7099 ExtVectorDecls.clear();
7100}
7101
Nico Weber72889432014-09-06 01:25:55 +00007102void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7103 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7104 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7105 ++I) {
7106 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7107 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7108 if (D)
7109 Decls.insert(D);
7110 }
7111 UnusedLocalTypedefNameCandidates.clear();
7112}
7113
Guy Benyei11169dd2012-12-18 14:30:41 +00007114void ASTReader::ReadReferencedSelectors(
7115 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7116 if (ReferencedSelectorsData.empty())
7117 return;
7118
7119 // If there are @selector references added them to its pool. This is for
7120 // implementation of -Wselector.
7121 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7122 unsigned I = 0;
7123 while (I < DataSize) {
7124 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7125 SourceLocation SelLoc
7126 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7127 Sels.push_back(std::make_pair(Sel, SelLoc));
7128 }
7129 ReferencedSelectorsData.clear();
7130}
7131
7132void ASTReader::ReadWeakUndeclaredIdentifiers(
7133 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7134 if (WeakUndeclaredIdentifiers.empty())
7135 return;
7136
7137 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7138 IdentifierInfo *WeakId
7139 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7140 IdentifierInfo *AliasId
7141 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7142 SourceLocation Loc
7143 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7144 bool Used = WeakUndeclaredIdentifiers[I++];
7145 WeakInfo WI(AliasId, Loc);
7146 WI.setUsed(Used);
7147 WeakIDs.push_back(std::make_pair(WeakId, WI));
7148 }
7149 WeakUndeclaredIdentifiers.clear();
7150}
7151
7152void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7153 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7154 ExternalVTableUse VT;
7155 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7156 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7157 VT.DefinitionRequired = VTableUses[Idx++];
7158 VTables.push_back(VT);
7159 }
7160
7161 VTableUses.clear();
7162}
7163
7164void ASTReader::ReadPendingInstantiations(
7165 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7166 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7167 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7168 SourceLocation Loc
7169 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7170
7171 Pending.push_back(std::make_pair(D, Loc));
7172 }
7173 PendingInstantiations.clear();
7174}
7175
Richard Smithe40f2ba2013-08-07 21:41:30 +00007176void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007177 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007178 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7179 /* In loop */) {
7180 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7181
7182 LateParsedTemplate *LT = new LateParsedTemplate;
7183 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7184
7185 ModuleFile *F = getOwningModuleFile(LT->D);
7186 assert(F && "No module");
7187
7188 unsigned TokN = LateParsedTemplates[Idx++];
7189 LT->Toks.reserve(TokN);
7190 for (unsigned T = 0; T < TokN; ++T)
7191 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7192
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007193 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007194 }
7195
7196 LateParsedTemplates.clear();
7197}
7198
Guy Benyei11169dd2012-12-18 14:30:41 +00007199void ASTReader::LoadSelector(Selector Sel) {
7200 // It would be complicated to avoid reading the methods anyway. So don't.
7201 ReadMethodPool(Sel);
7202}
7203
7204void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7205 assert(ID && "Non-zero identifier ID required");
7206 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7207 IdentifiersLoaded[ID - 1] = II;
7208 if (DeserializationListener)
7209 DeserializationListener->IdentifierRead(ID, II);
7210}
7211
7212/// \brief Set the globally-visible declarations associated with the given
7213/// identifier.
7214///
7215/// If the AST reader is currently in a state where the given declaration IDs
7216/// cannot safely be resolved, they are queued until it is safe to resolve
7217/// them.
7218///
7219/// \param II an IdentifierInfo that refers to one or more globally-visible
7220/// declarations.
7221///
7222/// \param DeclIDs the set of declaration IDs with the name @p II that are
7223/// visible at global scope.
7224///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007225/// \param Decls if non-null, this vector will be populated with the set of
7226/// deserialized declarations. These declarations will not be pushed into
7227/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007228void
7229ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7230 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007231 SmallVectorImpl<Decl *> *Decls) {
7232 if (NumCurrentElementsDeserializing && !Decls) {
7233 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007234 return;
7235 }
7236
7237 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007238 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007239 // Queue this declaration so that it will be added to the
7240 // translation unit scope and identifier's declaration chain
7241 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007242 PreloadedDeclIDs.push_back(DeclIDs[I]);
7243 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007244 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007245
7246 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7247
7248 // If we're simply supposed to record the declarations, do so now.
7249 if (Decls) {
7250 Decls->push_back(D);
7251 continue;
7252 }
7253
7254 // Introduce this declaration into the translation-unit scope
7255 // and add it to the declaration chain for this identifier, so
7256 // that (unqualified) name lookup will find it.
7257 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007258 }
7259}
7260
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007261IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007262 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007263 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007264
7265 if (IdentifiersLoaded.empty()) {
7266 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007267 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007268 }
7269
7270 ID -= 1;
7271 if (!IdentifiersLoaded[ID]) {
7272 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7273 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7274 ModuleFile *M = I->second;
7275 unsigned Index = ID - M->BaseIdentifierID;
7276 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7277
7278 // All of the strings in the AST file are preceded by a 16-bit length.
7279 // Extract that 16-bit length to avoid having to execute strlen().
7280 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7281 // unsigned integers. This is important to avoid integer overflow when
7282 // we cast them to 'unsigned'.
7283 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7284 unsigned StrLen = (((unsigned) StrLenPtr[0])
7285 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007286 IdentifiersLoaded[ID]
7287 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007288 if (DeserializationListener)
7289 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7290 }
7291
7292 return IdentifiersLoaded[ID];
7293}
7294
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007295IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7296 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007297}
7298
7299IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7300 if (LocalID < NUM_PREDEF_IDENT_IDS)
7301 return LocalID;
7302
7303 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7304 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7305 assert(I != M.IdentifierRemap.end()
7306 && "Invalid index into identifier index remap");
7307
7308 return LocalID + I->second;
7309}
7310
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007311MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007312 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007313 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007314
7315 if (MacrosLoaded.empty()) {
7316 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007317 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007318 }
7319
7320 ID -= NUM_PREDEF_MACRO_IDS;
7321 if (!MacrosLoaded[ID]) {
7322 GlobalMacroMapType::iterator I
7323 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7324 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7325 ModuleFile *M = I->second;
7326 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007327 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7328
7329 if (DeserializationListener)
7330 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7331 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007332 }
7333
7334 return MacrosLoaded[ID];
7335}
7336
7337MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7338 if (LocalID < NUM_PREDEF_MACRO_IDS)
7339 return LocalID;
7340
7341 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7342 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7343 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7344
7345 return LocalID + I->second;
7346}
7347
7348serialization::SubmoduleID
7349ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7350 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7351 return LocalID;
7352
7353 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7354 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7355 assert(I != M.SubmoduleRemap.end()
7356 && "Invalid index into submodule index remap");
7357
7358 return LocalID + I->second;
7359}
7360
7361Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7362 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7363 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007364 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007365 }
7366
7367 if (GlobalID > SubmodulesLoaded.size()) {
7368 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007369 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007370 }
7371
7372 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7373}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007374
7375Module *ASTReader::getModule(unsigned ID) {
7376 return getSubmodule(ID);
7377}
7378
Richard Smithd88a7f12015-09-01 20:35:42 +00007379ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7380 if (ID & 1) {
7381 // It's a module, look it up by submodule ID.
7382 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7383 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7384 } else {
7385 // It's a prefix (preamble, PCH, ...). Look it up by index.
7386 unsigned IndexFromEnd = ID >> 1;
7387 assert(IndexFromEnd && "got reference to unknown module file");
7388 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7389 }
7390}
7391
7392unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7393 if (!F)
7394 return 1;
7395
7396 // For a file representing a module, use the submodule ID of the top-level
7397 // module as the file ID. For any other kind of file, the number of such
7398 // files loaded beforehand will be the same on reload.
7399 // FIXME: Is this true even if we have an explicit module file and a PCH?
7400 if (F->isModule())
7401 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7402
7403 auto PCHModules = getModuleManager().pch_modules();
7404 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7405 assert(I != PCHModules.end() && "emitting reference to unknown file");
7406 return (I - PCHModules.end()) << 1;
7407}
7408
Adrian Prantl15bcf702015-06-30 17:39:43 +00007409llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7410ASTReader::getSourceDescriptor(unsigned ID) {
7411 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007412 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007413
7414 // If there is only a single PCH, return it instead.
7415 // Chained PCH are not suported.
7416 if (ModuleMgr.size() == 1) {
7417 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantlc6458d62015-09-19 00:10:32 +00007418 return ASTReader::ASTSourceDescriptor(
7419 MF.OriginalSourceFileName, MF.OriginalDir, MF.FileName, MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007420 }
7421 return None;
7422}
7423
Guy Benyei11169dd2012-12-18 14:30:41 +00007424Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7425 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7426}
7427
7428Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7429 if (ID == 0)
7430 return Selector();
7431
7432 if (ID > SelectorsLoaded.size()) {
7433 Error("selector ID out of range in AST file");
7434 return Selector();
7435 }
7436
Craig Toppera13603a2014-05-22 05:54:18 +00007437 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007438 // Load this selector from the selector table.
7439 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7440 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7441 ModuleFile &M = *I->second;
7442 ASTSelectorLookupTrait Trait(*this, M);
7443 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7444 SelectorsLoaded[ID - 1] =
7445 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7446 if (DeserializationListener)
7447 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7448 }
7449
7450 return SelectorsLoaded[ID - 1];
7451}
7452
7453Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7454 return DecodeSelector(ID);
7455}
7456
7457uint32_t ASTReader::GetNumExternalSelectors() {
7458 // ID 0 (the null selector) is considered an external selector.
7459 return getTotalNumSelectors() + 1;
7460}
7461
7462serialization::SelectorID
7463ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7464 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7465 return LocalID;
7466
7467 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7468 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7469 assert(I != M.SelectorRemap.end()
7470 && "Invalid index into selector index remap");
7471
7472 return LocalID + I->second;
7473}
7474
7475DeclarationName
7476ASTReader::ReadDeclarationName(ModuleFile &F,
7477 const RecordData &Record, unsigned &Idx) {
7478 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7479 switch (Kind) {
7480 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007481 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007482
7483 case DeclarationName::ObjCZeroArgSelector:
7484 case DeclarationName::ObjCOneArgSelector:
7485 case DeclarationName::ObjCMultiArgSelector:
7486 return DeclarationName(ReadSelector(F, Record, Idx));
7487
7488 case DeclarationName::CXXConstructorName:
7489 return Context.DeclarationNames.getCXXConstructorName(
7490 Context.getCanonicalType(readType(F, Record, Idx)));
7491
7492 case DeclarationName::CXXDestructorName:
7493 return Context.DeclarationNames.getCXXDestructorName(
7494 Context.getCanonicalType(readType(F, Record, Idx)));
7495
7496 case DeclarationName::CXXConversionFunctionName:
7497 return Context.DeclarationNames.getCXXConversionFunctionName(
7498 Context.getCanonicalType(readType(F, Record, Idx)));
7499
7500 case DeclarationName::CXXOperatorName:
7501 return Context.DeclarationNames.getCXXOperatorName(
7502 (OverloadedOperatorKind)Record[Idx++]);
7503
7504 case DeclarationName::CXXLiteralOperatorName:
7505 return Context.DeclarationNames.getCXXLiteralOperatorName(
7506 GetIdentifierInfo(F, Record, Idx));
7507
7508 case DeclarationName::CXXUsingDirective:
7509 return DeclarationName::getUsingDirectiveName();
7510 }
7511
7512 llvm_unreachable("Invalid NameKind!");
7513}
7514
7515void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7516 DeclarationNameLoc &DNLoc,
7517 DeclarationName Name,
7518 const RecordData &Record, unsigned &Idx) {
7519 switch (Name.getNameKind()) {
7520 case DeclarationName::CXXConstructorName:
7521 case DeclarationName::CXXDestructorName:
7522 case DeclarationName::CXXConversionFunctionName:
7523 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7524 break;
7525
7526 case DeclarationName::CXXOperatorName:
7527 DNLoc.CXXOperatorName.BeginOpNameLoc
7528 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7529 DNLoc.CXXOperatorName.EndOpNameLoc
7530 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7531 break;
7532
7533 case DeclarationName::CXXLiteralOperatorName:
7534 DNLoc.CXXLiteralOperatorName.OpNameLoc
7535 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7536 break;
7537
7538 case DeclarationName::Identifier:
7539 case DeclarationName::ObjCZeroArgSelector:
7540 case DeclarationName::ObjCOneArgSelector:
7541 case DeclarationName::ObjCMultiArgSelector:
7542 case DeclarationName::CXXUsingDirective:
7543 break;
7544 }
7545}
7546
7547void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7548 DeclarationNameInfo &NameInfo,
7549 const RecordData &Record, unsigned &Idx) {
7550 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7551 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7552 DeclarationNameLoc DNLoc;
7553 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7554 NameInfo.setInfo(DNLoc);
7555}
7556
7557void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7558 const RecordData &Record, unsigned &Idx) {
7559 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7560 unsigned NumTPLists = Record[Idx++];
7561 Info.NumTemplParamLists = NumTPLists;
7562 if (NumTPLists) {
7563 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7564 for (unsigned i=0; i != NumTPLists; ++i)
7565 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7566 }
7567}
7568
7569TemplateName
7570ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7571 unsigned &Idx) {
7572 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7573 switch (Kind) {
7574 case TemplateName::Template:
7575 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7576
7577 case TemplateName::OverloadedTemplate: {
7578 unsigned size = Record[Idx++];
7579 UnresolvedSet<8> Decls;
7580 while (size--)
7581 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7582
7583 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7584 }
7585
7586 case TemplateName::QualifiedTemplate: {
7587 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7588 bool hasTemplKeyword = Record[Idx++];
7589 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7590 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7591 }
7592
7593 case TemplateName::DependentTemplate: {
7594 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7595 if (Record[Idx++]) // isIdentifier
7596 return Context.getDependentTemplateName(NNS,
7597 GetIdentifierInfo(F, Record,
7598 Idx));
7599 return Context.getDependentTemplateName(NNS,
7600 (OverloadedOperatorKind)Record[Idx++]);
7601 }
7602
7603 case TemplateName::SubstTemplateTemplateParm: {
7604 TemplateTemplateParmDecl *param
7605 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7606 if (!param) return TemplateName();
7607 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7608 return Context.getSubstTemplateTemplateParm(param, replacement);
7609 }
7610
7611 case TemplateName::SubstTemplateTemplateParmPack: {
7612 TemplateTemplateParmDecl *Param
7613 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7614 if (!Param)
7615 return TemplateName();
7616
7617 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7618 if (ArgPack.getKind() != TemplateArgument::Pack)
7619 return TemplateName();
7620
7621 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7622 }
7623 }
7624
7625 llvm_unreachable("Unhandled template name kind!");
7626}
7627
Richard Smith2bb3c342015-08-09 01:05:31 +00007628TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7629 const RecordData &Record,
7630 unsigned &Idx,
7631 bool Canonicalize) {
7632 if (Canonicalize) {
7633 // The caller wants a canonical template argument. Sometimes the AST only
7634 // wants template arguments in canonical form (particularly as the template
7635 // argument lists of template specializations) so ensure we preserve that
7636 // canonical form across serialization.
7637 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7638 return Context.getCanonicalTemplateArgument(Arg);
7639 }
7640
Guy Benyei11169dd2012-12-18 14:30:41 +00007641 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7642 switch (Kind) {
7643 case TemplateArgument::Null:
7644 return TemplateArgument();
7645 case TemplateArgument::Type:
7646 return TemplateArgument(readType(F, Record, Idx));
7647 case TemplateArgument::Declaration: {
7648 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007649 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007650 }
7651 case TemplateArgument::NullPtr:
7652 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7653 case TemplateArgument::Integral: {
7654 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7655 QualType T = readType(F, Record, Idx);
7656 return TemplateArgument(Context, Value, T);
7657 }
7658 case TemplateArgument::Template:
7659 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7660 case TemplateArgument::TemplateExpansion: {
7661 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007662 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007663 if (unsigned NumExpansions = Record[Idx++])
7664 NumTemplateExpansions = NumExpansions - 1;
7665 return TemplateArgument(Name, NumTemplateExpansions);
7666 }
7667 case TemplateArgument::Expression:
7668 return TemplateArgument(ReadExpr(F));
7669 case TemplateArgument::Pack: {
7670 unsigned NumArgs = Record[Idx++];
7671 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7672 for (unsigned I = 0; I != NumArgs; ++I)
7673 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007674 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007675 }
7676 }
7677
7678 llvm_unreachable("Unhandled template argument kind!");
7679}
7680
7681TemplateParameterList *
7682ASTReader::ReadTemplateParameterList(ModuleFile &F,
7683 const RecordData &Record, unsigned &Idx) {
7684 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7685 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7686 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7687
7688 unsigned NumParams = Record[Idx++];
7689 SmallVector<NamedDecl *, 16> Params;
7690 Params.reserve(NumParams);
7691 while (NumParams--)
7692 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7693
7694 TemplateParameterList* TemplateParams =
7695 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7696 Params.data(), Params.size(), RAngleLoc);
7697 return TemplateParams;
7698}
7699
7700void
7701ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007702ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007703 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007704 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007705 unsigned NumTemplateArgs = Record[Idx++];
7706 TemplArgs.reserve(NumTemplateArgs);
7707 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007708 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007709}
7710
7711/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007712void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007713 const RecordData &Record, unsigned &Idx) {
7714 unsigned NumDecls = Record[Idx++];
7715 Set.reserve(Context, NumDecls);
7716 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007717 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007718 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007719 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007720 }
7721}
7722
7723CXXBaseSpecifier
7724ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7725 const RecordData &Record, unsigned &Idx) {
7726 bool isVirtual = static_cast<bool>(Record[Idx++]);
7727 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7728 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7729 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7730 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7731 SourceRange Range = ReadSourceRange(F, Record, Idx);
7732 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7733 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7734 EllipsisLoc);
7735 Result.setInheritConstructors(inheritConstructors);
7736 return Result;
7737}
7738
Richard Smithc2bb8182015-03-24 06:36:48 +00007739CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007740ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7741 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007742 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007743 assert(NumInitializers && "wrote ctor initializers but have no inits");
7744 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7745 for (unsigned i = 0; i != NumInitializers; ++i) {
7746 TypeSourceInfo *TInfo = nullptr;
7747 bool IsBaseVirtual = false;
7748 FieldDecl *Member = nullptr;
7749 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007750
Richard Smithc2bb8182015-03-24 06:36:48 +00007751 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7752 switch (Type) {
7753 case CTOR_INITIALIZER_BASE:
7754 TInfo = GetTypeSourceInfo(F, Record, Idx);
7755 IsBaseVirtual = Record[Idx++];
7756 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007757
Richard Smithc2bb8182015-03-24 06:36:48 +00007758 case CTOR_INITIALIZER_DELEGATING:
7759 TInfo = GetTypeSourceInfo(F, Record, Idx);
7760 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007761
Richard Smithc2bb8182015-03-24 06:36:48 +00007762 case CTOR_INITIALIZER_MEMBER:
7763 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7764 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007765
Richard Smithc2bb8182015-03-24 06:36:48 +00007766 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7767 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7768 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007769 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007770
7771 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7772 Expr *Init = ReadExpr(F);
7773 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7774 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7775 bool IsWritten = Record[Idx++];
7776 unsigned SourceOrderOrNumArrayIndices;
7777 SmallVector<VarDecl *, 8> Indices;
7778 if (IsWritten) {
7779 SourceOrderOrNumArrayIndices = Record[Idx++];
7780 } else {
7781 SourceOrderOrNumArrayIndices = Record[Idx++];
7782 Indices.reserve(SourceOrderOrNumArrayIndices);
7783 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7784 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7785 }
7786
7787 CXXCtorInitializer *BOMInit;
7788 if (Type == CTOR_INITIALIZER_BASE) {
7789 BOMInit = new (Context)
7790 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7791 RParenLoc, MemberOrEllipsisLoc);
7792 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7793 BOMInit = new (Context)
7794 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7795 } else if (IsWritten) {
7796 if (Member)
7797 BOMInit = new (Context) CXXCtorInitializer(
7798 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7799 else
7800 BOMInit = new (Context)
7801 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7802 LParenLoc, Init, RParenLoc);
7803 } else {
7804 if (IndirectMember) {
7805 assert(Indices.empty() && "Indirect field improperly initialized");
7806 BOMInit = new (Context)
7807 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7808 LParenLoc, Init, RParenLoc);
7809 } else {
7810 BOMInit = CXXCtorInitializer::Create(
7811 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7812 Indices.data(), Indices.size());
7813 }
7814 }
7815
7816 if (IsWritten)
7817 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7818 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007819 }
7820
Richard Smithc2bb8182015-03-24 06:36:48 +00007821 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007822}
7823
7824NestedNameSpecifier *
7825ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7826 const RecordData &Record, unsigned &Idx) {
7827 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007828 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007829 for (unsigned I = 0; I != N; ++I) {
7830 NestedNameSpecifier::SpecifierKind Kind
7831 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7832 switch (Kind) {
7833 case NestedNameSpecifier::Identifier: {
7834 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7835 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7836 break;
7837 }
7838
7839 case NestedNameSpecifier::Namespace: {
7840 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7841 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7842 break;
7843 }
7844
7845 case NestedNameSpecifier::NamespaceAlias: {
7846 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7847 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7848 break;
7849 }
7850
7851 case NestedNameSpecifier::TypeSpec:
7852 case NestedNameSpecifier::TypeSpecWithTemplate: {
7853 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7854 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007855 return nullptr;
7856
Guy Benyei11169dd2012-12-18 14:30:41 +00007857 bool Template = Record[Idx++];
7858 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7859 break;
7860 }
7861
7862 case NestedNameSpecifier::Global: {
7863 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7864 // No associated value, and there can't be a prefix.
7865 break;
7866 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007867
7868 case NestedNameSpecifier::Super: {
7869 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7870 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7871 break;
7872 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007873 }
7874 Prev = NNS;
7875 }
7876 return NNS;
7877}
7878
7879NestedNameSpecifierLoc
7880ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7881 unsigned &Idx) {
7882 unsigned N = Record[Idx++];
7883 NestedNameSpecifierLocBuilder Builder;
7884 for (unsigned I = 0; I != N; ++I) {
7885 NestedNameSpecifier::SpecifierKind Kind
7886 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7887 switch (Kind) {
7888 case NestedNameSpecifier::Identifier: {
7889 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7890 SourceRange Range = ReadSourceRange(F, Record, Idx);
7891 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7892 break;
7893 }
7894
7895 case NestedNameSpecifier::Namespace: {
7896 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7897 SourceRange Range = ReadSourceRange(F, Record, Idx);
7898 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7899 break;
7900 }
7901
7902 case NestedNameSpecifier::NamespaceAlias: {
7903 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7904 SourceRange Range = ReadSourceRange(F, Record, Idx);
7905 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7906 break;
7907 }
7908
7909 case NestedNameSpecifier::TypeSpec:
7910 case NestedNameSpecifier::TypeSpecWithTemplate: {
7911 bool Template = Record[Idx++];
7912 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7913 if (!T)
7914 return NestedNameSpecifierLoc();
7915 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7916
7917 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7918 Builder.Extend(Context,
7919 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7920 T->getTypeLoc(), ColonColonLoc);
7921 break;
7922 }
7923
7924 case NestedNameSpecifier::Global: {
7925 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7926 Builder.MakeGlobal(Context, ColonColonLoc);
7927 break;
7928 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007929
7930 case NestedNameSpecifier::Super: {
7931 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7932 SourceRange Range = ReadSourceRange(F, Record, Idx);
7933 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7934 break;
7935 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007936 }
7937 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007938
Guy Benyei11169dd2012-12-18 14:30:41 +00007939 return Builder.getWithLocInContext(Context);
7940}
7941
7942SourceRange
7943ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7944 unsigned &Idx) {
7945 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7946 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7947 return SourceRange(beg, end);
7948}
7949
7950/// \brief Read an integral value
7951llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7952 unsigned BitWidth = Record[Idx++];
7953 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7954 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7955 Idx += NumWords;
7956 return Result;
7957}
7958
7959/// \brief Read a signed integral value
7960llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7961 bool isUnsigned = Record[Idx++];
7962 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7963}
7964
7965/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007966llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7967 const llvm::fltSemantics &Sem,
7968 unsigned &Idx) {
7969 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007970}
7971
7972// \brief Read a string
7973std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7974 unsigned Len = Record[Idx++];
7975 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7976 Idx += Len;
7977 return Result;
7978}
7979
Richard Smith7ed1bc92014-12-05 22:42:13 +00007980std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7981 unsigned &Idx) {
7982 std::string Filename = ReadString(Record, Idx);
7983 ResolveImportedPath(F, Filename);
7984 return Filename;
7985}
7986
Guy Benyei11169dd2012-12-18 14:30:41 +00007987VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7988 unsigned &Idx) {
7989 unsigned Major = Record[Idx++];
7990 unsigned Minor = Record[Idx++];
7991 unsigned Subminor = Record[Idx++];
7992 if (Minor == 0)
7993 return VersionTuple(Major);
7994 if (Subminor == 0)
7995 return VersionTuple(Major, Minor - 1);
7996 return VersionTuple(Major, Minor - 1, Subminor - 1);
7997}
7998
7999CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8000 const RecordData &Record,
8001 unsigned &Idx) {
8002 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8003 return CXXTemporary::Create(Context, Decl);
8004}
8005
8006DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008007 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008008}
8009
8010DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8011 return Diags.Report(Loc, DiagID);
8012}
8013
8014/// \brief Retrieve the identifier table associated with the
8015/// preprocessor.
8016IdentifierTable &ASTReader::getIdentifierTable() {
8017 return PP.getIdentifierTable();
8018}
8019
8020/// \brief Record that the given ID maps to the given switch-case
8021/// statement.
8022void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008023 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008024 "Already have a SwitchCase with this ID");
8025 (*CurrSwitchCaseStmts)[ID] = SC;
8026}
8027
8028/// \brief Retrieve the switch-case statement with the given ID.
8029SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008030 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008031 return (*CurrSwitchCaseStmts)[ID];
8032}
8033
8034void ASTReader::ClearSwitchCaseIDs() {
8035 CurrSwitchCaseStmts->clear();
8036}
8037
8038void ASTReader::ReadComments() {
8039 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008040 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008041 serialization::ModuleFile *> >::iterator
8042 I = CommentsCursors.begin(),
8043 E = CommentsCursors.end();
8044 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008045 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008046 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008047 serialization::ModuleFile &F = *I->second;
8048 SavedStreamPosition SavedPosition(Cursor);
8049
8050 RecordData Record;
8051 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008052 llvm::BitstreamEntry Entry =
8053 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008054
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008055 switch (Entry.Kind) {
8056 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8057 case llvm::BitstreamEntry::Error:
8058 Error("malformed block record in AST file");
8059 return;
8060 case llvm::BitstreamEntry::EndBlock:
8061 goto NextCursor;
8062 case llvm::BitstreamEntry::Record:
8063 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008064 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008065 }
8066
8067 // Read a record.
8068 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008069 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008070 case COMMENTS_RAW_COMMENT: {
8071 unsigned Idx = 0;
8072 SourceRange SR = ReadSourceRange(F, Record, Idx);
8073 RawComment::CommentKind Kind =
8074 (RawComment::CommentKind) Record[Idx++];
8075 bool IsTrailingComment = Record[Idx++];
8076 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008077 Comments.push_back(new (Context) RawComment(
8078 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8079 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008080 break;
8081 }
8082 }
8083 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008084 NextCursor:
8085 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008086 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008087}
8088
Richard Smithcd45dbc2014-04-19 03:48:30 +00008089std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8090 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008091 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008092 return M->getFullModuleName();
8093
8094 // Otherwise, use the name of the top-level module the decl is within.
8095 if (ModuleFile *M = getOwningModuleFile(D))
8096 return M->ModuleName;
8097
8098 // Not from a module.
8099 return "";
8100}
8101
Guy Benyei11169dd2012-12-18 14:30:41 +00008102void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008103 while (!PendingIdentifierInfos.empty() ||
8104 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008105 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008106 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008107 // If any identifiers with corresponding top-level declarations have
8108 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008109 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8110 TopLevelDeclsMap;
8111 TopLevelDeclsMap TopLevelDecls;
8112
Guy Benyei11169dd2012-12-18 14:30:41 +00008113 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008114 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008115 SmallVector<uint32_t, 4> DeclIDs =
8116 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008117 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008118
8119 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008120 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008121
Richard Smith851072e2014-05-19 20:59:20 +00008122 // For each decl chain that we wanted to complete while deserializing, mark
8123 // it as "still needs to be completed".
8124 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8125 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8126 }
8127 PendingIncompleteDeclChains.clear();
8128
Guy Benyei11169dd2012-12-18 14:30:41 +00008129 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008130 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008131 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008132 PendingDeclChains.clear();
8133
Douglas Gregor6168bd22013-02-18 15:53:43 +00008134 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008135 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8136 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008137 IdentifierInfo *II = TLD->first;
8138 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008139 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008140 }
8141 }
8142
Guy Benyei11169dd2012-12-18 14:30:41 +00008143 // Load any pending macro definitions.
8144 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008145 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8146 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8147 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8148 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008149 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008150 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008151 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008152 if (Info.M->Kind != MK_ImplicitModule &&
8153 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008154 resolvePendingMacro(II, Info);
8155 }
8156 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008157 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008158 ++IDIdx) {
8159 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008160 if (Info.M->Kind == MK_ImplicitModule ||
8161 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008162 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008163 }
8164 }
8165 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008166
8167 // Wire up the DeclContexts for Decls that we delayed setting until
8168 // recursive loading is completed.
8169 while (!PendingDeclContextInfos.empty()) {
8170 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8171 PendingDeclContextInfos.pop_front();
8172 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8173 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8174 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8175 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008176
Richard Smithd1c46742014-04-30 02:24:17 +00008177 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008178 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008179 auto Update = PendingUpdateRecords.pop_back_val();
8180 ReadingKindTracker ReadingKind(Read_Decl, *this);
8181 loadDeclUpdateRecords(Update.first, Update.second);
8182 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008183 }
Richard Smith8a639892015-01-24 01:07:20 +00008184
8185 // At this point, all update records for loaded decls are in place, so any
8186 // fake class definitions should have become real.
8187 assert(PendingFakeDefinitionData.empty() &&
8188 "faked up a class definition but never saw the real one");
8189
Guy Benyei11169dd2012-12-18 14:30:41 +00008190 // If we deserialized any C++ or Objective-C class definitions, any
8191 // Objective-C protocol definitions, or any redeclarable templates, make sure
8192 // that all redeclarations point to the definitions. Note that this can only
8193 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008194 for (Decl *D : PendingDefinitions) {
8195 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008196 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008197 // Make sure that the TagType points at the definition.
8198 const_cast<TagType*>(TagT)->decl = TD;
8199 }
Richard Smith8ce51082015-03-11 01:44:51 +00008200
Craig Topperc6914d02014-08-25 04:15:02 +00008201 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008202 for (auto *R = getMostRecentExistingDecl(RD); R;
8203 R = R->getPreviousDecl()) {
8204 assert((R == D) ==
8205 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008206 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008207 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008208 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008209 }
8210
8211 continue;
8212 }
Richard Smith8ce51082015-03-11 01:44:51 +00008213
Craig Topperc6914d02014-08-25 04:15:02 +00008214 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008215 // Make sure that the ObjCInterfaceType points at the definition.
8216 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8217 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008218
8219 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8220 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8221
Guy Benyei11169dd2012-12-18 14:30:41 +00008222 continue;
8223 }
Richard Smith8ce51082015-03-11 01:44:51 +00008224
Craig Topperc6914d02014-08-25 04:15:02 +00008225 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008226 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8227 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8228
Guy Benyei11169dd2012-12-18 14:30:41 +00008229 continue;
8230 }
Richard Smith8ce51082015-03-11 01:44:51 +00008231
Craig Topperc6914d02014-08-25 04:15:02 +00008232 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008233 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8234 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008235 }
8236 PendingDefinitions.clear();
8237
8238 // Load the bodies of any functions or methods we've encountered. We do
8239 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008240 // have been fully wired up (hasBody relies on this).
8241 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008242 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8243 PBEnd = PendingBodies.end();
8244 PB != PBEnd; ++PB) {
8245 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8246 // FIXME: Check for =delete/=default?
8247 // FIXME: Complain about ODR violations here?
8248 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8249 FD->setLazyBody(PB->second);
8250 continue;
8251 }
8252
8253 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8254 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8255 MD->setLazyBody(PB->second);
8256 }
8257 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008258
8259 // Do some cleanup.
8260 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8261 getContext().deduplicateMergedDefinitonsFor(ND);
8262 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008263}
8264
8265void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008266 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8267 return;
8268
Richard Smitha0ce9c42014-07-29 23:23:27 +00008269 // Trigger the import of the full definition of each class that had any
8270 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008271 // These updates may in turn find and diagnose some ODR failures, so take
8272 // ownership of the set first.
8273 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8274 PendingOdrMergeFailures.clear();
8275 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008276 Merge.first->buildLookup();
8277 Merge.first->decls_begin();
8278 Merge.first->bases_begin();
8279 Merge.first->vbases_begin();
8280 for (auto *RD : Merge.second) {
8281 RD->decls_begin();
8282 RD->bases_begin();
8283 RD->vbases_begin();
8284 }
8285 }
8286
8287 // For each declaration from a merged context, check that the canonical
8288 // definition of that context also contains a declaration of the same
8289 // entity.
8290 //
8291 // Caution: this loop does things that might invalidate iterators into
8292 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8293 while (!PendingOdrMergeChecks.empty()) {
8294 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8295
8296 // FIXME: Skip over implicit declarations for now. This matters for things
8297 // like implicitly-declared special member functions. This isn't entirely
8298 // correct; we can end up with multiple unmerged declarations of the same
8299 // implicit entity.
8300 if (D->isImplicit())
8301 continue;
8302
8303 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008304
8305 bool Found = false;
8306 const Decl *DCanon = D->getCanonicalDecl();
8307
Richard Smith01bdb7a2014-08-28 05:44:07 +00008308 for (auto RI : D->redecls()) {
8309 if (RI->getLexicalDeclContext() == CanonDef) {
8310 Found = true;
8311 break;
8312 }
8313 }
8314 if (Found)
8315 continue;
8316
Richard Smith0f4e2c42015-08-06 04:23:48 +00008317 // Quick check failed, time to do the slow thing. Note, we can't just
8318 // look up the name of D in CanonDef here, because the member that is
8319 // in CanonDef might not be found by name lookup (it might have been
8320 // replaced by a more recent declaration in the lookup table), and we
8321 // can't necessarily find it in the redeclaration chain because it might
8322 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008323 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008324 for (auto *CanonMember : CanonDef->decls()) {
8325 if (CanonMember->getCanonicalDecl() == DCanon) {
8326 // This can happen if the declaration is merely mergeable and not
8327 // actually redeclarable (we looked for redeclarations earlier).
8328 //
8329 // FIXME: We should be able to detect this more efficiently, without
8330 // pulling in all of the members of CanonDef.
8331 Found = true;
8332 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008333 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008334 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8335 if (ND->getDeclName() == D->getDeclName())
8336 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008337 }
8338
8339 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008340 // The AST doesn't like TagDecls becoming invalid after they've been
8341 // completed. We only really need to mark FieldDecls as invalid here.
8342 if (!isa<TagDecl>(D))
8343 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008344
8345 // Ensure we don't accidentally recursively enter deserialization while
8346 // we're producing our diagnostic.
8347 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008348
8349 std::string CanonDefModule =
8350 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8351 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8352 << D << getOwningModuleNameForDiagnostic(D)
8353 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8354
8355 if (Candidates.empty())
8356 Diag(cast<Decl>(CanonDef)->getLocation(),
8357 diag::note_module_odr_violation_no_possible_decls) << D;
8358 else {
8359 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8360 Diag(Candidates[I]->getLocation(),
8361 diag::note_module_odr_violation_possible_decl)
8362 << Candidates[I];
8363 }
8364
8365 DiagnosedOdrMergeFailures.insert(CanonDef);
8366 }
8367 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008368
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008369 if (OdrMergeFailures.empty())
8370 return;
8371
8372 // Ensure we don't accidentally recursively enter deserialization while
8373 // we're producing our diagnostics.
8374 Deserializing RecursionGuard(this);
8375
Richard Smithcd45dbc2014-04-19 03:48:30 +00008376 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008377 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008378 // If we've already pointed out a specific problem with this class, don't
8379 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008380 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008381 continue;
8382
8383 bool Diagnosed = false;
8384 for (auto *RD : Merge.second) {
8385 // Multiple different declarations got merged together; tell the user
8386 // where they came from.
8387 if (Merge.first != RD) {
8388 // FIXME: Walk the definition, figure out what's different,
8389 // and diagnose that.
8390 if (!Diagnosed) {
8391 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8392 Diag(Merge.first->getLocation(),
8393 diag::err_module_odr_violation_different_definitions)
8394 << Merge.first << Module.empty() << Module;
8395 Diagnosed = true;
8396 }
8397
8398 Diag(RD->getLocation(),
8399 diag::note_module_odr_violation_different_definitions)
8400 << getOwningModuleNameForDiagnostic(RD);
8401 }
8402 }
8403
8404 if (!Diagnosed) {
8405 // All definitions are updates to the same declaration. This happens if a
8406 // module instantiates the declaration of a class template specialization
8407 // and two or more other modules instantiate its definition.
8408 //
8409 // FIXME: Indicate which modules had instantiations of this definition.
8410 // FIXME: How can this even happen?
8411 Diag(Merge.first->getLocation(),
8412 diag::err_module_odr_violation_different_instantiations)
8413 << Merge.first;
8414 }
8415 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008416}
8417
Richard Smithce18a182015-07-14 00:26:00 +00008418void ASTReader::StartedDeserializing() {
8419 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8420 ReadTimer->startTimer();
8421}
8422
Guy Benyei11169dd2012-12-18 14:30:41 +00008423void ASTReader::FinishedDeserializing() {
8424 assert(NumCurrentElementsDeserializing &&
8425 "FinishedDeserializing not paired with StartedDeserializing");
8426 if (NumCurrentElementsDeserializing == 1) {
8427 // We decrease NumCurrentElementsDeserializing only after pending actions
8428 // are finished, to avoid recursively re-calling finishPendingActions().
8429 finishPendingActions();
8430 }
8431 --NumCurrentElementsDeserializing;
8432
Richard Smitha0ce9c42014-07-29 23:23:27 +00008433 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008434 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008435 while (!PendingExceptionSpecUpdates.empty()) {
8436 auto Updates = std::move(PendingExceptionSpecUpdates);
8437 PendingExceptionSpecUpdates.clear();
8438 for (auto Update : Updates) {
8439 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008440 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00008441 if (auto *Listener = Context.getASTMutationListener())
8442 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00008443 for (auto *Redecl : Update.second->redecls())
8444 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008445 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008446 }
8447
Richard Smithce18a182015-07-14 00:26:00 +00008448 if (ReadTimer)
8449 ReadTimer->stopTimer();
8450
Richard Smith0f4e2c42015-08-06 04:23:48 +00008451 diagnoseOdrViolations();
8452
Richard Smith04d05b52014-03-23 00:27:18 +00008453 // We are not in recursive loading, so it's safe to pass the "interesting"
8454 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008455 if (Consumer)
8456 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008457 }
8458}
8459
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008460void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008461 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8462 // Remove any fake results before adding any real ones.
8463 auto It = PendingFakeLookupResults.find(II);
8464 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008465 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008466 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008467 // FIXME: this works around module+PCH performance issue.
8468 // Rather than erase the result from the map, which is O(n), just clear
8469 // the vector of NamedDecls.
8470 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008471 }
8472 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008473
8474 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8475 SemaObj->TUScope->AddDecl(D);
8476 } else if (SemaObj->TUScope) {
8477 // Adding the decl to IdResolver may have failed because it was already in
8478 // (even though it was not added in scope). If it is already in, make sure
8479 // it gets in the scope as well.
8480 if (std::find(SemaObj->IdResolver.begin(Name),
8481 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8482 SemaObj->TUScope->AddDecl(D);
8483 }
8484}
8485
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008486ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008487 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008488 StringRef isysroot, bool DisableValidation,
8489 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008490 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Richard Smithce18a182015-07-14 00:26:00 +00008491 bool UseGlobalIndex,
8492 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008493 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008494 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008495 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008496 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008497 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008498 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008499 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008500 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8501 AllowConfigurationMismatch(AllowConfigurationMismatch),
8502 ValidateSystemInputs(ValidateSystemInputs),
8503 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008504 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8505 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8506 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8507 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008508 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8509 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8510 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8511 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8512 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8513 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008514 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008515 SourceMgr.setExternalSLocEntrySource(this);
8516}
8517
8518ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008519 if (OwnsDeserializationListener)
8520 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008521}