blob: 2273979883aa2f167346adee724bbbefc6891d9c [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"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000025#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/SourceManagerInternals.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Basic/TargetOptions.h"
31#include "clang/Basic/Version.h"
32#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000033#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/HeaderSearchOptions.h"
36#include "clang/Lex/MacroInfo.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Lex/PreprocessorOptions.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/Sema.h"
42#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000043#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "clang/Serialization/ModuleManager.h"
45#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000046#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000047#include "llvm/ADT/StringExtras.h"
48#include "llvm/Bitcode/BitstreamReader.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/FileSystem.h"
51#include "llvm/Support/MemoryBuffer.h"
52#include "llvm/Support/Path.h"
53#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000054#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000056#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000058#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000059
60using namespace clang;
61using namespace clang::serialization;
62using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000063using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000064
Ben Langmuircb69b572014-03-07 06:40:32 +000065
66//===----------------------------------------------------------------------===//
67// ChainedASTReaderListener implementation
68//===----------------------------------------------------------------------===//
69
70bool
71ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
72 return First->ReadFullVersionInformation(FullVersion) ||
73 Second->ReadFullVersionInformation(FullVersion);
74}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000075void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
76 First->ReadModuleName(ModuleName);
77 Second->ReadModuleName(ModuleName);
78}
79void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
80 First->ReadModuleMapFile(ModuleMapPath);
81 Second->ReadModuleMapFile(ModuleMapPath);
82}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000083bool
84ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
85 bool Complain,
86 bool AllowCompatibleDifferences) {
87 return First->ReadLanguageOptions(LangOpts, Complain,
88 AllowCompatibleDifferences) ||
89 Second->ReadLanguageOptions(LangOpts, Complain,
90 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000091}
Chandler Carruth0d745bc2015-03-14 04:47:43 +000092bool ChainedASTReaderListener::ReadTargetOptions(
93 const TargetOptions &TargetOpts, bool Complain,
94 bool AllowCompatibleDifferences) {
95 return First->ReadTargetOptions(TargetOpts, Complain,
96 AllowCompatibleDifferences) ||
97 Second->ReadTargetOptions(TargetOpts, Complain,
98 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000099}
100bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000101 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000102 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
103 Second->ReadDiagnosticOptions(DiagOpts, Complain);
104}
105bool
106ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
107 bool Complain) {
108 return First->ReadFileSystemOptions(FSOpts, Complain) ||
109 Second->ReadFileSystemOptions(FSOpts, Complain);
110}
111
112bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000113 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
114 bool Complain) {
115 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
116 Complain) ||
117 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
118 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000119}
120bool ChainedASTReaderListener::ReadPreprocessorOptions(
121 const PreprocessorOptions &PPOpts, bool Complain,
122 std::string &SuggestedPredefines) {
123 return First->ReadPreprocessorOptions(PPOpts, Complain,
124 SuggestedPredefines) ||
125 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
126}
127void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
128 unsigned Value) {
129 First->ReadCounter(M, Value);
130 Second->ReadCounter(M, Value);
131}
132bool ChainedASTReaderListener::needsInputFileVisitation() {
133 return First->needsInputFileVisitation() ||
134 Second->needsInputFileVisitation();
135}
136bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
137 return First->needsSystemInputFileVisitation() ||
138 Second->needsSystemInputFileVisitation();
139}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000140void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
141 First->visitModuleFile(Filename);
142 Second->visitModuleFile(Filename);
143}
Ben Langmuircb69b572014-03-07 06:40:32 +0000144bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000145 bool isSystem,
146 bool isOverridden) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000147 bool Continue = false;
148 if (First->needsInputFileVisitation() &&
149 (!isSystem || First->needsSystemInputFileVisitation()))
150 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
151 if (Second->needsInputFileVisitation() &&
152 (!isSystem || Second->needsSystemInputFileVisitation()))
153 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
154 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000155}
156
Guy Benyei11169dd2012-12-18 14:30:41 +0000157//===----------------------------------------------------------------------===//
158// PCH validator implementation
159//===----------------------------------------------------------------------===//
160
161ASTReaderListener::~ASTReaderListener() {}
162
163/// \brief Compare the given set of language options against an existing set of
164/// language options.
165///
166/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000167/// \param AllowCompatibleDifferences If true, differences between compatible
168/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000169///
170/// \returns true if the languagae options mis-match, false otherwise.
171static bool checkLanguageOptions(const LangOptions &LangOpts,
172 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000173 DiagnosticsEngine *Diags,
174 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000175#define LANGOPT(Name, Bits, Default, Description) \
176 if (ExistingLangOpts.Name != LangOpts.Name) { \
177 if (Diags) \
178 Diags->Report(diag::err_pch_langopt_mismatch) \
179 << Description << LangOpts.Name << ExistingLangOpts.Name; \
180 return true; \
181 }
182
183#define VALUE_LANGOPT(Name, Bits, Default, Description) \
184 if (ExistingLangOpts.Name != LangOpts.Name) { \
185 if (Diags) \
186 Diags->Report(diag::err_pch_langopt_value_mismatch) \
187 << Description; \
188 return true; \
189 }
190
191#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
192 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
193 if (Diags) \
194 Diags->Report(diag::err_pch_langopt_value_mismatch) \
195 << Description; \
196 return true; \
197 }
198
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000199#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
200 if (!AllowCompatibleDifferences) \
201 LANGOPT(Name, Bits, Default, Description)
202
203#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
204 if (!AllowCompatibleDifferences) \
205 ENUM_LANGOPT(Name, Bits, Default, Description)
206
Guy Benyei11169dd2012-12-18 14:30:41 +0000207#define BENIGN_LANGOPT(Name, Bits, Default, Description)
208#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
209#include "clang/Basic/LangOptions.def"
210
211 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
212 if (Diags)
213 Diags->Report(diag::err_pch_langopt_value_mismatch)
214 << "target Objective-C runtime";
215 return true;
216 }
217
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000218 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
219 LangOpts.CommentOpts.BlockCommandNames) {
220 if (Diags)
221 Diags->Report(diag::err_pch_langopt_value_mismatch)
222 << "block command names";
223 return true;
224 }
225
Guy Benyei11169dd2012-12-18 14:30:41 +0000226 return false;
227}
228
229/// \brief Compare the given set of target options against an existing set of
230/// target options.
231///
232/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
233///
234/// \returns true if the target options mis-match, false otherwise.
235static bool checkTargetOptions(const TargetOptions &TargetOpts,
236 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000237 DiagnosticsEngine *Diags,
238 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000239#define CHECK_TARGET_OPT(Field, Name) \
240 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
241 if (Diags) \
242 Diags->Report(diag::err_pch_targetopt_mismatch) \
243 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
244 return true; \
245 }
246
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000247 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000248 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000249 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000250
251 // We can tolerate different CPUs in many cases, notably when one CPU
252 // supports a strict superset of another. When allowing compatible
253 // differences skip this check.
254 if (!AllowCompatibleDifferences)
255 CHECK_TARGET_OPT(CPU, "target CPU");
256
Guy Benyei11169dd2012-12-18 14:30:41 +0000257#undef CHECK_TARGET_OPT
258
259 // Compare feature sets.
260 SmallVector<StringRef, 4> ExistingFeatures(
261 ExistingTargetOpts.FeaturesAsWritten.begin(),
262 ExistingTargetOpts.FeaturesAsWritten.end());
263 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
264 TargetOpts.FeaturesAsWritten.end());
265 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
266 std::sort(ReadFeatures.begin(), ReadFeatures.end());
267
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000268 // We compute the set difference in both directions explicitly so that we can
269 // diagnose the differences differently.
270 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
271 std::set_difference(
272 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
273 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
274 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
275 ExistingFeatures.begin(), ExistingFeatures.end(),
276 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000277
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000278 // If we are allowing compatible differences and the read feature set is
279 // a strict subset of the existing feature set, there is nothing to diagnose.
280 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
281 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000282
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000283 if (Diags) {
284 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000285 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000286 << /* is-existing-feature */ false << Feature;
287 for (StringRef Feature : UnmatchedExistingFeatures)
288 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
289 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000290 }
291
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000292 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000293}
294
295bool
296PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000297 bool Complain,
298 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000299 const LangOptions &ExistingLangOpts = PP.getLangOpts();
300 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000301 Complain ? &Reader.Diags : nullptr,
302 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000303}
304
305bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000306 bool Complain,
307 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000308 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
309 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000310 Complain ? &Reader.Diags : nullptr,
311 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000312}
313
314namespace {
315 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
316 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000317 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
318 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000319}
320
Ben Langmuirb92de022014-04-29 16:25:26 +0000321static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
322 DiagnosticsEngine &Diags,
323 bool Complain) {
324 typedef DiagnosticsEngine::Level Level;
325
326 // Check current mappings for new -Werror mappings, and the stored mappings
327 // for cases that were explicitly mapped to *not* be errors that are now
328 // errors because of options like -Werror.
329 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
330
331 for (DiagnosticsEngine *MappingSource : MappingSources) {
332 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
333 diag::kind DiagID = DiagIDMappingPair.first;
334 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
335 if (CurLevel < DiagnosticsEngine::Error)
336 continue; // not significant
337 Level StoredLevel =
338 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
339 if (StoredLevel < DiagnosticsEngine::Error) {
340 if (Complain)
341 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
342 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
343 return true;
344 }
345 }
346 }
347
348 return false;
349}
350
Alp Tokerac4e8e52014-06-22 21:58:33 +0000351static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
352 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
353 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
354 return true;
355 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000356}
357
358static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
359 DiagnosticsEngine &Diags,
360 bool IsSystem, bool Complain) {
361 // Top-level options
362 if (IsSystem) {
363 if (Diags.getSuppressSystemWarnings())
364 return false;
365 // If -Wsystem-headers was not enabled before, be conservative
366 if (StoredDiags.getSuppressSystemWarnings()) {
367 if (Complain)
368 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
369 return true;
370 }
371 }
372
373 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
374 if (Complain)
375 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
376 return true;
377 }
378
379 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
380 !StoredDiags.getEnableAllWarnings()) {
381 if (Complain)
382 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
383 return true;
384 }
385
386 if (isExtHandlingFromDiagsError(Diags) &&
387 !isExtHandlingFromDiagsError(StoredDiags)) {
388 if (Complain)
389 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
390 return true;
391 }
392
393 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
394}
395
396bool PCHValidator::ReadDiagnosticOptions(
397 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
398 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
399 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
400 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000401 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000402 // This should never fail, because we would have processed these options
403 // before writing them to an ASTFile.
404 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
405
406 ModuleManager &ModuleMgr = Reader.getModuleManager();
407 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
408
409 // If the original import came from a file explicitly generated by the user,
410 // don't check the diagnostic mappings.
411 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000412 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000413 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
414 // the transitive closure of its imports, since unrelated modules cannot be
415 // imported until after this module finishes validation.
416 ModuleFile *TopImport = *ModuleMgr.rbegin();
417 while (!TopImport->ImportedBy.empty())
418 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000419 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000420 return false;
421
422 StringRef ModuleName = TopImport->ModuleName;
423 assert(!ModuleName.empty() && "diagnostic options read before module name");
424
425 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
426 assert(M && "missing module");
427
428 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
429 // contains the union of their flags.
430 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
431}
432
Guy Benyei11169dd2012-12-18 14:30:41 +0000433/// \brief Collect the macro definitions provided by the given preprocessor
434/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000435static void
436collectMacroDefinitions(const PreprocessorOptions &PPOpts,
437 MacroDefinitionsMap &Macros,
438 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000439 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
440 StringRef Macro = PPOpts.Macros[I].first;
441 bool IsUndef = PPOpts.Macros[I].second;
442
443 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
444 StringRef MacroName = MacroPair.first;
445 StringRef MacroBody = MacroPair.second;
446
447 // For an #undef'd macro, we only care about the name.
448 if (IsUndef) {
449 if (MacroNames && !Macros.count(MacroName))
450 MacroNames->push_back(MacroName);
451
452 Macros[MacroName] = std::make_pair("", true);
453 continue;
454 }
455
456 // For a #define'd macro, figure out the actual definition.
457 if (MacroName.size() == Macro.size())
458 MacroBody = "1";
459 else {
460 // Note: GCC drops anything following an end-of-line character.
461 StringRef::size_type End = MacroBody.find_first_of("\n\r");
462 MacroBody = MacroBody.substr(0, End);
463 }
464
465 if (MacroNames && !Macros.count(MacroName))
466 MacroNames->push_back(MacroName);
467 Macros[MacroName] = std::make_pair(MacroBody, false);
468 }
469}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000470
Guy Benyei11169dd2012-12-18 14:30:41 +0000471/// \brief Check the preprocessor options deserialized from the control block
472/// against the preprocessor options in an existing preprocessor.
473///
474/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
475static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
476 const PreprocessorOptions &ExistingPPOpts,
477 DiagnosticsEngine *Diags,
478 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000479 std::string &SuggestedPredefines,
480 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000481 // Check macro definitions.
482 MacroDefinitionsMap ASTFileMacros;
483 collectMacroDefinitions(PPOpts, ASTFileMacros);
484 MacroDefinitionsMap ExistingMacros;
485 SmallVector<StringRef, 4> ExistingMacroNames;
486 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
487
488 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
489 // Dig out the macro definition in the existing preprocessor options.
490 StringRef MacroName = ExistingMacroNames[I];
491 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
492
493 // Check whether we know anything about this macro name or not.
494 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
495 = ASTFileMacros.find(MacroName);
496 if (Known == ASTFileMacros.end()) {
497 // FIXME: Check whether this identifier was referenced anywhere in the
498 // AST file. If so, we should reject the AST file. Unfortunately, this
499 // information isn't in the control block. What shall we do about it?
500
501 if (Existing.second) {
502 SuggestedPredefines += "#undef ";
503 SuggestedPredefines += MacroName.str();
504 SuggestedPredefines += '\n';
505 } else {
506 SuggestedPredefines += "#define ";
507 SuggestedPredefines += MacroName.str();
508 SuggestedPredefines += ' ';
509 SuggestedPredefines += Existing.first.str();
510 SuggestedPredefines += '\n';
511 }
512 continue;
513 }
514
515 // If the macro was defined in one but undef'd in the other, we have a
516 // conflict.
517 if (Existing.second != Known->second.second) {
518 if (Diags) {
519 Diags->Report(diag::err_pch_macro_def_undef)
520 << MacroName << Known->second.second;
521 }
522 return true;
523 }
524
525 // If the macro was #undef'd in both, or if the macro bodies are identical,
526 // it's fine.
527 if (Existing.second || Existing.first == Known->second.first)
528 continue;
529
530 // The macro bodies differ; complain.
531 if (Diags) {
532 Diags->Report(diag::err_pch_macro_def_conflict)
533 << MacroName << Known->second.first << Existing.first;
534 }
535 return true;
536 }
537
538 // Check whether we're using predefines.
539 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
540 if (Diags) {
541 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
542 }
543 return true;
544 }
545
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000546 // Detailed record is important since it is used for the module cache hash.
547 if (LangOpts.Modules &&
548 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
549 if (Diags) {
550 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
551 }
552 return true;
553 }
554
Guy Benyei11169dd2012-12-18 14:30:41 +0000555 // Compute the #include and #include_macros lines we need.
556 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
557 StringRef File = ExistingPPOpts.Includes[I];
558 if (File == ExistingPPOpts.ImplicitPCHInclude)
559 continue;
560
561 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
562 != PPOpts.Includes.end())
563 continue;
564
565 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000566 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000567 SuggestedPredefines += "\"\n";
568 }
569
570 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
571 StringRef File = ExistingPPOpts.MacroIncludes[I];
572 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
573 File)
574 != PPOpts.MacroIncludes.end())
575 continue;
576
577 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000578 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000579 SuggestedPredefines += "\"\n##\n";
580 }
581
582 return false;
583}
584
585bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
586 bool Complain,
587 std::string &SuggestedPredefines) {
588 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
589
590 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000591 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000592 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000593 SuggestedPredefines,
594 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000595}
596
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000597/// Check the header search options deserialized from the control block
598/// against the header search options in an existing preprocessor.
599///
600/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
601static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
602 StringRef SpecificModuleCachePath,
603 StringRef ExistingModuleCachePath,
604 DiagnosticsEngine *Diags,
605 const LangOptions &LangOpts) {
606 if (LangOpts.Modules) {
607 if (SpecificModuleCachePath != ExistingModuleCachePath) {
608 if (Diags)
609 Diags->Report(diag::err_pch_modulecache_mismatch)
610 << SpecificModuleCachePath << ExistingModuleCachePath;
611 return true;
612 }
613 }
614
615 return false;
616}
617
618bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
619 StringRef SpecificModuleCachePath,
620 bool Complain) {
621 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
622 PP.getHeaderSearchInfo().getModuleCachePath(),
623 Complain ? &Reader.Diags : nullptr,
624 PP.getLangOpts());
625}
626
Guy Benyei11169dd2012-12-18 14:30:41 +0000627void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
628 PP.setCounterValue(Value);
629}
630
631//===----------------------------------------------------------------------===//
632// AST reader implementation
633//===----------------------------------------------------------------------===//
634
Nico Weber824285e2014-05-08 04:26:47 +0000635void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
636 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000637 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000638 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000639}
640
641
642
643unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
644 return serialization::ComputeHash(Sel);
645}
646
647
648std::pair<unsigned, unsigned>
649ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000650 using namespace llvm::support;
651 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
652 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000653 return std::make_pair(KeyLen, DataLen);
654}
655
656ASTSelectorLookupTrait::internal_key_type
657ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000658 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000659 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000660 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
661 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
662 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000663 if (N == 0)
664 return SelTable.getNullarySelector(FirstII);
665 else if (N == 1)
666 return SelTable.getUnarySelector(FirstII);
667
668 SmallVector<IdentifierInfo *, 16> Args;
669 Args.push_back(FirstII);
670 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000671 Args.push_back(Reader.getLocalIdentifier(
672 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000673
674 return SelTable.getSelector(N, Args.data());
675}
676
677ASTSelectorLookupTrait::data_type
678ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
679 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000680 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000681
682 data_type Result;
683
Justin Bogner57ba0b22014-03-28 22:03:24 +0000684 Result.ID = Reader.getGlobalSelectorID(
685 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000686 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
687 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
688 Result.InstanceBits = FullInstanceBits & 0x3;
689 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
690 Result.FactoryBits = FullFactoryBits & 0x3;
691 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
692 unsigned NumInstanceMethods = FullInstanceBits >> 3;
693 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000694
695 // Load instance methods
696 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000697 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
698 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000699 Result.Instance.push_back(Method);
700 }
701
702 // Load factory methods
703 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000704 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
705 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000706 Result.Factory.push_back(Method);
707 }
708
709 return Result;
710}
711
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000712unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
713 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000714}
715
716std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000717ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000718 using namespace llvm::support;
719 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
720 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000721 return std::make_pair(KeyLen, DataLen);
722}
723
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000724ASTIdentifierLookupTraitBase::internal_key_type
725ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000726 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000727 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000728}
729
Douglas Gregordcf25082013-02-11 18:16:18 +0000730/// \brief Whether the given identifier is "interesting".
731static bool isInterestingIdentifier(IdentifierInfo &II) {
732 return II.isPoisoned() ||
733 II.isExtensionToken() ||
734 II.getObjCOrBuiltinID() ||
735 II.hasRevertedTokenIDToIdentifier() ||
736 II.hadMacroDefinition() ||
737 II.getFETokenInfo<void>();
738}
739
Guy Benyei11169dd2012-12-18 14:30:41 +0000740IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
741 const unsigned char* d,
742 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000743 using namespace llvm::support;
744 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000745 bool IsInteresting = RawID & 0x01;
746
747 // Wipe out the "is interesting" bit.
748 RawID = RawID >> 1;
749
750 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
751 if (!IsInteresting) {
752 // For uninteresting identifiers, just build the IdentifierInfo
753 // and associate it with the persistent ID.
754 IdentifierInfo *II = KnownII;
755 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000756 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000757 KnownII = II;
758 }
759 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000760 if (!II->isFromAST()) {
761 bool WasInteresting = isInterestingIdentifier(*II);
762 II->setIsFromAST();
763 if (WasInteresting)
764 II->setChangedSinceDeserialization();
765 }
766 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000767 return II;
768 }
769
Justin Bogner57ba0b22014-03-28 22:03:24 +0000770 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
771 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000772 bool CPlusPlusOperatorKeyword = Bits & 0x01;
773 Bits >>= 1;
774 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
775 Bits >>= 1;
776 bool Poisoned = Bits & 0x01;
777 Bits >>= 1;
778 bool ExtensionToken = Bits & 0x01;
779 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000780 bool hasSubmoduleMacros = Bits & 0x01;
781 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000782 bool hadMacroDefinition = Bits & 0x01;
783 Bits >>= 1;
784
785 assert(Bits == 0 && "Extra bits in the identifier?");
786 DataLen -= 8;
787
788 // Build the IdentifierInfo itself and link the identifier ID with
789 // the new IdentifierInfo.
790 IdentifierInfo *II = KnownII;
791 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000792 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000793 KnownII = II;
794 }
795 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000796 if (!II->isFromAST()) {
797 bool WasInteresting = isInterestingIdentifier(*II);
798 II->setIsFromAST();
799 if (WasInteresting)
800 II->setChangedSinceDeserialization();
801 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000802
803 // Set or check the various bits in the IdentifierInfo structure.
804 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000805 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000806 II->RevertTokenIDToIdentifier();
807 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
808 assert(II->isExtensionToken() == ExtensionToken &&
809 "Incorrect extension token flag");
810 (void)ExtensionToken;
811 if (Poisoned)
812 II->setIsPoisoned(true);
813 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
814 "Incorrect C++ operator keyword flag");
815 (void)CPlusPlusOperatorKeyword;
816
817 // If this identifier is a macro, deserialize the macro
818 // definition.
819 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000820 uint32_t MacroDirectivesOffset =
821 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000822 DataLen -= 4;
823 SmallVector<uint32_t, 8> LocalMacroIDs;
824 if (hasSubmoduleMacros) {
Richard Smithdaa69e02014-07-25 04:40:03 +0000825 while (true) {
826 uint32_t LocalMacroID =
827 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000828 DataLen -= 4;
Richard Smithdf8a8312015-03-13 04:05:01 +0000829 if (LocalMacroID == (uint32_t)-1) break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000830 LocalMacroIDs.push_back(LocalMacroID);
831 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000832 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000833
Richard Smithe842a472014-10-22 02:05:46 +0000834 if (F.Kind == MK_ImplicitModule || F.Kind == MK_ExplicitModule) {
Richard Smith49f906a2014-03-01 00:08:04 +0000835 // Macro definitions are stored from newest to oldest, so reverse them
836 // before registering them.
837 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000838 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000839 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
840 unsigned Size = 1;
841
842 static const uint32_t HasOverridesFlag = 0x80000000U;
843 if (I + 1 != E && (I[1] & HasOverridesFlag))
844 Size += 1 + (I[1] & ~HasOverridesFlag);
845
846 MacroSizes.push_back(Size);
847 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000848 }
Richard Smith49f906a2014-03-01 00:08:04 +0000849
850 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
851 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
852 SE = MacroSizes.rend();
853 SI != SE; ++SI) {
854 I -= *SI;
855
856 uint32_t LocalMacroID = *I;
Craig Topper00bbdcf2014-06-28 23:22:23 +0000857 ArrayRef<uint32_t> Overrides;
Richard Smith49f906a2014-03-01 00:08:04 +0000858 if (*SI != 1)
859 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
860 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
861 }
862 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000863 } else {
864 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
865 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000866 }
867
868 Reader.SetIdentifierInfo(ID, II);
869
870 // Read all of the declarations visible at global scope with this
871 // name.
872 if (DataLen > 0) {
873 SmallVector<uint32_t, 4> DeclIDs;
874 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000875 DeclIDs.push_back(Reader.getGlobalDeclID(
876 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000877 Reader.SetGloballyVisibleDecls(II, DeclIDs);
878 }
879
880 return II;
881}
882
883unsigned
884ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
885 llvm::FoldingSetNodeID ID;
886 ID.AddInteger(Key.Kind);
887
888 switch (Key.Kind) {
889 case DeclarationName::Identifier:
890 case DeclarationName::CXXLiteralOperatorName:
891 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
892 break;
893 case DeclarationName::ObjCZeroArgSelector:
894 case DeclarationName::ObjCOneArgSelector:
895 case DeclarationName::ObjCMultiArgSelector:
896 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
897 break;
898 case DeclarationName::CXXOperatorName:
899 ID.AddInteger((OverloadedOperatorKind)Key.Data);
900 break;
901 case DeclarationName::CXXConstructorName:
902 case DeclarationName::CXXDestructorName:
903 case DeclarationName::CXXConversionFunctionName:
904 case DeclarationName::CXXUsingDirective:
905 break;
906 }
907
908 return ID.ComputeHash();
909}
910
911ASTDeclContextNameLookupTrait::internal_key_type
912ASTDeclContextNameLookupTrait::GetInternalKey(
913 const external_key_type& Name) const {
914 DeclNameKey Key;
915 Key.Kind = Name.getNameKind();
916 switch (Name.getNameKind()) {
917 case DeclarationName::Identifier:
918 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
919 break;
920 case DeclarationName::ObjCZeroArgSelector:
921 case DeclarationName::ObjCOneArgSelector:
922 case DeclarationName::ObjCMultiArgSelector:
923 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
924 break;
925 case DeclarationName::CXXOperatorName:
926 Key.Data = Name.getCXXOverloadedOperator();
927 break;
928 case DeclarationName::CXXLiteralOperatorName:
929 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
930 break;
931 case DeclarationName::CXXConstructorName:
932 case DeclarationName::CXXDestructorName:
933 case DeclarationName::CXXConversionFunctionName:
934 case DeclarationName::CXXUsingDirective:
935 Key.Data = 0;
936 break;
937 }
938
939 return Key;
940}
941
942std::pair<unsigned, unsigned>
943ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000944 using namespace llvm::support;
945 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
946 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000947 return std::make_pair(KeyLen, DataLen);
948}
949
950ASTDeclContextNameLookupTrait::internal_key_type
951ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000952 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000953
954 DeclNameKey Key;
955 Key.Kind = (DeclarationName::NameKind)*d++;
956 switch (Key.Kind) {
957 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000958 Key.Data = (uint64_t)Reader.getLocalIdentifier(
959 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000960 break;
961 case DeclarationName::ObjCZeroArgSelector:
962 case DeclarationName::ObjCOneArgSelector:
963 case DeclarationName::ObjCMultiArgSelector:
964 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000965 (uint64_t)Reader.getLocalSelector(
966 F, endian::readNext<uint32_t, little, unaligned>(
967 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000968 break;
969 case DeclarationName::CXXOperatorName:
970 Key.Data = *d++; // OverloadedOperatorKind
971 break;
972 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000973 Key.Data = (uint64_t)Reader.getLocalIdentifier(
974 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000975 break;
976 case DeclarationName::CXXConstructorName:
977 case DeclarationName::CXXDestructorName:
978 case DeclarationName::CXXConversionFunctionName:
979 case DeclarationName::CXXUsingDirective:
980 Key.Data = 0;
981 break;
982 }
983
984 return Key;
985}
986
987ASTDeclContextNameLookupTrait::data_type
988ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
989 const unsigned char* d,
990 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000991 using namespace llvm::support;
992 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000993 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
994 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000995 return std::make_pair(Start, Start + NumDecls);
996}
997
998bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000999 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00001000 const std::pair<uint64_t, uint64_t> &Offsets,
1001 DeclContextInfo &Info) {
1002 SavedStreamPosition SavedPosition(Cursor);
1003 // First the lexical decls.
1004 if (Offsets.first != 0) {
1005 Cursor.JumpToBit(Offsets.first);
1006
1007 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001008 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00001009 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001010 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001011 if (RecCode != DECL_CONTEXT_LEXICAL) {
1012 Error("Expected lexical block");
1013 return true;
1014 }
1015
Chris Lattner0e6c9402013-01-20 02:38:54 +00001016 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
1017 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +00001018 }
1019
1020 // Now the lookup table.
1021 if (Offsets.second != 0) {
1022 Cursor.JumpToBit(Offsets.second);
1023
1024 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001025 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00001026 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001027 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001028 if (RecCode != DECL_CONTEXT_VISIBLE) {
1029 Error("Expected visible lookup table block");
1030 return true;
1031 }
Justin Bognerda4e6502014-04-14 16:34:29 +00001032 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
1033 (const unsigned char *)Blob.data() + Record[0],
1034 (const unsigned char *)Blob.data() + sizeof(uint32_t),
1035 (const unsigned char *)Blob.data(),
1036 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +00001037 }
1038
1039 return false;
1040}
1041
1042void ASTReader::Error(StringRef Msg) {
1043 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001044 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1045 Diag(diag::note_module_cache_path)
1046 << PP.getHeaderSearchInfo().getModuleCachePath();
1047 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001048}
1049
1050void ASTReader::Error(unsigned DiagID,
1051 StringRef Arg1, StringRef Arg2) {
1052 if (Diags.isDiagnosticInFlight())
1053 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1054 else
1055 Diag(DiagID) << Arg1 << Arg2;
1056}
1057
1058//===----------------------------------------------------------------------===//
1059// Source Manager Deserialization
1060//===----------------------------------------------------------------------===//
1061
1062/// \brief Read the line table in the source manager block.
1063/// \returns true if there was an error.
1064bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001065 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001066 unsigned Idx = 0;
1067 LineTableInfo &LineTable = SourceMgr.getLineTable();
1068
1069 // Parse the file names
1070 std::map<int, int> FileIDs;
1071 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1072 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001073 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001074 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1075 }
1076
1077 // Parse the line entries
1078 std::vector<LineEntry> Entries;
1079 while (Idx < Record.size()) {
1080 int FID = Record[Idx++];
1081 assert(FID >= 0 && "Serialized line entries for non-local file.");
1082 // Remap FileID from 1-based old view.
1083 FID += F.SLocEntryBaseID - 1;
1084
1085 // Extract the line entries
1086 unsigned NumEntries = Record[Idx++];
1087 assert(NumEntries && "Numentries is 00000");
1088 Entries.clear();
1089 Entries.reserve(NumEntries);
1090 for (unsigned I = 0; I != NumEntries; ++I) {
1091 unsigned FileOffset = Record[Idx++];
1092 unsigned LineNo = Record[Idx++];
1093 int FilenameID = FileIDs[Record[Idx++]];
1094 SrcMgr::CharacteristicKind FileKind
1095 = (SrcMgr::CharacteristicKind)Record[Idx++];
1096 unsigned IncludeOffset = Record[Idx++];
1097 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1098 FileKind, IncludeOffset));
1099 }
1100 LineTable.AddEntry(FileID::get(FID), Entries);
1101 }
1102
1103 return false;
1104}
1105
1106/// \brief Read a source manager block
1107bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1108 using namespace SrcMgr;
1109
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001110 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001111
1112 // Set the source-location entry cursor to the current position in
1113 // the stream. This cursor will be used to read the contents of the
1114 // source manager block initially, and then lazily read
1115 // source-location entries as needed.
1116 SLocEntryCursor = F.Stream;
1117
1118 // The stream itself is going to skip over the source manager block.
1119 if (F.Stream.SkipBlock()) {
1120 Error("malformed block record in AST file");
1121 return true;
1122 }
1123
1124 // Enter the source manager block.
1125 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1126 Error("malformed source manager block record in AST file");
1127 return true;
1128 }
1129
1130 RecordData Record;
1131 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001132 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1133
1134 switch (E.Kind) {
1135 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1136 case llvm::BitstreamEntry::Error:
1137 Error("malformed block record in AST file");
1138 return true;
1139 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001140 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001141 case llvm::BitstreamEntry::Record:
1142 // The interesting case.
1143 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001144 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001145
Guy Benyei11169dd2012-12-18 14:30:41 +00001146 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001147 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001148 StringRef Blob;
1149 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001150 default: // Default behavior: ignore.
1151 break;
1152
1153 case SM_SLOC_FILE_ENTRY:
1154 case SM_SLOC_BUFFER_ENTRY:
1155 case SM_SLOC_EXPANSION_ENTRY:
1156 // Once we hit one of the source location entries, we're done.
1157 return false;
1158 }
1159 }
1160}
1161
1162/// \brief If a header file is not found at the path that we expect it to be
1163/// and the PCH file was moved from its original location, try to resolve the
1164/// file by assuming that header+PCH were moved together and the header is in
1165/// the same place relative to the PCH.
1166static std::string
1167resolveFileRelativeToOriginalDir(const std::string &Filename,
1168 const std::string &OriginalDir,
1169 const std::string &CurrDir) {
1170 assert(OriginalDir != CurrDir &&
1171 "No point trying to resolve the file if the PCH dir didn't change");
1172 using namespace llvm::sys;
1173 SmallString<128> filePath(Filename);
1174 fs::make_absolute(filePath);
1175 assert(path::is_absolute(OriginalDir));
1176 SmallString<128> currPCHPath(CurrDir);
1177
1178 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1179 fileDirE = path::end(path::parent_path(filePath));
1180 path::const_iterator origDirI = path::begin(OriginalDir),
1181 origDirE = path::end(OriginalDir);
1182 // Skip the common path components from filePath and OriginalDir.
1183 while (fileDirI != fileDirE && origDirI != origDirE &&
1184 *fileDirI == *origDirI) {
1185 ++fileDirI;
1186 ++origDirI;
1187 }
1188 for (; origDirI != origDirE; ++origDirI)
1189 path::append(currPCHPath, "..");
1190 path::append(currPCHPath, fileDirI, fileDirE);
1191 path::append(currPCHPath, path::filename(Filename));
1192 return currPCHPath.str();
1193}
1194
1195bool ASTReader::ReadSLocEntry(int ID) {
1196 if (ID == 0)
1197 return false;
1198
1199 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1200 Error("source location entry ID out-of-range for AST file");
1201 return true;
1202 }
1203
1204 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1205 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001206 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001207 unsigned BaseOffset = F->SLocEntryBaseOffset;
1208
1209 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001210 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1211 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001212 Error("incorrectly-formatted source location entry in AST file");
1213 return true;
1214 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001215
Guy Benyei11169dd2012-12-18 14:30:41 +00001216 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001217 StringRef Blob;
1218 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001219 default:
1220 Error("incorrectly-formatted source location entry in AST file");
1221 return true;
1222
1223 case SM_SLOC_FILE_ENTRY: {
1224 // We will detect whether a file changed and return 'Failure' for it, but
1225 // we will also try to fail gracefully by setting up the SLocEntry.
1226 unsigned InputID = Record[4];
1227 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001228 const FileEntry *File = IF.getFile();
1229 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001230
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001231 // Note that we only check if a File was returned. If it was out-of-date
1232 // we have complained but we will continue creating a FileID to recover
1233 // gracefully.
1234 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001235 return true;
1236
1237 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1238 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1239 // This is the module's main file.
1240 IncludeLoc = getImportLocation(F);
1241 }
1242 SrcMgr::CharacteristicKind
1243 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1244 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1245 ID, BaseOffset + Record[0]);
1246 SrcMgr::FileInfo &FileInfo =
1247 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1248 FileInfo.NumCreatedFIDs = Record[5];
1249 if (Record[3])
1250 FileInfo.setHasLineDirectives();
1251
1252 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1253 unsigned NumFileDecls = Record[7];
1254 if (NumFileDecls) {
1255 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1256 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1257 NumFileDecls));
1258 }
1259
1260 const SrcMgr::ContentCache *ContentCache
1261 = SourceMgr.getOrCreateContentCache(File,
1262 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1263 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1264 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1265 unsigned Code = SLocEntryCursor.ReadCode();
1266 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001267 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001268
1269 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1270 Error("AST record has invalid code");
1271 return true;
1272 }
1273
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001274 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001275 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001276 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001277 }
1278
1279 break;
1280 }
1281
1282 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001283 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001284 unsigned Offset = Record[0];
1285 SrcMgr::CharacteristicKind
1286 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1287 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001288 if (IncludeLoc.isInvalid() &&
1289 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001290 IncludeLoc = getImportLocation(F);
1291 }
1292 unsigned Code = SLocEntryCursor.ReadCode();
1293 Record.clear();
1294 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001295 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001296
1297 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1298 Error("AST record has invalid code");
1299 return true;
1300 }
1301
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001302 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1303 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001304 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001305 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001306 break;
1307 }
1308
1309 case SM_SLOC_EXPANSION_ENTRY: {
1310 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1311 SourceMgr.createExpansionLoc(SpellingLoc,
1312 ReadSourceLocation(*F, Record[2]),
1313 ReadSourceLocation(*F, Record[3]),
1314 Record[4],
1315 ID,
1316 BaseOffset + Record[0]);
1317 break;
1318 }
1319 }
1320
1321 return false;
1322}
1323
1324std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1325 if (ID == 0)
1326 return std::make_pair(SourceLocation(), "");
1327
1328 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1329 Error("source location entry ID out-of-range for AST file");
1330 return std::make_pair(SourceLocation(), "");
1331 }
1332
1333 // Find which module file this entry lands in.
1334 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001335 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001336 return std::make_pair(SourceLocation(), "");
1337
1338 // FIXME: Can we map this down to a particular submodule? That would be
1339 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001340 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001341}
1342
1343/// \brief Find the location where the module F is imported.
1344SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1345 if (F->ImportLoc.isValid())
1346 return F->ImportLoc;
1347
1348 // Otherwise we have a PCH. It's considered to be "imported" at the first
1349 // location of its includer.
1350 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001351 // Main file is the importer.
1352 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1353 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001354 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001355 return F->ImportedBy[0]->FirstLoc;
1356}
1357
1358/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1359/// specified cursor. Read the abbreviations that are at the top of the block
1360/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001361bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001362 if (Cursor.EnterSubBlock(BlockID)) {
1363 Error("malformed block record in AST file");
1364 return Failure;
1365 }
1366
1367 while (true) {
1368 uint64_t Offset = Cursor.GetCurrentBitNo();
1369 unsigned Code = Cursor.ReadCode();
1370
1371 // We expect all abbrevs to be at the start of the block.
1372 if (Code != llvm::bitc::DEFINE_ABBREV) {
1373 Cursor.JumpToBit(Offset);
1374 return false;
1375 }
1376 Cursor.ReadAbbrevRecord();
1377 }
1378}
1379
Richard Smithe40f2ba2013-08-07 21:41:30 +00001380Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001381 unsigned &Idx) {
1382 Token Tok;
1383 Tok.startToken();
1384 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1385 Tok.setLength(Record[Idx++]);
1386 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1387 Tok.setIdentifierInfo(II);
1388 Tok.setKind((tok::TokenKind)Record[Idx++]);
1389 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1390 return Tok;
1391}
1392
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001393MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001394 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001395
1396 // Keep track of where we are in the stream, then jump back there
1397 // after reading this macro.
1398 SavedStreamPosition SavedPosition(Stream);
1399
1400 Stream.JumpToBit(Offset);
1401 RecordData Record;
1402 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001403 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001404
Guy Benyei11169dd2012-12-18 14:30:41 +00001405 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001406 // Advance to the next record, but if we get to the end of the block, don't
1407 // pop it (removing all the abbreviations from the cursor) since we want to
1408 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001409 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001410 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1411
1412 switch (Entry.Kind) {
1413 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1414 case llvm::BitstreamEntry::Error:
1415 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001416 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001417 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001418 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001419 case llvm::BitstreamEntry::Record:
1420 // The interesting case.
1421 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001422 }
1423
1424 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001425 Record.clear();
1426 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001427 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001428 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001429 case PP_MACRO_DIRECTIVE_HISTORY:
1430 return Macro;
1431
Guy Benyei11169dd2012-12-18 14:30:41 +00001432 case PP_MACRO_OBJECT_LIKE:
1433 case PP_MACRO_FUNCTION_LIKE: {
1434 // If we already have a macro, that means that we've hit the end
1435 // of the definition of the macro we were looking for. We're
1436 // done.
1437 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001438 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001439
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001440 unsigned NextIndex = 1; // Skip identifier ID.
1441 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001442 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001443 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001444 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001445 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001446 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001447
Guy Benyei11169dd2012-12-18 14:30:41 +00001448 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1449 // Decode function-like macro info.
1450 bool isC99VarArgs = Record[NextIndex++];
1451 bool isGNUVarArgs = Record[NextIndex++];
1452 bool hasCommaPasting = Record[NextIndex++];
1453 MacroArgs.clear();
1454 unsigned NumArgs = Record[NextIndex++];
1455 for (unsigned i = 0; i != NumArgs; ++i)
1456 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1457
1458 // Install function-like macro info.
1459 MI->setIsFunctionLike();
1460 if (isC99VarArgs) MI->setIsC99Varargs();
1461 if (isGNUVarArgs) MI->setIsGNUVarargs();
1462 if (hasCommaPasting) MI->setHasCommaPasting();
1463 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1464 PP.getPreprocessorAllocator());
1465 }
1466
Guy Benyei11169dd2012-12-18 14:30:41 +00001467 // Remember that we saw this macro last so that we add the tokens that
1468 // form its body to it.
1469 Macro = MI;
1470
1471 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1472 Record[NextIndex]) {
1473 // We have a macro definition. Register the association
1474 PreprocessedEntityID
1475 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1476 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001477 PreprocessingRecord::PPEntityID
1478 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1479 MacroDefinition *PPDef =
1480 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1481 if (PPDef)
1482 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001483 }
1484
1485 ++NumMacrosRead;
1486 break;
1487 }
1488
1489 case PP_TOKEN: {
1490 // If we see a TOKEN before a PP_MACRO_*, then the file is
1491 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001492 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001493
John McCallf413f5e2013-05-03 00:10:13 +00001494 unsigned Idx = 0;
1495 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001496 Macro->AddTokenToBody(Tok);
1497 break;
1498 }
1499 }
1500 }
1501}
1502
1503PreprocessedEntityID
1504ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1505 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1506 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1507 assert(I != M.PreprocessedEntityRemap.end()
1508 && "Invalid index into preprocessed entity index remap");
1509
1510 return LocalID + I->second;
1511}
1512
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001513unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1514 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001515}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001516
Guy Benyei11169dd2012-12-18 14:30:41 +00001517HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001518HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1519 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001520 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001521 return ikey;
1522}
Guy Benyei11169dd2012-12-18 14:30:41 +00001523
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001524bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1525 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001526 return false;
1527
Richard Smith7ed1bc92014-12-05 22:42:13 +00001528 if (llvm::sys::path::is_absolute(a.Filename) &&
1529 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001530 return true;
1531
Guy Benyei11169dd2012-12-18 14:30:41 +00001532 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001533 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001534 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1535 if (!Key.Imported)
1536 return FileMgr.getFile(Key.Filename);
1537
1538 std::string Resolved = Key.Filename;
1539 Reader.ResolveImportedPath(M, Resolved);
1540 return FileMgr.getFile(Resolved);
1541 };
1542
1543 const FileEntry *FEA = GetFile(a);
1544 const FileEntry *FEB = GetFile(b);
1545 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001546}
1547
1548std::pair<unsigned, unsigned>
1549HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001550 using namespace llvm::support;
1551 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001552 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001553 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001554}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001555
1556HeaderFileInfoTrait::internal_key_type
1557HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001558 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001559 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001560 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1561 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001562 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001563 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001564 return ikey;
1565}
1566
Guy Benyei11169dd2012-12-18 14:30:41 +00001567HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001568HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001569 unsigned DataLen) {
1570 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001571 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001572 HeaderFileInfo HFI;
1573 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001574 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1575 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001576 HFI.isImport = (Flags >> 5) & 0x01;
1577 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1578 HFI.DirInfo = (Flags >> 2) & 0x03;
1579 HFI.Resolved = (Flags >> 1) & 0x01;
1580 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001581 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1582 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1583 M, endian::readNext<uint32_t, little, unaligned>(d));
1584 if (unsigned FrameworkOffset =
1585 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001586 // The framework offset is 1 greater than the actual offset,
1587 // since 0 is used as an indicator for "no framework name".
1588 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1589 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1590 }
1591
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001592 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001593 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001594 if (LocalSMID) {
1595 // This header is part of a module. Associate it with the module to enable
1596 // implicit module import.
1597 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1598 Module *Mod = Reader.getSubmodule(GlobalSMID);
1599 HFI.isModuleHeader = true;
1600 FileManager &FileMgr = Reader.getFileManager();
1601 ModuleMap &ModMap =
1602 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001603 // FIXME: This information should be propagated through the
1604 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001605 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001606 std::string Filename = key.Filename;
1607 if (key.Imported)
1608 Reader.ResolveImportedPath(M, Filename);
1609 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001610 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001611 }
1612 }
1613
Guy Benyei11169dd2012-12-18 14:30:41 +00001614 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1615 (void)End;
1616
1617 // This HeaderFileInfo was externally loaded.
1618 HFI.External = true;
1619 return HFI;
1620}
1621
Richard Smith49f906a2014-03-01 00:08:04 +00001622void
1623ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1624 GlobalMacroID GMacID,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001625 ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001626 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Craig Toppera13603a2014-05-22 05:54:18 +00001627 SubmoduleID *OverrideData = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001628 if (!Overrides.empty()) {
1629 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1630 OverrideData[0] = Overrides.size();
1631 for (unsigned I = 0; I != Overrides.size(); ++I)
1632 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1633 }
1634 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001635}
1636
1637void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1638 ModuleFile *M,
1639 uint64_t MacroDirectivesOffset) {
1640 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1641 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001642}
1643
1644void ASTReader::ReadDefinedMacros() {
1645 // Note that we are loading defined macros.
1646 Deserializing Macros(this);
1647
1648 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1649 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001650 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001651
1652 // If there was no preprocessor block, skip this file.
1653 if (!MacroCursor.getBitStreamReader())
1654 continue;
1655
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001656 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001657 Cursor.JumpToBit((*I)->MacroStartOffset);
1658
1659 RecordData Record;
1660 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001661 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1662
1663 switch (E.Kind) {
1664 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1665 case llvm::BitstreamEntry::Error:
1666 Error("malformed block record in AST file");
1667 return;
1668 case llvm::BitstreamEntry::EndBlock:
1669 goto NextCursor;
1670
1671 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001672 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001673 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001674 default: // Default behavior: ignore.
1675 break;
1676
1677 case PP_MACRO_OBJECT_LIKE:
1678 case PP_MACRO_FUNCTION_LIKE:
1679 getLocalIdentifier(**I, Record[0]);
1680 break;
1681
1682 case PP_TOKEN:
1683 // Ignore tokens.
1684 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001685 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001686 break;
1687 }
1688 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001689 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001690 }
1691}
1692
1693namespace {
1694 /// \brief Visitor class used to look up identifirs in an AST file.
1695 class IdentifierLookupVisitor {
1696 StringRef Name;
1697 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001698 unsigned &NumIdentifierLookups;
1699 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001700 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001701
Guy Benyei11169dd2012-12-18 14:30:41 +00001702 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001703 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1704 unsigned &NumIdentifierLookups,
1705 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001706 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001707 NumIdentifierLookups(NumIdentifierLookups),
1708 NumIdentifierLookupHits(NumIdentifierLookupHits),
1709 Found()
1710 {
1711 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001712
1713 static bool visit(ModuleFile &M, void *UserData) {
1714 IdentifierLookupVisitor *This
1715 = static_cast<IdentifierLookupVisitor *>(UserData);
1716
1717 // If we've already searched this module file, skip it now.
1718 if (M.Generation <= This->PriorGeneration)
1719 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001720
Guy Benyei11169dd2012-12-18 14:30:41 +00001721 ASTIdentifierLookupTable *IdTable
1722 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1723 if (!IdTable)
1724 return false;
1725
1726 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1727 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001728 ++This->NumIdentifierLookups;
1729 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001730 if (Pos == IdTable->end())
1731 return false;
1732
1733 // Dereferencing the iterator has the effect of building the
1734 // IdentifierInfo node and populating it with the various
1735 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001736 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001737 This->Found = *Pos;
1738 return true;
1739 }
1740
1741 // \brief Retrieve the identifier info found within the module
1742 // files.
1743 IdentifierInfo *getIdentifierInfo() const { return Found; }
1744 };
1745}
1746
1747void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1748 // Note that we are loading an identifier.
1749 Deserializing AnIdentifier(this);
1750
1751 unsigned PriorGeneration = 0;
1752 if (getContext().getLangOpts().Modules)
1753 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001754
1755 // If there is a global index, look there first to determine which modules
1756 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001757 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001758 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001759 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001760 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1761 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001762 }
1763 }
1764
Douglas Gregor7211ac12013-01-25 23:32:03 +00001765 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001766 NumIdentifierLookups,
1767 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001768 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001769 markIdentifierUpToDate(&II);
1770}
1771
1772void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1773 if (!II)
1774 return;
1775
1776 II->setOutOfDate(false);
1777
1778 // Update the generation for this identifier.
1779 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001780 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001781}
1782
Richard Smith49f906a2014-03-01 00:08:04 +00001783struct ASTReader::ModuleMacroInfo {
1784 SubmoduleID SubModID;
1785 MacroInfo *MI;
1786 SubmoduleID *Overrides;
1787 // FIXME: Remove this.
1788 ModuleFile *F;
1789
1790 bool isDefine() const { return MI; }
1791
1792 SubmoduleID getSubmoduleID() const { return SubModID; }
1793
Craig Topper00bbdcf2014-06-28 23:22:23 +00001794 ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
Richard Smith49f906a2014-03-01 00:08:04 +00001795 if (!Overrides)
Craig Topper00bbdcf2014-06-28 23:22:23 +00001796 return None;
Richard Smith49f906a2014-03-01 00:08:04 +00001797 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1798 }
1799
Richard Smithdaa69e02014-07-25 04:40:03 +00001800 MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
Richard Smith49f906a2014-03-01 00:08:04 +00001801 if (!MI)
Richard Smithdaa69e02014-07-25 04:40:03 +00001802 return PP.AllocateUndefMacroDirective(ImportLoc, SubModID,
1803 getOverriddenSubmodules());
1804 return PP.AllocateDefMacroDirective(MI, ImportLoc, SubModID,
1805 getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001806 }
1807};
1808
1809ASTReader::ModuleMacroInfo *
Richard Smithdf8a8312015-03-13 04:05:01 +00001810ASTReader::getModuleMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo) {
Richard Smith49f906a2014-03-01 00:08:04 +00001811 ModuleMacroInfo Info;
1812
1813 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1814 if (ID & 1) {
1815 // Macro undefinition.
1816 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
Craig Toppera13603a2014-05-22 05:54:18 +00001817 Info.MI = nullptr;
Richard Smithdf8a8312015-03-13 04:05:01 +00001818
1819 // If we've already loaded the #undef of this macro from this module,
1820 // don't do so again.
1821 if (!LoadedUndefs.insert(std::make_pair(II, Info.SubModID)).second)
1822 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001823 } else {
1824 // Macro definition.
1825 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1826 assert(GMacID);
1827
1828 // If this macro has already been loaded, don't do so again.
1829 // FIXME: This is highly dubious. Multiple macro definitions can have the
1830 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1831 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
Craig Toppera13603a2014-05-22 05:54:18 +00001832 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001833
1834 Info.MI = getMacro(GMacID);
1835 Info.SubModID = Info.MI->getOwningModuleID();
1836 }
1837 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1838 Info.F = PMInfo.M;
1839
1840 return new (Context) ModuleMacroInfo(Info);
1841}
1842
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001843void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1844 const PendingMacroInfo &PMInfo) {
1845 assert(II);
1846
Richard Smithe842a472014-10-22 02:05:46 +00001847 if (PMInfo.M->Kind != MK_ImplicitModule &&
1848 PMInfo.M->Kind != MK_ExplicitModule) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001849 installPCHMacroDirectives(II, *PMInfo.M,
1850 PMInfo.PCHMacroData.MacroDirectivesOffset);
1851 return;
1852 }
Richard Smith49f906a2014-03-01 00:08:04 +00001853
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001854 // Module Macro.
1855
Richard Smithdf8a8312015-03-13 04:05:01 +00001856 ModuleMacroInfo *MMI = getModuleMacro(II, PMInfo);
Richard Smith49f906a2014-03-01 00:08:04 +00001857 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001858 return;
1859
Richard Smith49f906a2014-03-01 00:08:04 +00001860 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1861 if (Owner && Owner->NameVisibility == Module::Hidden) {
1862 // Macros in the owning module are hidden. Just remember this macro to
1863 // install if we make this module visible.
1864 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1865 } else {
Richard Smithdaa69e02014-07-25 04:40:03 +00001866 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001867 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001868}
1869
1870void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1871 ModuleFile &M, uint64_t Offset) {
Richard Smithe842a472014-10-22 02:05:46 +00001872 assert(M.Kind != MK_ImplicitModule && M.Kind != MK_ExplicitModule);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001873
1874 BitstreamCursor &Cursor = M.MacroCursor;
1875 SavedStreamPosition SavedPosition(Cursor);
1876 Cursor.JumpToBit(Offset);
1877
1878 llvm::BitstreamEntry Entry =
1879 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1880 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1881 Error("malformed block record in AST file");
1882 return;
1883 }
1884
1885 RecordData Record;
1886 PreprocessorRecordTypes RecType =
1887 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1888 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1889 Error("malformed block record in AST file");
1890 return;
1891 }
1892
1893 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001894 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001895 unsigned Idx = 0, N = Record.size();
1896 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001897 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001898 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001899 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1900 switch (K) {
1901 case MacroDirective::MD_Define: {
1902 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1903 MacroInfo *MI = getMacro(GMacID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001904 SubmoduleID ImportedFrom = Record[Idx++];
1905 bool IsAmbiguous = Record[Idx++];
1906 llvm::SmallVector<unsigned, 4> Overrides;
1907 if (ImportedFrom) {
1908 Overrides.insert(Overrides.end(),
1909 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1910 Idx += Overrides.size() + 1;
1911 }
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001912 DefMacroDirective *DefMD =
Richard Smithdaa69e02014-07-25 04:40:03 +00001913 PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
1914 DefMD->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001915 MD = DefMD;
1916 break;
1917 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001918 case MacroDirective::MD_Undefine: {
1919 SubmoduleID ImportedFrom = Record[Idx++];
1920 llvm::SmallVector<unsigned, 4> Overrides;
1921 if (ImportedFrom) {
1922 Overrides.insert(Overrides.end(),
1923 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1924 Idx += Overrides.size() + 1;
1925 }
1926 MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001927 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001928 }
1929 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001930 bool isPublic = Record[Idx++];
1931 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1932 break;
1933 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001934
1935 if (!Latest)
1936 Latest = MD;
1937 if (Earliest)
1938 Earliest->setPrevious(MD);
1939 Earliest = MD;
1940 }
1941
1942 PP.setLoadedMacroDirective(II, Latest);
1943}
1944
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001945/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001946/// modules.
1947static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001948 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001949 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001950 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001951 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1952 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001953 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001954 return false;
Chandler Carruthc2132d82015-03-13 08:29:54 +00001955 SourceManager &SrcMgr = Reader.getSourceManager();
1956 bool PrevInSystem = (PrevOwner && PrevOwner->IsSystem) ||
1957 SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1958 bool NewInSystem = (NewOwner && NewOwner->IsSystem) ||
1959 SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
Douglas Gregor5e461192013-06-07 22:56:11 +00001960 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001961}
1962
Richard Smith49f906a2014-03-01 00:08:04 +00001963void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001964 SourceLocation ImportLoc,
Richard Smith49f906a2014-03-01 00:08:04 +00001965 AmbiguousMacros &Ambig,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001966 ArrayRef<SubmoduleID> Overrides) {
Richard Smith49f906a2014-03-01 00:08:04 +00001967 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1968 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001969
Richard Smith49f906a2014-03-01 00:08:04 +00001970 // If this macro is not yet visible, remove it from the hidden names list.
Richard Smithbb853c72014-08-13 01:23:33 +00001971 // It won't be there if we're in the middle of making the owner visible.
Richard Smith49f906a2014-03-01 00:08:04 +00001972 Module *Owner = getSubmodule(OwnerID);
Richard Smithbb853c72014-08-13 01:23:33 +00001973 auto HiddenIt = HiddenNamesMap.find(Owner);
1974 if (HiddenIt != HiddenNamesMap.end()) {
1975 HiddenNames &Hidden = HiddenIt->second;
1976 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1977 if (HI != Hidden.HiddenMacros.end()) {
1978 // Register the macro now so we don't lose it when we re-export.
1979 PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
Richard Smithdaa69e02014-07-25 04:40:03 +00001980
Richard Smithbb853c72014-08-13 01:23:33 +00001981 auto SubOverrides = HI->second->getOverriddenSubmodules();
1982 Hidden.HiddenMacros.erase(HI);
1983 removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
1984 }
Richard Smith49f906a2014-03-01 00:08:04 +00001985 }
1986
1987 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001988 Ambig.erase(
1989 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1990 return MD->getInfo()->getOwningModuleID() == OwnerID;
1991 }),
1992 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001993 }
1994}
1995
1996ASTReader::AmbiguousMacros *
1997ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001998 SourceLocation ImportLoc,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001999 ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002000 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00002001 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00002002 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00002003
Craig Toppera13603a2014-05-22 05:54:18 +00002004 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
2005 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00002006 if (PrevDef && PrevDef->isAmbiguous()) {
2007 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
2008 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
2009 Ambig.push_back(PrevDef);
2010
Richard Smithdaa69e02014-07-25 04:40:03 +00002011 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00002012
2013 if (!Ambig.empty())
2014 return &Ambig;
2015
2016 AmbiguousMacroDefs.erase(II);
2017 } else {
2018 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00002019 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00002020 if (PrevDef)
2021 Ambig.push_back(PrevDef);
2022
Richard Smithdaa69e02014-07-25 04:40:03 +00002023 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00002024
2025 if (!Ambig.empty()) {
2026 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00002027 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00002028 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002029 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002030 }
Richard Smith49f906a2014-03-01 00:08:04 +00002031
2032 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00002033 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00002034}
2035
2036void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
Richard Smithdaa69e02014-07-25 04:40:03 +00002037 Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00002038 assert(II && Owner);
2039
2040 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smithdaa69e02014-07-25 04:40:03 +00002041 if (ImportLoc.isInvalid()) {
Richard Smith49f906a2014-03-01 00:08:04 +00002042 // FIXME: If we made macros from this module visible but didn't provide a
2043 // source location for the import, we don't have a location for the macro.
2044 // Use the location at which the containing module file was first imported
2045 // for now.
2046 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00002047 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00002048 }
2049
Benjamin Kramer834652a2014-05-03 18:44:26 +00002050 AmbiguousMacros *Prev =
Richard Smithdaa69e02014-07-25 04:40:03 +00002051 removeOverriddenMacros(II, ImportLoc, MMI->getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00002052
Richard Smith49f906a2014-03-01 00:08:04 +00002053 // Create a synthetic macro definition corresponding to the import (or null
2054 // if this was an undefinition of the macro).
Richard Smithdaa69e02014-07-25 04:40:03 +00002055 MacroDirective *Imported = MMI->import(PP, ImportLoc);
2056 DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002057
2058 // If there's no ambiguity, just install the macro.
2059 if (!Prev) {
Richard Smithdaa69e02014-07-25 04:40:03 +00002060 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002061 return;
2062 }
2063 assert(!Prev->empty());
2064
2065 if (!MD) {
2066 // We imported a #undef that didn't remove all prior definitions. The most
2067 // recent prior definition remains, and we install it in the place of the
Richard Smithdaa69e02014-07-25 04:40:03 +00002068 // imported directive, as if by a local #pragma pop_macro.
Richard Smith49f906a2014-03-01 00:08:04 +00002069 MacroInfo *NewMI = Prev->back()->getInfo();
2070 Prev->pop_back();
Richard Smithdaa69e02014-07-25 04:40:03 +00002071 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
2072
2073 // Install our #undef first so that we don't lose track of it. We'll replace
2074 // this with whichever macro definition ends up winning.
2075 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002076 }
2077
2078 // We're introducing a macro definition that creates or adds to an ambiguity.
2079 // We can resolve that ambiguity if this macro is token-for-token identical to
2080 // all of the existing definitions.
2081 MacroInfo *NewMI = MD->getInfo();
2082 assert(NewMI && "macro definition with no MacroInfo?");
2083 while (!Prev->empty()) {
2084 MacroInfo *PrevMI = Prev->back()->getInfo();
2085 assert(PrevMI && "macro definition with no MacroInfo?");
2086
2087 // Before marking the macros as ambiguous, check if this is a case where
2088 // both macros are in system headers. If so, we trust that the system
2089 // did not get it wrong. This also handles cases where Clang's own
2090 // headers have a different spelling of certain system macros:
2091 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
2092 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2093 //
2094 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2095 // overrides the system limits.h's macros, so there's no conflict here.
2096 if (NewMI != PrevMI &&
2097 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2098 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2099 break;
2100
2101 // The previous definition is the same as this one (or both are defined in
2102 // system modules so we can assume they're equivalent); we don't need to
2103 // track it any more.
2104 Prev->pop_back();
2105 }
2106
2107 if (!Prev->empty())
2108 MD->setAmbiguous(true);
2109
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002110 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002111}
2112
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002113ASTReader::InputFileInfo
2114ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002115 // Go find this input file.
2116 BitstreamCursor &Cursor = F.InputFilesCursor;
2117 SavedStreamPosition SavedPosition(Cursor);
2118 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2119
2120 unsigned Code = Cursor.ReadCode();
2121 RecordData Record;
2122 StringRef Blob;
2123
2124 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2125 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2126 "invalid record type for input file");
2127 (void)Result;
2128
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002129 std::string Filename;
2130 off_t StoredSize;
2131 time_t StoredTime;
2132 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002133
Ben Langmuir198c1682014-03-07 07:27:49 +00002134 assert(Record[0] == ID && "Bogus stored ID or offset");
2135 StoredSize = static_cast<off_t>(Record[1]);
2136 StoredTime = static_cast<time_t>(Record[2]);
2137 Overridden = static_cast<bool>(Record[3]);
2138 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002139 ResolveImportedPath(F, Filename);
2140
Hans Wennborg73945142014-03-14 17:45:06 +00002141 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2142 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002143}
2144
2145std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002146 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002147}
2148
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002149InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002150 // If this ID is bogus, just return an empty input file.
2151 if (ID == 0 || ID > F.InputFilesLoaded.size())
2152 return InputFile();
2153
2154 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002155 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002156 return F.InputFilesLoaded[ID-1];
2157
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002158 if (F.InputFilesLoaded[ID-1].isNotFound())
2159 return InputFile();
2160
Guy Benyei11169dd2012-12-18 14:30:41 +00002161 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002162 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002163 SavedStreamPosition SavedPosition(Cursor);
2164 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2165
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002166 InputFileInfo FI = readInputFileInfo(F, ID);
2167 off_t StoredSize = FI.StoredSize;
2168 time_t StoredTime = FI.StoredTime;
2169 bool Overridden = FI.Overridden;
2170 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002171
Ben Langmuir198c1682014-03-07 07:27:49 +00002172 const FileEntry *File
2173 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2174 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2175
2176 // If we didn't find the file, resolve it relative to the
2177 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002178 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002179 F.OriginalDir != CurrentDir) {
2180 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2181 F.OriginalDir,
2182 CurrentDir);
2183 if (!Resolved.empty())
2184 File = FileMgr.getFile(Resolved);
2185 }
2186
2187 // For an overridden file, create a virtual file with the stored
2188 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002189 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002190 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2191 }
2192
Craig Toppera13603a2014-05-22 05:54:18 +00002193 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002194 if (Complain) {
2195 std::string ErrorStr = "could not find file '";
2196 ErrorStr += Filename;
2197 ErrorStr += "' referenced by AST file";
2198 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002199 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002200 // Record that we didn't find the file.
2201 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2202 return InputFile();
2203 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002204
Ben Langmuir198c1682014-03-07 07:27:49 +00002205 // Check if there was a request to override the contents of the file
2206 // that was part of the precompiled header. Overridding such a file
2207 // can lead to problems when lexing using the source locations from the
2208 // PCH.
2209 SourceManager &SM = getSourceManager();
2210 if (!Overridden && SM.isFileOverridden(File)) {
2211 if (Complain)
2212 Error(diag::err_fe_pch_file_overridden, Filename);
2213 // After emitting the diagnostic, recover by disabling the override so
2214 // that the original file will be used.
2215 SM.disableFileContentsOverride(File);
2216 // The FileEntry is a virtual file entry with the size of the contents
2217 // that would override the original contents. Set it to the original's
2218 // size/time.
2219 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2220 StoredSize, StoredTime);
2221 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002222
Ben Langmuir198c1682014-03-07 07:27:49 +00002223 bool IsOutOfDate = false;
2224
2225 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002226 if (!Overridden && //
2227 (StoredSize != File->getSize() ||
2228#if defined(LLVM_ON_WIN32)
2229 false
2230#else
Ben Langmuir198c1682014-03-07 07:27:49 +00002231 // In our regression testing, the Windows file system seems to
2232 // have inconsistent modification times that sometimes
2233 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00002234 //
2235 // This also happens in networked file systems, so disable this
2236 // check if validation is disabled or if we have an explicitly
2237 // built PCM file.
2238 //
2239 // FIXME: Should we also do this for PCH files? They could also
2240 // reasonably get shared across a network during a distributed build.
2241 (StoredTime != File->getModificationTime() && !DisableValidation &&
2242 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00002243#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002244 )) {
2245 if (Complain) {
2246 // Build a list of the PCH imports that got us here (in reverse).
2247 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2248 while (ImportStack.back()->ImportedBy.size() > 0)
2249 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002250
Ben Langmuir198c1682014-03-07 07:27:49 +00002251 // The top-level PCH is stale.
2252 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2253 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002254
Ben Langmuir198c1682014-03-07 07:27:49 +00002255 // Print the import stack.
2256 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2257 Diag(diag::note_pch_required_by)
2258 << Filename << ImportStack[0]->FileName;
2259 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002260 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002261 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002262 }
2263
Ben Langmuir198c1682014-03-07 07:27:49 +00002264 if (!Diags.isDiagnosticInFlight())
2265 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002266 }
2267
Ben Langmuir198c1682014-03-07 07:27:49 +00002268 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002269 }
2270
Ben Langmuir198c1682014-03-07 07:27:49 +00002271 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2272
2273 // Note that we've loaded this input file.
2274 F.InputFilesLoaded[ID-1] = IF;
2275 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002276}
2277
Richard Smith7ed1bc92014-12-05 22:42:13 +00002278/// \brief If we are loading a relocatable PCH or module file, and the filename
2279/// is not an absolute path, add the system or module root to the beginning of
2280/// the file name.
2281void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2282 // Resolve relative to the base directory, if we have one.
2283 if (!M.BaseDirectory.empty())
2284 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002285}
2286
Richard Smith7ed1bc92014-12-05 22:42:13 +00002287void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2289 return;
2290
Richard Smith7ed1bc92014-12-05 22:42:13 +00002291 SmallString<128> Buffer;
2292 llvm::sys::path::append(Buffer, Prefix, Filename);
2293 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002294}
2295
2296ASTReader::ASTReadResult
2297ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002298 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002299 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002300 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002301 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002302
2303 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2304 Error("malformed block record in AST file");
2305 return Failure;
2306 }
2307
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002308 // Should we allow the configuration of the module file to differ from the
2309 // configuration of the current translation unit in a compatible way?
2310 //
2311 // FIXME: Allow this for files explicitly specified with -include-pch too.
2312 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2313
Guy Benyei11169dd2012-12-18 14:30:41 +00002314 // Read all of the records and blocks in the control block.
2315 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002316 unsigned NumInputs = 0;
2317 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002318 while (1) {
2319 llvm::BitstreamEntry Entry = Stream.advance();
2320
2321 switch (Entry.Kind) {
2322 case llvm::BitstreamEntry::Error:
2323 Error("malformed block record in AST file");
2324 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002325 case llvm::BitstreamEntry::EndBlock: {
2326 // Validate input files.
2327 const HeaderSearchOptions &HSOpts =
2328 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002329
Richard Smitha1825302014-10-23 22:18:29 +00002330 // All user input files reside at the index range [0, NumUserInputs), and
2331 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002332 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002333 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002334
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002335 // If we are reading a module, we will create a verification timestamp,
2336 // so we verify all input files. Otherwise, verify only user input
2337 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002338
2339 unsigned N = NumUserInputs;
2340 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002341 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002342 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002343 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002344 N = NumInputs;
2345
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002346 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002347 InputFile IF = getInputFile(F, I+1, Complain);
2348 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002349 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002350 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002351 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002352
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002353 if (Listener)
2354 Listener->visitModuleFile(F.FileName);
2355
Ben Langmuircb69b572014-03-07 06:40:32 +00002356 if (Listener && Listener->needsInputFileVisitation()) {
2357 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2358 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002359 for (unsigned I = 0; I < N; ++I) {
2360 bool IsSystem = I >= NumUserInputs;
2361 InputFileInfo FI = readInputFileInfo(F, I+1);
2362 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2363 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002364 }
2365
Guy Benyei11169dd2012-12-18 14:30:41 +00002366 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002367 }
2368
Chris Lattnere7b154b2013-01-19 21:39:22 +00002369 case llvm::BitstreamEntry::SubBlock:
2370 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 case INPUT_FILES_BLOCK_ID:
2372 F.InputFilesCursor = Stream;
2373 if (Stream.SkipBlock() || // Skip with the main cursor
2374 // Read the abbreviations
2375 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2376 Error("malformed block record in AST file");
2377 return Failure;
2378 }
2379 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002380
Guy Benyei11169dd2012-12-18 14:30:41 +00002381 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002382 if (Stream.SkipBlock()) {
2383 Error("malformed block record in AST file");
2384 return Failure;
2385 }
2386 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002387 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002388
2389 case llvm::BitstreamEntry::Record:
2390 // The interesting case.
2391 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 }
2393
2394 // Read and process a record.
2395 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002396 StringRef Blob;
2397 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002398 case METADATA: {
2399 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2400 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002401 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2402 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 return VersionMismatch;
2404 }
2405
2406 bool hasErrors = Record[5];
2407 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2408 Diag(diag::err_pch_with_compiler_errors);
2409 return HadErrors;
2410 }
2411
2412 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002413 // Relative paths in a relocatable PCH are relative to our sysroot.
2414 if (F.RelocatablePCH)
2415 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002416
2417 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002418 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002419 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2420 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002421 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 return VersionMismatch;
2423 }
2424 break;
2425 }
2426
Ben Langmuir487ea142014-10-23 18:05:36 +00002427 case SIGNATURE:
2428 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2429 F.Signature = Record[0];
2430 break;
2431
Guy Benyei11169dd2012-12-18 14:30:41 +00002432 case IMPORTS: {
2433 // Load each of the imported PCH files.
2434 unsigned Idx = 0, N = Record.size();
2435 while (Idx < N) {
2436 // Read information about the AST file.
2437 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2438 // The import location will be the local one for now; we will adjust
2439 // all import locations of module imports after the global source
2440 // location info are setup.
2441 SourceLocation ImportLoc =
2442 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002443 off_t StoredSize = (off_t)Record[Idx++];
2444 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002445 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002446 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002447
2448 // Load the AST file.
2449 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002450 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002451 ClientLoadCapabilities)) {
2452 case Failure: return Failure;
2453 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002454 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 case OutOfDate: return OutOfDate;
2456 case VersionMismatch: return VersionMismatch;
2457 case ConfigurationMismatch: return ConfigurationMismatch;
2458 case HadErrors: return HadErrors;
2459 case Success: break;
2460 }
2461 }
2462 break;
2463 }
2464
Richard Smith7f330cd2015-03-18 01:42:29 +00002465 case KNOWN_MODULE_FILES:
2466 break;
2467
Guy Benyei11169dd2012-12-18 14:30:41 +00002468 case LANGUAGE_OPTIONS: {
2469 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002470 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002472 ParseLanguageOptions(Record, Complain, *Listener,
2473 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002474 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 return ConfigurationMismatch;
2476 break;
2477 }
2478
2479 case TARGET_OPTIONS: {
2480 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2481 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002482 ParseTargetOptions(Record, Complain, *Listener,
2483 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002484 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002485 return ConfigurationMismatch;
2486 break;
2487 }
2488
2489 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002490 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002492 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002494 !DisableValidation)
2495 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 break;
2497 }
2498
2499 case FILE_SYSTEM_OPTIONS: {
2500 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2501 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002502 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002504 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002505 return ConfigurationMismatch;
2506 break;
2507 }
2508
2509 case HEADER_SEARCH_OPTIONS: {
2510 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2511 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002512 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002513 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002514 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002515 return ConfigurationMismatch;
2516 break;
2517 }
2518
2519 case PREPROCESSOR_OPTIONS: {
2520 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2521 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002522 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 ParsePreprocessorOptions(Record, Complain, *Listener,
2524 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002525 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 return ConfigurationMismatch;
2527 break;
2528 }
2529
2530 case ORIGINAL_FILE:
2531 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002532 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002533 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002534 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 break;
2536
2537 case ORIGINAL_FILE_ID:
2538 F.OriginalSourceFileID = FileID::get(Record[0]);
2539 break;
2540
2541 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002542 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002543 break;
2544
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002545 case MODULE_NAME:
2546 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002547 if (Listener)
2548 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002549 break;
2550
Richard Smith223d3f22014-12-06 03:21:08 +00002551 case MODULE_DIRECTORY: {
2552 assert(!F.ModuleName.empty() &&
2553 "MODULE_DIRECTORY found before MODULE_NAME");
2554 // If we've already loaded a module map file covering this module, we may
2555 // have a better path for it (relative to the current build).
2556 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2557 if (M && M->Directory) {
2558 // If we're implicitly loading a module, the base directory can't
2559 // change between the build and use.
2560 if (F.Kind != MK_ExplicitModule) {
2561 const DirectoryEntry *BuildDir =
2562 PP.getFileManager().getDirectory(Blob);
2563 if (!BuildDir || BuildDir != M->Directory) {
2564 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2565 Diag(diag::err_imported_module_relocated)
2566 << F.ModuleName << Blob << M->Directory->getName();
2567 return OutOfDate;
2568 }
2569 }
2570 F.BaseDirectory = M->Directory->getName();
2571 } else {
2572 F.BaseDirectory = Blob;
2573 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002574 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002575 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002576
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002577 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002578 if (ASTReadResult Result =
2579 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2580 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002581 break;
2582
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002584 NumInputs = Record[0];
2585 NumUserInputs = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00002586 F.InputFileOffsets = (const uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002587 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 break;
2589 }
2590 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002591}
2592
Ben Langmuir2c9af442014-04-10 17:57:43 +00002593ASTReader::ASTReadResult
2594ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002595 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002596
2597 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2598 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002599 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 }
2601
2602 // Read all of the records and blocks for the AST file.
2603 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002604 while (1) {
2605 llvm::BitstreamEntry Entry = Stream.advance();
2606
2607 switch (Entry.Kind) {
2608 case llvm::BitstreamEntry::Error:
2609 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002610 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002611 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002612 // Outside of C++, we do not store a lookup map for the translation unit.
2613 // Instead, mark it as needing a lookup map to be built if this module
2614 // contains any declarations lexically within it (which it always does!).
2615 // This usually has no cost, since we very rarely need the lookup map for
2616 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002617 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002618 if (DC->hasExternalLexicalStorage() &&
2619 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002621
Ben Langmuir2c9af442014-04-10 17:57:43 +00002622 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002623 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002624 case llvm::BitstreamEntry::SubBlock:
2625 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002626 case DECLTYPES_BLOCK_ID:
2627 // We lazily load the decls block, but we want to set up the
2628 // DeclsCursor cursor to point into it. Clone our current bitcode
2629 // cursor to it, enter the block and read the abbrevs in that block.
2630 // With the main cursor, we just skip over it.
2631 F.DeclsCursor = Stream;
2632 if (Stream.SkipBlock() || // Skip with the main cursor.
2633 // Read the abbrevs.
2634 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2635 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002636 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 }
2638 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002639
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 case PREPROCESSOR_BLOCK_ID:
2641 F.MacroCursor = Stream;
2642 if (!PP.getExternalSource())
2643 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002644
Guy Benyei11169dd2012-12-18 14:30:41 +00002645 if (Stream.SkipBlock() ||
2646 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2647 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002648 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002649 }
2650 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2651 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002652
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 case PREPROCESSOR_DETAIL_BLOCK_ID:
2654 F.PreprocessorDetailCursor = Stream;
2655 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002656 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002658 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002659 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002660 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002662 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2663
Guy Benyei11169dd2012-12-18 14:30:41 +00002664 if (!PP.getPreprocessingRecord())
2665 PP.createPreprocessingRecord();
2666 if (!PP.getPreprocessingRecord()->getExternalSource())
2667 PP.getPreprocessingRecord()->SetExternalSource(*this);
2668 break;
2669
2670 case SOURCE_MANAGER_BLOCK_ID:
2671 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002672 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002673 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002674
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002676 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2677 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002678 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002679
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002681 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002682 if (Stream.SkipBlock() ||
2683 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2684 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002685 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 }
2687 CommentsCursors.push_back(std::make_pair(C, &F));
2688 break;
2689 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002690
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002692 if (Stream.SkipBlock()) {
2693 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002694 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002695 }
2696 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 }
2698 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002699
2700 case llvm::BitstreamEntry::Record:
2701 // The interesting case.
2702 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002703 }
2704
2705 // Read and process a record.
2706 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002707 StringRef Blob;
2708 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002709 default: // Default behavior: ignore.
2710 break;
2711
2712 case TYPE_OFFSET: {
2713 if (F.LocalNumTypes != 0) {
2714 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002715 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002717 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002718 F.LocalNumTypes = Record[0];
2719 unsigned LocalBaseTypeIndex = Record[1];
2720 F.BaseTypeIndex = getTotalNumTypes();
2721
2722 if (F.LocalNumTypes > 0) {
2723 // Introduce the global -> local mapping for types within this module.
2724 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2725
2726 // Introduce the local -> global mapping for types within this module.
2727 F.TypeRemap.insertOrReplace(
2728 std::make_pair(LocalBaseTypeIndex,
2729 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002730
2731 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 }
2733 break;
2734 }
2735
2736 case DECL_OFFSET: {
2737 if (F.LocalNumDecls != 0) {
2738 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002739 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002741 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 F.LocalNumDecls = Record[0];
2743 unsigned LocalBaseDeclID = Record[1];
2744 F.BaseDeclID = getTotalNumDecls();
2745
2746 if (F.LocalNumDecls > 0) {
2747 // Introduce the global -> local mapping for declarations within this
2748 // module.
2749 GlobalDeclMap.insert(
2750 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2751
2752 // Introduce the local -> global mapping for declarations within this
2753 // module.
2754 F.DeclRemap.insertOrReplace(
2755 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2756
2757 // Introduce the global -> local mapping for declarations within this
2758 // module.
2759 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002760
Ben Langmuir52ca6782014-10-20 16:27:32 +00002761 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2762 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002763 break;
2764 }
2765
2766 case TU_UPDATE_LEXICAL: {
2767 DeclContext *TU = Context.getTranslationUnitDecl();
2768 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002769 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002770 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002771 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002772 TU->setHasExternalLexicalStorage(true);
2773 break;
2774 }
2775
2776 case UPDATE_VISIBLE: {
2777 unsigned Idx = 0;
2778 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2779 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002780 ASTDeclContextNameLookupTable::Create(
2781 (const unsigned char *)Blob.data() + Record[Idx++],
2782 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2783 (const unsigned char *)Blob.data(),
2784 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002785 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002786 auto *DC = cast<DeclContext>(D);
2787 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002788 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2789 delete LookupTable;
2790 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002791 } else
2792 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2793 break;
2794 }
2795
2796 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002797 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002798 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002799 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2800 (const unsigned char *)F.IdentifierTableData + Record[0],
2801 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2802 (const unsigned char *)F.IdentifierTableData,
2803 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002804
2805 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2806 }
2807 break;
2808
2809 case IDENTIFIER_OFFSET: {
2810 if (F.LocalNumIdentifiers != 0) {
2811 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002812 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002813 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002814 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002815 F.LocalNumIdentifiers = Record[0];
2816 unsigned LocalBaseIdentifierID = Record[1];
2817 F.BaseIdentifierID = getTotalNumIdentifiers();
2818
2819 if (F.LocalNumIdentifiers > 0) {
2820 // Introduce the global -> local mapping for identifiers within this
2821 // module.
2822 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2823 &F));
2824
2825 // Introduce the local -> global mapping for identifiers within this
2826 // module.
2827 F.IdentifierRemap.insertOrReplace(
2828 std::make_pair(LocalBaseIdentifierID,
2829 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002830
Ben Langmuir52ca6782014-10-20 16:27:32 +00002831 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2832 + F.LocalNumIdentifiers);
2833 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002834 break;
2835 }
2836
Ben Langmuir332aafe2014-01-31 01:06:56 +00002837 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002838 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2839 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002840 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002841 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002842 break;
2843
2844 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002845 if (SpecialTypes.empty()) {
2846 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2847 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2848 break;
2849 }
2850
2851 if (SpecialTypes.size() != Record.size()) {
2852 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002853 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002854 }
2855
2856 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2857 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2858 if (!SpecialTypes[I])
2859 SpecialTypes[I] = ID;
2860 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2861 // merge step?
2862 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002863 break;
2864
2865 case STATISTICS:
2866 TotalNumStatements += Record[0];
2867 TotalNumMacros += Record[1];
2868 TotalLexicalDeclContexts += Record[2];
2869 TotalVisibleDeclContexts += Record[3];
2870 break;
2871
2872 case UNUSED_FILESCOPED_DECLS:
2873 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2874 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2875 break;
2876
2877 case DELEGATING_CTORS:
2878 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2879 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2880 break;
2881
2882 case WEAK_UNDECLARED_IDENTIFIERS:
2883 if (Record.size() % 4 != 0) {
2884 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002885 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002886 }
2887
2888 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2889 // files. This isn't the way to do it :)
2890 WeakUndeclaredIdentifiers.clear();
2891
2892 // Translate the weak, undeclared identifiers into global IDs.
2893 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2894 WeakUndeclaredIdentifiers.push_back(
2895 getGlobalIdentifierID(F, Record[I++]));
2896 WeakUndeclaredIdentifiers.push_back(
2897 getGlobalIdentifierID(F, Record[I++]));
2898 WeakUndeclaredIdentifiers.push_back(
2899 ReadSourceLocation(F, Record, I).getRawEncoding());
2900 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2901 }
2902 break;
2903
Guy Benyei11169dd2012-12-18 14:30:41 +00002904 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002905 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002906 F.LocalNumSelectors = Record[0];
2907 unsigned LocalBaseSelectorID = Record[1];
2908 F.BaseSelectorID = getTotalNumSelectors();
2909
2910 if (F.LocalNumSelectors > 0) {
2911 // Introduce the global -> local mapping for selectors within this
2912 // module.
2913 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2914
2915 // Introduce the local -> global mapping for selectors within this
2916 // module.
2917 F.SelectorRemap.insertOrReplace(
2918 std::make_pair(LocalBaseSelectorID,
2919 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002920
2921 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002922 }
2923 break;
2924 }
2925
2926 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002927 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002928 if (Record[0])
2929 F.SelectorLookupTable
2930 = ASTSelectorLookupTable::Create(
2931 F.SelectorLookupTableData + Record[0],
2932 F.SelectorLookupTableData,
2933 ASTSelectorLookupTrait(*this, F));
2934 TotalNumMethodPoolEntries += Record[1];
2935 break;
2936
2937 case REFERENCED_SELECTOR_POOL:
2938 if (!Record.empty()) {
2939 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2940 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2941 Record[Idx++]));
2942 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2943 getRawEncoding());
2944 }
2945 }
2946 break;
2947
2948 case PP_COUNTER_VALUE:
2949 if (!Record.empty() && Listener)
2950 Listener->ReadCounter(F, Record[0]);
2951 break;
2952
2953 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002954 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002955 F.NumFileSortedDecls = Record[0];
2956 break;
2957
2958 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002959 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002960 F.LocalNumSLocEntries = Record[0];
2961 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002962 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002963 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002964 SLocSpaceSize);
2965 // Make our entry in the range map. BaseID is negative and growing, so
2966 // we invert it. Because we invert it, though, we need the other end of
2967 // the range.
2968 unsigned RangeStart =
2969 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2970 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2971 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2972
2973 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2974 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2975 GlobalSLocOffsetMap.insert(
2976 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2977 - SLocSpaceSize,&F));
2978
2979 // Initialize the remapping table.
2980 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002981 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002982 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002983 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002984 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2985
2986 TotalNumSLocEntries += F.LocalNumSLocEntries;
2987 break;
2988 }
2989
2990 case MODULE_OFFSET_MAP: {
2991 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002992 const unsigned char *Data = (const unsigned char*)Blob.data();
2993 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002994
2995 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2996 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2997 F.SLocRemap.insert(std::make_pair(0U, 0));
2998 F.SLocRemap.insert(std::make_pair(2U, 1));
2999 }
3000
Guy Benyei11169dd2012-12-18 14:30:41 +00003001 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00003002 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
3003 RemapBuilder;
3004 RemapBuilder SLocRemap(F.SLocRemap);
3005 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3006 RemapBuilder MacroRemap(F.MacroRemap);
3007 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3008 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3009 RemapBuilder SelectorRemap(F.SelectorRemap);
3010 RemapBuilder DeclRemap(F.DeclRemap);
3011 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003012
3013 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00003014 using namespace llvm::support;
3015 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00003016 StringRef Name = StringRef((const char*)Data, Len);
3017 Data += Len;
3018 ModuleFile *OM = ModuleMgr.lookup(Name);
3019 if (!OM) {
3020 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003021 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003022 }
3023
Justin Bogner57ba0b22014-03-28 22:03:24 +00003024 uint32_t SLocOffset =
3025 endian::readNext<uint32_t, little, unaligned>(Data);
3026 uint32_t IdentifierIDOffset =
3027 endian::readNext<uint32_t, little, unaligned>(Data);
3028 uint32_t MacroIDOffset =
3029 endian::readNext<uint32_t, little, unaligned>(Data);
3030 uint32_t PreprocessedEntityIDOffset =
3031 endian::readNext<uint32_t, little, unaligned>(Data);
3032 uint32_t SubmoduleIDOffset =
3033 endian::readNext<uint32_t, little, unaligned>(Data);
3034 uint32_t SelectorIDOffset =
3035 endian::readNext<uint32_t, little, unaligned>(Data);
3036 uint32_t DeclIDOffset =
3037 endian::readNext<uint32_t, little, unaligned>(Data);
3038 uint32_t TypeIndexOffset =
3039 endian::readNext<uint32_t, little, unaligned>(Data);
3040
Ben Langmuir785180e2014-10-20 16:27:30 +00003041 uint32_t None = std::numeric_limits<uint32_t>::max();
3042
3043 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3044 RemapBuilder &Remap) {
3045 if (Offset != None)
3046 Remap.insert(std::make_pair(Offset,
3047 static_cast<int>(BaseOffset - Offset)));
3048 };
3049 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3050 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3051 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3052 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3053 PreprocessedEntityRemap);
3054 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3055 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3056 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3057 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003058
3059 // Global -> local mappings.
3060 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3061 }
3062 break;
3063 }
3064
3065 case SOURCE_MANAGER_LINE_TABLE:
3066 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003067 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003068 break;
3069
3070 case SOURCE_LOCATION_PRELOADS: {
3071 // Need to transform from the local view (1-based IDs) to the global view,
3072 // which is based off F.SLocEntryBaseID.
3073 if (!F.PreloadSLocEntries.empty()) {
3074 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003075 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 }
3077
3078 F.PreloadSLocEntries.swap(Record);
3079 break;
3080 }
3081
3082 case EXT_VECTOR_DECLS:
3083 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3084 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3085 break;
3086
3087 case VTABLE_USES:
3088 if (Record.size() % 3 != 0) {
3089 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003090 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003091 }
3092
3093 // Later tables overwrite earlier ones.
3094 // FIXME: Modules will have some trouble with this. This is clearly not
3095 // the right way to do this.
3096 VTableUses.clear();
3097
3098 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3099 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3100 VTableUses.push_back(
3101 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3102 VTableUses.push_back(Record[Idx++]);
3103 }
3104 break;
3105
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 case PENDING_IMPLICIT_INSTANTIATIONS:
3107 if (PendingInstantiations.size() % 2 != 0) {
3108 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003109 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 }
3111
3112 if (Record.size() % 2 != 0) {
3113 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003114 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003115 }
3116
3117 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3118 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3119 PendingInstantiations.push_back(
3120 ReadSourceLocation(F, Record, I).getRawEncoding());
3121 }
3122 break;
3123
3124 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003125 if (Record.size() != 2) {
3126 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003127 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003128 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003129 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3130 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3131 break;
3132
3133 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003134 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3135 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3136 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003137
3138 unsigned LocalBasePreprocessedEntityID = Record[0];
3139
3140 unsigned StartingID;
3141 if (!PP.getPreprocessingRecord())
3142 PP.createPreprocessingRecord();
3143 if (!PP.getPreprocessingRecord()->getExternalSource())
3144 PP.getPreprocessingRecord()->SetExternalSource(*this);
3145 StartingID
3146 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003147 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003148 F.BasePreprocessedEntityID = StartingID;
3149
3150 if (F.NumPreprocessedEntities > 0) {
3151 // Introduce the global -> local mapping for preprocessed entities in
3152 // this module.
3153 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3154
3155 // Introduce the local -> global mapping for preprocessed entities in
3156 // this module.
3157 F.PreprocessedEntityRemap.insertOrReplace(
3158 std::make_pair(LocalBasePreprocessedEntityID,
3159 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3160 }
3161
3162 break;
3163 }
3164
3165 case DECL_UPDATE_OFFSETS: {
3166 if (Record.size() % 2 != 0) {
3167 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003168 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003169 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003170 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3171 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3172 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3173
3174 // If we've already loaded the decl, perform the updates when we finish
3175 // loading this block.
3176 if (Decl *D = GetExistingDecl(ID))
3177 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3178 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003179 break;
3180 }
3181
3182 case DECL_REPLACEMENTS: {
3183 if (Record.size() % 3 != 0) {
3184 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003185 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003186 }
3187 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3188 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3189 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3190 break;
3191 }
3192
3193 case OBJC_CATEGORIES_MAP: {
3194 if (F.LocalNumObjCCategoriesInMap != 0) {
3195 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003196 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003197 }
3198
3199 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003200 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003201 break;
3202 }
3203
3204 case OBJC_CATEGORIES:
3205 F.ObjCCategories.swap(Record);
3206 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003207
Guy Benyei11169dd2012-12-18 14:30:41 +00003208 case CXX_BASE_SPECIFIER_OFFSETS: {
3209 if (F.LocalNumCXXBaseSpecifiers != 0) {
3210 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003211 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003212 }
Richard Smithc2bb8182015-03-24 06:36:48 +00003213
Guy Benyei11169dd2012-12-18 14:30:41 +00003214 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003215 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00003216 break;
3217 }
3218
3219 case CXX_CTOR_INITIALIZERS_OFFSETS: {
3220 if (F.LocalNumCXXCtorInitializers != 0) {
3221 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
3222 return Failure;
3223 }
3224
3225 F.LocalNumCXXCtorInitializers = Record[0];
3226 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003227 break;
3228 }
3229
3230 case DIAG_PRAGMA_MAPPINGS:
3231 if (F.PragmaDiagMappings.empty())
3232 F.PragmaDiagMappings.swap(Record);
3233 else
3234 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3235 Record.begin(), Record.end());
3236 break;
3237
3238 case CUDA_SPECIAL_DECL_REFS:
3239 // Later tables overwrite earlier ones.
3240 // FIXME: Modules will have trouble with this.
3241 CUDASpecialDeclRefs.clear();
3242 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3243 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3244 break;
3245
3246 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003247 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003248 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003249 if (Record[0]) {
3250 F.HeaderFileInfoTable
3251 = HeaderFileInfoLookupTable::Create(
3252 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3253 (const unsigned char *)F.HeaderFileInfoTableData,
3254 HeaderFileInfoTrait(*this, F,
3255 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003256 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003257
3258 PP.getHeaderSearchInfo().SetExternalSource(this);
3259 if (!PP.getHeaderSearchInfo().getExternalLookup())
3260 PP.getHeaderSearchInfo().SetExternalLookup(this);
3261 }
3262 break;
3263 }
3264
3265 case FP_PRAGMA_OPTIONS:
3266 // Later tables overwrite earlier ones.
3267 FPPragmaOptions.swap(Record);
3268 break;
3269
3270 case OPENCL_EXTENSIONS:
3271 // Later tables overwrite earlier ones.
3272 OpenCLExtensions.swap(Record);
3273 break;
3274
3275 case TENTATIVE_DEFINITIONS:
3276 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3277 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3278 break;
3279
3280 case KNOWN_NAMESPACES:
3281 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3282 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3283 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003284
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003285 case UNDEFINED_BUT_USED:
3286 if (UndefinedButUsed.size() % 2 != 0) {
3287 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003288 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003289 }
3290
3291 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003292 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003293 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003294 }
3295 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003296 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3297 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003298 ReadSourceLocation(F, Record, I).getRawEncoding());
3299 }
3300 break;
3301
Guy Benyei11169dd2012-12-18 14:30:41 +00003302 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003303 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003304 // If we aren't loading a module (which has its own exports), make
3305 // all of the imported modules visible.
3306 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003307 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3308 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3309 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3310 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003311 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003312 }
3313 }
3314 break;
3315 }
3316
3317 case LOCAL_REDECLARATIONS: {
3318 F.RedeclarationChains.swap(Record);
3319 break;
3320 }
3321
3322 case LOCAL_REDECLARATIONS_MAP: {
3323 if (F.LocalNumRedeclarationsInMap != 0) {
3324 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003325 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003326 }
3327
3328 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003329 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003330 break;
3331 }
3332
Guy Benyei11169dd2012-12-18 14:30:41 +00003333 case MACRO_OFFSET: {
3334 if (F.LocalNumMacros != 0) {
3335 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003336 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003337 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003338 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003339 F.LocalNumMacros = Record[0];
3340 unsigned LocalBaseMacroID = Record[1];
3341 F.BaseMacroID = getTotalNumMacros();
3342
3343 if (F.LocalNumMacros > 0) {
3344 // Introduce the global -> local mapping for macros within this module.
3345 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3346
3347 // Introduce the local -> global mapping for macros within this module.
3348 F.MacroRemap.insertOrReplace(
3349 std::make_pair(LocalBaseMacroID,
3350 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003351
3352 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003353 }
3354 break;
3355 }
3356
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003357 case MACRO_TABLE: {
3358 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003359 break;
3360 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003361
3362 case LATE_PARSED_TEMPLATE: {
3363 LateParsedTemplates.append(Record.begin(), Record.end());
3364 break;
3365 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003366
3367 case OPTIMIZE_PRAGMA_OPTIONS:
3368 if (Record.size() != 1) {
3369 Error("invalid pragma optimize record");
3370 return Failure;
3371 }
3372 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3373 break;
Nico Weber72889432014-09-06 01:25:55 +00003374
3375 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3376 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3377 UnusedLocalTypedefNameCandidates.push_back(
3378 getGlobalDeclID(F, Record[I]));
3379 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003380 }
3381 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003382}
3383
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003384ASTReader::ASTReadResult
3385ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3386 const ModuleFile *ImportedBy,
3387 unsigned ClientLoadCapabilities) {
3388 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003389 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003390
Richard Smithe842a472014-10-22 02:05:46 +00003391 if (F.Kind == MK_ExplicitModule) {
3392 // For an explicitly-loaded module, we don't care whether the original
3393 // module map file exists or matches.
3394 return Success;
3395 }
3396
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003397 // Try to resolve ModuleName in the current header search context and
3398 // verify that it is found in the same module map file as we saved. If the
3399 // top-level AST file is a main file, skip this check because there is no
3400 // usable header search context.
3401 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003402 "MODULE_NAME should come before MODULE_MAP_FILE");
3403 if (F.Kind == MK_ImplicitModule &&
3404 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3405 // An implicitly-loaded module file should have its module listed in some
3406 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003407 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003408 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3409 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3410 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003411 assert(ImportedBy && "top-level import should be verified");
3412 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003413 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3414 << ImportedBy->FileName
3415 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003416 return Missing;
3417 }
3418
Richard Smithe842a472014-10-22 02:05:46 +00003419 assert(M->Name == F.ModuleName && "found module with different name");
3420
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003421 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003422 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003423 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3424 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003425 assert(ImportedBy && "top-level import should be verified");
3426 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3427 Diag(diag::err_imported_module_modmap_changed)
3428 << F.ModuleName << ImportedBy->FileName
3429 << ModMap->getName() << F.ModuleMapPath;
3430 return OutOfDate;
3431 }
3432
3433 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3434 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3435 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003436 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003437 const FileEntry *F =
3438 FileMgr.getFile(Filename, false, false);
3439 if (F == nullptr) {
3440 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3441 Error("could not find file '" + Filename +"' referenced by AST file");
3442 return OutOfDate;
3443 }
3444 AdditionalStoredMaps.insert(F);
3445 }
3446
3447 // Check any additional module map files (e.g. module.private.modulemap)
3448 // that are not in the pcm.
3449 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3450 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3451 // Remove files that match
3452 // Note: SmallPtrSet::erase is really remove
3453 if (!AdditionalStoredMaps.erase(ModMap)) {
3454 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3455 Diag(diag::err_module_different_modmap)
3456 << F.ModuleName << /*new*/0 << ModMap->getName();
3457 return OutOfDate;
3458 }
3459 }
3460 }
3461
3462 // Check any additional module map files that are in the pcm, but not
3463 // found in header search. Cases that match are already removed.
3464 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3465 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3466 Diag(diag::err_module_different_modmap)
3467 << F.ModuleName << /*not new*/1 << ModMap->getName();
3468 return OutOfDate;
3469 }
3470 }
3471
3472 if (Listener)
3473 Listener->ReadModuleMapFile(F.ModuleMapPath);
3474 return Success;
3475}
3476
3477
Douglas Gregorc1489562013-02-12 23:36:21 +00003478/// \brief Move the given method to the back of the global list of methods.
3479static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3480 // Find the entry for this selector in the method pool.
3481 Sema::GlobalMethodPool::iterator Known
3482 = S.MethodPool.find(Method->getSelector());
3483 if (Known == S.MethodPool.end())
3484 return;
3485
3486 // Retrieve the appropriate method list.
3487 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3488 : Known->second.second;
3489 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003490 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003491 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003492 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003493 Found = true;
3494 } else {
3495 // Keep searching.
3496 continue;
3497 }
3498 }
3499
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003500 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003501 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003502 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003503 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003504 }
3505}
3506
Richard Smithe657bbd2014-07-18 22:13:40 +00003507void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3508 bool FromFinalization) {
3509 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith57721ac2014-07-21 04:10:40 +00003510 for (Decl *D : Names.HiddenDecls) {
Richard Smith49f906a2014-03-01 00:08:04 +00003511 bool wasHidden = D->Hidden;
3512 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003513
Richard Smith49f906a2014-03-01 00:08:04 +00003514 if (wasHidden && SemaObj) {
3515 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3516 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003517 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003518 }
3519 }
Richard Smith49f906a2014-03-01 00:08:04 +00003520
Richard Smithe657bbd2014-07-18 22:13:40 +00003521 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3522 "nothing to make visible?");
Richard Smithdaa69e02014-07-25 04:40:03 +00003523 for (const auto &Macro : Names.HiddenMacros) {
3524 if (FromFinalization)
3525 PP.appendMacroDirective(Macro.first,
3526 Macro.second->import(PP, SourceLocation()));
3527 else
3528 installImportedMacro(Macro.first, Macro.second, Owner);
3529 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003530}
3531
Richard Smith49f906a2014-03-01 00:08:04 +00003532void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003533 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003534 SourceLocation ImportLoc,
3535 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003536 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003537 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003538 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003539 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003540 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003541
3542 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003543 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003544 // there is nothing more to do.
3545 continue;
3546 }
Richard Smith49f906a2014-03-01 00:08:04 +00003547
Guy Benyei11169dd2012-12-18 14:30:41 +00003548 if (!Mod->isAvailable()) {
3549 // Modules that aren't available cannot be made visible.
3550 continue;
3551 }
3552
3553 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003554 if (NameVisibility >= Module::MacrosVisible &&
3555 Mod->NameVisibility < Module::MacrosVisible)
3556 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003557 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003558
Guy Benyei11169dd2012-12-18 14:30:41 +00003559 // If we've already deserialized any names from this module,
3560 // mark them as visible.
3561 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3562 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003563 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003564 HiddenNamesMap.erase(Hidden);
Richard Smith57721ac2014-07-21 04:10:40 +00003565 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3566 /*FromFinalization*/false);
3567 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3568 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003569 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003570
Guy Benyei11169dd2012-12-18 14:30:41 +00003571 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003572 SmallVector<Module *, 16> Exports;
3573 Mod->getExportedModules(Exports);
3574 for (SmallVectorImpl<Module *>::iterator
3575 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3576 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003577 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003578 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003579 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003580
3581 // Detect any conflicts.
3582 if (Complain) {
3583 assert(ImportLoc.isValid() && "Missing import location");
3584 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3585 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3586 Diag(ImportLoc, diag::warn_module_conflict)
3587 << Mod->getFullModuleName()
3588 << Mod->Conflicts[I].Other->getFullModuleName()
3589 << Mod->Conflicts[I].Message;
3590 // FIXME: Need note where the other module was imported.
3591 }
3592 }
3593 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003594 }
3595}
3596
Douglas Gregore060e572013-01-25 01:03:03 +00003597bool ASTReader::loadGlobalIndex() {
3598 if (GlobalIndex)
3599 return false;
3600
3601 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3602 !Context.getLangOpts().Modules)
3603 return true;
3604
3605 // Try to load the global index.
3606 TriedLoadingGlobalIndex = true;
3607 StringRef ModuleCachePath
3608 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3609 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003610 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003611 if (!Result.first)
3612 return true;
3613
3614 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003615 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003616 return false;
3617}
3618
3619bool ASTReader::isGlobalIndexUnavailable() const {
3620 return Context.getLangOpts().Modules && UseGlobalIndex &&
3621 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3622}
3623
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003624static void updateModuleTimestamp(ModuleFile &MF) {
3625 // Overwrite the timestamp file contents so that file's mtime changes.
3626 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003627 std::error_code EC;
3628 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3629 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003630 return;
3631 OS << "Timestamp file\n";
3632}
3633
Guy Benyei11169dd2012-12-18 14:30:41 +00003634ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3635 ModuleKind Type,
3636 SourceLocation ImportLoc,
3637 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003638 llvm::SaveAndRestore<SourceLocation>
3639 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3640
Richard Smithd1c46742014-04-30 02:24:17 +00003641 // Defer any pending actions until we get to the end of reading the AST file.
3642 Deserializing AnASTFile(this);
3643
Guy Benyei11169dd2012-12-18 14:30:41 +00003644 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003645 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003646
3647 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003648 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003649 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003650 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003651 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003652 ClientLoadCapabilities)) {
3653 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003654 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003655 case OutOfDate:
3656 case VersionMismatch:
3657 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003658 case HadErrors: {
3659 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3660 for (const ImportedModule &IM : Loaded)
3661 LoadedSet.insert(IM.Mod);
3662
Douglas Gregor7029ce12013-03-19 00:28:20 +00003663 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003664 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003665 Context.getLangOpts().Modules
3666 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003667 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003668
3669 // If we find that any modules are unusable, the global index is going
3670 // to be out-of-date. Just remove it.
3671 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003672 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003673 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003674 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003675 case Success:
3676 break;
3677 }
3678
3679 // Here comes stuff that we only do once the entire chain is loaded.
3680
3681 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003682 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3683 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003684 M != MEnd; ++M) {
3685 ModuleFile &F = *M->Mod;
3686
3687 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003688 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3689 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003690
3691 // Once read, set the ModuleFile bit base offset and update the size in
3692 // bits of all files we've seen.
3693 F.GlobalBitOffset = TotalModulesSizeInBits;
3694 TotalModulesSizeInBits += F.SizeInBits;
3695 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3696
3697 // Preload SLocEntries.
3698 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3699 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3700 // Load it through the SourceManager and don't call ReadSLocEntry()
3701 // directly because the entry may have already been loaded in which case
3702 // calling ReadSLocEntry() directly would trigger an assertion in
3703 // SourceManager.
3704 SourceMgr.getLoadedSLocEntryByID(Index);
3705 }
3706 }
3707
Douglas Gregor603cd862013-03-22 18:50:14 +00003708 // Setup the import locations and notify the module manager that we've
3709 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003710 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3711 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003712 M != MEnd; ++M) {
3713 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003714
3715 ModuleMgr.moduleFileAccepted(&F);
3716
3717 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003718 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003719 if (!M->ImportedBy)
3720 F.ImportLoc = M->ImportLoc;
3721 else
3722 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3723 M->ImportLoc.getRawEncoding());
3724 }
3725
3726 // Mark all of the identifiers in the identifier table as being out of date,
3727 // so that various accessors know to check the loaded modules when the
3728 // identifier is used.
3729 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3730 IdEnd = PP.getIdentifierTable().end();
3731 Id != IdEnd; ++Id)
3732 Id->second->setOutOfDate(true);
3733
3734 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003735 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3736 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003737 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3738 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003739
3740 switch (Unresolved.Kind) {
3741 case UnresolvedModuleRef::Conflict:
3742 if (ResolvedMod) {
3743 Module::Conflict Conflict;
3744 Conflict.Other = ResolvedMod;
3745 Conflict.Message = Unresolved.String.str();
3746 Unresolved.Mod->Conflicts.push_back(Conflict);
3747 }
3748 continue;
3749
3750 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003751 if (ResolvedMod)
3752 Unresolved.Mod->Imports.push_back(ResolvedMod);
3753 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003754
Douglas Gregorfb912652013-03-20 21:10:35 +00003755 case UnresolvedModuleRef::Export:
3756 if (ResolvedMod || Unresolved.IsWildcard)
3757 Unresolved.Mod->Exports.push_back(
3758 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3759 continue;
3760 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003761 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003762 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003763
3764 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3765 // Might be unnecessary as use declarations are only used to build the
3766 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003767
3768 InitializeContext();
3769
Richard Smith3d8e97e2013-10-18 06:54:39 +00003770 if (SemaObj)
3771 UpdateSema();
3772
Guy Benyei11169dd2012-12-18 14:30:41 +00003773 if (DeserializationListener)
3774 DeserializationListener->ReaderInitialized(this);
3775
3776 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3777 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3778 PrimaryModule.OriginalSourceFileID
3779 = FileID::get(PrimaryModule.SLocEntryBaseID
3780 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3781
3782 // If this AST file is a precompiled preamble, then set the
3783 // preamble file ID of the source manager to the file source file
3784 // from which the preamble was built.
3785 if (Type == MK_Preamble) {
3786 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3787 } else if (Type == MK_MainFile) {
3788 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3789 }
3790 }
3791
3792 // For any Objective-C class definitions we have already loaded, make sure
3793 // that we load any additional categories.
3794 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3795 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3796 ObjCClassesLoaded[I],
3797 PreviousGeneration);
3798 }
Douglas Gregore060e572013-01-25 01:03:03 +00003799
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003800 if (PP.getHeaderSearchInfo()
3801 .getHeaderSearchOpts()
3802 .ModulesValidateOncePerBuildSession) {
3803 // Now we are certain that the module and all modules it depends on are
3804 // up to date. Create or update timestamp files for modules that are
3805 // located in the module cache (not for PCH files that could be anywhere
3806 // in the filesystem).
3807 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3808 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003809 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003810 updateModuleTimestamp(*M.Mod);
3811 }
3812 }
3813 }
3814
Guy Benyei11169dd2012-12-18 14:30:41 +00003815 return Success;
3816}
3817
Ben Langmuir487ea142014-10-23 18:05:36 +00003818static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3819
Ben Langmuir70a1b812015-03-24 04:43:52 +00003820/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3821static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3822 return Stream.Read(8) == 'C' &&
3823 Stream.Read(8) == 'P' &&
3824 Stream.Read(8) == 'C' &&
3825 Stream.Read(8) == 'H';
3826}
3827
Guy Benyei11169dd2012-12-18 14:30:41 +00003828ASTReader::ASTReadResult
3829ASTReader::ReadASTCore(StringRef FileName,
3830 ModuleKind Type,
3831 SourceLocation ImportLoc,
3832 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003833 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003834 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003835 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003836 unsigned ClientLoadCapabilities) {
3837 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003838 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003839 ModuleManager::AddModuleResult AddResult
3840 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003841 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003842 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003843 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003844
Douglas Gregor7029ce12013-03-19 00:28:20 +00003845 switch (AddResult) {
3846 case ModuleManager::AlreadyLoaded:
3847 return Success;
3848
3849 case ModuleManager::NewlyLoaded:
3850 // Load module file below.
3851 break;
3852
3853 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003854 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003855 // it.
3856 if (ClientLoadCapabilities & ARR_Missing)
3857 return Missing;
3858
3859 // Otherwise, return an error.
3860 {
3861 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3862 + ErrorStr;
3863 Error(Msg);
3864 }
3865 return Failure;
3866
3867 case ModuleManager::OutOfDate:
3868 // We couldn't load the module file because it is out-of-date. If the
3869 // client can handle out-of-date, return it.
3870 if (ClientLoadCapabilities & ARR_OutOfDate)
3871 return OutOfDate;
3872
3873 // Otherwise, return an error.
3874 {
3875 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3876 + ErrorStr;
3877 Error(Msg);
3878 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003879 return Failure;
3880 }
3881
Douglas Gregor7029ce12013-03-19 00:28:20 +00003882 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003883
3884 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3885 // module?
3886 if (FileName != "-") {
3887 CurrentDir = llvm::sys::path::parent_path(FileName);
3888 if (CurrentDir.empty()) CurrentDir = ".";
3889 }
3890
3891 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003892 BitstreamCursor &Stream = F.Stream;
Rafael Espindolafd832392014-11-12 14:48:44 +00003893 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003894 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3895
Guy Benyei11169dd2012-12-18 14:30:41 +00003896 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003897 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003898 Diag(diag::err_not_a_pch_file) << FileName;
3899 return Failure;
3900 }
3901
3902 // This is used for compatibility with older PCH formats.
3903 bool HaveReadControlBlock = false;
3904
Chris Lattnerefa77172013-01-20 00:00:22 +00003905 while (1) {
3906 llvm::BitstreamEntry Entry = Stream.advance();
3907
3908 switch (Entry.Kind) {
3909 case llvm::BitstreamEntry::Error:
3910 case llvm::BitstreamEntry::EndBlock:
3911 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003912 Error("invalid record at top-level of AST file");
3913 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003914
3915 case llvm::BitstreamEntry::SubBlock:
3916 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003917 }
3918
Guy Benyei11169dd2012-12-18 14:30:41 +00003919 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003920 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003921 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3922 if (Stream.ReadBlockInfoBlock()) {
3923 Error("malformed BlockInfoBlock in AST file");
3924 return Failure;
3925 }
3926 break;
3927 case CONTROL_BLOCK_ID:
3928 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003929 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003930 case Success:
3931 break;
3932
3933 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003934 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003935 case OutOfDate: return OutOfDate;
3936 case VersionMismatch: return VersionMismatch;
3937 case ConfigurationMismatch: return ConfigurationMismatch;
3938 case HadErrors: return HadErrors;
3939 }
3940 break;
3941 case AST_BLOCK_ID:
3942 if (!HaveReadControlBlock) {
3943 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003944 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003945 return VersionMismatch;
3946 }
3947
3948 // Record that we've loaded this module.
3949 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3950 return Success;
3951
3952 default:
3953 if (Stream.SkipBlock()) {
3954 Error("malformed block record in AST file");
3955 return Failure;
3956 }
3957 break;
3958 }
3959 }
3960
3961 return Success;
3962}
3963
3964void ASTReader::InitializeContext() {
3965 // If there's a listener, notify them that we "read" the translation unit.
3966 if (DeserializationListener)
3967 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3968 Context.getTranslationUnitDecl());
3969
Guy Benyei11169dd2012-12-18 14:30:41 +00003970 // FIXME: Find a better way to deal with collisions between these
3971 // built-in types. Right now, we just ignore the problem.
3972
3973 // Load the special types.
3974 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3975 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3976 if (!Context.CFConstantStringTypeDecl)
3977 Context.setCFConstantStringType(GetType(String));
3978 }
3979
3980 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3981 QualType FileType = GetType(File);
3982 if (FileType.isNull()) {
3983 Error("FILE type is NULL");
3984 return;
3985 }
3986
3987 if (!Context.FILEDecl) {
3988 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3989 Context.setFILEDecl(Typedef->getDecl());
3990 else {
3991 const TagType *Tag = FileType->getAs<TagType>();
3992 if (!Tag) {
3993 Error("Invalid FILE type in AST file");
3994 return;
3995 }
3996 Context.setFILEDecl(Tag->getDecl());
3997 }
3998 }
3999 }
4000
4001 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4002 QualType Jmp_bufType = GetType(Jmp_buf);
4003 if (Jmp_bufType.isNull()) {
4004 Error("jmp_buf type is NULL");
4005 return;
4006 }
4007
4008 if (!Context.jmp_bufDecl) {
4009 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4010 Context.setjmp_bufDecl(Typedef->getDecl());
4011 else {
4012 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4013 if (!Tag) {
4014 Error("Invalid jmp_buf type in AST file");
4015 return;
4016 }
4017 Context.setjmp_bufDecl(Tag->getDecl());
4018 }
4019 }
4020 }
4021
4022 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4023 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4024 if (Sigjmp_bufType.isNull()) {
4025 Error("sigjmp_buf type is NULL");
4026 return;
4027 }
4028
4029 if (!Context.sigjmp_bufDecl) {
4030 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4031 Context.setsigjmp_bufDecl(Typedef->getDecl());
4032 else {
4033 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4034 assert(Tag && "Invalid sigjmp_buf type in AST file");
4035 Context.setsigjmp_bufDecl(Tag->getDecl());
4036 }
4037 }
4038 }
4039
4040 if (unsigned ObjCIdRedef
4041 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4042 if (Context.ObjCIdRedefinitionType.isNull())
4043 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4044 }
4045
4046 if (unsigned ObjCClassRedef
4047 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4048 if (Context.ObjCClassRedefinitionType.isNull())
4049 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4050 }
4051
4052 if (unsigned ObjCSelRedef
4053 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4054 if (Context.ObjCSelRedefinitionType.isNull())
4055 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4056 }
4057
4058 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4059 QualType Ucontext_tType = GetType(Ucontext_t);
4060 if (Ucontext_tType.isNull()) {
4061 Error("ucontext_t type is NULL");
4062 return;
4063 }
4064
4065 if (!Context.ucontext_tDecl) {
4066 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4067 Context.setucontext_tDecl(Typedef->getDecl());
4068 else {
4069 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4070 assert(Tag && "Invalid ucontext_t type in AST file");
4071 Context.setucontext_tDecl(Tag->getDecl());
4072 }
4073 }
4074 }
4075 }
4076
4077 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4078
4079 // If there were any CUDA special declarations, deserialize them.
4080 if (!CUDASpecialDeclRefs.empty()) {
4081 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4082 Context.setcudaConfigureCallDecl(
4083 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4084 }
Richard Smith56be7542014-03-21 00:33:59 +00004085
Guy Benyei11169dd2012-12-18 14:30:41 +00004086 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00004087 // FIXME: This does not make macro-only imports visible again. It also doesn't
4088 // make #includes mapped to module imports visible.
4089 for (auto &Import : ImportedModules) {
4090 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004091 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00004092 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00004093 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00004094 }
4095 ImportedModules.clear();
4096}
4097
4098void ASTReader::finalizeForWriting() {
Richard Smith57721ac2014-07-21 04:10:40 +00004099 while (!HiddenNamesMap.empty()) {
4100 auto HiddenNames = std::move(*HiddenNamesMap.begin());
4101 HiddenNamesMap.erase(HiddenNamesMap.begin());
4102 makeNamesVisible(HiddenNames.second, HiddenNames.first,
4103 /*FromFinalization*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004104 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004105}
4106
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004107/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
4108/// cursor into the start of the given block ID, returning false on success and
4109/// true on failure.
4110static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004111 while (1) {
4112 llvm::BitstreamEntry Entry = Cursor.advance();
4113 switch (Entry.Kind) {
4114 case llvm::BitstreamEntry::Error:
4115 case llvm::BitstreamEntry::EndBlock:
4116 return true;
4117
4118 case llvm::BitstreamEntry::Record:
4119 // Ignore top-level records.
4120 Cursor.skipRecord(Entry.ID);
4121 break;
4122
4123 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004124 if (Entry.ID == BlockID) {
4125 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004126 return true;
4127 // Found it!
4128 return false;
4129 }
4130
4131 if (Cursor.SkipBlock())
4132 return true;
4133 }
4134 }
4135}
4136
Ben Langmuir70a1b812015-03-24 04:43:52 +00004137/// \brief Reads and return the signature record from \p StreamFile's control
4138/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00004139static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4140 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004141 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004142 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004143
4144 // Scan for the CONTROL_BLOCK_ID block.
4145 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4146 return 0;
4147
4148 // Scan for SIGNATURE inside the control block.
4149 ASTReader::RecordData Record;
4150 while (1) {
4151 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4152 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4153 Entry.Kind != llvm::BitstreamEntry::Record)
4154 return 0;
4155
4156 Record.clear();
4157 StringRef Blob;
4158 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4159 return Record[0];
4160 }
4161}
4162
Guy Benyei11169dd2012-12-18 14:30:41 +00004163/// \brief Retrieve the name of the original source file name
4164/// directly from the AST file, without actually loading the AST
4165/// file.
4166std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
4167 FileManager &FileMgr,
4168 DiagnosticsEngine &Diags) {
4169 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004170 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004171 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004172 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4173 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004174 return std::string();
4175 }
4176
4177 // Initialize the stream
4178 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004179 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4180 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004181 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004182
4183 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004184 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004185 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4186 return std::string();
4187 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004188
Chris Lattnere7b154b2013-01-19 21:39:22 +00004189 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004190 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004191 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4192 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004193 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004194
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004195 // Scan for ORIGINAL_FILE inside the control block.
4196 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004197 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004198 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004199 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4200 return std::string();
4201
4202 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4203 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4204 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004205 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004206
Guy Benyei11169dd2012-12-18 14:30:41 +00004207 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004208 StringRef Blob;
4209 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4210 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004211 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004212}
4213
4214namespace {
4215 class SimplePCHValidator : public ASTReaderListener {
4216 const LangOptions &ExistingLangOpts;
4217 const TargetOptions &ExistingTargetOpts;
4218 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004219 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004220 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004221
Guy Benyei11169dd2012-12-18 14:30:41 +00004222 public:
4223 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4224 const TargetOptions &ExistingTargetOpts,
4225 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004226 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004227 FileManager &FileMgr)
4228 : ExistingLangOpts(ExistingLangOpts),
4229 ExistingTargetOpts(ExistingTargetOpts),
4230 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004231 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 FileMgr(FileMgr)
4233 {
4234 }
4235
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004236 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4237 bool AllowCompatibleDifferences) override {
4238 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4239 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004240 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004241 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4242 bool AllowCompatibleDifferences) override {
4243 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4244 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004245 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004246 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4247 StringRef SpecificModuleCachePath,
4248 bool Complain) override {
4249 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4250 ExistingModuleCachePath,
4251 nullptr, ExistingLangOpts);
4252 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004253 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4254 bool Complain,
4255 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004256 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004257 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004258 }
4259 };
4260}
4261
4262bool ASTReader::readASTFileControlBlock(StringRef Filename,
4263 FileManager &FileMgr,
4264 ASTReaderListener &Listener) {
4265 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004266 // FIXME: This allows use of the VFS; we do not allow use of the
4267 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004268 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 if (!Buffer) {
4270 return true;
4271 }
4272
4273 // Initialize the stream
4274 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004275 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4276 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004277 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004278
4279 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004280 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004281 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004282
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004283 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004284 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004285 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004286
4287 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004288 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004289 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004290 BitstreamCursor InputFilesCursor;
4291 if (NeedsInputFiles) {
4292 InputFilesCursor = Stream;
4293 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4294 return true;
4295
4296 // Read the abbreviations
4297 while (true) {
4298 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4299 unsigned Code = InputFilesCursor.ReadCode();
4300
4301 // We expect all abbrevs to be at the start of the block.
4302 if (Code != llvm::bitc::DEFINE_ABBREV) {
4303 InputFilesCursor.JumpToBit(Offset);
4304 break;
4305 }
4306 InputFilesCursor.ReadAbbrevRecord();
4307 }
4308 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004309
4310 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004312 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004313 while (1) {
4314 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4315 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4316 return false;
4317
4318 if (Entry.Kind != llvm::BitstreamEntry::Record)
4319 return true;
4320
Guy Benyei11169dd2012-12-18 14:30:41 +00004321 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004322 StringRef Blob;
4323 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004324 switch ((ControlRecordTypes)RecCode) {
4325 case METADATA: {
4326 if (Record[0] != VERSION_MAJOR)
4327 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004328
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004329 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004330 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004331
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004332 break;
4333 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004334 case MODULE_NAME:
4335 Listener.ReadModuleName(Blob);
4336 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004337 case MODULE_DIRECTORY:
4338 ModuleDir = Blob;
4339 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004340 case MODULE_MAP_FILE: {
4341 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004342 auto Path = ReadString(Record, Idx);
4343 ResolveImportedPath(Path, ModuleDir);
4344 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004345 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004346 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004347 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004348 if (ParseLanguageOptions(Record, false, Listener,
4349 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004350 return true;
4351 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004352
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004353 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004354 if (ParseTargetOptions(Record, false, Listener,
4355 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004356 return true;
4357 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004358
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004359 case DIAGNOSTIC_OPTIONS:
4360 if (ParseDiagnosticOptions(Record, false, Listener))
4361 return true;
4362 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004363
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004364 case FILE_SYSTEM_OPTIONS:
4365 if (ParseFileSystemOptions(Record, false, Listener))
4366 return true;
4367 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004368
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004369 case HEADER_SEARCH_OPTIONS:
4370 if (ParseHeaderSearchOptions(Record, false, Listener))
4371 return true;
4372 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004373
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004374 case PREPROCESSOR_OPTIONS: {
4375 std::string IgnoredSuggestedPredefines;
4376 if (ParsePreprocessorOptions(Record, false, Listener,
4377 IgnoredSuggestedPredefines))
4378 return true;
4379 break;
4380 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004381
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004382 case INPUT_FILE_OFFSETS: {
4383 if (!NeedsInputFiles)
4384 break;
4385
4386 unsigned NumInputFiles = Record[0];
4387 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004388 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004389 for (unsigned I = 0; I != NumInputFiles; ++I) {
4390 // Go find this input file.
4391 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004392
4393 if (isSystemFile && !NeedsSystemInputFiles)
4394 break; // the rest are system input files
4395
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004396 BitstreamCursor &Cursor = InputFilesCursor;
4397 SavedStreamPosition SavedPosition(Cursor);
4398 Cursor.JumpToBit(InputFileOffs[I]);
4399
4400 unsigned Code = Cursor.ReadCode();
4401 RecordData Record;
4402 StringRef Blob;
4403 bool shouldContinue = false;
4404 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4405 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004406 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004407 std::string Filename = Blob;
4408 ResolveImportedPath(Filename, ModuleDir);
4409 shouldContinue =
4410 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004411 break;
4412 }
4413 if (!shouldContinue)
4414 break;
4415 }
4416 break;
4417 }
4418
Richard Smithd4b230b2014-10-27 23:01:16 +00004419 case IMPORTS: {
4420 if (!NeedsImports)
4421 break;
4422
4423 unsigned Idx = 0, N = Record.size();
4424 while (Idx < N) {
4425 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004426 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004427 std::string Filename = ReadString(Record, Idx);
4428 ResolveImportedPath(Filename, ModuleDir);
4429 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004430 }
4431 break;
4432 }
4433
Richard Smith7f330cd2015-03-18 01:42:29 +00004434 case KNOWN_MODULE_FILES: {
4435 // Known-but-not-technically-used module files are treated as imports.
4436 if (!NeedsImports)
4437 break;
4438
4439 unsigned Idx = 0, N = Record.size();
4440 while (Idx < N) {
4441 std::string Filename = ReadString(Record, Idx);
4442 ResolveImportedPath(Filename, ModuleDir);
4443 Listener.visitImport(Filename);
4444 }
4445 break;
4446 }
4447
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004448 default:
4449 // No other validation to perform.
4450 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 }
4452 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004453}
4454
4455
4456bool ASTReader::isAcceptableASTFile(StringRef Filename,
4457 FileManager &FileMgr,
4458 const LangOptions &LangOpts,
4459 const TargetOptions &TargetOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004460 const PreprocessorOptions &PPOpts,
4461 std::string ExistingModuleCachePath) {
4462 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4463 ExistingModuleCachePath, FileMgr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 return !readASTFileControlBlock(Filename, FileMgr, validator);
4465}
4466
Ben Langmuir2c9af442014-04-10 17:57:43 +00004467ASTReader::ASTReadResult
4468ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 // Enter the submodule block.
4470 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4471 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004472 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 }
4474
4475 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4476 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004477 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 RecordData Record;
4479 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004480 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4481
4482 switch (Entry.Kind) {
4483 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4484 case llvm::BitstreamEntry::Error:
4485 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004486 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004487 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004488 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004489 case llvm::BitstreamEntry::Record:
4490 // The interesting case.
4491 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004493
Guy Benyei11169dd2012-12-18 14:30:41 +00004494 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004495 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004496 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004497 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4498
4499 if ((Kind == SUBMODULE_METADATA) != First) {
4500 Error("submodule metadata record should be at beginning of block");
4501 return Failure;
4502 }
4503 First = false;
4504
4505 // Submodule information is only valid if we have a current module.
4506 // FIXME: Should we error on these cases?
4507 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4508 Kind != SUBMODULE_DEFINITION)
4509 continue;
4510
4511 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004512 default: // Default behavior: ignore.
4513 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004514
Richard Smith03478d92014-10-23 22:12:14 +00004515 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004516 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004518 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004519 }
Richard Smith03478d92014-10-23 22:12:14 +00004520
Chris Lattner0e6c9402013-01-20 02:38:54 +00004521 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004522 unsigned Idx = 0;
4523 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4524 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4525 bool IsFramework = Record[Idx++];
4526 bool IsExplicit = Record[Idx++];
4527 bool IsSystem = Record[Idx++];
4528 bool IsExternC = Record[Idx++];
4529 bool InferSubmodules = Record[Idx++];
4530 bool InferExplicitSubmodules = Record[Idx++];
4531 bool InferExportWildcard = Record[Idx++];
4532 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004533
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004534 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004535 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004536 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004537
Guy Benyei11169dd2012-12-18 14:30:41 +00004538 // Retrieve this (sub)module from the module map, creating it if
4539 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004540 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004541 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004542
4543 // FIXME: set the definition loc for CurrentModule, or call
4544 // ModMap.setInferredModuleAllowedBy()
4545
Guy Benyei11169dd2012-12-18 14:30:41 +00004546 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4547 if (GlobalIndex >= SubmodulesLoaded.size() ||
4548 SubmodulesLoaded[GlobalIndex]) {
4549 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004550 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004551 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004552
Douglas Gregor7029ce12013-03-19 00:28:20 +00004553 if (!ParentModule) {
4554 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4555 if (CurFile != F.File) {
4556 if (!Diags.isDiagnosticInFlight()) {
4557 Diag(diag::err_module_file_conflict)
4558 << CurrentModule->getTopLevelModuleName()
4559 << CurFile->getName()
4560 << F.File->getName();
4561 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004562 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004563 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004564 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004565
4566 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004567 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004568
Guy Benyei11169dd2012-12-18 14:30:41 +00004569 CurrentModule->IsFromModuleFile = true;
4570 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004571 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004572 CurrentModule->InferSubmodules = InferSubmodules;
4573 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4574 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004575 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004576 if (DeserializationListener)
4577 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4578
4579 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004580
Douglas Gregorfb912652013-03-20 21:10:35 +00004581 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004582 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004583 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004584 CurrentModule->UnresolvedConflicts.clear();
4585 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004586 break;
4587 }
4588
4589 case SUBMODULE_UMBRELLA_HEADER: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004590 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004591 if (!CurrentModule->getUmbrellaHeader())
4592 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4593 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004594 // This can be a spurious difference caused by changing the VFS to
4595 // point to a different copy of the file, and it is too late to
4596 // to rebuild safely.
4597 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4598 // after input file validation only real problems would remain and we
4599 // could just error. For now, assume it's okay.
4600 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 }
4602 }
4603 break;
4604 }
4605
Richard Smith202210b2014-10-24 20:23:01 +00004606 case SUBMODULE_HEADER:
4607 case SUBMODULE_EXCLUDED_HEADER:
4608 case SUBMODULE_PRIVATE_HEADER:
4609 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004610 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4611 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004612 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004613
Richard Smith202210b2014-10-24 20:23:01 +00004614 case SUBMODULE_TEXTUAL_HEADER:
4615 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4616 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4617 // them here.
4618 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004619
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004621 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004622 break;
4623 }
4624
4625 case SUBMODULE_UMBRELLA_DIR: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004626 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004627 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004628 if (!CurrentModule->getUmbrellaDir())
4629 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4630 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004631 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4632 Error("mismatched umbrella directories in submodule");
4633 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004634 }
4635 }
4636 break;
4637 }
4638
4639 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004640 F.BaseSubmoduleID = getTotalNumSubmodules();
4641 F.LocalNumSubmodules = Record[0];
4642 unsigned LocalBaseSubmoduleID = Record[1];
4643 if (F.LocalNumSubmodules > 0) {
4644 // Introduce the global -> local mapping for submodules within this
4645 // module.
4646 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4647
4648 // Introduce the local -> global mapping for submodules within this
4649 // module.
4650 F.SubmoduleRemap.insertOrReplace(
4651 std::make_pair(LocalBaseSubmoduleID,
4652 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004653
Ben Langmuir52ca6782014-10-20 16:27:32 +00004654 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4655 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004656 break;
4657 }
4658
4659 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004660 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004661 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004662 Unresolved.File = &F;
4663 Unresolved.Mod = CurrentModule;
4664 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004665 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004666 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004667 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004668 }
4669 break;
4670 }
4671
4672 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004673 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004674 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004675 Unresolved.File = &F;
4676 Unresolved.Mod = CurrentModule;
4677 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004678 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004679 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004680 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004681 }
4682
4683 // Once we've loaded the set of exports, there's no reason to keep
4684 // the parsed, unresolved exports around.
4685 CurrentModule->UnresolvedExports.clear();
4686 break;
4687 }
4688 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004689 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004690 Context.getTargetInfo());
4691 break;
4692 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004693
4694 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004695 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004696 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004697 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004698
4699 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004700 CurrentModule->ConfigMacros.push_back(Blob.str());
4701 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004702
4703 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004704 UnresolvedModuleRef Unresolved;
4705 Unresolved.File = &F;
4706 Unresolved.Mod = CurrentModule;
4707 Unresolved.ID = Record[0];
4708 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4709 Unresolved.IsWildcard = false;
4710 Unresolved.String = Blob;
4711 UnresolvedModuleRefs.push_back(Unresolved);
4712 break;
4713 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004714 }
4715 }
4716}
4717
4718/// \brief Parse the record that corresponds to a LangOptions data
4719/// structure.
4720///
4721/// This routine parses the language options from the AST file and then gives
4722/// them to the AST listener if one is set.
4723///
4724/// \returns true if the listener deems the file unacceptable, false otherwise.
4725bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4726 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004727 ASTReaderListener &Listener,
4728 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004729 LangOptions LangOpts;
4730 unsigned Idx = 0;
4731#define LANGOPT(Name, Bits, Default, Description) \
4732 LangOpts.Name = Record[Idx++];
4733#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4734 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4735#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004736#define SANITIZER(NAME, ID) \
4737 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004738#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004739
4740 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4741 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4742 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4743
4744 unsigned Length = Record[Idx++];
4745 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4746 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004747
4748 Idx += Length;
4749
4750 // Comment options.
4751 for (unsigned N = Record[Idx++]; N; --N) {
4752 LangOpts.CommentOpts.BlockCommandNames.push_back(
4753 ReadString(Record, Idx));
4754 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004755 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004756
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004757 return Listener.ReadLanguageOptions(LangOpts, Complain,
4758 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004759}
4760
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004761bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4762 ASTReaderListener &Listener,
4763 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004764 unsigned Idx = 0;
4765 TargetOptions TargetOpts;
4766 TargetOpts.Triple = ReadString(Record, Idx);
4767 TargetOpts.CPU = ReadString(Record, Idx);
4768 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 for (unsigned N = Record[Idx++]; N; --N) {
4770 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4771 }
4772 for (unsigned N = Record[Idx++]; N; --N) {
4773 TargetOpts.Features.push_back(ReadString(Record, Idx));
4774 }
4775
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004776 return Listener.ReadTargetOptions(TargetOpts, Complain,
4777 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004778}
4779
4780bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4781 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004782 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004784#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004785#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004786 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004787#include "clang/Basic/DiagnosticOptions.def"
4788
Richard Smith3be1cb22014-08-07 00:24:21 +00004789 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004790 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004791 for (unsigned N = Record[Idx++]; N; --N)
4792 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004793
4794 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4795}
4796
4797bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4798 ASTReaderListener &Listener) {
4799 FileSystemOptions FSOpts;
4800 unsigned Idx = 0;
4801 FSOpts.WorkingDir = ReadString(Record, Idx);
4802 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4803}
4804
4805bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4806 bool Complain,
4807 ASTReaderListener &Listener) {
4808 HeaderSearchOptions HSOpts;
4809 unsigned Idx = 0;
4810 HSOpts.Sysroot = ReadString(Record, Idx);
4811
4812 // Include entries.
4813 for (unsigned N = Record[Idx++]; N; --N) {
4814 std::string Path = ReadString(Record, Idx);
4815 frontend::IncludeDirGroup Group
4816 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004817 bool IsFramework = Record[Idx++];
4818 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004819 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004820 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004821 }
4822
4823 // System header prefixes.
4824 for (unsigned N = Record[Idx++]; N; --N) {
4825 std::string Prefix = ReadString(Record, Idx);
4826 bool IsSystemHeader = Record[Idx++];
4827 HSOpts.SystemHeaderPrefixes.push_back(
4828 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4829 }
4830
4831 HSOpts.ResourceDir = ReadString(Record, Idx);
4832 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004833 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004834 HSOpts.DisableModuleHash = Record[Idx++];
4835 HSOpts.UseBuiltinIncludes = Record[Idx++];
4836 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4837 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4838 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004839 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004840
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004841 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4842 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004843}
4844
4845bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4846 bool Complain,
4847 ASTReaderListener &Listener,
4848 std::string &SuggestedPredefines) {
4849 PreprocessorOptions PPOpts;
4850 unsigned Idx = 0;
4851
4852 // Macro definitions/undefs
4853 for (unsigned N = Record[Idx++]; N; --N) {
4854 std::string Macro = ReadString(Record, Idx);
4855 bool IsUndef = Record[Idx++];
4856 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4857 }
4858
4859 // Includes
4860 for (unsigned N = Record[Idx++]; N; --N) {
4861 PPOpts.Includes.push_back(ReadString(Record, Idx));
4862 }
4863
4864 // Macro Includes
4865 for (unsigned N = Record[Idx++]; N; --N) {
4866 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4867 }
4868
4869 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004870 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004871 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4872 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4873 PPOpts.ObjCXXARCStandardLibrary =
4874 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4875 SuggestedPredefines.clear();
4876 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4877 SuggestedPredefines);
4878}
4879
4880std::pair<ModuleFile *, unsigned>
4881ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4882 GlobalPreprocessedEntityMapType::iterator
4883 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4884 assert(I != GlobalPreprocessedEntityMap.end() &&
4885 "Corrupted global preprocessed entity map");
4886 ModuleFile *M = I->second;
4887 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4888 return std::make_pair(M, LocalIndex);
4889}
4890
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004891llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004892ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4893 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4894 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4895 Mod.NumPreprocessedEntities);
4896
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004897 return llvm::make_range(PreprocessingRecord::iterator(),
4898 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004899}
4900
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004901llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004902ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004903 return llvm::make_range(
4904 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4905 ModuleDeclIterator(this, &Mod,
4906 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004907}
4908
4909PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4910 PreprocessedEntityID PPID = Index+1;
4911 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4912 ModuleFile &M = *PPInfo.first;
4913 unsigned LocalIndex = PPInfo.second;
4914 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4915
Guy Benyei11169dd2012-12-18 14:30:41 +00004916 if (!PP.getPreprocessingRecord()) {
4917 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004918 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004919 }
4920
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004921 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4922 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4923
4924 llvm::BitstreamEntry Entry =
4925 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4926 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004927 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004928
Guy Benyei11169dd2012-12-18 14:30:41 +00004929 // Read the record.
4930 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4931 ReadSourceLocation(M, PPOffs.End));
4932 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004933 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004934 RecordData Record;
4935 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004936 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4937 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004938 switch (RecType) {
4939 case PPD_MACRO_EXPANSION: {
4940 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004941 IdentifierInfo *Name = nullptr;
4942 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004943 if (isBuiltin)
4944 Name = getLocalIdentifier(M, Record[1]);
4945 else {
4946 PreprocessedEntityID
4947 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4948 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4949 }
4950
4951 MacroExpansion *ME;
4952 if (isBuiltin)
4953 ME = new (PPRec) MacroExpansion(Name, Range);
4954 else
4955 ME = new (PPRec) MacroExpansion(Def, Range);
4956
4957 return ME;
4958 }
4959
4960 case PPD_MACRO_DEFINITION: {
4961 // Decode the identifier info and then check again; if the macro is
4962 // still defined and associated with the identifier,
4963 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4964 MacroDefinition *MD
4965 = new (PPRec) MacroDefinition(II, Range);
4966
4967 if (DeserializationListener)
4968 DeserializationListener->MacroDefinitionRead(PPID, MD);
4969
4970 return MD;
4971 }
4972
4973 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004974 const char *FullFileNameStart = Blob.data() + Record[0];
4975 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004976 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004977 if (!FullFileName.empty())
4978 File = PP.getFileManager().getFile(FullFileName);
4979
4980 // FIXME: Stable encoding
4981 InclusionDirective::InclusionKind Kind
4982 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4983 InclusionDirective *ID
4984 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004985 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004986 Record[1], Record[3],
4987 File,
4988 Range);
4989 return ID;
4990 }
4991 }
4992
4993 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4994}
4995
4996/// \brief \arg SLocMapI points at a chunk of a module that contains no
4997/// preprocessed entities or the entities it contains are not the ones we are
4998/// looking for. Find the next module that contains entities and return the ID
4999/// of the first entry.
5000PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5001 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5002 ++SLocMapI;
5003 for (GlobalSLocOffsetMapType::const_iterator
5004 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5005 ModuleFile &M = *SLocMapI->second;
5006 if (M.NumPreprocessedEntities)
5007 return M.BasePreprocessedEntityID;
5008 }
5009
5010 return getTotalNumPreprocessedEntities();
5011}
5012
5013namespace {
5014
5015template <unsigned PPEntityOffset::*PPLoc>
5016struct PPEntityComp {
5017 const ASTReader &Reader;
5018 ModuleFile &M;
5019
5020 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5021
5022 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5023 SourceLocation LHS = getLoc(L);
5024 SourceLocation RHS = getLoc(R);
5025 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5026 }
5027
5028 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5029 SourceLocation LHS = getLoc(L);
5030 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5031 }
5032
5033 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5034 SourceLocation RHS = getLoc(R);
5035 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5036 }
5037
5038 SourceLocation getLoc(const PPEntityOffset &PPE) const {
5039 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
5040 }
5041};
5042
5043}
5044
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005045PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5046 bool EndsAfter) const {
5047 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005048 return getTotalNumPreprocessedEntities();
5049
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005050 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5051 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5053 "Corrupted global sloc offset map");
5054
5055 if (SLocMapI->second->NumPreprocessedEntities == 0)
5056 return findNextPreprocessedEntity(SLocMapI);
5057
5058 ModuleFile &M = *SLocMapI->second;
5059 typedef const PPEntityOffset *pp_iterator;
5060 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5061 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5062
5063 size_t Count = M.NumPreprocessedEntities;
5064 size_t Half;
5065 pp_iterator First = pp_begin;
5066 pp_iterator PPI;
5067
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005068 if (EndsAfter) {
5069 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5070 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
5071 } else {
5072 // Do a binary search manually instead of using std::lower_bound because
5073 // The end locations of entities may be unordered (when a macro expansion
5074 // is inside another macro argument), but for this case it is not important
5075 // whether we get the first macro expansion or its containing macro.
5076 while (Count > 0) {
5077 Half = Count / 2;
5078 PPI = First;
5079 std::advance(PPI, Half);
5080 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
5081 Loc)) {
5082 First = PPI;
5083 ++First;
5084 Count = Count - Half - 1;
5085 } else
5086 Count = Half;
5087 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005088 }
5089
5090 if (PPI == pp_end)
5091 return findNextPreprocessedEntity(SLocMapI);
5092
5093 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5094}
5095
Guy Benyei11169dd2012-12-18 14:30:41 +00005096/// \brief Returns a pair of [Begin, End) indices of preallocated
5097/// preprocessed entities that \arg Range encompasses.
5098std::pair<unsigned, unsigned>
5099 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5100 if (Range.isInvalid())
5101 return std::make_pair(0,0);
5102 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5103
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005104 PreprocessedEntityID BeginID =
5105 findPreprocessedEntity(Range.getBegin(), false);
5106 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 return std::make_pair(BeginID, EndID);
5108}
5109
5110/// \brief Optionally returns true or false if the preallocated preprocessed
5111/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005112Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 FileID FID) {
5114 if (FID.isInvalid())
5115 return false;
5116
5117 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5118 ModuleFile &M = *PPInfo.first;
5119 unsigned LocalIndex = PPInfo.second;
5120 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5121
5122 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5123 if (Loc.isInvalid())
5124 return false;
5125
5126 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5127 return true;
5128 else
5129 return false;
5130}
5131
5132namespace {
5133 /// \brief Visitor used to search for information about a header file.
5134 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 const FileEntry *FE;
5136
David Blaikie05785d12013-02-20 22:23:23 +00005137 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005138
5139 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005140 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5141 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00005142
5143 static bool visit(ModuleFile &M, void *UserData) {
5144 HeaderFileInfoVisitor *This
5145 = static_cast<HeaderFileInfoVisitor *>(UserData);
5146
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 HeaderFileInfoLookupTable *Table
5148 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5149 if (!Table)
5150 return false;
5151
5152 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00005153 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 if (Pos == Table->end())
5155 return false;
5156
5157 This->HFI = *Pos;
5158 return true;
5159 }
5160
David Blaikie05785d12013-02-20 22:23:23 +00005161 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 };
5163}
5164
5165HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005166 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005167 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005168 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005169 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005170
5171 return HeaderFileInfo();
5172}
5173
5174void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5175 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005176 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005177 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5178 ModuleFile &F = *(*I);
5179 unsigned Idx = 0;
5180 DiagStates.clear();
5181 assert(!Diag.DiagStates.empty());
5182 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5183 while (Idx < F.PragmaDiagMappings.size()) {
5184 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5185 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5186 if (DiagStateID != 0) {
5187 Diag.DiagStatePoints.push_back(
5188 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5189 FullSourceLoc(Loc, SourceMgr)));
5190 continue;
5191 }
5192
5193 assert(DiagStateID == 0);
5194 // A new DiagState was created here.
5195 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5196 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5197 DiagStates.push_back(NewState);
5198 Diag.DiagStatePoints.push_back(
5199 DiagnosticsEngine::DiagStatePoint(NewState,
5200 FullSourceLoc(Loc, SourceMgr)));
5201 while (1) {
5202 assert(Idx < F.PragmaDiagMappings.size() &&
5203 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5204 if (Idx >= F.PragmaDiagMappings.size()) {
5205 break; // Something is messed up but at least avoid infinite loop in
5206 // release build.
5207 }
5208 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5209 if (DiagID == (unsigned)-1) {
5210 break; // no more diag/map pairs for this location.
5211 }
Alp Tokerc726c362014-06-10 09:31:37 +00005212 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5213 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5214 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005215 }
5216 }
5217 }
5218}
5219
5220/// \brief Get the correct cursor and offset for loading a type.
5221ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5222 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5223 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5224 ModuleFile *M = I->second;
5225 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5226}
5227
5228/// \brief Read and return the type with the given index..
5229///
5230/// The index is the type ID, shifted and minus the number of predefs. This
5231/// routine actually reads the record corresponding to the type at the given
5232/// location. It is a helper routine for GetType, which deals with reading type
5233/// IDs.
5234QualType ASTReader::readTypeRecord(unsigned Index) {
5235 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005236 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005237
5238 // Keep track of where we are in the stream, then jump back there
5239 // after reading this type.
5240 SavedStreamPosition SavedPosition(DeclsCursor);
5241
5242 ReadingKindTracker ReadingKind(Read_Type, *this);
5243
5244 // Note that we are loading a type record.
5245 Deserializing AType(this);
5246
5247 unsigned Idx = 0;
5248 DeclsCursor.JumpToBit(Loc.Offset);
5249 RecordData Record;
5250 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005251 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005252 case TYPE_EXT_QUAL: {
5253 if (Record.size() != 2) {
5254 Error("Incorrect encoding of extended qualifier type");
5255 return QualType();
5256 }
5257 QualType Base = readType(*Loc.F, Record, Idx);
5258 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5259 return Context.getQualifiedType(Base, Quals);
5260 }
5261
5262 case TYPE_COMPLEX: {
5263 if (Record.size() != 1) {
5264 Error("Incorrect encoding of complex type");
5265 return QualType();
5266 }
5267 QualType ElemType = readType(*Loc.F, Record, Idx);
5268 return Context.getComplexType(ElemType);
5269 }
5270
5271 case TYPE_POINTER: {
5272 if (Record.size() != 1) {
5273 Error("Incorrect encoding of pointer type");
5274 return QualType();
5275 }
5276 QualType PointeeType = readType(*Loc.F, Record, Idx);
5277 return Context.getPointerType(PointeeType);
5278 }
5279
Reid Kleckner8a365022013-06-24 17:51:48 +00005280 case TYPE_DECAYED: {
5281 if (Record.size() != 1) {
5282 Error("Incorrect encoding of decayed type");
5283 return QualType();
5284 }
5285 QualType OriginalType = readType(*Loc.F, Record, Idx);
5286 QualType DT = Context.getAdjustedParameterType(OriginalType);
5287 if (!isa<DecayedType>(DT))
5288 Error("Decayed type does not decay");
5289 return DT;
5290 }
5291
Reid Kleckner0503a872013-12-05 01:23:43 +00005292 case TYPE_ADJUSTED: {
5293 if (Record.size() != 2) {
5294 Error("Incorrect encoding of adjusted type");
5295 return QualType();
5296 }
5297 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5298 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5299 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5300 }
5301
Guy Benyei11169dd2012-12-18 14:30:41 +00005302 case TYPE_BLOCK_POINTER: {
5303 if (Record.size() != 1) {
5304 Error("Incorrect encoding of block pointer type");
5305 return QualType();
5306 }
5307 QualType PointeeType = readType(*Loc.F, Record, Idx);
5308 return Context.getBlockPointerType(PointeeType);
5309 }
5310
5311 case TYPE_LVALUE_REFERENCE: {
5312 if (Record.size() != 2) {
5313 Error("Incorrect encoding of lvalue reference type");
5314 return QualType();
5315 }
5316 QualType PointeeType = readType(*Loc.F, Record, Idx);
5317 return Context.getLValueReferenceType(PointeeType, Record[1]);
5318 }
5319
5320 case TYPE_RVALUE_REFERENCE: {
5321 if (Record.size() != 1) {
5322 Error("Incorrect encoding of rvalue reference type");
5323 return QualType();
5324 }
5325 QualType PointeeType = readType(*Loc.F, Record, Idx);
5326 return Context.getRValueReferenceType(PointeeType);
5327 }
5328
5329 case TYPE_MEMBER_POINTER: {
5330 if (Record.size() != 2) {
5331 Error("Incorrect encoding of member pointer type");
5332 return QualType();
5333 }
5334 QualType PointeeType = readType(*Loc.F, Record, Idx);
5335 QualType ClassType = readType(*Loc.F, Record, Idx);
5336 if (PointeeType.isNull() || ClassType.isNull())
5337 return QualType();
5338
5339 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5340 }
5341
5342 case TYPE_CONSTANT_ARRAY: {
5343 QualType ElementType = readType(*Loc.F, Record, Idx);
5344 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5345 unsigned IndexTypeQuals = Record[2];
5346 unsigned Idx = 3;
5347 llvm::APInt Size = ReadAPInt(Record, Idx);
5348 return Context.getConstantArrayType(ElementType, Size,
5349 ASM, IndexTypeQuals);
5350 }
5351
5352 case TYPE_INCOMPLETE_ARRAY: {
5353 QualType ElementType = readType(*Loc.F, Record, Idx);
5354 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5355 unsigned IndexTypeQuals = Record[2];
5356 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5357 }
5358
5359 case TYPE_VARIABLE_ARRAY: {
5360 QualType ElementType = readType(*Loc.F, Record, Idx);
5361 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5362 unsigned IndexTypeQuals = Record[2];
5363 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5364 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5365 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5366 ASM, IndexTypeQuals,
5367 SourceRange(LBLoc, RBLoc));
5368 }
5369
5370 case TYPE_VECTOR: {
5371 if (Record.size() != 3) {
5372 Error("incorrect encoding of vector type in AST file");
5373 return QualType();
5374 }
5375
5376 QualType ElementType = readType(*Loc.F, Record, Idx);
5377 unsigned NumElements = Record[1];
5378 unsigned VecKind = Record[2];
5379 return Context.getVectorType(ElementType, NumElements,
5380 (VectorType::VectorKind)VecKind);
5381 }
5382
5383 case TYPE_EXT_VECTOR: {
5384 if (Record.size() != 3) {
5385 Error("incorrect encoding of extended vector type in AST file");
5386 return QualType();
5387 }
5388
5389 QualType ElementType = readType(*Loc.F, Record, Idx);
5390 unsigned NumElements = Record[1];
5391 return Context.getExtVectorType(ElementType, NumElements);
5392 }
5393
5394 case TYPE_FUNCTION_NO_PROTO: {
5395 if (Record.size() != 6) {
5396 Error("incorrect encoding of no-proto function type");
5397 return QualType();
5398 }
5399 QualType ResultType = readType(*Loc.F, Record, Idx);
5400 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5401 (CallingConv)Record[4], Record[5]);
5402 return Context.getFunctionNoProtoType(ResultType, Info);
5403 }
5404
5405 case TYPE_FUNCTION_PROTO: {
5406 QualType ResultType = readType(*Loc.F, Record, Idx);
5407
5408 FunctionProtoType::ExtProtoInfo EPI;
5409 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5410 /*hasregparm*/ Record[2],
5411 /*regparm*/ Record[3],
5412 static_cast<CallingConv>(Record[4]),
5413 /*produces*/ Record[5]);
5414
5415 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005416
5417 EPI.Variadic = Record[Idx++];
5418 EPI.HasTrailingReturn = Record[Idx++];
5419 EPI.TypeQuals = Record[Idx++];
5420 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005421 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005422 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005423
5424 unsigned NumParams = Record[Idx++];
5425 SmallVector<QualType, 16> ParamTypes;
5426 for (unsigned I = 0; I != NumParams; ++I)
5427 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5428
Jordan Rose5c382722013-03-08 21:51:21 +00005429 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005430 }
5431
5432 case TYPE_UNRESOLVED_USING: {
5433 unsigned Idx = 0;
5434 return Context.getTypeDeclType(
5435 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5436 }
5437
5438 case TYPE_TYPEDEF: {
5439 if (Record.size() != 2) {
5440 Error("incorrect encoding of typedef type");
5441 return QualType();
5442 }
5443 unsigned Idx = 0;
5444 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5445 QualType Canonical = readType(*Loc.F, Record, Idx);
5446 if (!Canonical.isNull())
5447 Canonical = Context.getCanonicalType(Canonical);
5448 return Context.getTypedefType(Decl, Canonical);
5449 }
5450
5451 case TYPE_TYPEOF_EXPR:
5452 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5453
5454 case TYPE_TYPEOF: {
5455 if (Record.size() != 1) {
5456 Error("incorrect encoding of typeof(type) in AST file");
5457 return QualType();
5458 }
5459 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5460 return Context.getTypeOfType(UnderlyingType);
5461 }
5462
5463 case TYPE_DECLTYPE: {
5464 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5465 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5466 }
5467
5468 case TYPE_UNARY_TRANSFORM: {
5469 QualType BaseType = readType(*Loc.F, Record, Idx);
5470 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5471 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5472 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5473 }
5474
Richard Smith74aeef52013-04-26 16:15:35 +00005475 case TYPE_AUTO: {
5476 QualType Deduced = readType(*Loc.F, Record, Idx);
5477 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005478 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005479 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005480 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005481
5482 case TYPE_RECORD: {
5483 if (Record.size() != 2) {
5484 Error("incorrect encoding of record type");
5485 return QualType();
5486 }
5487 unsigned Idx = 0;
5488 bool IsDependent = Record[Idx++];
5489 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5490 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5491 QualType T = Context.getRecordType(RD);
5492 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5493 return T;
5494 }
5495
5496 case TYPE_ENUM: {
5497 if (Record.size() != 2) {
5498 Error("incorrect encoding of enum type");
5499 return QualType();
5500 }
5501 unsigned Idx = 0;
5502 bool IsDependent = Record[Idx++];
5503 QualType T
5504 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5505 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5506 return T;
5507 }
5508
5509 case TYPE_ATTRIBUTED: {
5510 if (Record.size() != 3) {
5511 Error("incorrect encoding of attributed type");
5512 return QualType();
5513 }
5514 QualType modifiedType = readType(*Loc.F, Record, Idx);
5515 QualType equivalentType = readType(*Loc.F, Record, Idx);
5516 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5517 return Context.getAttributedType(kind, modifiedType, equivalentType);
5518 }
5519
5520 case TYPE_PAREN: {
5521 if (Record.size() != 1) {
5522 Error("incorrect encoding of paren type");
5523 return QualType();
5524 }
5525 QualType InnerType = readType(*Loc.F, Record, Idx);
5526 return Context.getParenType(InnerType);
5527 }
5528
5529 case TYPE_PACK_EXPANSION: {
5530 if (Record.size() != 2) {
5531 Error("incorrect encoding of pack expansion type");
5532 return QualType();
5533 }
5534 QualType Pattern = readType(*Loc.F, Record, Idx);
5535 if (Pattern.isNull())
5536 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005537 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005538 if (Record[1])
5539 NumExpansions = Record[1] - 1;
5540 return Context.getPackExpansionType(Pattern, NumExpansions);
5541 }
5542
5543 case TYPE_ELABORATED: {
5544 unsigned Idx = 0;
5545 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5546 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5547 QualType NamedType = readType(*Loc.F, Record, Idx);
5548 return Context.getElaboratedType(Keyword, NNS, NamedType);
5549 }
5550
5551 case TYPE_OBJC_INTERFACE: {
5552 unsigned Idx = 0;
5553 ObjCInterfaceDecl *ItfD
5554 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5555 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5556 }
5557
5558 case TYPE_OBJC_OBJECT: {
5559 unsigned Idx = 0;
5560 QualType Base = readType(*Loc.F, Record, Idx);
5561 unsigned NumProtos = Record[Idx++];
5562 SmallVector<ObjCProtocolDecl*, 4> Protos;
5563 for (unsigned I = 0; I != NumProtos; ++I)
5564 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5565 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5566 }
5567
5568 case TYPE_OBJC_OBJECT_POINTER: {
5569 unsigned Idx = 0;
5570 QualType Pointee = readType(*Loc.F, Record, Idx);
5571 return Context.getObjCObjectPointerType(Pointee);
5572 }
5573
5574 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5575 unsigned Idx = 0;
5576 QualType Parm = readType(*Loc.F, Record, Idx);
5577 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005578 return Context.getSubstTemplateTypeParmType(
5579 cast<TemplateTypeParmType>(Parm),
5580 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005581 }
5582
5583 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5584 unsigned Idx = 0;
5585 QualType Parm = readType(*Loc.F, Record, Idx);
5586 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5587 return Context.getSubstTemplateTypeParmPackType(
5588 cast<TemplateTypeParmType>(Parm),
5589 ArgPack);
5590 }
5591
5592 case TYPE_INJECTED_CLASS_NAME: {
5593 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5594 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5595 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5596 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005597 const Type *T = nullptr;
5598 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5599 if (const Type *Existing = DI->getTypeForDecl()) {
5600 T = Existing;
5601 break;
5602 }
5603 }
5604 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005605 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005606 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5607 DI->setTypeForDecl(T);
5608 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005609 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005610 }
5611
5612 case TYPE_TEMPLATE_TYPE_PARM: {
5613 unsigned Idx = 0;
5614 unsigned Depth = Record[Idx++];
5615 unsigned Index = Record[Idx++];
5616 bool Pack = Record[Idx++];
5617 TemplateTypeParmDecl *D
5618 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5619 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5620 }
5621
5622 case TYPE_DEPENDENT_NAME: {
5623 unsigned Idx = 0;
5624 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5625 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5626 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5627 QualType Canon = readType(*Loc.F, Record, Idx);
5628 if (!Canon.isNull())
5629 Canon = Context.getCanonicalType(Canon);
5630 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5631 }
5632
5633 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5634 unsigned Idx = 0;
5635 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5636 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5637 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5638 unsigned NumArgs = Record[Idx++];
5639 SmallVector<TemplateArgument, 8> Args;
5640 Args.reserve(NumArgs);
5641 while (NumArgs--)
5642 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5643 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5644 Args.size(), Args.data());
5645 }
5646
5647 case TYPE_DEPENDENT_SIZED_ARRAY: {
5648 unsigned Idx = 0;
5649
5650 // ArrayType
5651 QualType ElementType = readType(*Loc.F, Record, Idx);
5652 ArrayType::ArraySizeModifier ASM
5653 = (ArrayType::ArraySizeModifier)Record[Idx++];
5654 unsigned IndexTypeQuals = Record[Idx++];
5655
5656 // DependentSizedArrayType
5657 Expr *NumElts = ReadExpr(*Loc.F);
5658 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5659
5660 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5661 IndexTypeQuals, Brackets);
5662 }
5663
5664 case TYPE_TEMPLATE_SPECIALIZATION: {
5665 unsigned Idx = 0;
5666 bool IsDependent = Record[Idx++];
5667 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5668 SmallVector<TemplateArgument, 8> Args;
5669 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5670 QualType Underlying = readType(*Loc.F, Record, Idx);
5671 QualType T;
5672 if (Underlying.isNull())
5673 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5674 Args.size());
5675 else
5676 T = Context.getTemplateSpecializationType(Name, Args.data(),
5677 Args.size(), Underlying);
5678 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5679 return T;
5680 }
5681
5682 case TYPE_ATOMIC: {
5683 if (Record.size() != 1) {
5684 Error("Incorrect encoding of atomic type");
5685 return QualType();
5686 }
5687 QualType ValueType = readType(*Loc.F, Record, Idx);
5688 return Context.getAtomicType(ValueType);
5689 }
5690 }
5691 llvm_unreachable("Invalid TypeCode!");
5692}
5693
Richard Smith564417a2014-03-20 21:47:22 +00005694void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5695 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005696 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005697 const RecordData &Record, unsigned &Idx) {
5698 ExceptionSpecificationType EST =
5699 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005700 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005701 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005702 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005703 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005704 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005705 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005706 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005707 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005708 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5709 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005710 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005711 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005712 }
5713}
5714
Guy Benyei11169dd2012-12-18 14:30:41 +00005715class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5716 ASTReader &Reader;
5717 ModuleFile &F;
5718 const ASTReader::RecordData &Record;
5719 unsigned &Idx;
5720
5721 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5722 unsigned &I) {
5723 return Reader.ReadSourceLocation(F, R, I);
5724 }
5725
5726 template<typename T>
5727 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5728 return Reader.ReadDeclAs<T>(F, Record, Idx);
5729 }
5730
5731public:
5732 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5733 const ASTReader::RecordData &Record, unsigned &Idx)
5734 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5735 { }
5736
5737 // We want compile-time assurance that we've enumerated all of
5738 // these, so unfortunately we have to declare them first, then
5739 // define them out-of-line.
5740#define ABSTRACT_TYPELOC(CLASS, PARENT)
5741#define TYPELOC(CLASS, PARENT) \
5742 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5743#include "clang/AST/TypeLocNodes.def"
5744
5745 void VisitFunctionTypeLoc(FunctionTypeLoc);
5746 void VisitArrayTypeLoc(ArrayTypeLoc);
5747};
5748
5749void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5750 // nothing to do
5751}
5752void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5753 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5754 if (TL.needsExtraLocalData()) {
5755 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5756 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5757 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5758 TL.setModeAttr(Record[Idx++]);
5759 }
5760}
5761void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5762 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5763}
5764void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5765 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5766}
Reid Kleckner8a365022013-06-24 17:51:48 +00005767void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5768 // nothing to do
5769}
Reid Kleckner0503a872013-12-05 01:23:43 +00005770void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5771 // nothing to do
5772}
Guy Benyei11169dd2012-12-18 14:30:41 +00005773void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5774 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5775}
5776void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5777 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5778}
5779void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5780 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5781}
5782void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5783 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5784 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5785}
5786void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5787 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5788 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5789 if (Record[Idx++])
5790 TL.setSizeExpr(Reader.ReadExpr(F));
5791 else
Craig Toppera13603a2014-05-22 05:54:18 +00005792 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005793}
5794void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5795 VisitArrayTypeLoc(TL);
5796}
5797void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5798 VisitArrayTypeLoc(TL);
5799}
5800void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5801 VisitArrayTypeLoc(TL);
5802}
5803void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5804 DependentSizedArrayTypeLoc TL) {
5805 VisitArrayTypeLoc(TL);
5806}
5807void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5808 DependentSizedExtVectorTypeLoc TL) {
5809 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5810}
5811void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5812 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5813}
5814void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5815 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5816}
5817void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5818 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5819 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5820 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5821 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005822 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5823 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005824 }
5825}
5826void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5827 VisitFunctionTypeLoc(TL);
5828}
5829void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5830 VisitFunctionTypeLoc(TL);
5831}
5832void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5833 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5834}
5835void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5836 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5837}
5838void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5839 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5840 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5841 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5842}
5843void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5844 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5845 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5846 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5847 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5848}
5849void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5850 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5851}
5852void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5853 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5854 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5855 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5856 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5857}
5858void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5859 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5860}
5861void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5862 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5863}
5864void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5865 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5866}
5867void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5868 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5869 if (TL.hasAttrOperand()) {
5870 SourceRange range;
5871 range.setBegin(ReadSourceLocation(Record, Idx));
5872 range.setEnd(ReadSourceLocation(Record, Idx));
5873 TL.setAttrOperandParensRange(range);
5874 }
5875 if (TL.hasAttrExprOperand()) {
5876 if (Record[Idx++])
5877 TL.setAttrExprOperand(Reader.ReadExpr(F));
5878 else
Craig Toppera13603a2014-05-22 05:54:18 +00005879 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005880 } else if (TL.hasAttrEnumOperand())
5881 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5882}
5883void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5884 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5885}
5886void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5887 SubstTemplateTypeParmTypeLoc TL) {
5888 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5889}
5890void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5891 SubstTemplateTypeParmPackTypeLoc TL) {
5892 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5893}
5894void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5895 TemplateSpecializationTypeLoc TL) {
5896 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5897 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5898 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5899 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5900 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5901 TL.setArgLocInfo(i,
5902 Reader.GetTemplateArgumentLocInfo(F,
5903 TL.getTypePtr()->getArg(i).getKind(),
5904 Record, Idx));
5905}
5906void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5907 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5908 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5909}
5910void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5911 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5912 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5913}
5914void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5915 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5916}
5917void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5918 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5919 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5920 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5921}
5922void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5923 DependentTemplateSpecializationTypeLoc TL) {
5924 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5925 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5926 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5927 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5928 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5929 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5930 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5931 TL.setArgLocInfo(I,
5932 Reader.GetTemplateArgumentLocInfo(F,
5933 TL.getTypePtr()->getArg(I).getKind(),
5934 Record, Idx));
5935}
5936void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5937 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5938}
5939void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5940 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5941}
5942void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5943 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5944 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5945 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5946 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5947 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5948}
5949void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5950 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5951}
5952void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5953 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5954 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5955 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5956}
5957
5958TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5959 const RecordData &Record,
5960 unsigned &Idx) {
5961 QualType InfoTy = readType(F, Record, Idx);
5962 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005963 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005964
5965 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5966 TypeLocReader TLR(*this, F, Record, Idx);
5967 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5968 TLR.Visit(TL);
5969 return TInfo;
5970}
5971
5972QualType ASTReader::GetType(TypeID ID) {
5973 unsigned FastQuals = ID & Qualifiers::FastMask;
5974 unsigned Index = ID >> Qualifiers::FastWidth;
5975
5976 if (Index < NUM_PREDEF_TYPE_IDS) {
5977 QualType T;
5978 switch ((PredefinedTypeIDs)Index) {
5979 case PREDEF_TYPE_NULL_ID: return QualType();
5980 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5981 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5982
5983 case PREDEF_TYPE_CHAR_U_ID:
5984 case PREDEF_TYPE_CHAR_S_ID:
5985 // FIXME: Check that the signedness of CharTy is correct!
5986 T = Context.CharTy;
5987 break;
5988
5989 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5990 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5991 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5992 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5993 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5994 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5995 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5996 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5997 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5998 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5999 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
6000 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
6001 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
6002 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
6003 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
6004 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
6005 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
6006 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
6007 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
6008 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
6009 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
6010 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
6011 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
6012 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
6013 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
6014 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
6015 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
6016 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00006017 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
6018 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
6019 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
6020 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
6021 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
6022 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00006023 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006024 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006025 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
6026
6027 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6028 T = Context.getAutoRRefDeductType();
6029 break;
6030
6031 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6032 T = Context.ARCUnbridgedCastTy;
6033 break;
6034
6035 case PREDEF_TYPE_VA_LIST_TAG:
6036 T = Context.getVaListTagType();
6037 break;
6038
6039 case PREDEF_TYPE_BUILTIN_FN:
6040 T = Context.BuiltinFnTy;
6041 break;
6042 }
6043
6044 assert(!T.isNull() && "Unknown predefined type");
6045 return T.withFastQualifiers(FastQuals);
6046 }
6047
6048 Index -= NUM_PREDEF_TYPE_IDS;
6049 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6050 if (TypesLoaded[Index].isNull()) {
6051 TypesLoaded[Index] = readTypeRecord(Index);
6052 if (TypesLoaded[Index].isNull())
6053 return QualType();
6054
6055 TypesLoaded[Index]->setFromAST();
6056 if (DeserializationListener)
6057 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6058 TypesLoaded[Index]);
6059 }
6060
6061 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6062}
6063
6064QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6065 return GetType(getGlobalTypeID(F, LocalID));
6066}
6067
6068serialization::TypeID
6069ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6070 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6071 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6072
6073 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6074 return LocalID;
6075
6076 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6077 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6078 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6079
6080 unsigned GlobalIndex = LocalIndex + I->second;
6081 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6082}
6083
6084TemplateArgumentLocInfo
6085ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6086 TemplateArgument::ArgKind Kind,
6087 const RecordData &Record,
6088 unsigned &Index) {
6089 switch (Kind) {
6090 case TemplateArgument::Expression:
6091 return ReadExpr(F);
6092 case TemplateArgument::Type:
6093 return GetTypeSourceInfo(F, Record, Index);
6094 case TemplateArgument::Template: {
6095 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6096 Index);
6097 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6098 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6099 SourceLocation());
6100 }
6101 case TemplateArgument::TemplateExpansion: {
6102 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6103 Index);
6104 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6105 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6106 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6107 EllipsisLoc);
6108 }
6109 case TemplateArgument::Null:
6110 case TemplateArgument::Integral:
6111 case TemplateArgument::Declaration:
6112 case TemplateArgument::NullPtr:
6113 case TemplateArgument::Pack:
6114 // FIXME: Is this right?
6115 return TemplateArgumentLocInfo();
6116 }
6117 llvm_unreachable("unexpected template argument loc");
6118}
6119
6120TemplateArgumentLoc
6121ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6122 const RecordData &Record, unsigned &Index) {
6123 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6124
6125 if (Arg.getKind() == TemplateArgument::Expression) {
6126 if (Record[Index++]) // bool InfoHasSameExpr.
6127 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6128 }
6129 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6130 Record, Index));
6131}
6132
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006133const ASTTemplateArgumentListInfo*
6134ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6135 const RecordData &Record,
6136 unsigned &Index) {
6137 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6138 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6139 unsigned NumArgsAsWritten = Record[Index++];
6140 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6141 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6142 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6143 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6144}
6145
Guy Benyei11169dd2012-12-18 14:30:41 +00006146Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6147 return GetDecl(ID);
6148}
6149
Richard Smith50895422015-01-31 03:04:55 +00006150template<typename TemplateSpecializationDecl>
6151static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6152 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6153 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6154}
6155
Richard Smith053f6c62014-05-16 23:01:30 +00006156void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006157 if (NumCurrentElementsDeserializing) {
6158 // We arrange to not care about the complete redeclaration chain while we're
6159 // deserializing. Just remember that the AST has marked this one as complete
6160 // but that it's not actually complete yet, so we know we still need to
6161 // complete it later.
6162 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6163 return;
6164 }
6165
Richard Smith053f6c62014-05-16 23:01:30 +00006166 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6167
Richard Smith053f6c62014-05-16 23:01:30 +00006168 // If this is a named declaration, complete it by looking it up
6169 // within its context.
6170 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006171 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006172 // all mergeable entities within it.
6173 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6174 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6175 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6176 auto *II = Name.getAsIdentifierInfo();
6177 if (isa<TranslationUnitDecl>(DC) && II) {
6178 // Outside of C++, we don't have a lookup table for the TU, so update
6179 // the identifier instead. In C++, either way should work fine.
6180 if (II->isOutOfDate())
6181 updateOutOfDateIdentifier(*II);
6182 } else
6183 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006184 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6185 // FIXME: It'd be nice to do something a bit more targeted here.
6186 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00006187 }
6188 }
Richard Smith50895422015-01-31 03:04:55 +00006189
6190 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6191 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6192 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6193 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6194 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6195 if (auto *Template = FD->getPrimaryTemplate())
6196 Template->LoadLazySpecializations();
6197 }
Richard Smith053f6c62014-05-16 23:01:30 +00006198}
6199
Richard Smithc2bb8182015-03-24 06:36:48 +00006200uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
6201 const RecordData &Record,
6202 unsigned &Idx) {
6203 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
6204 Error("malformed AST file: missing C++ ctor initializers");
6205 return 0;
6206 }
6207
6208 unsigned LocalID = Record[Idx++];
6209 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6210}
6211
6212CXXCtorInitializer **
6213ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6214 RecordLocation Loc = getLocalBitOffset(Offset);
6215 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6216 SavedStreamPosition SavedPosition(Cursor);
6217 Cursor.JumpToBit(Loc.Offset);
6218 ReadingKindTracker ReadingKind(Read_Decl, *this);
6219
6220 RecordData Record;
6221 unsigned Code = Cursor.ReadCode();
6222 unsigned RecCode = Cursor.readRecord(Code, Record);
6223 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6224 Error("malformed AST file: missing C++ ctor initializers");
6225 return nullptr;
6226 }
6227
6228 unsigned Idx = 0;
6229 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6230}
6231
Richard Smithcd45dbc2014-04-19 03:48:30 +00006232uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6233 const RecordData &Record,
6234 unsigned &Idx) {
6235 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6236 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006237 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006238 }
6239
Guy Benyei11169dd2012-12-18 14:30:41 +00006240 unsigned LocalID = Record[Idx++];
6241 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6242}
6243
6244CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6245 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006246 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006247 SavedStreamPosition SavedPosition(Cursor);
6248 Cursor.JumpToBit(Loc.Offset);
6249 ReadingKindTracker ReadingKind(Read_Decl, *this);
6250 RecordData Record;
6251 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006252 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006253 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006254 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006255 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006256 }
6257
6258 unsigned Idx = 0;
6259 unsigned NumBases = Record[Idx++];
6260 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6261 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6262 for (unsigned I = 0; I != NumBases; ++I)
6263 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6264 return Bases;
6265}
6266
6267serialization::DeclID
6268ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6269 if (LocalID < NUM_PREDEF_DECL_IDS)
6270 return LocalID;
6271
6272 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6273 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6274 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6275
6276 return LocalID + I->second;
6277}
6278
6279bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6280 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006281 // Predefined decls aren't from any module.
6282 if (ID < NUM_PREDEF_DECL_IDS)
6283 return false;
6284
Guy Benyei11169dd2012-12-18 14:30:41 +00006285 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6286 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6287 return &M == I->second;
6288}
6289
Douglas Gregor9f782892013-01-21 15:25:38 +00006290ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006291 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006292 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006293 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6294 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6295 return I->second;
6296}
6297
6298SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6299 if (ID < NUM_PREDEF_DECL_IDS)
6300 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006301
Guy Benyei11169dd2012-12-18 14:30:41 +00006302 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6303
6304 if (Index > DeclsLoaded.size()) {
6305 Error("declaration ID out-of-range for AST file");
6306 return SourceLocation();
6307 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006308
Guy Benyei11169dd2012-12-18 14:30:41 +00006309 if (Decl *D = DeclsLoaded[Index])
6310 return D->getLocation();
6311
6312 unsigned RawLocation = 0;
6313 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6314 return ReadSourceLocation(*Rec.F, RawLocation);
6315}
6316
Richard Smithfe620d22015-03-05 23:24:12 +00006317static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6318 switch (ID) {
6319 case PREDEF_DECL_NULL_ID:
6320 return nullptr;
6321
6322 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6323 return Context.getTranslationUnitDecl();
6324
6325 case PREDEF_DECL_OBJC_ID_ID:
6326 return Context.getObjCIdDecl();
6327
6328 case PREDEF_DECL_OBJC_SEL_ID:
6329 return Context.getObjCSelDecl();
6330
6331 case PREDEF_DECL_OBJC_CLASS_ID:
6332 return Context.getObjCClassDecl();
6333
6334 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6335 return Context.getObjCProtocolDecl();
6336
6337 case PREDEF_DECL_INT_128_ID:
6338 return Context.getInt128Decl();
6339
6340 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6341 return Context.getUInt128Decl();
6342
6343 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6344 return Context.getObjCInstanceTypeDecl();
6345
6346 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6347 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006348
6349 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6350 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006351 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006352 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006353}
6354
Richard Smithcd45dbc2014-04-19 03:48:30 +00006355Decl *ASTReader::GetExistingDecl(DeclID ID) {
6356 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006357 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6358 if (D) {
6359 // Track that we have merged the declaration with ID \p ID into the
6360 // pre-existing predefined declaration \p D.
6361 auto &Merged = MergedDecls[D->getCanonicalDecl()];
6362 if (Merged.empty())
6363 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006364 }
Richard Smithfe620d22015-03-05 23:24:12 +00006365 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006366 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006367
Guy Benyei11169dd2012-12-18 14:30:41 +00006368 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6369
6370 if (Index >= DeclsLoaded.size()) {
6371 assert(0 && "declaration ID out-of-range for AST file");
6372 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006373 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006374 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006375
6376 return DeclsLoaded[Index];
6377}
6378
6379Decl *ASTReader::GetDecl(DeclID ID) {
6380 if (ID < NUM_PREDEF_DECL_IDS)
6381 return GetExistingDecl(ID);
6382
6383 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6384
6385 if (Index >= DeclsLoaded.size()) {
6386 assert(0 && "declaration ID out-of-range for AST file");
6387 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006388 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006389 }
6390
Guy Benyei11169dd2012-12-18 14:30:41 +00006391 if (!DeclsLoaded[Index]) {
6392 ReadDeclRecord(ID);
6393 if (DeserializationListener)
6394 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6395 }
6396
6397 return DeclsLoaded[Index];
6398}
6399
6400DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6401 DeclID GlobalID) {
6402 if (GlobalID < NUM_PREDEF_DECL_IDS)
6403 return GlobalID;
6404
6405 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6406 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6407 ModuleFile *Owner = I->second;
6408
6409 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6410 = M.GlobalToLocalDeclIDs.find(Owner);
6411 if (Pos == M.GlobalToLocalDeclIDs.end())
6412 return 0;
6413
6414 return GlobalID - Owner->BaseDeclID + Pos->second;
6415}
6416
6417serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6418 const RecordData &Record,
6419 unsigned &Idx) {
6420 if (Idx >= Record.size()) {
6421 Error("Corrupted AST file");
6422 return 0;
6423 }
6424
6425 return getGlobalDeclID(F, Record[Idx++]);
6426}
6427
6428/// \brief Resolve the offset of a statement into a statement.
6429///
6430/// This operation will read a new statement from the external
6431/// source each time it is called, and is meant to be used via a
6432/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6433Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6434 // Switch case IDs are per Decl.
6435 ClearSwitchCaseIDs();
6436
6437 // Offset here is a global offset across the entire chain.
6438 RecordLocation Loc = getLocalBitOffset(Offset);
6439 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6440 return ReadStmtFromStream(*Loc.F);
6441}
6442
6443namespace {
6444 class FindExternalLexicalDeclsVisitor {
6445 ASTReader &Reader;
6446 const DeclContext *DC;
6447 bool (*isKindWeWant)(Decl::Kind);
6448
6449 SmallVectorImpl<Decl*> &Decls;
6450 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6451
6452 public:
6453 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6454 bool (*isKindWeWant)(Decl::Kind),
6455 SmallVectorImpl<Decl*> &Decls)
6456 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6457 {
6458 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6459 PredefsVisited[I] = false;
6460 }
6461
6462 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6463 if (Preorder)
6464 return false;
6465
6466 FindExternalLexicalDeclsVisitor *This
6467 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6468
6469 ModuleFile::DeclContextInfosMap::iterator Info
6470 = M.DeclContextInfos.find(This->DC);
6471 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6472 return false;
6473
6474 // Load all of the declaration IDs
6475 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6476 *IDE = ID + Info->second.NumLexicalDecls;
6477 ID != IDE; ++ID) {
6478 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6479 continue;
6480
6481 // Don't add predefined declarations to the lexical context more
6482 // than once.
6483 if (ID->second < NUM_PREDEF_DECL_IDS) {
6484 if (This->PredefsVisited[ID->second])
6485 continue;
6486
6487 This->PredefsVisited[ID->second] = true;
6488 }
6489
6490 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6491 if (!This->DC->isDeclInLexicalTraversal(D))
6492 This->Decls.push_back(D);
6493 }
6494 }
6495
6496 return false;
6497 }
6498 };
6499}
6500
6501ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6502 bool (*isKindWeWant)(Decl::Kind),
6503 SmallVectorImpl<Decl*> &Decls) {
6504 // There might be lexical decls in multiple modules, for the TU at
6505 // least. Walk all of the modules in the order they were loaded.
6506 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6507 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6508 ++NumLexicalDeclContextsRead;
6509 return ELR_Success;
6510}
6511
6512namespace {
6513
6514class DeclIDComp {
6515 ASTReader &Reader;
6516 ModuleFile &Mod;
6517
6518public:
6519 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6520
6521 bool operator()(LocalDeclID L, LocalDeclID R) const {
6522 SourceLocation LHS = getLocation(L);
6523 SourceLocation RHS = getLocation(R);
6524 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6525 }
6526
6527 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6528 SourceLocation RHS = getLocation(R);
6529 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6530 }
6531
6532 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6533 SourceLocation LHS = getLocation(L);
6534 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6535 }
6536
6537 SourceLocation getLocation(LocalDeclID ID) const {
6538 return Reader.getSourceManager().getFileLoc(
6539 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6540 }
6541};
6542
6543}
6544
6545void ASTReader::FindFileRegionDecls(FileID File,
6546 unsigned Offset, unsigned Length,
6547 SmallVectorImpl<Decl *> &Decls) {
6548 SourceManager &SM = getSourceManager();
6549
6550 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6551 if (I == FileDeclIDs.end())
6552 return;
6553
6554 FileDeclsInfo &DInfo = I->second;
6555 if (DInfo.Decls.empty())
6556 return;
6557
6558 SourceLocation
6559 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6560 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6561
6562 DeclIDComp DIDComp(*this, *DInfo.Mod);
6563 ArrayRef<serialization::LocalDeclID>::iterator
6564 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6565 BeginLoc, DIDComp);
6566 if (BeginIt != DInfo.Decls.begin())
6567 --BeginIt;
6568
6569 // If we are pointing at a top-level decl inside an objc container, we need
6570 // to backtrack until we find it otherwise we will fail to report that the
6571 // region overlaps with an objc container.
6572 while (BeginIt != DInfo.Decls.begin() &&
6573 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6574 ->isTopLevelDeclInObjCContainer())
6575 --BeginIt;
6576
6577 ArrayRef<serialization::LocalDeclID>::iterator
6578 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6579 EndLoc, DIDComp);
6580 if (EndIt != DInfo.Decls.end())
6581 ++EndIt;
6582
6583 for (ArrayRef<serialization::LocalDeclID>::iterator
6584 DIt = BeginIt; DIt != EndIt; ++DIt)
6585 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6586}
6587
6588namespace {
6589 /// \brief ModuleFile visitor used to perform name lookup into a
6590 /// declaration context.
6591 class DeclContextNameLookupVisitor {
6592 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006593 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006594 DeclarationName Name;
6595 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006596 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006597
6598 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006599 DeclContextNameLookupVisitor(ASTReader &Reader,
6600 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006601 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006602 SmallVectorImpl<NamedDecl *> &Decls,
6603 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
6604 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls),
6605 DeclSet(DeclSet) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006606
6607 static bool visit(ModuleFile &M, void *UserData) {
6608 DeclContextNameLookupVisitor *This
6609 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6610
6611 // Check whether we have any visible declaration information for
6612 // this context in this module.
6613 ModuleFile::DeclContextInfosMap::iterator Info;
6614 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006615 for (auto *DC : This->Contexts) {
6616 Info = M.DeclContextInfos.find(DC);
6617 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006618 Info->second.NameLookupTableData) {
6619 FoundInfo = true;
6620 break;
6621 }
6622 }
6623
6624 if (!FoundInfo)
6625 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006626
Guy Benyei11169dd2012-12-18 14:30:41 +00006627 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006628 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006629 Info->second.NameLookupTableData;
6630 ASTDeclContextNameLookupTable::iterator Pos
6631 = LookupTable->find(This->Name);
6632 if (Pos == LookupTable->end())
6633 return false;
6634
6635 bool FoundAnything = false;
6636 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6637 for (; Data.first != Data.second; ++Data.first) {
6638 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6639 if (!ND)
6640 continue;
6641
6642 if (ND->getDeclName() != This->Name) {
6643 // A name might be null because the decl's redeclarable part is
6644 // currently read before reading its name. The lookup is triggered by
6645 // building that decl (likely indirectly), and so it is later in the
6646 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006647 // FIXME: This should not happen; deserializing declarations should
6648 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006649 continue;
6650 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006651
Guy Benyei11169dd2012-12-18 14:30:41 +00006652 // Record this declaration.
6653 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006654 if (This->DeclSet.insert(ND).second)
6655 This->Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006656 }
6657
6658 return FoundAnything;
6659 }
6660 };
6661}
6662
Douglas Gregor9f782892013-01-21 15:25:38 +00006663/// \brief Retrieve the "definitive" module file for the definition of the
6664/// given declaration context, if there is one.
6665///
6666/// The "definitive" module file is the only place where we need to look to
6667/// find information about the declarations within the given declaration
6668/// context. For example, C++ and Objective-C classes, C structs/unions, and
6669/// Objective-C protocols, categories, and extensions are all defined in a
6670/// single place in the source code, so they have definitive module files
6671/// associated with them. C++ namespaces, on the other hand, can have
6672/// definitions in multiple different module files.
6673///
6674/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6675/// NDEBUG checking.
6676static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6677 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006678 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6679 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006680
Craig Toppera13603a2014-05-22 05:54:18 +00006681 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006682}
6683
Richard Smith9ce12e32013-02-07 03:30:24 +00006684bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006685ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6686 DeclarationName Name) {
6687 assert(DC->hasExternalVisibleStorage() &&
6688 "DeclContext has no visible decls in storage");
6689 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006690 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006691
Richard Smith8c913ec2014-08-14 02:21:01 +00006692 Deserializing LookupResults(this);
6693
Guy Benyei11169dd2012-12-18 14:30:41 +00006694 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006695 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006696
Guy Benyei11169dd2012-12-18 14:30:41 +00006697 // Compute the declaration contexts we need to look into. Multiple such
6698 // declaration contexts occur when two declaration contexts from disjoint
6699 // modules get merged, e.g., when two namespaces with the same name are
6700 // independently defined in separate modules.
6701 SmallVector<const DeclContext *, 2> Contexts;
6702 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006703
Guy Benyei11169dd2012-12-18 14:30:41 +00006704 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006705 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006706 if (Merged != MergedDecls.end()) {
6707 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6708 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6709 }
6710 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006711
6712 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
Richard Smith52874ec2015-02-13 20:17:14 +00006713 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006714
6715 // If we can definitively determine which module file to look into,
6716 // only look there. Otherwise, look in all module files.
6717 ModuleFile *Definitive;
6718 if (Contexts.size() == 1 &&
6719 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6720 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6721 } else {
6722 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6723 }
6724 };
6725
6726 LookUpInContexts(Contexts);
6727
6728 // If this might be an implicit special member function, then also search
6729 // all merged definitions of the surrounding class. We need to search them
6730 // individually, because finding an entity in one of them doesn't imply that
6731 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006732 if (isa<CXXRecordDecl>(DC)) {
Richard Smith8c913ec2014-08-14 02:21:01 +00006733 auto Kind = Name.getNameKind();
6734 if (Kind == DeclarationName::CXXConstructorName ||
6735 Kind == DeclarationName::CXXDestructorName ||
6736 (Kind == DeclarationName::CXXOperatorName &&
6737 Name.getCXXOverloadedOperator() == OO_Equal)) {
6738 auto Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006739 if (Merged != MergedLookups.end()) {
6740 for (unsigned I = 0; I != Merged->second.size(); ++I) {
Daniel Jasperc0b7c802015-02-18 14:13:46 +00006741 const DeclContext *Context = Merged->second[I];
6742 LookUpInContexts(Context);
Richard Smithe0612472014-11-21 05:16:13 +00006743 // We might have just added some more merged lookups. If so, our
6744 // iterator is now invalid, so grab a fresh one before continuing.
6745 Merged = MergedLookups.find(DC);
6746 }
6747 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006748 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006749 }
6750
Guy Benyei11169dd2012-12-18 14:30:41 +00006751 ++NumVisibleDeclContextsRead;
6752 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006753 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006754}
6755
6756namespace {
6757 /// \brief ModuleFile visitor used to retrieve all visible names in a
6758 /// declaration context.
6759 class DeclContextAllNamesVisitor {
6760 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006761 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006762 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006763 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006764 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006765
6766 public:
6767 DeclContextAllNamesVisitor(ASTReader &Reader,
6768 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006769 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006770 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006771
6772 static bool visit(ModuleFile &M, void *UserData) {
6773 DeclContextAllNamesVisitor *This
6774 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6775
6776 // Check whether we have any visible declaration information for
6777 // this context in this module.
6778 ModuleFile::DeclContextInfosMap::iterator Info;
6779 bool FoundInfo = false;
6780 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6781 Info = M.DeclContextInfos.find(This->Contexts[I]);
6782 if (Info != M.DeclContextInfos.end() &&
6783 Info->second.NameLookupTableData) {
6784 FoundInfo = true;
6785 break;
6786 }
6787 }
6788
6789 if (!FoundInfo)
6790 return false;
6791
Richard Smith52e3fba2014-03-11 07:17:35 +00006792 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006793 Info->second.NameLookupTableData;
6794 bool FoundAnything = false;
6795 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006796 I = LookupTable->data_begin(), E = LookupTable->data_end();
6797 I != E;
6798 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006799 ASTDeclContextNameLookupTrait::data_type Data = *I;
6800 for (; Data.first != Data.second; ++Data.first) {
6801 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6802 *Data.first);
6803 if (!ND)
6804 continue;
6805
6806 // Record this declaration.
6807 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006808 if (This->DeclSet.insert(ND).second)
6809 This->Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006810 }
6811 }
6812
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006813 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006814 }
6815 };
6816}
6817
6818void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6819 if (!DC->hasExternalVisibleStorage())
6820 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006821 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006822
6823 // Compute the declaration contexts we need to look into. Multiple such
6824 // declaration contexts occur when two declaration contexts from disjoint
6825 // modules get merged, e.g., when two namespaces with the same name are
6826 // independently defined in separate modules.
6827 SmallVector<const DeclContext *, 2> Contexts;
6828 Contexts.push_back(DC);
6829
6830 if (DC->isNamespace()) {
6831 MergedDeclsMap::iterator Merged
6832 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6833 if (Merged != MergedDecls.end()) {
6834 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6835 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6836 }
6837 }
6838
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006839 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6840 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006841 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6842 ++NumVisibleDeclContextsRead;
6843
Craig Topper79be4cd2013-07-05 04:33:53 +00006844 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006845 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6846 }
6847 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6848}
6849
6850/// \brief Under non-PCH compilation the consumer receives the objc methods
6851/// before receiving the implementation, and codegen depends on this.
6852/// We simulate this by deserializing and passing to consumer the methods of the
6853/// implementation before passing the deserialized implementation decl.
6854static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6855 ASTConsumer *Consumer) {
6856 assert(ImplD && Consumer);
6857
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006858 for (auto *I : ImplD->methods())
6859 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006860
6861 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6862}
6863
6864void ASTReader::PassInterestingDeclsToConsumer() {
6865 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006866
6867 if (PassingDeclsToConsumer)
6868 return;
6869
6870 // Guard variable to avoid recursively redoing the process of passing
6871 // decls to consumer.
6872 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6873 true);
6874
Richard Smith9e2341d2015-03-23 03:25:59 +00006875 // Ensure that we've loaded all potentially-interesting declarations
6876 // that need to be eagerly loaded.
6877 for (auto ID : EagerlyDeserializedDecls)
6878 GetDecl(ID);
6879 EagerlyDeserializedDecls.clear();
6880
Guy Benyei11169dd2012-12-18 14:30:41 +00006881 while (!InterestingDecls.empty()) {
6882 Decl *D = InterestingDecls.front();
6883 InterestingDecls.pop_front();
6884
6885 PassInterestingDeclToConsumer(D);
6886 }
6887}
6888
6889void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6890 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6891 PassObjCImplDeclToConsumer(ImplD, Consumer);
6892 else
6893 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6894}
6895
6896void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6897 this->Consumer = Consumer;
6898
Richard Smith9e2341d2015-03-23 03:25:59 +00006899 if (Consumer)
6900 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006901
6902 if (DeserializationListener)
6903 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006904}
6905
6906void ASTReader::PrintStats() {
6907 std::fprintf(stderr, "*** AST File Statistics:\n");
6908
6909 unsigned NumTypesLoaded
6910 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6911 QualType());
6912 unsigned NumDeclsLoaded
6913 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006914 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006915 unsigned NumIdentifiersLoaded
6916 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6917 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006918 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006919 unsigned NumMacrosLoaded
6920 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6921 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006922 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006923 unsigned NumSelectorsLoaded
6924 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6925 SelectorsLoaded.end(),
6926 Selector());
6927
6928 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6929 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6930 NumSLocEntriesRead, TotalNumSLocEntries,
6931 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6932 if (!TypesLoaded.empty())
6933 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6934 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6935 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6936 if (!DeclsLoaded.empty())
6937 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6938 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6939 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6940 if (!IdentifiersLoaded.empty())
6941 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6942 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6943 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6944 if (!MacrosLoaded.empty())
6945 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6946 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6947 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6948 if (!SelectorsLoaded.empty())
6949 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6950 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6951 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6952 if (TotalNumStatements)
6953 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6954 NumStatementsRead, TotalNumStatements,
6955 ((float)NumStatementsRead/TotalNumStatements * 100));
6956 if (TotalNumMacros)
6957 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6958 NumMacrosRead, TotalNumMacros,
6959 ((float)NumMacrosRead/TotalNumMacros * 100));
6960 if (TotalLexicalDeclContexts)
6961 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6962 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6963 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6964 * 100));
6965 if (TotalVisibleDeclContexts)
6966 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6967 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6968 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6969 * 100));
6970 if (TotalNumMethodPoolEntries) {
6971 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6972 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6973 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6974 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006975 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006976 if (NumMethodPoolLookups) {
6977 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6978 NumMethodPoolHits, NumMethodPoolLookups,
6979 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6980 }
6981 if (NumMethodPoolTableLookups) {
6982 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6983 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6984 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6985 * 100.0));
6986 }
6987
Douglas Gregor00a50f72013-01-25 00:38:33 +00006988 if (NumIdentifierLookupHits) {
6989 std::fprintf(stderr,
6990 " %u / %u identifier table lookups succeeded (%f%%)\n",
6991 NumIdentifierLookupHits, NumIdentifierLookups,
6992 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6993 }
6994
Douglas Gregore060e572013-01-25 01:03:03 +00006995 if (GlobalIndex) {
6996 std::fprintf(stderr, "\n");
6997 GlobalIndex->printStats();
6998 }
6999
Guy Benyei11169dd2012-12-18 14:30:41 +00007000 std::fprintf(stderr, "\n");
7001 dump();
7002 std::fprintf(stderr, "\n");
7003}
7004
7005template<typename Key, typename ModuleFile, unsigned InitialCapacity>
7006static void
7007dumpModuleIDMap(StringRef Name,
7008 const ContinuousRangeMap<Key, ModuleFile *,
7009 InitialCapacity> &Map) {
7010 if (Map.begin() == Map.end())
7011 return;
7012
7013 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7014 llvm::errs() << Name << ":\n";
7015 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7016 I != IEnd; ++I) {
7017 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7018 << "\n";
7019 }
7020}
7021
7022void ASTReader::dump() {
7023 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7024 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7025 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7026 dumpModuleIDMap("Global type map", GlobalTypeMap);
7027 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7028 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7029 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7030 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7031 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
7032 dumpModuleIDMap("Global preprocessed entity map",
7033 GlobalPreprocessedEntityMap);
7034
7035 llvm::errs() << "\n*** PCH/Modules Loaded:";
7036 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
7037 MEnd = ModuleMgr.end();
7038 M != MEnd; ++M)
7039 (*M)->dump();
7040}
7041
7042/// Return the amount of memory used by memory buffers, breaking down
7043/// by heap-backed versus mmap'ed memory.
7044void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
7045 for (ModuleConstIterator I = ModuleMgr.begin(),
7046 E = ModuleMgr.end(); I != E; ++I) {
7047 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
7048 size_t bytes = buf->getBufferSize();
7049 switch (buf->getBufferKind()) {
7050 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7051 sizes.malloc_bytes += bytes;
7052 break;
7053 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7054 sizes.mmap_bytes += bytes;
7055 break;
7056 }
7057 }
7058 }
7059}
7060
7061void ASTReader::InitializeSema(Sema &S) {
7062 SemaObj = &S;
7063 S.addExternalSource(this);
7064
7065 // Makes sure any declarations that were deserialized "too early"
7066 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007067 for (uint64_t ID : PreloadedDeclIDs) {
7068 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7069 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007070 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007071 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007072
Richard Smith3d8e97e2013-10-18 06:54:39 +00007073 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007074 if (!FPPragmaOptions.empty()) {
7075 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7076 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7077 }
7078
Richard Smith3d8e97e2013-10-18 06:54:39 +00007079 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007080 if (!OpenCLExtensions.empty()) {
7081 unsigned I = 0;
7082#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
7083#include "clang/Basic/OpenCLExtensions.def"
7084
7085 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
7086 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00007087
7088 UpdateSema();
7089}
7090
7091void ASTReader::UpdateSema() {
7092 assert(SemaObj && "no Sema to update");
7093
7094 // Load the offsets of the declarations that Sema references.
7095 // They will be lazily deserialized when needed.
7096 if (!SemaDeclRefs.empty()) {
7097 assert(SemaDeclRefs.size() % 2 == 0);
7098 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
7099 if (!SemaObj->StdNamespace)
7100 SemaObj->StdNamespace = SemaDeclRefs[I];
7101 if (!SemaObj->StdBadAlloc)
7102 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
7103 }
7104 SemaDeclRefs.clear();
7105 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007106
7107 // Update the state of 'pragma clang optimize'. Use the same API as if we had
7108 // encountered the pragma in the source.
7109 if(OptimizeOffPragmaLocation.isValid())
7110 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00007111}
7112
7113IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
7114 // Note that we are loading an identifier.
7115 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007116 StringRef Name(NameStart, NameEnd - NameStart);
7117
7118 // If there is a global index, look there first to determine which modules
7119 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00007120 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00007121 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00007122 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00007123 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7124 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00007125 }
7126 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00007127 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007128 NumIdentifierLookups,
7129 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00007130 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007131 IdentifierInfo *II = Visitor.getIdentifierInfo();
7132 markIdentifierUpToDate(II);
7133 return II;
7134}
7135
7136namespace clang {
7137 /// \brief An identifier-lookup iterator that enumerates all of the
7138 /// identifiers stored within a set of AST files.
7139 class ASTIdentifierIterator : public IdentifierIterator {
7140 /// \brief The AST reader whose identifiers are being enumerated.
7141 const ASTReader &Reader;
7142
7143 /// \brief The current index into the chain of AST files stored in
7144 /// the AST reader.
7145 unsigned Index;
7146
7147 /// \brief The current position within the identifier lookup table
7148 /// of the current AST file.
7149 ASTIdentifierLookupTable::key_iterator Current;
7150
7151 /// \brief The end position within the identifier lookup table of
7152 /// the current AST file.
7153 ASTIdentifierLookupTable::key_iterator End;
7154
7155 public:
7156 explicit ASTIdentifierIterator(const ASTReader &Reader);
7157
Craig Topper3e89dfe2014-03-13 02:13:41 +00007158 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007159 };
7160}
7161
7162ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7163 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7164 ASTIdentifierLookupTable *IdTable
7165 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7166 Current = IdTable->key_begin();
7167 End = IdTable->key_end();
7168}
7169
7170StringRef ASTIdentifierIterator::Next() {
7171 while (Current == End) {
7172 // If we have exhausted all of our AST files, we're done.
7173 if (Index == 0)
7174 return StringRef();
7175
7176 --Index;
7177 ASTIdentifierLookupTable *IdTable
7178 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7179 IdentifierLookupTable;
7180 Current = IdTable->key_begin();
7181 End = IdTable->key_end();
7182 }
7183
7184 // We have any identifiers remaining in the current AST file; return
7185 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007186 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007187 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007188 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007189}
7190
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007191IdentifierIterator *ASTReader::getIdentifiers() {
7192 if (!loadGlobalIndex())
7193 return GlobalIndex->createIdentifierIterator();
7194
Guy Benyei11169dd2012-12-18 14:30:41 +00007195 return new ASTIdentifierIterator(*this);
7196}
7197
7198namespace clang { namespace serialization {
7199 class ReadMethodPoolVisitor {
7200 ASTReader &Reader;
7201 Selector Sel;
7202 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007203 unsigned InstanceBits;
7204 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007205 bool InstanceHasMoreThanOneDecl;
7206 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007207 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7208 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007209
7210 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007211 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007212 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007213 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007214 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7215 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007216
Guy Benyei11169dd2012-12-18 14:30:41 +00007217 static bool visit(ModuleFile &M, void *UserData) {
7218 ReadMethodPoolVisitor *This
7219 = static_cast<ReadMethodPoolVisitor *>(UserData);
7220
7221 if (!M.SelectorLookupTable)
7222 return false;
7223
7224 // If we've already searched this module file, skip it now.
7225 if (M.Generation <= This->PriorGeneration)
7226 return true;
7227
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007228 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007229 ASTSelectorLookupTable *PoolTable
7230 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7231 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
7232 if (Pos == PoolTable->end())
7233 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007234
7235 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007236 ++This->Reader.NumSelectorsRead;
7237 // FIXME: Not quite happy with the statistics here. We probably should
7238 // disable this tracking when called via LoadSelector.
7239 // Also, should entries without methods count as misses?
7240 ++This->Reader.NumMethodPoolEntriesRead;
7241 ASTSelectorLookupTrait::data_type Data = *Pos;
7242 if (This->Reader.DeserializationListener)
7243 This->Reader.DeserializationListener->SelectorRead(Data.ID,
7244 This->Sel);
7245
7246 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7247 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007248 This->InstanceBits = Data.InstanceBits;
7249 This->FactoryBits = Data.FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007250 This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7251 This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007252 return true;
7253 }
7254
7255 /// \brief Retrieve the instance methods found by this visitor.
7256 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7257 return InstanceMethods;
7258 }
7259
7260 /// \brief Retrieve the instance methods found by this visitor.
7261 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7262 return FactoryMethods;
7263 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007264
7265 unsigned getInstanceBits() const { return InstanceBits; }
7266 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007267 bool instanceHasMoreThanOneDecl() const {
7268 return InstanceHasMoreThanOneDecl;
7269 }
7270 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007271 };
7272} } // end namespace clang::serialization
7273
7274/// \brief Add the given set of methods to the method list.
7275static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7276 ObjCMethodList &List) {
7277 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7278 S.addMethodToGlobalList(&List, Methods[I]);
7279 }
7280}
7281
7282void ASTReader::ReadMethodPool(Selector Sel) {
7283 // Get the selector generation and update it to the current generation.
7284 unsigned &Generation = SelectorGeneration[Sel];
7285 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007286 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007287
7288 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007289 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007290 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7291 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7292
7293 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007294 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007295 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007296
7297 ++NumMethodPoolHits;
7298
Guy Benyei11169dd2012-12-18 14:30:41 +00007299 if (!getSema())
7300 return;
7301
7302 Sema &S = *getSema();
7303 Sema::GlobalMethodPool::iterator Pos
7304 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007305
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007306 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007307 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007308 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007309 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007310
7311 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7312 // when building a module we keep every method individually and may need to
7313 // update hasMoreThanOneDecl as we add the methods.
7314 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7315 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007316}
7317
7318void ASTReader::ReadKnownNamespaces(
7319 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7320 Namespaces.clear();
7321
7322 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7323 if (NamespaceDecl *Namespace
7324 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7325 Namespaces.push_back(Namespace);
7326 }
7327}
7328
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007329void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007330 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007331 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7332 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007333 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007334 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007335 Undefined.insert(std::make_pair(D, Loc));
7336 }
7337}
Nick Lewycky8334af82013-01-26 00:35:08 +00007338
Guy Benyei11169dd2012-12-18 14:30:41 +00007339void ASTReader::ReadTentativeDefinitions(
7340 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7341 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7342 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7343 if (Var)
7344 TentativeDefs.push_back(Var);
7345 }
7346 TentativeDefinitions.clear();
7347}
7348
7349void ASTReader::ReadUnusedFileScopedDecls(
7350 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7351 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7352 DeclaratorDecl *D
7353 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7354 if (D)
7355 Decls.push_back(D);
7356 }
7357 UnusedFileScopedDecls.clear();
7358}
7359
7360void ASTReader::ReadDelegatingConstructors(
7361 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7362 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7363 CXXConstructorDecl *D
7364 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7365 if (D)
7366 Decls.push_back(D);
7367 }
7368 DelegatingCtorDecls.clear();
7369}
7370
7371void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7372 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7373 TypedefNameDecl *D
7374 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7375 if (D)
7376 Decls.push_back(D);
7377 }
7378 ExtVectorDecls.clear();
7379}
7380
Nico Weber72889432014-09-06 01:25:55 +00007381void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7382 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7383 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7384 ++I) {
7385 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7386 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7387 if (D)
7388 Decls.insert(D);
7389 }
7390 UnusedLocalTypedefNameCandidates.clear();
7391}
7392
Guy Benyei11169dd2012-12-18 14:30:41 +00007393void ASTReader::ReadReferencedSelectors(
7394 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7395 if (ReferencedSelectorsData.empty())
7396 return;
7397
7398 // If there are @selector references added them to its pool. This is for
7399 // implementation of -Wselector.
7400 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7401 unsigned I = 0;
7402 while (I < DataSize) {
7403 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7404 SourceLocation SelLoc
7405 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7406 Sels.push_back(std::make_pair(Sel, SelLoc));
7407 }
7408 ReferencedSelectorsData.clear();
7409}
7410
7411void ASTReader::ReadWeakUndeclaredIdentifiers(
7412 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7413 if (WeakUndeclaredIdentifiers.empty())
7414 return;
7415
7416 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7417 IdentifierInfo *WeakId
7418 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7419 IdentifierInfo *AliasId
7420 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7421 SourceLocation Loc
7422 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7423 bool Used = WeakUndeclaredIdentifiers[I++];
7424 WeakInfo WI(AliasId, Loc);
7425 WI.setUsed(Used);
7426 WeakIDs.push_back(std::make_pair(WeakId, WI));
7427 }
7428 WeakUndeclaredIdentifiers.clear();
7429}
7430
7431void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7432 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7433 ExternalVTableUse VT;
7434 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7435 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7436 VT.DefinitionRequired = VTableUses[Idx++];
7437 VTables.push_back(VT);
7438 }
7439
7440 VTableUses.clear();
7441}
7442
7443void ASTReader::ReadPendingInstantiations(
7444 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7445 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7446 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7447 SourceLocation Loc
7448 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7449
7450 Pending.push_back(std::make_pair(D, Loc));
7451 }
7452 PendingInstantiations.clear();
7453}
7454
Richard Smithe40f2ba2013-08-07 21:41:30 +00007455void ASTReader::ReadLateParsedTemplates(
7456 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7457 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7458 /* In loop */) {
7459 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7460
7461 LateParsedTemplate *LT = new LateParsedTemplate;
7462 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7463
7464 ModuleFile *F = getOwningModuleFile(LT->D);
7465 assert(F && "No module");
7466
7467 unsigned TokN = LateParsedTemplates[Idx++];
7468 LT->Toks.reserve(TokN);
7469 for (unsigned T = 0; T < TokN; ++T)
7470 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7471
7472 LPTMap[FD] = LT;
7473 }
7474
7475 LateParsedTemplates.clear();
7476}
7477
Guy Benyei11169dd2012-12-18 14:30:41 +00007478void ASTReader::LoadSelector(Selector Sel) {
7479 // It would be complicated to avoid reading the methods anyway. So don't.
7480 ReadMethodPool(Sel);
7481}
7482
7483void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7484 assert(ID && "Non-zero identifier ID required");
7485 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7486 IdentifiersLoaded[ID - 1] = II;
7487 if (DeserializationListener)
7488 DeserializationListener->IdentifierRead(ID, II);
7489}
7490
7491/// \brief Set the globally-visible declarations associated with the given
7492/// identifier.
7493///
7494/// If the AST reader is currently in a state where the given declaration IDs
7495/// cannot safely be resolved, they are queued until it is safe to resolve
7496/// them.
7497///
7498/// \param II an IdentifierInfo that refers to one or more globally-visible
7499/// declarations.
7500///
7501/// \param DeclIDs the set of declaration IDs with the name @p II that are
7502/// visible at global scope.
7503///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007504/// \param Decls if non-null, this vector will be populated with the set of
7505/// deserialized declarations. These declarations will not be pushed into
7506/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007507void
7508ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7509 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007510 SmallVectorImpl<Decl *> *Decls) {
7511 if (NumCurrentElementsDeserializing && !Decls) {
7512 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007513 return;
7514 }
7515
7516 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007517 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007518 // Queue this declaration so that it will be added to the
7519 // translation unit scope and identifier's declaration chain
7520 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007521 PreloadedDeclIDs.push_back(DeclIDs[I]);
7522 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007523 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007524
7525 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7526
7527 // If we're simply supposed to record the declarations, do so now.
7528 if (Decls) {
7529 Decls->push_back(D);
7530 continue;
7531 }
7532
7533 // Introduce this declaration into the translation-unit scope
7534 // and add it to the declaration chain for this identifier, so
7535 // that (unqualified) name lookup will find it.
7536 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007537 }
7538}
7539
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007540IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007541 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007542 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007543
7544 if (IdentifiersLoaded.empty()) {
7545 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007546 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007547 }
7548
7549 ID -= 1;
7550 if (!IdentifiersLoaded[ID]) {
7551 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7552 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7553 ModuleFile *M = I->second;
7554 unsigned Index = ID - M->BaseIdentifierID;
7555 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7556
7557 // All of the strings in the AST file are preceded by a 16-bit length.
7558 // Extract that 16-bit length to avoid having to execute strlen().
7559 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7560 // unsigned integers. This is important to avoid integer overflow when
7561 // we cast them to 'unsigned'.
7562 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7563 unsigned StrLen = (((unsigned) StrLenPtr[0])
7564 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007565 IdentifiersLoaded[ID]
7566 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007567 if (DeserializationListener)
7568 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7569 }
7570
7571 return IdentifiersLoaded[ID];
7572}
7573
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007574IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7575 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007576}
7577
7578IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7579 if (LocalID < NUM_PREDEF_IDENT_IDS)
7580 return LocalID;
7581
7582 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7583 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7584 assert(I != M.IdentifierRemap.end()
7585 && "Invalid index into identifier index remap");
7586
7587 return LocalID + I->second;
7588}
7589
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007590MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007591 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007592 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007593
7594 if (MacrosLoaded.empty()) {
7595 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007596 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007597 }
7598
7599 ID -= NUM_PREDEF_MACRO_IDS;
7600 if (!MacrosLoaded[ID]) {
7601 GlobalMacroMapType::iterator I
7602 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7603 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7604 ModuleFile *M = I->second;
7605 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007606 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7607
7608 if (DeserializationListener)
7609 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7610 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007611 }
7612
7613 return MacrosLoaded[ID];
7614}
7615
7616MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7617 if (LocalID < NUM_PREDEF_MACRO_IDS)
7618 return LocalID;
7619
7620 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7621 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7622 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7623
7624 return LocalID + I->second;
7625}
7626
7627serialization::SubmoduleID
7628ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7629 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7630 return LocalID;
7631
7632 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7633 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7634 assert(I != M.SubmoduleRemap.end()
7635 && "Invalid index into submodule index remap");
7636
7637 return LocalID + I->second;
7638}
7639
7640Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7641 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7642 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007643 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007644 }
7645
7646 if (GlobalID > SubmodulesLoaded.size()) {
7647 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007648 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007649 }
7650
7651 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7652}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007653
7654Module *ASTReader::getModule(unsigned ID) {
7655 return getSubmodule(ID);
7656}
7657
Guy Benyei11169dd2012-12-18 14:30:41 +00007658Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7659 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7660}
7661
7662Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7663 if (ID == 0)
7664 return Selector();
7665
7666 if (ID > SelectorsLoaded.size()) {
7667 Error("selector ID out of range in AST file");
7668 return Selector();
7669 }
7670
Craig Toppera13603a2014-05-22 05:54:18 +00007671 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007672 // Load this selector from the selector table.
7673 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7674 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7675 ModuleFile &M = *I->second;
7676 ASTSelectorLookupTrait Trait(*this, M);
7677 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7678 SelectorsLoaded[ID - 1] =
7679 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7680 if (DeserializationListener)
7681 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7682 }
7683
7684 return SelectorsLoaded[ID - 1];
7685}
7686
7687Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7688 return DecodeSelector(ID);
7689}
7690
7691uint32_t ASTReader::GetNumExternalSelectors() {
7692 // ID 0 (the null selector) is considered an external selector.
7693 return getTotalNumSelectors() + 1;
7694}
7695
7696serialization::SelectorID
7697ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7698 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7699 return LocalID;
7700
7701 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7702 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7703 assert(I != M.SelectorRemap.end()
7704 && "Invalid index into selector index remap");
7705
7706 return LocalID + I->second;
7707}
7708
7709DeclarationName
7710ASTReader::ReadDeclarationName(ModuleFile &F,
7711 const RecordData &Record, unsigned &Idx) {
7712 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7713 switch (Kind) {
7714 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007715 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007716
7717 case DeclarationName::ObjCZeroArgSelector:
7718 case DeclarationName::ObjCOneArgSelector:
7719 case DeclarationName::ObjCMultiArgSelector:
7720 return DeclarationName(ReadSelector(F, Record, Idx));
7721
7722 case DeclarationName::CXXConstructorName:
7723 return Context.DeclarationNames.getCXXConstructorName(
7724 Context.getCanonicalType(readType(F, Record, Idx)));
7725
7726 case DeclarationName::CXXDestructorName:
7727 return Context.DeclarationNames.getCXXDestructorName(
7728 Context.getCanonicalType(readType(F, Record, Idx)));
7729
7730 case DeclarationName::CXXConversionFunctionName:
7731 return Context.DeclarationNames.getCXXConversionFunctionName(
7732 Context.getCanonicalType(readType(F, Record, Idx)));
7733
7734 case DeclarationName::CXXOperatorName:
7735 return Context.DeclarationNames.getCXXOperatorName(
7736 (OverloadedOperatorKind)Record[Idx++]);
7737
7738 case DeclarationName::CXXLiteralOperatorName:
7739 return Context.DeclarationNames.getCXXLiteralOperatorName(
7740 GetIdentifierInfo(F, Record, Idx));
7741
7742 case DeclarationName::CXXUsingDirective:
7743 return DeclarationName::getUsingDirectiveName();
7744 }
7745
7746 llvm_unreachable("Invalid NameKind!");
7747}
7748
7749void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7750 DeclarationNameLoc &DNLoc,
7751 DeclarationName Name,
7752 const RecordData &Record, unsigned &Idx) {
7753 switch (Name.getNameKind()) {
7754 case DeclarationName::CXXConstructorName:
7755 case DeclarationName::CXXDestructorName:
7756 case DeclarationName::CXXConversionFunctionName:
7757 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7758 break;
7759
7760 case DeclarationName::CXXOperatorName:
7761 DNLoc.CXXOperatorName.BeginOpNameLoc
7762 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7763 DNLoc.CXXOperatorName.EndOpNameLoc
7764 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7765 break;
7766
7767 case DeclarationName::CXXLiteralOperatorName:
7768 DNLoc.CXXLiteralOperatorName.OpNameLoc
7769 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7770 break;
7771
7772 case DeclarationName::Identifier:
7773 case DeclarationName::ObjCZeroArgSelector:
7774 case DeclarationName::ObjCOneArgSelector:
7775 case DeclarationName::ObjCMultiArgSelector:
7776 case DeclarationName::CXXUsingDirective:
7777 break;
7778 }
7779}
7780
7781void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7782 DeclarationNameInfo &NameInfo,
7783 const RecordData &Record, unsigned &Idx) {
7784 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7785 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7786 DeclarationNameLoc DNLoc;
7787 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7788 NameInfo.setInfo(DNLoc);
7789}
7790
7791void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7792 const RecordData &Record, unsigned &Idx) {
7793 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7794 unsigned NumTPLists = Record[Idx++];
7795 Info.NumTemplParamLists = NumTPLists;
7796 if (NumTPLists) {
7797 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7798 for (unsigned i=0; i != NumTPLists; ++i)
7799 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7800 }
7801}
7802
7803TemplateName
7804ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7805 unsigned &Idx) {
7806 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7807 switch (Kind) {
7808 case TemplateName::Template:
7809 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7810
7811 case TemplateName::OverloadedTemplate: {
7812 unsigned size = Record[Idx++];
7813 UnresolvedSet<8> Decls;
7814 while (size--)
7815 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7816
7817 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7818 }
7819
7820 case TemplateName::QualifiedTemplate: {
7821 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7822 bool hasTemplKeyword = Record[Idx++];
7823 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7824 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7825 }
7826
7827 case TemplateName::DependentTemplate: {
7828 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7829 if (Record[Idx++]) // isIdentifier
7830 return Context.getDependentTemplateName(NNS,
7831 GetIdentifierInfo(F, Record,
7832 Idx));
7833 return Context.getDependentTemplateName(NNS,
7834 (OverloadedOperatorKind)Record[Idx++]);
7835 }
7836
7837 case TemplateName::SubstTemplateTemplateParm: {
7838 TemplateTemplateParmDecl *param
7839 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7840 if (!param) return TemplateName();
7841 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7842 return Context.getSubstTemplateTemplateParm(param, replacement);
7843 }
7844
7845 case TemplateName::SubstTemplateTemplateParmPack: {
7846 TemplateTemplateParmDecl *Param
7847 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7848 if (!Param)
7849 return TemplateName();
7850
7851 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7852 if (ArgPack.getKind() != TemplateArgument::Pack)
7853 return TemplateName();
7854
7855 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7856 }
7857 }
7858
7859 llvm_unreachable("Unhandled template name kind!");
7860}
7861
7862TemplateArgument
7863ASTReader::ReadTemplateArgument(ModuleFile &F,
7864 const RecordData &Record, unsigned &Idx) {
7865 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7866 switch (Kind) {
7867 case TemplateArgument::Null:
7868 return TemplateArgument();
7869 case TemplateArgument::Type:
7870 return TemplateArgument(readType(F, Record, Idx));
7871 case TemplateArgument::Declaration: {
7872 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007873 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007874 }
7875 case TemplateArgument::NullPtr:
7876 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7877 case TemplateArgument::Integral: {
7878 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7879 QualType T = readType(F, Record, Idx);
7880 return TemplateArgument(Context, Value, T);
7881 }
7882 case TemplateArgument::Template:
7883 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7884 case TemplateArgument::TemplateExpansion: {
7885 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007886 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007887 if (unsigned NumExpansions = Record[Idx++])
7888 NumTemplateExpansions = NumExpansions - 1;
7889 return TemplateArgument(Name, NumTemplateExpansions);
7890 }
7891 case TemplateArgument::Expression:
7892 return TemplateArgument(ReadExpr(F));
7893 case TemplateArgument::Pack: {
7894 unsigned NumArgs = Record[Idx++];
7895 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7896 for (unsigned I = 0; I != NumArgs; ++I)
7897 Args[I] = ReadTemplateArgument(F, Record, Idx);
7898 return TemplateArgument(Args, NumArgs);
7899 }
7900 }
7901
7902 llvm_unreachable("Unhandled template argument kind!");
7903}
7904
7905TemplateParameterList *
7906ASTReader::ReadTemplateParameterList(ModuleFile &F,
7907 const RecordData &Record, unsigned &Idx) {
7908 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7909 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7910 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7911
7912 unsigned NumParams = Record[Idx++];
7913 SmallVector<NamedDecl *, 16> Params;
7914 Params.reserve(NumParams);
7915 while (NumParams--)
7916 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7917
7918 TemplateParameterList* TemplateParams =
7919 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7920 Params.data(), Params.size(), RAngleLoc);
7921 return TemplateParams;
7922}
7923
7924void
7925ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007926ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007927 ModuleFile &F, const RecordData &Record,
7928 unsigned &Idx) {
7929 unsigned NumTemplateArgs = Record[Idx++];
7930 TemplArgs.reserve(NumTemplateArgs);
7931 while (NumTemplateArgs--)
7932 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7933}
7934
7935/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007936void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007937 const RecordData &Record, unsigned &Idx) {
7938 unsigned NumDecls = Record[Idx++];
7939 Set.reserve(Context, NumDecls);
7940 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007941 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007942 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007943 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007944 }
7945}
7946
7947CXXBaseSpecifier
7948ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7949 const RecordData &Record, unsigned &Idx) {
7950 bool isVirtual = static_cast<bool>(Record[Idx++]);
7951 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7952 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7953 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7954 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7955 SourceRange Range = ReadSourceRange(F, Record, Idx);
7956 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7957 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7958 EllipsisLoc);
7959 Result.setInheritConstructors(inheritConstructors);
7960 return Result;
7961}
7962
Richard Smithc2bb8182015-03-24 06:36:48 +00007963CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007964ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7965 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007966 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007967 assert(NumInitializers && "wrote ctor initializers but have no inits");
7968 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7969 for (unsigned i = 0; i != NumInitializers; ++i) {
7970 TypeSourceInfo *TInfo = nullptr;
7971 bool IsBaseVirtual = false;
7972 FieldDecl *Member = nullptr;
7973 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007974
Richard Smithc2bb8182015-03-24 06:36:48 +00007975 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7976 switch (Type) {
7977 case CTOR_INITIALIZER_BASE:
7978 TInfo = GetTypeSourceInfo(F, Record, Idx);
7979 IsBaseVirtual = Record[Idx++];
7980 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007981
Richard Smithc2bb8182015-03-24 06:36:48 +00007982 case CTOR_INITIALIZER_DELEGATING:
7983 TInfo = GetTypeSourceInfo(F, Record, Idx);
7984 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007985
Richard Smithc2bb8182015-03-24 06:36:48 +00007986 case CTOR_INITIALIZER_MEMBER:
7987 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7988 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007989
Richard Smithc2bb8182015-03-24 06:36:48 +00007990 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7991 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7992 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007993 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007994
7995 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7996 Expr *Init = ReadExpr(F);
7997 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7998 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7999 bool IsWritten = Record[Idx++];
8000 unsigned SourceOrderOrNumArrayIndices;
8001 SmallVector<VarDecl *, 8> Indices;
8002 if (IsWritten) {
8003 SourceOrderOrNumArrayIndices = Record[Idx++];
8004 } else {
8005 SourceOrderOrNumArrayIndices = Record[Idx++];
8006 Indices.reserve(SourceOrderOrNumArrayIndices);
8007 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
8008 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
8009 }
8010
8011 CXXCtorInitializer *BOMInit;
8012 if (Type == CTOR_INITIALIZER_BASE) {
8013 BOMInit = new (Context)
8014 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8015 RParenLoc, MemberOrEllipsisLoc);
8016 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
8017 BOMInit = new (Context)
8018 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
8019 } else if (IsWritten) {
8020 if (Member)
8021 BOMInit = new (Context) CXXCtorInitializer(
8022 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
8023 else
8024 BOMInit = new (Context)
8025 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8026 LParenLoc, Init, RParenLoc);
8027 } else {
8028 if (IndirectMember) {
8029 assert(Indices.empty() && "Indirect field improperly initialized");
8030 BOMInit = new (Context)
8031 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8032 LParenLoc, Init, RParenLoc);
8033 } else {
8034 BOMInit = CXXCtorInitializer::Create(
8035 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
8036 Indices.data(), Indices.size());
8037 }
8038 }
8039
8040 if (IsWritten)
8041 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
8042 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008043 }
8044
Richard Smithc2bb8182015-03-24 06:36:48 +00008045 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008046}
8047
8048NestedNameSpecifier *
8049ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8050 const RecordData &Record, unsigned &Idx) {
8051 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008052 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008053 for (unsigned I = 0; I != N; ++I) {
8054 NestedNameSpecifier::SpecifierKind Kind
8055 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8056 switch (Kind) {
8057 case NestedNameSpecifier::Identifier: {
8058 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8059 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8060 break;
8061 }
8062
8063 case NestedNameSpecifier::Namespace: {
8064 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8065 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8066 break;
8067 }
8068
8069 case NestedNameSpecifier::NamespaceAlias: {
8070 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8071 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8072 break;
8073 }
8074
8075 case NestedNameSpecifier::TypeSpec:
8076 case NestedNameSpecifier::TypeSpecWithTemplate: {
8077 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8078 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008079 return nullptr;
8080
Guy Benyei11169dd2012-12-18 14:30:41 +00008081 bool Template = Record[Idx++];
8082 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8083 break;
8084 }
8085
8086 case NestedNameSpecifier::Global: {
8087 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8088 // No associated value, and there can't be a prefix.
8089 break;
8090 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008091
8092 case NestedNameSpecifier::Super: {
8093 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8094 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8095 break;
8096 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008097 }
8098 Prev = NNS;
8099 }
8100 return NNS;
8101}
8102
8103NestedNameSpecifierLoc
8104ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8105 unsigned &Idx) {
8106 unsigned N = Record[Idx++];
8107 NestedNameSpecifierLocBuilder Builder;
8108 for (unsigned I = 0; I != N; ++I) {
8109 NestedNameSpecifier::SpecifierKind Kind
8110 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8111 switch (Kind) {
8112 case NestedNameSpecifier::Identifier: {
8113 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8114 SourceRange Range = ReadSourceRange(F, Record, Idx);
8115 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8116 break;
8117 }
8118
8119 case NestedNameSpecifier::Namespace: {
8120 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8121 SourceRange Range = ReadSourceRange(F, Record, Idx);
8122 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8123 break;
8124 }
8125
8126 case NestedNameSpecifier::NamespaceAlias: {
8127 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8128 SourceRange Range = ReadSourceRange(F, Record, Idx);
8129 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8130 break;
8131 }
8132
8133 case NestedNameSpecifier::TypeSpec:
8134 case NestedNameSpecifier::TypeSpecWithTemplate: {
8135 bool Template = Record[Idx++];
8136 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8137 if (!T)
8138 return NestedNameSpecifierLoc();
8139 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8140
8141 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8142 Builder.Extend(Context,
8143 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8144 T->getTypeLoc(), ColonColonLoc);
8145 break;
8146 }
8147
8148 case NestedNameSpecifier::Global: {
8149 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8150 Builder.MakeGlobal(Context, ColonColonLoc);
8151 break;
8152 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008153
8154 case NestedNameSpecifier::Super: {
8155 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8156 SourceRange Range = ReadSourceRange(F, Record, Idx);
8157 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8158 break;
8159 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008160 }
8161 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008162
Guy Benyei11169dd2012-12-18 14:30:41 +00008163 return Builder.getWithLocInContext(Context);
8164}
8165
8166SourceRange
8167ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8168 unsigned &Idx) {
8169 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8170 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8171 return SourceRange(beg, end);
8172}
8173
8174/// \brief Read an integral value
8175llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8176 unsigned BitWidth = Record[Idx++];
8177 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8178 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8179 Idx += NumWords;
8180 return Result;
8181}
8182
8183/// \brief Read a signed integral value
8184llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8185 bool isUnsigned = Record[Idx++];
8186 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8187}
8188
8189/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008190llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8191 const llvm::fltSemantics &Sem,
8192 unsigned &Idx) {
8193 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008194}
8195
8196// \brief Read a string
8197std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8198 unsigned Len = Record[Idx++];
8199 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8200 Idx += Len;
8201 return Result;
8202}
8203
Richard Smith7ed1bc92014-12-05 22:42:13 +00008204std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8205 unsigned &Idx) {
8206 std::string Filename = ReadString(Record, Idx);
8207 ResolveImportedPath(F, Filename);
8208 return Filename;
8209}
8210
Guy Benyei11169dd2012-12-18 14:30:41 +00008211VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8212 unsigned &Idx) {
8213 unsigned Major = Record[Idx++];
8214 unsigned Minor = Record[Idx++];
8215 unsigned Subminor = Record[Idx++];
8216 if (Minor == 0)
8217 return VersionTuple(Major);
8218 if (Subminor == 0)
8219 return VersionTuple(Major, Minor - 1);
8220 return VersionTuple(Major, Minor - 1, Subminor - 1);
8221}
8222
8223CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8224 const RecordData &Record,
8225 unsigned &Idx) {
8226 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8227 return CXXTemporary::Create(Context, Decl);
8228}
8229
8230DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008231 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008232}
8233
8234DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8235 return Diags.Report(Loc, DiagID);
8236}
8237
8238/// \brief Retrieve the identifier table associated with the
8239/// preprocessor.
8240IdentifierTable &ASTReader::getIdentifierTable() {
8241 return PP.getIdentifierTable();
8242}
8243
8244/// \brief Record that the given ID maps to the given switch-case
8245/// statement.
8246void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008247 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008248 "Already have a SwitchCase with this ID");
8249 (*CurrSwitchCaseStmts)[ID] = SC;
8250}
8251
8252/// \brief Retrieve the switch-case statement with the given ID.
8253SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008254 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008255 return (*CurrSwitchCaseStmts)[ID];
8256}
8257
8258void ASTReader::ClearSwitchCaseIDs() {
8259 CurrSwitchCaseStmts->clear();
8260}
8261
8262void ASTReader::ReadComments() {
8263 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008264 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008265 serialization::ModuleFile *> >::iterator
8266 I = CommentsCursors.begin(),
8267 E = CommentsCursors.end();
8268 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008269 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008270 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008271 serialization::ModuleFile &F = *I->second;
8272 SavedStreamPosition SavedPosition(Cursor);
8273
8274 RecordData Record;
8275 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008276 llvm::BitstreamEntry Entry =
8277 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008278
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008279 switch (Entry.Kind) {
8280 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8281 case llvm::BitstreamEntry::Error:
8282 Error("malformed block record in AST file");
8283 return;
8284 case llvm::BitstreamEntry::EndBlock:
8285 goto NextCursor;
8286 case llvm::BitstreamEntry::Record:
8287 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008288 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008289 }
8290
8291 // Read a record.
8292 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008293 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008294 case COMMENTS_RAW_COMMENT: {
8295 unsigned Idx = 0;
8296 SourceRange SR = ReadSourceRange(F, Record, Idx);
8297 RawComment::CommentKind Kind =
8298 (RawComment::CommentKind) Record[Idx++];
8299 bool IsTrailingComment = Record[Idx++];
8300 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008301 Comments.push_back(new (Context) RawComment(
8302 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8303 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008304 break;
8305 }
8306 }
8307 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008308 NextCursor:
8309 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008310 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008311}
8312
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008313void ASTReader::getInputFiles(ModuleFile &F,
8314 SmallVectorImpl<serialization::InputFile> &Files) {
8315 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8316 unsigned ID = I+1;
8317 Files.push_back(getInputFile(F, ID));
8318 }
8319}
8320
Richard Smithcd45dbc2014-04-19 03:48:30 +00008321std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8322 // If we know the owning module, use it.
8323 if (Module *M = D->getOwningModule())
8324 return M->getFullModuleName();
8325
8326 // Otherwise, use the name of the top-level module the decl is within.
8327 if (ModuleFile *M = getOwningModuleFile(D))
8328 return M->ModuleName;
8329
8330 // Not from a module.
8331 return "";
8332}
8333
Guy Benyei11169dd2012-12-18 14:30:41 +00008334void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008335 while (!PendingIdentifierInfos.empty() ||
8336 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008337 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008338 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008339 // If any identifiers with corresponding top-level declarations have
8340 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008341 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8342 TopLevelDeclsMap;
8343 TopLevelDeclsMap TopLevelDecls;
8344
Guy Benyei11169dd2012-12-18 14:30:41 +00008345 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008346 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008347 SmallVector<uint32_t, 4> DeclIDs =
8348 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008349 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008350
8351 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008352 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008353
Richard Smith851072e2014-05-19 20:59:20 +00008354 // For each decl chain that we wanted to complete while deserializing, mark
8355 // it as "still needs to be completed".
8356 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8357 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8358 }
8359 PendingIncompleteDeclChains.clear();
8360
Guy Benyei11169dd2012-12-18 14:30:41 +00008361 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008362 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008363 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008364 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008365 }
8366 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008367 PendingDeclChains.clear();
8368
Douglas Gregor6168bd22013-02-18 15:53:43 +00008369 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008370 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8371 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008372 IdentifierInfo *II = TLD->first;
8373 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008374 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008375 }
8376 }
8377
Guy Benyei11169dd2012-12-18 14:30:41 +00008378 // Load any pending macro definitions.
8379 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008380 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8381 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8382 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8383 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008384 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008385 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008386 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008387 if (Info.M->Kind != MK_ImplicitModule &&
8388 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008389 resolvePendingMacro(II, Info);
8390 }
8391 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008392 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008393 ++IDIdx) {
8394 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008395 if (Info.M->Kind == MK_ImplicitModule ||
8396 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008397 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008398 }
8399 }
8400 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008401
8402 // Wire up the DeclContexts for Decls that we delayed setting until
8403 // recursive loading is completed.
8404 while (!PendingDeclContextInfos.empty()) {
8405 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8406 PendingDeclContextInfos.pop_front();
8407 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8408 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8409 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8410 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008411
Richard Smithd1c46742014-04-30 02:24:17 +00008412 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008413 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008414 auto Update = PendingUpdateRecords.pop_back_val();
8415 ReadingKindTracker ReadingKind(Read_Decl, *this);
8416 loadDeclUpdateRecords(Update.first, Update.second);
8417 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008418 }
Richard Smith8a639892015-01-24 01:07:20 +00008419
8420 // At this point, all update records for loaded decls are in place, so any
8421 // fake class definitions should have become real.
8422 assert(PendingFakeDefinitionData.empty() &&
8423 "faked up a class definition but never saw the real one");
8424
Guy Benyei11169dd2012-12-18 14:30:41 +00008425 // If we deserialized any C++ or Objective-C class definitions, any
8426 // Objective-C protocol definitions, or any redeclarable templates, make sure
8427 // that all redeclarations point to the definitions. Note that this can only
8428 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008429 for (Decl *D : PendingDefinitions) {
8430 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008431 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008432 // Make sure that the TagType points at the definition.
8433 const_cast<TagType*>(TagT)->decl = TD;
8434 }
Richard Smith8ce51082015-03-11 01:44:51 +00008435
Craig Topperc6914d02014-08-25 04:15:02 +00008436 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008437 for (auto *R = getMostRecentExistingDecl(RD); R;
8438 R = R->getPreviousDecl()) {
8439 assert((R == D) ==
8440 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008441 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008442 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008443 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008444 }
8445
8446 continue;
8447 }
Richard Smith8ce51082015-03-11 01:44:51 +00008448
Craig Topperc6914d02014-08-25 04:15:02 +00008449 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008450 // Make sure that the ObjCInterfaceType points at the definition.
8451 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8452 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008453
8454 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8455 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8456
Guy Benyei11169dd2012-12-18 14:30:41 +00008457 continue;
8458 }
Richard Smith8ce51082015-03-11 01:44:51 +00008459
Craig Topperc6914d02014-08-25 04:15:02 +00008460 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008461 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8462 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8463
Guy Benyei11169dd2012-12-18 14:30:41 +00008464 continue;
8465 }
Richard Smith8ce51082015-03-11 01:44:51 +00008466
Craig Topperc6914d02014-08-25 04:15:02 +00008467 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008468 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8469 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008470 }
8471 PendingDefinitions.clear();
8472
8473 // Load the bodies of any functions or methods we've encountered. We do
8474 // this now (delayed) so that we can be sure that the declaration chains
8475 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008476 // FIXME: There seems to be no point in delaying this, it does not depend
8477 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008478 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8479 PBEnd = PendingBodies.end();
8480 PB != PBEnd; ++PB) {
8481 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8482 // FIXME: Check for =delete/=default?
8483 // FIXME: Complain about ODR violations here?
8484 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8485 FD->setLazyBody(PB->second);
8486 continue;
8487 }
8488
8489 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8490 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8491 MD->setLazyBody(PB->second);
8492 }
8493 PendingBodies.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008494}
8495
8496void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008497 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8498 return;
8499
Richard Smitha0ce9c42014-07-29 23:23:27 +00008500 // Trigger the import of the full definition of each class that had any
8501 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008502 // These updates may in turn find and diagnose some ODR failures, so take
8503 // ownership of the set first.
8504 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8505 PendingOdrMergeFailures.clear();
8506 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008507 Merge.first->buildLookup();
8508 Merge.first->decls_begin();
8509 Merge.first->bases_begin();
8510 Merge.first->vbases_begin();
8511 for (auto *RD : Merge.second) {
8512 RD->decls_begin();
8513 RD->bases_begin();
8514 RD->vbases_begin();
8515 }
8516 }
8517
8518 // For each declaration from a merged context, check that the canonical
8519 // definition of that context also contains a declaration of the same
8520 // entity.
8521 //
8522 // Caution: this loop does things that might invalidate iterators into
8523 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8524 while (!PendingOdrMergeChecks.empty()) {
8525 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8526
8527 // FIXME: Skip over implicit declarations for now. This matters for things
8528 // like implicitly-declared special member functions. This isn't entirely
8529 // correct; we can end up with multiple unmerged declarations of the same
8530 // implicit entity.
8531 if (D->isImplicit())
8532 continue;
8533
8534 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008535
8536 bool Found = false;
8537 const Decl *DCanon = D->getCanonicalDecl();
8538
Richard Smith01bdb7a2014-08-28 05:44:07 +00008539 for (auto RI : D->redecls()) {
8540 if (RI->getLexicalDeclContext() == CanonDef) {
8541 Found = true;
8542 break;
8543 }
8544 }
8545 if (Found)
8546 continue;
8547
Richard Smitha0ce9c42014-07-29 23:23:27 +00008548 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008549 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008550 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8551 !Found && I != E; ++I) {
8552 for (auto RI : (*I)->redecls()) {
8553 if (RI->getLexicalDeclContext() == CanonDef) {
8554 // This declaration is present in the canonical definition. If it's
8555 // in the same redecl chain, it's the one we're looking for.
8556 if (RI->getCanonicalDecl() == DCanon)
8557 Found = true;
8558 else
8559 Candidates.push_back(cast<NamedDecl>(RI));
8560 break;
8561 }
8562 }
8563 }
8564
8565 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008566 // The AST doesn't like TagDecls becoming invalid after they've been
8567 // completed. We only really need to mark FieldDecls as invalid here.
8568 if (!isa<TagDecl>(D))
8569 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008570
8571 // Ensure we don't accidentally recursively enter deserialization while
8572 // we're producing our diagnostic.
8573 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008574
8575 std::string CanonDefModule =
8576 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8577 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8578 << D << getOwningModuleNameForDiagnostic(D)
8579 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8580
8581 if (Candidates.empty())
8582 Diag(cast<Decl>(CanonDef)->getLocation(),
8583 diag::note_module_odr_violation_no_possible_decls) << D;
8584 else {
8585 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8586 Diag(Candidates[I]->getLocation(),
8587 diag::note_module_odr_violation_possible_decl)
8588 << Candidates[I];
8589 }
8590
8591 DiagnosedOdrMergeFailures.insert(CanonDef);
8592 }
8593 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008594
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008595 if (OdrMergeFailures.empty())
8596 return;
8597
8598 // Ensure we don't accidentally recursively enter deserialization while
8599 // we're producing our diagnostics.
8600 Deserializing RecursionGuard(this);
8601
Richard Smithcd45dbc2014-04-19 03:48:30 +00008602 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008603 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008604 // If we've already pointed out a specific problem with this class, don't
8605 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008606 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008607 continue;
8608
8609 bool Diagnosed = false;
8610 for (auto *RD : Merge.second) {
8611 // Multiple different declarations got merged together; tell the user
8612 // where they came from.
8613 if (Merge.first != RD) {
8614 // FIXME: Walk the definition, figure out what's different,
8615 // and diagnose that.
8616 if (!Diagnosed) {
8617 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8618 Diag(Merge.first->getLocation(),
8619 diag::err_module_odr_violation_different_definitions)
8620 << Merge.first << Module.empty() << Module;
8621 Diagnosed = true;
8622 }
8623
8624 Diag(RD->getLocation(),
8625 diag::note_module_odr_violation_different_definitions)
8626 << getOwningModuleNameForDiagnostic(RD);
8627 }
8628 }
8629
8630 if (!Diagnosed) {
8631 // All definitions are updates to the same declaration. This happens if a
8632 // module instantiates the declaration of a class template specialization
8633 // and two or more other modules instantiate its definition.
8634 //
8635 // FIXME: Indicate which modules had instantiations of this definition.
8636 // FIXME: How can this even happen?
8637 Diag(Merge.first->getLocation(),
8638 diag::err_module_odr_violation_different_instantiations)
8639 << Merge.first;
8640 }
8641 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008642}
8643
8644void ASTReader::FinishedDeserializing() {
8645 assert(NumCurrentElementsDeserializing &&
8646 "FinishedDeserializing not paired with StartedDeserializing");
8647 if (NumCurrentElementsDeserializing == 1) {
8648 // We decrease NumCurrentElementsDeserializing only after pending actions
8649 // are finished, to avoid recursively re-calling finishPendingActions().
8650 finishPendingActions();
8651 }
8652 --NumCurrentElementsDeserializing;
8653
Richard Smitha0ce9c42014-07-29 23:23:27 +00008654 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008655 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008656 while (!PendingExceptionSpecUpdates.empty()) {
8657 auto Updates = std::move(PendingExceptionSpecUpdates);
8658 PendingExceptionSpecUpdates.clear();
8659 for (auto Update : Updates) {
8660 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8661 SemaObj->UpdateExceptionSpec(Update.second,
8662 FPT->getExtProtoInfo().ExceptionSpec);
8663 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008664 }
8665
Richard Smitha0ce9c42014-07-29 23:23:27 +00008666 diagnoseOdrViolations();
8667
Richard Smith04d05b52014-03-23 00:27:18 +00008668 // We are not in recursive loading, so it's safe to pass the "interesting"
8669 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008670 if (Consumer)
8671 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008672 }
8673}
8674
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008675void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008676 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8677 // Remove any fake results before adding any real ones.
8678 auto It = PendingFakeLookupResults.find(II);
8679 if (It != PendingFakeLookupResults.end()) {
8680 for (auto *ND : PendingFakeLookupResults[II])
8681 SemaObj->IdResolver.RemoveDecl(ND);
8682 PendingFakeLookupResults.erase(It);
8683 }
8684 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008685
8686 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8687 SemaObj->TUScope->AddDecl(D);
8688 } else if (SemaObj->TUScope) {
8689 // Adding the decl to IdResolver may have failed because it was already in
8690 // (even though it was not added in scope). If it is already in, make sure
8691 // it gets in the scope as well.
8692 if (std::find(SemaObj->IdResolver.begin(Name),
8693 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8694 SemaObj->TUScope->AddDecl(D);
8695 }
8696}
8697
Nico Weber824285e2014-05-08 04:26:47 +00008698ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8699 bool DisableValidation, bool AllowASTWithCompilerErrors,
8700 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008701 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008702 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008703 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008704 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8705 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8706 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8707 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008708 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8709 AllowConfigurationMismatch(AllowConfigurationMismatch),
8710 ValidateSystemInputs(ValidateSystemInputs),
8711 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008712 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008713 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8714 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8715 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8716 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8717 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8718 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8719 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8720 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8721 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008722 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008723 SourceMgr.setExternalSLocEntrySource(this);
8724}
8725
8726ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008727 if (OwnsDeserializationListener)
8728 delete DeserializationListener;
8729
Guy Benyei11169dd2012-12-18 14:30:41 +00008730 for (DeclContextVisibleUpdatesPending::iterator
8731 I = PendingVisibleUpdates.begin(),
8732 E = PendingVisibleUpdates.end();
8733 I != E; ++I) {
8734 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8735 F = I->second.end();
8736 J != F; ++J)
8737 delete J->first;
8738 }
8739}