blob: 1ea30f95977ee0bf873f2afe8c67e400b4638d9f [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;
780 bool hadMacroDefinition = Bits & 0x01;
781 Bits >>= 1;
782
783 assert(Bits == 0 && "Extra bits in the identifier?");
784 DataLen -= 8;
785
786 // Build the IdentifierInfo itself and link the identifier ID with
787 // the new IdentifierInfo.
788 IdentifierInfo *II = KnownII;
789 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000790 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000791 KnownII = II;
792 }
793 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000794 if (!II->isFromAST()) {
795 bool WasInteresting = isInterestingIdentifier(*II);
796 II->setIsFromAST();
797 if (WasInteresting)
798 II->setChangedSinceDeserialization();
799 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000800
801 // Set or check the various bits in the IdentifierInfo structure.
802 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000803 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000804 II->RevertTokenIDToIdentifier();
805 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
806 assert(II->isExtensionToken() == ExtensionToken &&
807 "Incorrect extension token flag");
808 (void)ExtensionToken;
809 if (Poisoned)
810 II->setIsPoisoned(true);
811 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
812 "Incorrect C++ operator keyword flag");
813 (void)CPlusPlusOperatorKeyword;
814
815 // If this identifier is a macro, deserialize the macro
816 // definition.
817 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000818 uint32_t MacroDirectivesOffset =
819 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000820 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000821
Richard Smithd7329392015-04-21 21:46:32 +0000822 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000823 }
824
825 Reader.SetIdentifierInfo(ID, II);
826
827 // Read all of the declarations visible at global scope with this
828 // name.
829 if (DataLen > 0) {
830 SmallVector<uint32_t, 4> DeclIDs;
831 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000832 DeclIDs.push_back(Reader.getGlobalDeclID(
833 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000834 Reader.SetGloballyVisibleDecls(II, DeclIDs);
835 }
836
837 return II;
838}
839
840unsigned
841ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
842 llvm::FoldingSetNodeID ID;
843 ID.AddInteger(Key.Kind);
844
845 switch (Key.Kind) {
846 case DeclarationName::Identifier:
847 case DeclarationName::CXXLiteralOperatorName:
848 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
849 break;
850 case DeclarationName::ObjCZeroArgSelector:
851 case DeclarationName::ObjCOneArgSelector:
852 case DeclarationName::ObjCMultiArgSelector:
853 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
854 break;
855 case DeclarationName::CXXOperatorName:
856 ID.AddInteger((OverloadedOperatorKind)Key.Data);
857 break;
858 case DeclarationName::CXXConstructorName:
859 case DeclarationName::CXXDestructorName:
860 case DeclarationName::CXXConversionFunctionName:
861 case DeclarationName::CXXUsingDirective:
862 break;
863 }
864
865 return ID.ComputeHash();
866}
867
868ASTDeclContextNameLookupTrait::internal_key_type
869ASTDeclContextNameLookupTrait::GetInternalKey(
870 const external_key_type& Name) const {
871 DeclNameKey Key;
872 Key.Kind = Name.getNameKind();
873 switch (Name.getNameKind()) {
874 case DeclarationName::Identifier:
875 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
876 break;
877 case DeclarationName::ObjCZeroArgSelector:
878 case DeclarationName::ObjCOneArgSelector:
879 case DeclarationName::ObjCMultiArgSelector:
880 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
881 break;
882 case DeclarationName::CXXOperatorName:
883 Key.Data = Name.getCXXOverloadedOperator();
884 break;
885 case DeclarationName::CXXLiteralOperatorName:
886 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
887 break;
888 case DeclarationName::CXXConstructorName:
889 case DeclarationName::CXXDestructorName:
890 case DeclarationName::CXXConversionFunctionName:
891 case DeclarationName::CXXUsingDirective:
892 Key.Data = 0;
893 break;
894 }
895
896 return Key;
897}
898
899std::pair<unsigned, unsigned>
900ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000901 using namespace llvm::support;
902 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
903 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000904 return std::make_pair(KeyLen, DataLen);
905}
906
907ASTDeclContextNameLookupTrait::internal_key_type
908ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000909 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000910
911 DeclNameKey Key;
912 Key.Kind = (DeclarationName::NameKind)*d++;
913 switch (Key.Kind) {
914 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000915 Key.Data = (uint64_t)Reader.getLocalIdentifier(
916 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000917 break;
918 case DeclarationName::ObjCZeroArgSelector:
919 case DeclarationName::ObjCOneArgSelector:
920 case DeclarationName::ObjCMultiArgSelector:
921 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000922 (uint64_t)Reader.getLocalSelector(
923 F, endian::readNext<uint32_t, little, unaligned>(
924 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000925 break;
926 case DeclarationName::CXXOperatorName:
927 Key.Data = *d++; // OverloadedOperatorKind
928 break;
929 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000930 Key.Data = (uint64_t)Reader.getLocalIdentifier(
931 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000932 break;
933 case DeclarationName::CXXConstructorName:
934 case DeclarationName::CXXDestructorName:
935 case DeclarationName::CXXConversionFunctionName:
936 case DeclarationName::CXXUsingDirective:
937 Key.Data = 0;
938 break;
939 }
940
941 return Key;
942}
943
944ASTDeclContextNameLookupTrait::data_type
945ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
946 const unsigned char* d,
947 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000948 using namespace llvm::support;
949 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000950 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
951 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000952 return std::make_pair(Start, Start + NumDecls);
953}
954
955bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000956 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000957 const std::pair<uint64_t, uint64_t> &Offsets,
958 DeclContextInfo &Info) {
959 SavedStreamPosition SavedPosition(Cursor);
960 // First the lexical decls.
961 if (Offsets.first != 0) {
962 Cursor.JumpToBit(Offsets.first);
963
964 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000965 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000966 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000967 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000968 if (RecCode != DECL_CONTEXT_LEXICAL) {
969 Error("Expected lexical block");
970 return true;
971 }
972
Chris Lattner0e6c9402013-01-20 02:38:54 +0000973 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
974 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000975 }
976
977 // Now the lookup table.
978 if (Offsets.second != 0) {
979 Cursor.JumpToBit(Offsets.second);
980
981 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000982 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000983 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000984 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000985 if (RecCode != DECL_CONTEXT_VISIBLE) {
986 Error("Expected visible lookup table block");
987 return true;
988 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000989 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
990 (const unsigned char *)Blob.data() + Record[0],
991 (const unsigned char *)Blob.data() + sizeof(uint32_t),
992 (const unsigned char *)Blob.data(),
993 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000994 }
995
996 return false;
997}
998
999void ASTReader::Error(StringRef Msg) {
1000 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001001 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1002 Diag(diag::note_module_cache_path)
1003 << PP.getHeaderSearchInfo().getModuleCachePath();
1004 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001005}
1006
1007void ASTReader::Error(unsigned DiagID,
1008 StringRef Arg1, StringRef Arg2) {
1009 if (Diags.isDiagnosticInFlight())
1010 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1011 else
1012 Diag(DiagID) << Arg1 << Arg2;
1013}
1014
1015//===----------------------------------------------------------------------===//
1016// Source Manager Deserialization
1017//===----------------------------------------------------------------------===//
1018
1019/// \brief Read the line table in the source manager block.
1020/// \returns true if there was an error.
1021bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001022 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 unsigned Idx = 0;
1024 LineTableInfo &LineTable = SourceMgr.getLineTable();
1025
1026 // Parse the file names
1027 std::map<int, int> FileIDs;
1028 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1029 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001030 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001031 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1032 }
1033
1034 // Parse the line entries
1035 std::vector<LineEntry> Entries;
1036 while (Idx < Record.size()) {
1037 int FID = Record[Idx++];
1038 assert(FID >= 0 && "Serialized line entries for non-local file.");
1039 // Remap FileID from 1-based old view.
1040 FID += F.SLocEntryBaseID - 1;
1041
1042 // Extract the line entries
1043 unsigned NumEntries = Record[Idx++];
1044 assert(NumEntries && "Numentries is 00000");
1045 Entries.clear();
1046 Entries.reserve(NumEntries);
1047 for (unsigned I = 0; I != NumEntries; ++I) {
1048 unsigned FileOffset = Record[Idx++];
1049 unsigned LineNo = Record[Idx++];
1050 int FilenameID = FileIDs[Record[Idx++]];
1051 SrcMgr::CharacteristicKind FileKind
1052 = (SrcMgr::CharacteristicKind)Record[Idx++];
1053 unsigned IncludeOffset = Record[Idx++];
1054 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1055 FileKind, IncludeOffset));
1056 }
1057 LineTable.AddEntry(FileID::get(FID), Entries);
1058 }
1059
1060 return false;
1061}
1062
1063/// \brief Read a source manager block
1064bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1065 using namespace SrcMgr;
1066
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001067 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001068
1069 // Set the source-location entry cursor to the current position in
1070 // the stream. This cursor will be used to read the contents of the
1071 // source manager block initially, and then lazily read
1072 // source-location entries as needed.
1073 SLocEntryCursor = F.Stream;
1074
1075 // The stream itself is going to skip over the source manager block.
1076 if (F.Stream.SkipBlock()) {
1077 Error("malformed block record in AST file");
1078 return true;
1079 }
1080
1081 // Enter the source manager block.
1082 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1083 Error("malformed source manager block record in AST file");
1084 return true;
1085 }
1086
1087 RecordData Record;
1088 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001089 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1090
1091 switch (E.Kind) {
1092 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1093 case llvm::BitstreamEntry::Error:
1094 Error("malformed block record in AST file");
1095 return true;
1096 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001097 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001098 case llvm::BitstreamEntry::Record:
1099 // The interesting case.
1100 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001101 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001102
Guy Benyei11169dd2012-12-18 14:30:41 +00001103 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001105 StringRef Blob;
1106 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001107 default: // Default behavior: ignore.
1108 break;
1109
1110 case SM_SLOC_FILE_ENTRY:
1111 case SM_SLOC_BUFFER_ENTRY:
1112 case SM_SLOC_EXPANSION_ENTRY:
1113 // Once we hit one of the source location entries, we're done.
1114 return false;
1115 }
1116 }
1117}
1118
1119/// \brief If a header file is not found at the path that we expect it to be
1120/// and the PCH file was moved from its original location, try to resolve the
1121/// file by assuming that header+PCH were moved together and the header is in
1122/// the same place relative to the PCH.
1123static std::string
1124resolveFileRelativeToOriginalDir(const std::string &Filename,
1125 const std::string &OriginalDir,
1126 const std::string &CurrDir) {
1127 assert(OriginalDir != CurrDir &&
1128 "No point trying to resolve the file if the PCH dir didn't change");
1129 using namespace llvm::sys;
1130 SmallString<128> filePath(Filename);
1131 fs::make_absolute(filePath);
1132 assert(path::is_absolute(OriginalDir));
1133 SmallString<128> currPCHPath(CurrDir);
1134
1135 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1136 fileDirE = path::end(path::parent_path(filePath));
1137 path::const_iterator origDirI = path::begin(OriginalDir),
1138 origDirE = path::end(OriginalDir);
1139 // Skip the common path components from filePath and OriginalDir.
1140 while (fileDirI != fileDirE && origDirI != origDirE &&
1141 *fileDirI == *origDirI) {
1142 ++fileDirI;
1143 ++origDirI;
1144 }
1145 for (; origDirI != origDirE; ++origDirI)
1146 path::append(currPCHPath, "..");
1147 path::append(currPCHPath, fileDirI, fileDirE);
1148 path::append(currPCHPath, path::filename(Filename));
1149 return currPCHPath.str();
1150}
1151
1152bool ASTReader::ReadSLocEntry(int ID) {
1153 if (ID == 0)
1154 return false;
1155
1156 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1157 Error("source location entry ID out-of-range for AST file");
1158 return true;
1159 }
1160
1161 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1162 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001163 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001164 unsigned BaseOffset = F->SLocEntryBaseOffset;
1165
1166 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001167 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1168 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001169 Error("incorrectly-formatted source location entry in AST file");
1170 return true;
1171 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001172
Guy Benyei11169dd2012-12-18 14:30:41 +00001173 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001174 StringRef Blob;
1175 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001176 default:
1177 Error("incorrectly-formatted source location entry in AST file");
1178 return true;
1179
1180 case SM_SLOC_FILE_ENTRY: {
1181 // We will detect whether a file changed and return 'Failure' for it, but
1182 // we will also try to fail gracefully by setting up the SLocEntry.
1183 unsigned InputID = Record[4];
1184 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001185 const FileEntry *File = IF.getFile();
1186 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001187
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001188 // Note that we only check if a File was returned. If it was out-of-date
1189 // we have complained but we will continue creating a FileID to recover
1190 // gracefully.
1191 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001192 return true;
1193
1194 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1195 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1196 // This is the module's main file.
1197 IncludeLoc = getImportLocation(F);
1198 }
1199 SrcMgr::CharacteristicKind
1200 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1201 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1202 ID, BaseOffset + Record[0]);
1203 SrcMgr::FileInfo &FileInfo =
1204 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1205 FileInfo.NumCreatedFIDs = Record[5];
1206 if (Record[3])
1207 FileInfo.setHasLineDirectives();
1208
1209 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1210 unsigned NumFileDecls = Record[7];
1211 if (NumFileDecls) {
1212 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1213 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1214 NumFileDecls));
1215 }
1216
1217 const SrcMgr::ContentCache *ContentCache
1218 = SourceMgr.getOrCreateContentCache(File,
1219 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1220 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1221 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1222 unsigned Code = SLocEntryCursor.ReadCode();
1223 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001224 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001225
1226 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1227 Error("AST record has invalid code");
1228 return true;
1229 }
1230
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001231 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001232 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001233 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001234 }
1235
1236 break;
1237 }
1238
1239 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001240 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001241 unsigned Offset = Record[0];
1242 SrcMgr::CharacteristicKind
1243 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1244 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001245 if (IncludeLoc.isInvalid() &&
1246 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001247 IncludeLoc = getImportLocation(F);
1248 }
1249 unsigned Code = SLocEntryCursor.ReadCode();
1250 Record.clear();
1251 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001252 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001253
1254 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1255 Error("AST record has invalid code");
1256 return true;
1257 }
1258
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001259 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1260 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001261 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001262 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001263 break;
1264 }
1265
1266 case SM_SLOC_EXPANSION_ENTRY: {
1267 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1268 SourceMgr.createExpansionLoc(SpellingLoc,
1269 ReadSourceLocation(*F, Record[2]),
1270 ReadSourceLocation(*F, Record[3]),
1271 Record[4],
1272 ID,
1273 BaseOffset + Record[0]);
1274 break;
1275 }
1276 }
1277
1278 return false;
1279}
1280
1281std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1282 if (ID == 0)
1283 return std::make_pair(SourceLocation(), "");
1284
1285 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1286 Error("source location entry ID out-of-range for AST file");
1287 return std::make_pair(SourceLocation(), "");
1288 }
1289
1290 // Find which module file this entry lands in.
1291 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001292 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001293 return std::make_pair(SourceLocation(), "");
1294
1295 // FIXME: Can we map this down to a particular submodule? That would be
1296 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001297 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001298}
1299
1300/// \brief Find the location where the module F is imported.
1301SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1302 if (F->ImportLoc.isValid())
1303 return F->ImportLoc;
1304
1305 // Otherwise we have a PCH. It's considered to be "imported" at the first
1306 // location of its includer.
1307 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001308 // Main file is the importer.
1309 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1310 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001312 return F->ImportedBy[0]->FirstLoc;
1313}
1314
1315/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1316/// specified cursor. Read the abbreviations that are at the top of the block
1317/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001318bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001319 if (Cursor.EnterSubBlock(BlockID)) {
1320 Error("malformed block record in AST file");
1321 return Failure;
1322 }
1323
1324 while (true) {
1325 uint64_t Offset = Cursor.GetCurrentBitNo();
1326 unsigned Code = Cursor.ReadCode();
1327
1328 // We expect all abbrevs to be at the start of the block.
1329 if (Code != llvm::bitc::DEFINE_ABBREV) {
1330 Cursor.JumpToBit(Offset);
1331 return false;
1332 }
1333 Cursor.ReadAbbrevRecord();
1334 }
1335}
1336
Richard Smithe40f2ba2013-08-07 21:41:30 +00001337Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001338 unsigned &Idx) {
1339 Token Tok;
1340 Tok.startToken();
1341 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1342 Tok.setLength(Record[Idx++]);
1343 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1344 Tok.setIdentifierInfo(II);
1345 Tok.setKind((tok::TokenKind)Record[Idx++]);
1346 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1347 return Tok;
1348}
1349
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001350MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001351 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001352
1353 // Keep track of where we are in the stream, then jump back there
1354 // after reading this macro.
1355 SavedStreamPosition SavedPosition(Stream);
1356
1357 Stream.JumpToBit(Offset);
1358 RecordData Record;
1359 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001360 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001361
Guy Benyei11169dd2012-12-18 14:30:41 +00001362 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001363 // Advance to the next record, but if we get to the end of the block, don't
1364 // pop it (removing all the abbreviations from the cursor) since we want to
1365 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001366 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001367 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1368
1369 switch (Entry.Kind) {
1370 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1371 case llvm::BitstreamEntry::Error:
1372 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001373 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001374 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001375 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001376 case llvm::BitstreamEntry::Record:
1377 // The interesting case.
1378 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001379 }
1380
1381 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001382 Record.clear();
1383 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001384 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001385 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001386 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001387 case PP_MACRO_DIRECTIVE_HISTORY:
1388 return Macro;
1389
Guy Benyei11169dd2012-12-18 14:30:41 +00001390 case PP_MACRO_OBJECT_LIKE:
1391 case PP_MACRO_FUNCTION_LIKE: {
1392 // If we already have a macro, that means that we've hit the end
1393 // of the definition of the macro we were looking for. We're
1394 // done.
1395 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001396 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001397
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001398 unsigned NextIndex = 1; // Skip identifier ID.
1399 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001401 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001402 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001403 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001404 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001405
Guy Benyei11169dd2012-12-18 14:30:41 +00001406 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1407 // Decode function-like macro info.
1408 bool isC99VarArgs = Record[NextIndex++];
1409 bool isGNUVarArgs = Record[NextIndex++];
1410 bool hasCommaPasting = Record[NextIndex++];
1411 MacroArgs.clear();
1412 unsigned NumArgs = Record[NextIndex++];
1413 for (unsigned i = 0; i != NumArgs; ++i)
1414 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1415
1416 // Install function-like macro info.
1417 MI->setIsFunctionLike();
1418 if (isC99VarArgs) MI->setIsC99Varargs();
1419 if (isGNUVarArgs) MI->setIsGNUVarargs();
1420 if (hasCommaPasting) MI->setHasCommaPasting();
1421 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1422 PP.getPreprocessorAllocator());
1423 }
1424
Guy Benyei11169dd2012-12-18 14:30:41 +00001425 // Remember that we saw this macro last so that we add the tokens that
1426 // form its body to it.
1427 Macro = MI;
1428
1429 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1430 Record[NextIndex]) {
1431 // We have a macro definition. Register the association
1432 PreprocessedEntityID
1433 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1434 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001435 PreprocessingRecord::PPEntityID
1436 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1437 MacroDefinition *PPDef =
1438 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1439 if (PPDef)
1440 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001441 }
1442
1443 ++NumMacrosRead;
1444 break;
1445 }
1446
1447 case PP_TOKEN: {
1448 // If we see a TOKEN before a PP_MACRO_*, then the file is
1449 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001450 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001451
John McCallf413f5e2013-05-03 00:10:13 +00001452 unsigned Idx = 0;
1453 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001454 Macro->AddTokenToBody(Tok);
1455 break;
1456 }
1457 }
1458 }
1459}
1460
1461PreprocessedEntityID
1462ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1463 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1464 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1465 assert(I != M.PreprocessedEntityRemap.end()
1466 && "Invalid index into preprocessed entity index remap");
1467
1468 return LocalID + I->second;
1469}
1470
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001471unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1472 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001473}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001474
Guy Benyei11169dd2012-12-18 14:30:41 +00001475HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001476HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1477 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001478 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001479 return ikey;
1480}
Guy Benyei11169dd2012-12-18 14:30:41 +00001481
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001482bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1483 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001484 return false;
1485
Richard Smith7ed1bc92014-12-05 22:42:13 +00001486 if (llvm::sys::path::is_absolute(a.Filename) &&
1487 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001488 return true;
1489
Guy Benyei11169dd2012-12-18 14:30:41 +00001490 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001491 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001492 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1493 if (!Key.Imported)
1494 return FileMgr.getFile(Key.Filename);
1495
1496 std::string Resolved = Key.Filename;
1497 Reader.ResolveImportedPath(M, Resolved);
1498 return FileMgr.getFile(Resolved);
1499 };
1500
1501 const FileEntry *FEA = GetFile(a);
1502 const FileEntry *FEB = GetFile(b);
1503 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001504}
1505
1506std::pair<unsigned, unsigned>
1507HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001508 using namespace llvm::support;
1509 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001510 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001511 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001512}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001513
1514HeaderFileInfoTrait::internal_key_type
1515HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001516 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001517 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001518 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1519 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001520 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001521 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001522 return ikey;
1523}
1524
Guy Benyei11169dd2012-12-18 14:30:41 +00001525HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001526HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001527 unsigned DataLen) {
1528 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001529 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001530 HeaderFileInfo HFI;
1531 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001532 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1533 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001534 HFI.isImport = (Flags >> 5) & 0x01;
1535 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1536 HFI.DirInfo = (Flags >> 2) & 0x03;
1537 HFI.Resolved = (Flags >> 1) & 0x01;
1538 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001539 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1540 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1541 M, endian::readNext<uint32_t, little, unaligned>(d));
1542 if (unsigned FrameworkOffset =
1543 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001544 // The framework offset is 1 greater than the actual offset,
1545 // since 0 is used as an indicator for "no framework name".
1546 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1547 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1548 }
1549
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001550 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001551 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001552 if (LocalSMID) {
1553 // This header is part of a module. Associate it with the module to enable
1554 // implicit module import.
1555 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1556 Module *Mod = Reader.getSubmodule(GlobalSMID);
1557 HFI.isModuleHeader = true;
1558 FileManager &FileMgr = Reader.getFileManager();
1559 ModuleMap &ModMap =
1560 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001561 // FIXME: This information should be propagated through the
1562 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001563 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001564 std::string Filename = key.Filename;
1565 if (key.Imported)
1566 Reader.ResolveImportedPath(M, Filename);
1567 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001568 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001569 }
1570 }
1571
Guy Benyei11169dd2012-12-18 14:30:41 +00001572 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1573 (void)End;
1574
1575 // This HeaderFileInfo was externally loaded.
1576 HFI.External = true;
1577 return HFI;
1578}
1579
Richard Smithd7329392015-04-21 21:46:32 +00001580void ASTReader::addPendingMacro(IdentifierInfo *II,
1581 ModuleFile *M,
1582 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001583 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1584 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001585}
1586
1587void ASTReader::ReadDefinedMacros() {
1588 // Note that we are loading defined macros.
1589 Deserializing Macros(this);
1590
1591 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1592 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001593 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001594
1595 // If there was no preprocessor block, skip this file.
1596 if (!MacroCursor.getBitStreamReader())
1597 continue;
1598
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001599 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001600 Cursor.JumpToBit((*I)->MacroStartOffset);
1601
1602 RecordData Record;
1603 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001604 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1605
1606 switch (E.Kind) {
1607 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1608 case llvm::BitstreamEntry::Error:
1609 Error("malformed block record in AST file");
1610 return;
1611 case llvm::BitstreamEntry::EndBlock:
1612 goto NextCursor;
1613
1614 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001615 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001616 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001617 default: // Default behavior: ignore.
1618 break;
1619
1620 case PP_MACRO_OBJECT_LIKE:
1621 case PP_MACRO_FUNCTION_LIKE:
1622 getLocalIdentifier(**I, Record[0]);
1623 break;
1624
1625 case PP_TOKEN:
1626 // Ignore tokens.
1627 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001628 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001629 break;
1630 }
1631 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001632 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001633 }
1634}
1635
1636namespace {
1637 /// \brief Visitor class used to look up identifirs in an AST file.
1638 class IdentifierLookupVisitor {
1639 StringRef Name;
1640 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001641 unsigned &NumIdentifierLookups;
1642 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001643 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001644
Guy Benyei11169dd2012-12-18 14:30:41 +00001645 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001646 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1647 unsigned &NumIdentifierLookups,
1648 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001649 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001650 NumIdentifierLookups(NumIdentifierLookups),
1651 NumIdentifierLookupHits(NumIdentifierLookupHits),
1652 Found()
1653 {
1654 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001655
1656 static bool visit(ModuleFile &M, void *UserData) {
1657 IdentifierLookupVisitor *This
1658 = static_cast<IdentifierLookupVisitor *>(UserData);
1659
1660 // If we've already searched this module file, skip it now.
1661 if (M.Generation <= This->PriorGeneration)
1662 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001663
Guy Benyei11169dd2012-12-18 14:30:41 +00001664 ASTIdentifierLookupTable *IdTable
1665 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1666 if (!IdTable)
1667 return false;
1668
1669 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1670 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001671 ++This->NumIdentifierLookups;
1672 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001673 if (Pos == IdTable->end())
1674 return false;
1675
1676 // Dereferencing the iterator has the effect of building the
1677 // IdentifierInfo node and populating it with the various
1678 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001679 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001680 This->Found = *Pos;
1681 return true;
1682 }
1683
1684 // \brief Retrieve the identifier info found within the module
1685 // files.
1686 IdentifierInfo *getIdentifierInfo() const { return Found; }
1687 };
1688}
1689
1690void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1691 // Note that we are loading an identifier.
1692 Deserializing AnIdentifier(this);
1693
1694 unsigned PriorGeneration = 0;
1695 if (getContext().getLangOpts().Modules)
1696 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001697
1698 // If there is a global index, look there first to determine which modules
1699 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001700 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001701 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001702 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001703 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1704 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001705 }
1706 }
1707
Douglas Gregor7211ac12013-01-25 23:32:03 +00001708 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001709 NumIdentifierLookups,
1710 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001711 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001712 markIdentifierUpToDate(&II);
1713}
1714
1715void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1716 if (!II)
1717 return;
1718
1719 II->setOutOfDate(false);
1720
1721 // Update the generation for this identifier.
1722 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001723 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001724}
1725
Richard Smith49f906a2014-03-01 00:08:04 +00001726struct ASTReader::ModuleMacroInfo {
1727 SubmoduleID SubModID;
1728 MacroInfo *MI;
Richard Smithd7329392015-04-21 21:46:32 +00001729 ArrayRef<SubmoduleID> Overrides;
Richard Smith49f906a2014-03-01 00:08:04 +00001730 // FIXME: Remove this.
1731 ModuleFile *F;
1732
1733 bool isDefine() const { return MI; }
1734
1735 SubmoduleID getSubmoduleID() const { return SubModID; }
1736
Richard Smithd7329392015-04-21 21:46:32 +00001737 ArrayRef<SubmoduleID> getOverriddenSubmodules() const { return Overrides; }
Richard Smith49f906a2014-03-01 00:08:04 +00001738
Richard Smithdaa69e02014-07-25 04:40:03 +00001739 MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
Richard Smith49f906a2014-03-01 00:08:04 +00001740 if (!MI)
Richard Smithdaa69e02014-07-25 04:40:03 +00001741 return PP.AllocateUndefMacroDirective(ImportLoc, SubModID,
1742 getOverriddenSubmodules());
1743 return PP.AllocateDefMacroDirective(MI, ImportLoc, SubModID,
1744 getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001745 }
1746};
1747
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001748void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1749 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001750 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001751
1752 BitstreamCursor &Cursor = M.MacroCursor;
1753 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001754 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001755
Richard Smithe56c8bc2015-04-22 00:26:11 +00001756 llvm::SmallVector<ModuleMacroInfo, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001757
Richard Smithd7329392015-04-21 21:46:32 +00001758 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1759 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1760 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001761 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001762 while (true) {
1763 llvm::BitstreamEntry Entry =
1764 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1765 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1766 Error("malformed block record in AST file");
1767 return;
1768 }
1769
1770 Record.clear();
1771 switch (PreprocessorRecordTypes RecType =
1772 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
1773 case PP_MACRO_DIRECTIVE_HISTORY:
1774 break;
1775
1776 case PP_MODULE_MACRO: {
Richard Smithd7329392015-04-21 21:46:32 +00001777 ModuleMacroInfo Info;
Richard Smithe56c8bc2015-04-22 00:26:11 +00001778 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1779 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smithd7329392015-04-21 21:46:32 +00001780 Info.F = &M;
1781
1782 if (Record.size() > 2) {
1783 auto *Overrides = new (Context) SubmoduleID[Record.size() - 2];
1784 for (int I = 2, N = Record.size(); I != N; ++I)
1785 Overrides[I - 2] = getGlobalSubmoduleID(M, Record[I]);
1786 Info.Overrides =
1787 llvm::makeArrayRef(Overrides, Overrides + Record.size() - 2);
1788 }
1789
Richard Smithe56c8bc2015-04-22 00:26:11 +00001790 ModuleMacros.push_back(Info);
Richard Smithd7329392015-04-21 21:46:32 +00001791 continue;
1792 }
1793
1794 default:
1795 Error("malformed block record in AST file");
1796 return;
1797 }
1798
1799 // We found the macro directive history; that's the last record
1800 // for this macro.
1801 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001802 }
1803
Richard Smithd7329392015-04-21 21:46:32 +00001804 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001805 {
1806 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001807 llvm::SmallVector<ModuleMacro*, 8> Overrides;
1808 for (auto &MMI : ModuleMacros) {
1809 Overrides.clear();
1810 for (unsigned ModID : MMI.Overrides) {
Richard Smith5dbef922015-04-22 02:09:43 +00001811 auto *Macro = PP.getModuleMacro(ModID, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001812 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001813 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001814 }
1815
1816 bool Inserted = false;
Richard Smith5dbef922015-04-22 02:09:43 +00001817 PP.addModuleMacro(MMI.SubModID, II, MMI.MI, Overrides, Inserted);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001818 if (!Inserted)
1819 continue;
1820
1821 Module *Owner = getSubmodule(MMI.getSubmoduleID());
1822 if (Owner->NameVisibility == Module::Hidden) {
1823 // Macros in the owning module are hidden. Just remember this macro to
1824 // install if we make this module visible.
1825 HiddenNamesMap[Owner].HiddenMacros.insert(
Richard Smith5dbef922015-04-22 02:09:43 +00001826 std::make_pair(II, new (Context) ModuleMacroInfo(MMI)));
Richard Smithe56c8bc2015-04-22 00:26:11 +00001827 } else {
1828 installImportedMacro(II, MMI, Owner);
1829 }
Richard Smithd7329392015-04-21 21:46:32 +00001830 }
1831 }
1832
1833 // Don't read the directive history for a module; we don't have anywhere
1834 // to put it.
1835 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1836 return;
1837
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001838 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001839 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001840 unsigned Idx = 0, N = Record.size();
1841 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001842 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001843 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001844 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1845 switch (K) {
1846 case MacroDirective::MD_Define: {
1847 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1848 MacroInfo *MI = getMacro(GMacID);
Richard Smithd7329392015-04-21 21:46:32 +00001849 SubmoduleID ImportedFrom = getGlobalSubmoduleID(M, Record[Idx++]);
Richard Smithdaa69e02014-07-25 04:40:03 +00001850 bool IsAmbiguous = Record[Idx++];
1851 llvm::SmallVector<unsigned, 4> Overrides;
1852 if (ImportedFrom) {
1853 Overrides.insert(Overrides.end(),
1854 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
Richard Smithd7329392015-04-21 21:46:32 +00001855 for (auto &ID : Overrides)
1856 ID = getGlobalSubmoduleID(M, ID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001857 Idx += Overrides.size() + 1;
1858 }
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001859 DefMacroDirective *DefMD =
Richard Smithdaa69e02014-07-25 04:40:03 +00001860 PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
1861 DefMD->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001862 MD = DefMD;
1863 break;
1864 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001865 case MacroDirective::MD_Undefine: {
Richard Smithd7329392015-04-21 21:46:32 +00001866 SubmoduleID ImportedFrom = getGlobalSubmoduleID(M, Record[Idx++]);
Richard Smithdaa69e02014-07-25 04:40:03 +00001867 llvm::SmallVector<unsigned, 4> Overrides;
1868 if (ImportedFrom) {
1869 Overrides.insert(Overrides.end(),
1870 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
Richard Smithd7329392015-04-21 21:46:32 +00001871 for (auto &ID : Overrides)
1872 ID = getGlobalSubmoduleID(M, ID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001873 Idx += Overrides.size() + 1;
1874 }
1875 MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001876 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001877 }
1878 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001879 bool isPublic = Record[Idx++];
1880 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1881 break;
1882 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001883
1884 if (!Latest)
1885 Latest = MD;
1886 if (Earliest)
1887 Earliest->setPrevious(MD);
1888 Earliest = MD;
1889 }
1890
1891 PP.setLoadedMacroDirective(II, Latest);
1892}
1893
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001894/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001895/// modules.
1896static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001897 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001898 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001899 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001900 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1901 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001902 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001903 return false;
Chandler Carruthc2132d82015-03-13 08:29:54 +00001904 SourceManager &SrcMgr = Reader.getSourceManager();
1905 bool PrevInSystem = (PrevOwner && PrevOwner->IsSystem) ||
1906 SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1907 bool NewInSystem = (NewOwner && NewOwner->IsSystem) ||
1908 SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
Douglas Gregor5e461192013-06-07 22:56:11 +00001909 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001910}
1911
Richard Smith49f906a2014-03-01 00:08:04 +00001912void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001913 SourceLocation ImportLoc,
Richard Smith49f906a2014-03-01 00:08:04 +00001914 AmbiguousMacros &Ambig,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001915 ArrayRef<SubmoduleID> Overrides) {
Richard Smith49f906a2014-03-01 00:08:04 +00001916 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1917 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001918
Richard Smith49f906a2014-03-01 00:08:04 +00001919 // If this macro is not yet visible, remove it from the hidden names list.
Richard Smithbb853c72014-08-13 01:23:33 +00001920 // It won't be there if we're in the middle of making the owner visible.
Richard Smith49f906a2014-03-01 00:08:04 +00001921 Module *Owner = getSubmodule(OwnerID);
Richard Smithbb853c72014-08-13 01:23:33 +00001922 auto HiddenIt = HiddenNamesMap.find(Owner);
1923 if (HiddenIt != HiddenNamesMap.end()) {
1924 HiddenNames &Hidden = HiddenIt->second;
1925 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1926 if (HI != Hidden.HiddenMacros.end()) {
1927 // Register the macro now so we don't lose it when we re-export.
1928 PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
Richard Smithdaa69e02014-07-25 04:40:03 +00001929
Richard Smithbb853c72014-08-13 01:23:33 +00001930 auto SubOverrides = HI->second->getOverriddenSubmodules();
1931 Hidden.HiddenMacros.erase(HI);
1932 removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
1933 }
Richard Smith49f906a2014-03-01 00:08:04 +00001934 }
1935
1936 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001937 Ambig.erase(
1938 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1939 return MD->getInfo()->getOwningModuleID() == OwnerID;
1940 }),
1941 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001942 }
1943}
1944
1945ASTReader::AmbiguousMacros *
1946ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001947 SourceLocation ImportLoc,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001948 ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001949 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001950 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00001951 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001952
Craig Toppera13603a2014-05-22 05:54:18 +00001953 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
1954 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001955 if (PrevDef && PrevDef->isAmbiguous()) {
1956 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1957 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1958 Ambig.push_back(PrevDef);
1959
Richard Smithdaa69e02014-07-25 04:40:03 +00001960 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001961
1962 if (!Ambig.empty())
1963 return &Ambig;
1964
1965 AmbiguousMacroDefs.erase(II);
1966 } else {
1967 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001968 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001969 if (PrevDef)
1970 Ambig.push_back(PrevDef);
1971
Richard Smithdaa69e02014-07-25 04:40:03 +00001972 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001973
1974 if (!Ambig.empty()) {
1975 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001976 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001977 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001978 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001979 }
Richard Smith49f906a2014-03-01 00:08:04 +00001980
1981 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00001982 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001983}
1984
Richard Smithe56c8bc2015-04-22 00:26:11 +00001985void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo &MMI,
Richard Smithdaa69e02014-07-25 04:40:03 +00001986 Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00001987 assert(II && Owner);
1988
1989 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smithdaa69e02014-07-25 04:40:03 +00001990 if (ImportLoc.isInvalid()) {
Richard Smith49f906a2014-03-01 00:08:04 +00001991 // FIXME: If we made macros from this module visible but didn't provide a
1992 // source location for the import, we don't have a location for the macro.
1993 // Use the location at which the containing module file was first imported
1994 // for now.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001995 ImportLoc = MMI.F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00001996 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00001997 }
1998
Benjamin Kramer834652a2014-05-03 18:44:26 +00001999 AmbiguousMacros *Prev =
Richard Smithe56c8bc2015-04-22 00:26:11 +00002000 removeOverriddenMacros(II, ImportLoc, MMI.getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00002001
Richard Smith49f906a2014-03-01 00:08:04 +00002002 // Create a synthetic macro definition corresponding to the import (or null
2003 // if this was an undefinition of the macro).
Richard Smithe56c8bc2015-04-22 00:26:11 +00002004 MacroDirective *Imported = MMI.import(PP, ImportLoc);
Richard Smithdaa69e02014-07-25 04:40:03 +00002005 DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002006
2007 // If there's no ambiguity, just install the macro.
2008 if (!Prev) {
Richard Smithdaa69e02014-07-25 04:40:03 +00002009 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002010 return;
2011 }
2012 assert(!Prev->empty());
2013
2014 if (!MD) {
2015 // We imported a #undef that didn't remove all prior definitions. The most
2016 // recent prior definition remains, and we install it in the place of the
Richard Smithdaa69e02014-07-25 04:40:03 +00002017 // imported directive, as if by a local #pragma pop_macro.
Richard Smith49f906a2014-03-01 00:08:04 +00002018 MacroInfo *NewMI = Prev->back()->getInfo();
2019 Prev->pop_back();
Richard Smithdaa69e02014-07-25 04:40:03 +00002020 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
2021
2022 // Install our #undef first so that we don't lose track of it. We'll replace
2023 // this with whichever macro definition ends up winning.
2024 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002025 }
2026
2027 // We're introducing a macro definition that creates or adds to an ambiguity.
2028 // We can resolve that ambiguity if this macro is token-for-token identical to
2029 // all of the existing definitions.
2030 MacroInfo *NewMI = MD->getInfo();
2031 assert(NewMI && "macro definition with no MacroInfo?");
2032 while (!Prev->empty()) {
2033 MacroInfo *PrevMI = Prev->back()->getInfo();
2034 assert(PrevMI && "macro definition with no MacroInfo?");
2035
2036 // Before marking the macros as ambiguous, check if this is a case where
2037 // both macros are in system headers. If so, we trust that the system
2038 // did not get it wrong. This also handles cases where Clang's own
2039 // headers have a different spelling of certain system macros:
2040 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
2041 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2042 //
2043 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2044 // overrides the system limits.h's macros, so there's no conflict here.
2045 if (NewMI != PrevMI &&
2046 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2047 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2048 break;
2049
2050 // The previous definition is the same as this one (or both are defined in
2051 // system modules so we can assume they're equivalent); we don't need to
2052 // track it any more.
2053 Prev->pop_back();
2054 }
2055
2056 if (!Prev->empty())
2057 MD->setAmbiguous(true);
2058
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002059 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002060}
2061
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002062ASTReader::InputFileInfo
2063ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002064 // Go find this input file.
2065 BitstreamCursor &Cursor = F.InputFilesCursor;
2066 SavedStreamPosition SavedPosition(Cursor);
2067 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2068
2069 unsigned Code = Cursor.ReadCode();
2070 RecordData Record;
2071 StringRef Blob;
2072
2073 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2074 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2075 "invalid record type for input file");
2076 (void)Result;
2077
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002078 std::string Filename;
2079 off_t StoredSize;
2080 time_t StoredTime;
2081 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002082
Ben Langmuir198c1682014-03-07 07:27:49 +00002083 assert(Record[0] == ID && "Bogus stored ID or offset");
2084 StoredSize = static_cast<off_t>(Record[1]);
2085 StoredTime = static_cast<time_t>(Record[2]);
2086 Overridden = static_cast<bool>(Record[3]);
2087 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002088 ResolveImportedPath(F, Filename);
2089
Hans Wennborg73945142014-03-14 17:45:06 +00002090 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2091 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002092}
2093
2094std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002095 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002096}
2097
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002098InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002099 // If this ID is bogus, just return an empty input file.
2100 if (ID == 0 || ID > F.InputFilesLoaded.size())
2101 return InputFile();
2102
2103 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002104 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002105 return F.InputFilesLoaded[ID-1];
2106
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002107 if (F.InputFilesLoaded[ID-1].isNotFound())
2108 return InputFile();
2109
Guy Benyei11169dd2012-12-18 14:30:41 +00002110 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002111 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002112 SavedStreamPosition SavedPosition(Cursor);
2113 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2114
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002115 InputFileInfo FI = readInputFileInfo(F, ID);
2116 off_t StoredSize = FI.StoredSize;
2117 time_t StoredTime = FI.StoredTime;
2118 bool Overridden = FI.Overridden;
2119 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002120
Ben Langmuir198c1682014-03-07 07:27:49 +00002121 const FileEntry *File
2122 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2123 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2124
2125 // If we didn't find the file, resolve it relative to the
2126 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002127 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002128 F.OriginalDir != CurrentDir) {
2129 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2130 F.OriginalDir,
2131 CurrentDir);
2132 if (!Resolved.empty())
2133 File = FileMgr.getFile(Resolved);
2134 }
2135
2136 // For an overridden file, create a virtual file with the stored
2137 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002138 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002139 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2140 }
2141
Craig Toppera13603a2014-05-22 05:54:18 +00002142 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002143 if (Complain) {
2144 std::string ErrorStr = "could not find file '";
2145 ErrorStr += Filename;
2146 ErrorStr += "' referenced by AST file";
2147 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002148 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002149 // Record that we didn't find the file.
2150 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2151 return InputFile();
2152 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002153
Ben Langmuir198c1682014-03-07 07:27:49 +00002154 // Check if there was a request to override the contents of the file
2155 // that was part of the precompiled header. Overridding such a file
2156 // can lead to problems when lexing using the source locations from the
2157 // PCH.
2158 SourceManager &SM = getSourceManager();
2159 if (!Overridden && SM.isFileOverridden(File)) {
2160 if (Complain)
2161 Error(diag::err_fe_pch_file_overridden, Filename);
2162 // After emitting the diagnostic, recover by disabling the override so
2163 // that the original file will be used.
2164 SM.disableFileContentsOverride(File);
2165 // The FileEntry is a virtual file entry with the size of the contents
2166 // that would override the original contents. Set it to the original's
2167 // size/time.
2168 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2169 StoredSize, StoredTime);
2170 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002171
Ben Langmuir198c1682014-03-07 07:27:49 +00002172 bool IsOutOfDate = false;
2173
2174 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002175 if (!Overridden && //
2176 (StoredSize != File->getSize() ||
2177#if defined(LLVM_ON_WIN32)
2178 false
2179#else
Ben Langmuir198c1682014-03-07 07:27:49 +00002180 // In our regression testing, the Windows file system seems to
2181 // have inconsistent modification times that sometimes
2182 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00002183 //
2184 // This also happens in networked file systems, so disable this
2185 // check if validation is disabled or if we have an explicitly
2186 // built PCM file.
2187 //
2188 // FIXME: Should we also do this for PCH files? They could also
2189 // reasonably get shared across a network during a distributed build.
2190 (StoredTime != File->getModificationTime() && !DisableValidation &&
2191 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00002192#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002193 )) {
2194 if (Complain) {
2195 // Build a list of the PCH imports that got us here (in reverse).
2196 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2197 while (ImportStack.back()->ImportedBy.size() > 0)
2198 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002199
Ben Langmuir198c1682014-03-07 07:27:49 +00002200 // The top-level PCH is stale.
2201 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2202 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002203
Ben Langmuir198c1682014-03-07 07:27:49 +00002204 // Print the import stack.
2205 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2206 Diag(diag::note_pch_required_by)
2207 << Filename << ImportStack[0]->FileName;
2208 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002209 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002210 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002211 }
2212
Ben Langmuir198c1682014-03-07 07:27:49 +00002213 if (!Diags.isDiagnosticInFlight())
2214 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002215 }
2216
Ben Langmuir198c1682014-03-07 07:27:49 +00002217 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002218 }
2219
Ben Langmuir198c1682014-03-07 07:27:49 +00002220 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2221
2222 // Note that we've loaded this input file.
2223 F.InputFilesLoaded[ID-1] = IF;
2224 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002225}
2226
Richard Smith7ed1bc92014-12-05 22:42:13 +00002227/// \brief If we are loading a relocatable PCH or module file, and the filename
2228/// is not an absolute path, add the system or module root to the beginning of
2229/// the file name.
2230void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2231 // Resolve relative to the base directory, if we have one.
2232 if (!M.BaseDirectory.empty())
2233 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002234}
2235
Richard Smith7ed1bc92014-12-05 22:42:13 +00002236void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002237 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2238 return;
2239
Richard Smith7ed1bc92014-12-05 22:42:13 +00002240 SmallString<128> Buffer;
2241 llvm::sys::path::append(Buffer, Prefix, Filename);
2242 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002243}
2244
2245ASTReader::ASTReadResult
2246ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002247 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002248 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002249 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002250 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002251
2252 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2253 Error("malformed block record in AST file");
2254 return Failure;
2255 }
2256
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002257 // Should we allow the configuration of the module file to differ from the
2258 // configuration of the current translation unit in a compatible way?
2259 //
2260 // FIXME: Allow this for files explicitly specified with -include-pch too.
2261 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2262
Guy Benyei11169dd2012-12-18 14:30:41 +00002263 // Read all of the records and blocks in the control block.
2264 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002265 unsigned NumInputs = 0;
2266 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002267 while (1) {
2268 llvm::BitstreamEntry Entry = Stream.advance();
2269
2270 switch (Entry.Kind) {
2271 case llvm::BitstreamEntry::Error:
2272 Error("malformed block record in AST file");
2273 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002274 case llvm::BitstreamEntry::EndBlock: {
2275 // Validate input files.
2276 const HeaderSearchOptions &HSOpts =
2277 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002278
Richard Smitha1825302014-10-23 22:18:29 +00002279 // All user input files reside at the index range [0, NumUserInputs), and
2280 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002281 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002282 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002283
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002284 // If we are reading a module, we will create a verification timestamp,
2285 // so we verify all input files. Otherwise, verify only user input
2286 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002287
2288 unsigned N = NumUserInputs;
2289 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002290 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002291 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002292 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002293 N = NumInputs;
2294
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002295 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002296 InputFile IF = getInputFile(F, I+1, Complain);
2297 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002298 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002299 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002300 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002301
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002302 if (Listener)
2303 Listener->visitModuleFile(F.FileName);
2304
Ben Langmuircb69b572014-03-07 06:40:32 +00002305 if (Listener && Listener->needsInputFileVisitation()) {
2306 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2307 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002308 for (unsigned I = 0; I < N; ++I) {
2309 bool IsSystem = I >= NumUserInputs;
2310 InputFileInfo FI = readInputFileInfo(F, I+1);
2311 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2312 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002313 }
2314
Guy Benyei11169dd2012-12-18 14:30:41 +00002315 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002316 }
2317
Chris Lattnere7b154b2013-01-19 21:39:22 +00002318 case llvm::BitstreamEntry::SubBlock:
2319 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002320 case INPUT_FILES_BLOCK_ID:
2321 F.InputFilesCursor = Stream;
2322 if (Stream.SkipBlock() || // Skip with the main cursor
2323 // Read the abbreviations
2324 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2325 Error("malformed block record in AST file");
2326 return Failure;
2327 }
2328 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002329
Guy Benyei11169dd2012-12-18 14:30:41 +00002330 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002331 if (Stream.SkipBlock()) {
2332 Error("malformed block record in AST file");
2333 return Failure;
2334 }
2335 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002336 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002337
2338 case llvm::BitstreamEntry::Record:
2339 // The interesting case.
2340 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002341 }
2342
2343 // Read and process a record.
2344 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002345 StringRef Blob;
2346 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002347 case METADATA: {
2348 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2349 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002350 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2351 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002352 return VersionMismatch;
2353 }
2354
2355 bool hasErrors = Record[5];
2356 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2357 Diag(diag::err_pch_with_compiler_errors);
2358 return HadErrors;
2359 }
2360
2361 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002362 // Relative paths in a relocatable PCH are relative to our sysroot.
2363 if (F.RelocatablePCH)
2364 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002365
2366 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002367 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2369 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002370 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 return VersionMismatch;
2372 }
2373 break;
2374 }
2375
Ben Langmuir487ea142014-10-23 18:05:36 +00002376 case SIGNATURE:
2377 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2378 F.Signature = Record[0];
2379 break;
2380
Guy Benyei11169dd2012-12-18 14:30:41 +00002381 case IMPORTS: {
2382 // Load each of the imported PCH files.
2383 unsigned Idx = 0, N = Record.size();
2384 while (Idx < N) {
2385 // Read information about the AST file.
2386 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2387 // The import location will be the local one for now; we will adjust
2388 // all import locations of module imports after the global source
2389 // location info are setup.
2390 SourceLocation ImportLoc =
2391 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002392 off_t StoredSize = (off_t)Record[Idx++];
2393 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002394 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002395 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002396
2397 // Load the AST file.
2398 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002399 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002400 ClientLoadCapabilities)) {
2401 case Failure: return Failure;
2402 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002403 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002404 case OutOfDate: return OutOfDate;
2405 case VersionMismatch: return VersionMismatch;
2406 case ConfigurationMismatch: return ConfigurationMismatch;
2407 case HadErrors: return HadErrors;
2408 case Success: break;
2409 }
2410 }
2411 break;
2412 }
2413
Richard Smith7f330cd2015-03-18 01:42:29 +00002414 case KNOWN_MODULE_FILES:
2415 break;
2416
Guy Benyei11169dd2012-12-18 14:30:41 +00002417 case LANGUAGE_OPTIONS: {
2418 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002419 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002421 ParseLanguageOptions(Record, Complain, *Listener,
2422 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002423 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 return ConfigurationMismatch;
2425 break;
2426 }
2427
2428 case TARGET_OPTIONS: {
2429 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2430 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002431 ParseTargetOptions(Record, Complain, *Listener,
2432 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002433 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 return ConfigurationMismatch;
2435 break;
2436 }
2437
2438 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002439 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002440 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002441 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002442 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002443 !DisableValidation)
2444 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002445 break;
2446 }
2447
2448 case FILE_SYSTEM_OPTIONS: {
2449 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2450 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002451 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002452 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002453 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002454 return ConfigurationMismatch;
2455 break;
2456 }
2457
2458 case HEADER_SEARCH_OPTIONS: {
2459 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2460 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002461 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002462 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002463 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 return ConfigurationMismatch;
2465 break;
2466 }
2467
2468 case PREPROCESSOR_OPTIONS: {
2469 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2470 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002471 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 ParsePreprocessorOptions(Record, Complain, *Listener,
2473 SuggestedPredefines) &&
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 ORIGINAL_FILE:
2480 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002481 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002482 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002483 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002484 break;
2485
2486 case ORIGINAL_FILE_ID:
2487 F.OriginalSourceFileID = FileID::get(Record[0]);
2488 break;
2489
2490 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002491 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002492 break;
2493
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002494 case MODULE_NAME:
2495 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002496 if (Listener)
2497 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002498 break;
2499
Richard Smith223d3f22014-12-06 03:21:08 +00002500 case MODULE_DIRECTORY: {
2501 assert(!F.ModuleName.empty() &&
2502 "MODULE_DIRECTORY found before MODULE_NAME");
2503 // If we've already loaded a module map file covering this module, we may
2504 // have a better path for it (relative to the current build).
2505 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2506 if (M && M->Directory) {
2507 // If we're implicitly loading a module, the base directory can't
2508 // change between the build and use.
2509 if (F.Kind != MK_ExplicitModule) {
2510 const DirectoryEntry *BuildDir =
2511 PP.getFileManager().getDirectory(Blob);
2512 if (!BuildDir || BuildDir != M->Directory) {
2513 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2514 Diag(diag::err_imported_module_relocated)
2515 << F.ModuleName << Blob << M->Directory->getName();
2516 return OutOfDate;
2517 }
2518 }
2519 F.BaseDirectory = M->Directory->getName();
2520 } else {
2521 F.BaseDirectory = Blob;
2522 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002523 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002524 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002525
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002526 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002527 if (ASTReadResult Result =
2528 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2529 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002530 break;
2531
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002533 NumInputs = Record[0];
2534 NumUserInputs = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00002535 F.InputFileOffsets = (const uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002536 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002537 break;
2538 }
2539 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002540}
2541
Ben Langmuir2c9af442014-04-10 17:57:43 +00002542ASTReader::ASTReadResult
2543ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002544 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002545
2546 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2547 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002548 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002549 }
2550
2551 // Read all of the records and blocks for the AST file.
2552 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002553 while (1) {
2554 llvm::BitstreamEntry Entry = Stream.advance();
2555
2556 switch (Entry.Kind) {
2557 case llvm::BitstreamEntry::Error:
2558 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002559 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002560 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002561 // Outside of C++, we do not store a lookup map for the translation unit.
2562 // Instead, mark it as needing a lookup map to be built if this module
2563 // contains any declarations lexically within it (which it always does!).
2564 // This usually has no cost, since we very rarely need the lookup map for
2565 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002567 if (DC->hasExternalLexicalStorage() &&
2568 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002569 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002570
Ben Langmuir2c9af442014-04-10 17:57:43 +00002571 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002573 case llvm::BitstreamEntry::SubBlock:
2574 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 case DECLTYPES_BLOCK_ID:
2576 // We lazily load the decls block, but we want to set up the
2577 // DeclsCursor cursor to point into it. Clone our current bitcode
2578 // cursor to it, enter the block and read the abbrevs in that block.
2579 // With the main cursor, we just skip over it.
2580 F.DeclsCursor = Stream;
2581 if (Stream.SkipBlock() || // Skip with the main cursor.
2582 // Read the abbrevs.
2583 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2584 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002585 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 }
2587 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002588
Guy Benyei11169dd2012-12-18 14:30:41 +00002589 case PREPROCESSOR_BLOCK_ID:
2590 F.MacroCursor = Stream;
2591 if (!PP.getExternalSource())
2592 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002593
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 if (Stream.SkipBlock() ||
2595 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2596 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002597 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 }
2599 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2600 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002601
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 case PREPROCESSOR_DETAIL_BLOCK_ID:
2603 F.PreprocessorDetailCursor = Stream;
2604 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002605 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002606 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002607 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002608 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002609 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002611 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2612
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 if (!PP.getPreprocessingRecord())
2614 PP.createPreprocessingRecord();
2615 if (!PP.getPreprocessingRecord()->getExternalSource())
2616 PP.getPreprocessingRecord()->SetExternalSource(*this);
2617 break;
2618
2619 case SOURCE_MANAGER_BLOCK_ID:
2620 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002621 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002623
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002625 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2626 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002627 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002628
Guy Benyei11169dd2012-12-18 14:30:41 +00002629 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002630 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 if (Stream.SkipBlock() ||
2632 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2633 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002634 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 }
2636 CommentsCursors.push_back(std::make_pair(C, &F));
2637 break;
2638 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002639
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002641 if (Stream.SkipBlock()) {
2642 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002643 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002644 }
2645 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 }
2647 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002648
2649 case llvm::BitstreamEntry::Record:
2650 // The interesting case.
2651 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002652 }
2653
2654 // Read and process a record.
2655 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002656 StringRef Blob;
2657 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002658 default: // Default behavior: ignore.
2659 break;
2660
2661 case TYPE_OFFSET: {
2662 if (F.LocalNumTypes != 0) {
2663 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002664 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002666 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002667 F.LocalNumTypes = Record[0];
2668 unsigned LocalBaseTypeIndex = Record[1];
2669 F.BaseTypeIndex = getTotalNumTypes();
2670
2671 if (F.LocalNumTypes > 0) {
2672 // Introduce the global -> local mapping for types within this module.
2673 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2674
2675 // Introduce the local -> global mapping for types within this module.
2676 F.TypeRemap.insertOrReplace(
2677 std::make_pair(LocalBaseTypeIndex,
2678 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002679
2680 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002681 }
2682 break;
2683 }
2684
2685 case DECL_OFFSET: {
2686 if (F.LocalNumDecls != 0) {
2687 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002688 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002690 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 F.LocalNumDecls = Record[0];
2692 unsigned LocalBaseDeclID = Record[1];
2693 F.BaseDeclID = getTotalNumDecls();
2694
2695 if (F.LocalNumDecls > 0) {
2696 // Introduce the global -> local mapping for declarations within this
2697 // module.
2698 GlobalDeclMap.insert(
2699 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2700
2701 // Introduce the local -> global mapping for declarations within this
2702 // module.
2703 F.DeclRemap.insertOrReplace(
2704 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2705
2706 // Introduce the global -> local mapping for declarations within this
2707 // module.
2708 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002709
Ben Langmuir52ca6782014-10-20 16:27:32 +00002710 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2711 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 break;
2713 }
2714
2715 case TU_UPDATE_LEXICAL: {
2716 DeclContext *TU = Context.getTranslationUnitDecl();
2717 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002718 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002720 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 TU->setHasExternalLexicalStorage(true);
2722 break;
2723 }
2724
2725 case UPDATE_VISIBLE: {
2726 unsigned Idx = 0;
2727 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2728 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002729 ASTDeclContextNameLookupTable::Create(
2730 (const unsigned char *)Blob.data() + Record[Idx++],
2731 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2732 (const unsigned char *)Blob.data(),
2733 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002734 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002735 auto *DC = cast<DeclContext>(D);
2736 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002737 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2738 delete LookupTable;
2739 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 } else
2741 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2742 break;
2743 }
2744
2745 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002746 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002748 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2749 (const unsigned char *)F.IdentifierTableData + Record[0],
2750 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2751 (const unsigned char *)F.IdentifierTableData,
2752 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002753
2754 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2755 }
2756 break;
2757
2758 case IDENTIFIER_OFFSET: {
2759 if (F.LocalNumIdentifiers != 0) {
2760 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002761 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002762 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002763 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002764 F.LocalNumIdentifiers = Record[0];
2765 unsigned LocalBaseIdentifierID = Record[1];
2766 F.BaseIdentifierID = getTotalNumIdentifiers();
2767
2768 if (F.LocalNumIdentifiers > 0) {
2769 // Introduce the global -> local mapping for identifiers within this
2770 // module.
2771 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2772 &F));
2773
2774 // Introduce the local -> global mapping for identifiers within this
2775 // module.
2776 F.IdentifierRemap.insertOrReplace(
2777 std::make_pair(LocalBaseIdentifierID,
2778 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002779
Ben Langmuir52ca6782014-10-20 16:27:32 +00002780 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2781 + F.LocalNumIdentifiers);
2782 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002783 break;
2784 }
2785
Ben Langmuir332aafe2014-01-31 01:06:56 +00002786 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002787 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2788 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002789 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002790 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002791 break;
2792
2793 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002794 if (SpecialTypes.empty()) {
2795 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2796 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2797 break;
2798 }
2799
2800 if (SpecialTypes.size() != Record.size()) {
2801 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002802 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002803 }
2804
2805 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2806 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2807 if (!SpecialTypes[I])
2808 SpecialTypes[I] = ID;
2809 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2810 // merge step?
2811 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002812 break;
2813
2814 case STATISTICS:
2815 TotalNumStatements += Record[0];
2816 TotalNumMacros += Record[1];
2817 TotalLexicalDeclContexts += Record[2];
2818 TotalVisibleDeclContexts += Record[3];
2819 break;
2820
2821 case UNUSED_FILESCOPED_DECLS:
2822 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2823 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2824 break;
2825
2826 case DELEGATING_CTORS:
2827 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2828 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2829 break;
2830
2831 case WEAK_UNDECLARED_IDENTIFIERS:
2832 if (Record.size() % 4 != 0) {
2833 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002834 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002835 }
2836
2837 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2838 // files. This isn't the way to do it :)
2839 WeakUndeclaredIdentifiers.clear();
2840
2841 // Translate the weak, undeclared identifiers into global IDs.
2842 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2843 WeakUndeclaredIdentifiers.push_back(
2844 getGlobalIdentifierID(F, Record[I++]));
2845 WeakUndeclaredIdentifiers.push_back(
2846 getGlobalIdentifierID(F, Record[I++]));
2847 WeakUndeclaredIdentifiers.push_back(
2848 ReadSourceLocation(F, Record, I).getRawEncoding());
2849 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2850 }
2851 break;
2852
Guy Benyei11169dd2012-12-18 14:30:41 +00002853 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002854 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002855 F.LocalNumSelectors = Record[0];
2856 unsigned LocalBaseSelectorID = Record[1];
2857 F.BaseSelectorID = getTotalNumSelectors();
2858
2859 if (F.LocalNumSelectors > 0) {
2860 // Introduce the global -> local mapping for selectors within this
2861 // module.
2862 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2863
2864 // Introduce the local -> global mapping for selectors within this
2865 // module.
2866 F.SelectorRemap.insertOrReplace(
2867 std::make_pair(LocalBaseSelectorID,
2868 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002869
2870 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002871 }
2872 break;
2873 }
2874
2875 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002876 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002877 if (Record[0])
2878 F.SelectorLookupTable
2879 = ASTSelectorLookupTable::Create(
2880 F.SelectorLookupTableData + Record[0],
2881 F.SelectorLookupTableData,
2882 ASTSelectorLookupTrait(*this, F));
2883 TotalNumMethodPoolEntries += Record[1];
2884 break;
2885
2886 case REFERENCED_SELECTOR_POOL:
2887 if (!Record.empty()) {
2888 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2889 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2890 Record[Idx++]));
2891 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2892 getRawEncoding());
2893 }
2894 }
2895 break;
2896
2897 case PP_COUNTER_VALUE:
2898 if (!Record.empty() && Listener)
2899 Listener->ReadCounter(F, Record[0]);
2900 break;
2901
2902 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002903 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002904 F.NumFileSortedDecls = Record[0];
2905 break;
2906
2907 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002908 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002909 F.LocalNumSLocEntries = Record[0];
2910 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002911 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002912 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002913 SLocSpaceSize);
2914 // Make our entry in the range map. BaseID is negative and growing, so
2915 // we invert it. Because we invert it, though, we need the other end of
2916 // the range.
2917 unsigned RangeStart =
2918 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2919 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2920 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2921
2922 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2923 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2924 GlobalSLocOffsetMap.insert(
2925 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2926 - SLocSpaceSize,&F));
2927
2928 // Initialize the remapping table.
2929 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002930 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002931 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002932 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2934
2935 TotalNumSLocEntries += F.LocalNumSLocEntries;
2936 break;
2937 }
2938
2939 case MODULE_OFFSET_MAP: {
2940 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002941 const unsigned char *Data = (const unsigned char*)Blob.data();
2942 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002943
2944 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2945 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2946 F.SLocRemap.insert(std::make_pair(0U, 0));
2947 F.SLocRemap.insert(std::make_pair(2U, 1));
2948 }
2949
Guy Benyei11169dd2012-12-18 14:30:41 +00002950 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002951 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2952 RemapBuilder;
2953 RemapBuilder SLocRemap(F.SLocRemap);
2954 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2955 RemapBuilder MacroRemap(F.MacroRemap);
2956 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2957 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2958 RemapBuilder SelectorRemap(F.SelectorRemap);
2959 RemapBuilder DeclRemap(F.DeclRemap);
2960 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002961
2962 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002963 using namespace llvm::support;
2964 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002965 StringRef Name = StringRef((const char*)Data, Len);
2966 Data += Len;
2967 ModuleFile *OM = ModuleMgr.lookup(Name);
2968 if (!OM) {
2969 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002970 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002971 }
2972
Justin Bogner57ba0b22014-03-28 22:03:24 +00002973 uint32_t SLocOffset =
2974 endian::readNext<uint32_t, little, unaligned>(Data);
2975 uint32_t IdentifierIDOffset =
2976 endian::readNext<uint32_t, little, unaligned>(Data);
2977 uint32_t MacroIDOffset =
2978 endian::readNext<uint32_t, little, unaligned>(Data);
2979 uint32_t PreprocessedEntityIDOffset =
2980 endian::readNext<uint32_t, little, unaligned>(Data);
2981 uint32_t SubmoduleIDOffset =
2982 endian::readNext<uint32_t, little, unaligned>(Data);
2983 uint32_t SelectorIDOffset =
2984 endian::readNext<uint32_t, little, unaligned>(Data);
2985 uint32_t DeclIDOffset =
2986 endian::readNext<uint32_t, little, unaligned>(Data);
2987 uint32_t TypeIndexOffset =
2988 endian::readNext<uint32_t, little, unaligned>(Data);
2989
Ben Langmuir785180e2014-10-20 16:27:30 +00002990 uint32_t None = std::numeric_limits<uint32_t>::max();
2991
2992 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2993 RemapBuilder &Remap) {
2994 if (Offset != None)
2995 Remap.insert(std::make_pair(Offset,
2996 static_cast<int>(BaseOffset - Offset)));
2997 };
2998 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2999 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3000 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3001 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3002 PreprocessedEntityRemap);
3003 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3004 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3005 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3006 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003007
3008 // Global -> local mappings.
3009 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3010 }
3011 break;
3012 }
3013
3014 case SOURCE_MANAGER_LINE_TABLE:
3015 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003016 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003017 break;
3018
3019 case SOURCE_LOCATION_PRELOADS: {
3020 // Need to transform from the local view (1-based IDs) to the global view,
3021 // which is based off F.SLocEntryBaseID.
3022 if (!F.PreloadSLocEntries.empty()) {
3023 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003024 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003025 }
3026
3027 F.PreloadSLocEntries.swap(Record);
3028 break;
3029 }
3030
3031 case EXT_VECTOR_DECLS:
3032 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3033 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3034 break;
3035
3036 case VTABLE_USES:
3037 if (Record.size() % 3 != 0) {
3038 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003039 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003040 }
3041
3042 // Later tables overwrite earlier ones.
3043 // FIXME: Modules will have some trouble with this. This is clearly not
3044 // the right way to do this.
3045 VTableUses.clear();
3046
3047 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3048 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3049 VTableUses.push_back(
3050 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3051 VTableUses.push_back(Record[Idx++]);
3052 }
3053 break;
3054
Guy Benyei11169dd2012-12-18 14:30:41 +00003055 case PENDING_IMPLICIT_INSTANTIATIONS:
3056 if (PendingInstantiations.size() % 2 != 0) {
3057 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003058 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003059 }
3060
3061 if (Record.size() % 2 != 0) {
3062 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003063 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003064 }
3065
3066 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3067 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3068 PendingInstantiations.push_back(
3069 ReadSourceLocation(F, Record, I).getRawEncoding());
3070 }
3071 break;
3072
3073 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003074 if (Record.size() != 2) {
3075 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003076 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003077 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003078 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3079 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3080 break;
3081
3082 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003083 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3084 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3085 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003086
3087 unsigned LocalBasePreprocessedEntityID = Record[0];
3088
3089 unsigned StartingID;
3090 if (!PP.getPreprocessingRecord())
3091 PP.createPreprocessingRecord();
3092 if (!PP.getPreprocessingRecord()->getExternalSource())
3093 PP.getPreprocessingRecord()->SetExternalSource(*this);
3094 StartingID
3095 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003096 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003097 F.BasePreprocessedEntityID = StartingID;
3098
3099 if (F.NumPreprocessedEntities > 0) {
3100 // Introduce the global -> local mapping for preprocessed entities in
3101 // this module.
3102 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3103
3104 // Introduce the local -> global mapping for preprocessed entities in
3105 // this module.
3106 F.PreprocessedEntityRemap.insertOrReplace(
3107 std::make_pair(LocalBasePreprocessedEntityID,
3108 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3109 }
3110
3111 break;
3112 }
3113
3114 case DECL_UPDATE_OFFSETS: {
3115 if (Record.size() % 2 != 0) {
3116 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003117 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003118 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003119 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3120 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3121 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3122
3123 // If we've already loaded the decl, perform the updates when we finish
3124 // loading this block.
3125 if (Decl *D = GetExistingDecl(ID))
3126 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3127 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 break;
3129 }
3130
3131 case DECL_REPLACEMENTS: {
3132 if (Record.size() % 3 != 0) {
3133 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003134 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003135 }
3136 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3137 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3138 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3139 break;
3140 }
3141
3142 case OBJC_CATEGORIES_MAP: {
3143 if (F.LocalNumObjCCategoriesInMap != 0) {
3144 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003145 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 }
3147
3148 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003149 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003150 break;
3151 }
3152
3153 case OBJC_CATEGORIES:
3154 F.ObjCCategories.swap(Record);
3155 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003156
Guy Benyei11169dd2012-12-18 14:30:41 +00003157 case CXX_BASE_SPECIFIER_OFFSETS: {
3158 if (F.LocalNumCXXBaseSpecifiers != 0) {
3159 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003160 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003161 }
Richard Smithc2bb8182015-03-24 06:36:48 +00003162
Guy Benyei11169dd2012-12-18 14:30:41 +00003163 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003164 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00003165 break;
3166 }
3167
3168 case CXX_CTOR_INITIALIZERS_OFFSETS: {
3169 if (F.LocalNumCXXCtorInitializers != 0) {
3170 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
3171 return Failure;
3172 }
3173
3174 F.LocalNumCXXCtorInitializers = Record[0];
3175 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003176 break;
3177 }
3178
3179 case DIAG_PRAGMA_MAPPINGS:
3180 if (F.PragmaDiagMappings.empty())
3181 F.PragmaDiagMappings.swap(Record);
3182 else
3183 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3184 Record.begin(), Record.end());
3185 break;
3186
3187 case CUDA_SPECIAL_DECL_REFS:
3188 // Later tables overwrite earlier ones.
3189 // FIXME: Modules will have trouble with this.
3190 CUDASpecialDeclRefs.clear();
3191 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3192 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3193 break;
3194
3195 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003196 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003197 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003198 if (Record[0]) {
3199 F.HeaderFileInfoTable
3200 = HeaderFileInfoLookupTable::Create(
3201 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3202 (const unsigned char *)F.HeaderFileInfoTableData,
3203 HeaderFileInfoTrait(*this, F,
3204 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003205 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003206
3207 PP.getHeaderSearchInfo().SetExternalSource(this);
3208 if (!PP.getHeaderSearchInfo().getExternalLookup())
3209 PP.getHeaderSearchInfo().SetExternalLookup(this);
3210 }
3211 break;
3212 }
3213
3214 case FP_PRAGMA_OPTIONS:
3215 // Later tables overwrite earlier ones.
3216 FPPragmaOptions.swap(Record);
3217 break;
3218
3219 case OPENCL_EXTENSIONS:
3220 // Later tables overwrite earlier ones.
3221 OpenCLExtensions.swap(Record);
3222 break;
3223
3224 case TENTATIVE_DEFINITIONS:
3225 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3226 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3227 break;
3228
3229 case KNOWN_NAMESPACES:
3230 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3231 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3232 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003233
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003234 case UNDEFINED_BUT_USED:
3235 if (UndefinedButUsed.size() % 2 != 0) {
3236 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003237 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003238 }
3239
3240 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003241 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003242 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003243 }
3244 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003245 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3246 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003247 ReadSourceLocation(F, Record, I).getRawEncoding());
3248 }
3249 break;
3250
Guy Benyei11169dd2012-12-18 14:30:41 +00003251 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003252 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003253 // If we aren't loading a module (which has its own exports), make
3254 // all of the imported modules visible.
3255 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003256 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3257 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3258 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3259 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003260 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003261 }
3262 }
3263 break;
3264 }
3265
3266 case LOCAL_REDECLARATIONS: {
3267 F.RedeclarationChains.swap(Record);
3268 break;
3269 }
3270
3271 case LOCAL_REDECLARATIONS_MAP: {
3272 if (F.LocalNumRedeclarationsInMap != 0) {
3273 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003274 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003275 }
3276
3277 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003278 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003279 break;
3280 }
3281
Guy Benyei11169dd2012-12-18 14:30:41 +00003282 case MACRO_OFFSET: {
3283 if (F.LocalNumMacros != 0) {
3284 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003285 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003286 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003287 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003288 F.LocalNumMacros = Record[0];
3289 unsigned LocalBaseMacroID = Record[1];
3290 F.BaseMacroID = getTotalNumMacros();
3291
3292 if (F.LocalNumMacros > 0) {
3293 // Introduce the global -> local mapping for macros within this module.
3294 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3295
3296 // Introduce the local -> global mapping for macros within this module.
3297 F.MacroRemap.insertOrReplace(
3298 std::make_pair(LocalBaseMacroID,
3299 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003300
3301 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003302 }
3303 break;
3304 }
3305
Richard Smithe40f2ba2013-08-07 21:41:30 +00003306 case LATE_PARSED_TEMPLATE: {
3307 LateParsedTemplates.append(Record.begin(), Record.end());
3308 break;
3309 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003310
3311 case OPTIMIZE_PRAGMA_OPTIONS:
3312 if (Record.size() != 1) {
3313 Error("invalid pragma optimize record");
3314 return Failure;
3315 }
3316 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3317 break;
Nico Weber72889432014-09-06 01:25:55 +00003318
3319 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3320 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3321 UnusedLocalTypedefNameCandidates.push_back(
3322 getGlobalDeclID(F, Record[I]));
3323 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003324 }
3325 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003326}
3327
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003328ASTReader::ASTReadResult
3329ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3330 const ModuleFile *ImportedBy,
3331 unsigned ClientLoadCapabilities) {
3332 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003333 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003334
Richard Smithe842a472014-10-22 02:05:46 +00003335 if (F.Kind == MK_ExplicitModule) {
3336 // For an explicitly-loaded module, we don't care whether the original
3337 // module map file exists or matches.
3338 return Success;
3339 }
3340
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003341 // Try to resolve ModuleName in the current header search context and
3342 // verify that it is found in the same module map file as we saved. If the
3343 // top-level AST file is a main file, skip this check because there is no
3344 // usable header search context.
3345 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003346 "MODULE_NAME should come before MODULE_MAP_FILE");
3347 if (F.Kind == MK_ImplicitModule &&
3348 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3349 // An implicitly-loaded module file should have its module listed in some
3350 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003351 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003352 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3353 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3354 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003355 assert(ImportedBy && "top-level import should be verified");
3356 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003357 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3358 << ImportedBy->FileName
3359 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003360 return Missing;
3361 }
3362
Richard Smithe842a472014-10-22 02:05:46 +00003363 assert(M->Name == F.ModuleName && "found module with different name");
3364
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003365 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003366 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003367 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3368 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003369 assert(ImportedBy && "top-level import should be verified");
3370 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3371 Diag(diag::err_imported_module_modmap_changed)
3372 << F.ModuleName << ImportedBy->FileName
3373 << ModMap->getName() << F.ModuleMapPath;
3374 return OutOfDate;
3375 }
3376
3377 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3378 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3379 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003380 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003381 const FileEntry *F =
3382 FileMgr.getFile(Filename, false, false);
3383 if (F == nullptr) {
3384 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3385 Error("could not find file '" + Filename +"' referenced by AST file");
3386 return OutOfDate;
3387 }
3388 AdditionalStoredMaps.insert(F);
3389 }
3390
3391 // Check any additional module map files (e.g. module.private.modulemap)
3392 // that are not in the pcm.
3393 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3394 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3395 // Remove files that match
3396 // Note: SmallPtrSet::erase is really remove
3397 if (!AdditionalStoredMaps.erase(ModMap)) {
3398 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3399 Diag(diag::err_module_different_modmap)
3400 << F.ModuleName << /*new*/0 << ModMap->getName();
3401 return OutOfDate;
3402 }
3403 }
3404 }
3405
3406 // Check any additional module map files that are in the pcm, but not
3407 // found in header search. Cases that match are already removed.
3408 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3409 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3410 Diag(diag::err_module_different_modmap)
3411 << F.ModuleName << /*not new*/1 << ModMap->getName();
3412 return OutOfDate;
3413 }
3414 }
3415
3416 if (Listener)
3417 Listener->ReadModuleMapFile(F.ModuleMapPath);
3418 return Success;
3419}
3420
3421
Douglas Gregorc1489562013-02-12 23:36:21 +00003422/// \brief Move the given method to the back of the global list of methods.
3423static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3424 // Find the entry for this selector in the method pool.
3425 Sema::GlobalMethodPool::iterator Known
3426 = S.MethodPool.find(Method->getSelector());
3427 if (Known == S.MethodPool.end())
3428 return;
3429
3430 // Retrieve the appropriate method list.
3431 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3432 : Known->second.second;
3433 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003434 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003435 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003436 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003437 Found = true;
3438 } else {
3439 // Keep searching.
3440 continue;
3441 }
3442 }
3443
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003444 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003445 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003446 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003447 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003448 }
3449}
3450
Richard Smithe657bbd2014-07-18 22:13:40 +00003451void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3452 bool FromFinalization) {
3453 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith57721ac2014-07-21 04:10:40 +00003454 for (Decl *D : Names.HiddenDecls) {
Richard Smith49f906a2014-03-01 00:08:04 +00003455 bool wasHidden = D->Hidden;
3456 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003457
Richard Smith49f906a2014-03-01 00:08:04 +00003458 if (wasHidden && SemaObj) {
3459 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3460 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003461 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003462 }
3463 }
Richard Smith49f906a2014-03-01 00:08:04 +00003464
Richard Smithe657bbd2014-07-18 22:13:40 +00003465 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3466 "nothing to make visible?");
Richard Smithdaa69e02014-07-25 04:40:03 +00003467 for (const auto &Macro : Names.HiddenMacros) {
3468 if (FromFinalization)
3469 PP.appendMacroDirective(Macro.first,
3470 Macro.second->import(PP, SourceLocation()));
3471 else
Richard Smithe56c8bc2015-04-22 00:26:11 +00003472 installImportedMacro(Macro.first, *Macro.second, Owner);
Richard Smithdaa69e02014-07-25 04:40:03 +00003473 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003474}
3475
Richard Smith49f906a2014-03-01 00:08:04 +00003476void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003477 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003478 SourceLocation ImportLoc,
3479 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003480 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003481 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003482 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003483 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003484 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003485
3486 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003487 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003488 // there is nothing more to do.
3489 continue;
3490 }
Richard Smith49f906a2014-03-01 00:08:04 +00003491
Guy Benyei11169dd2012-12-18 14:30:41 +00003492 if (!Mod->isAvailable()) {
3493 // Modules that aren't available cannot be made visible.
3494 continue;
3495 }
3496
3497 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003498 if (NameVisibility >= Module::MacrosVisible &&
3499 Mod->NameVisibility < Module::MacrosVisible)
3500 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003501 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003502
Guy Benyei11169dd2012-12-18 14:30:41 +00003503 // If we've already deserialized any names from this module,
3504 // mark them as visible.
3505 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3506 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003507 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003508 HiddenNamesMap.erase(Hidden);
Richard Smith57721ac2014-07-21 04:10:40 +00003509 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3510 /*FromFinalization*/false);
3511 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3512 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003513 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003514
Guy Benyei11169dd2012-12-18 14:30:41 +00003515 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003516 SmallVector<Module *, 16> Exports;
3517 Mod->getExportedModules(Exports);
3518 for (SmallVectorImpl<Module *>::iterator
3519 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3520 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003521 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003522 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003523 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003524
3525 // Detect any conflicts.
3526 if (Complain) {
3527 assert(ImportLoc.isValid() && "Missing import location");
3528 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3529 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3530 Diag(ImportLoc, diag::warn_module_conflict)
3531 << Mod->getFullModuleName()
3532 << Mod->Conflicts[I].Other->getFullModuleName()
3533 << Mod->Conflicts[I].Message;
3534 // FIXME: Need note where the other module was imported.
3535 }
3536 }
3537 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003538 }
3539}
3540
Douglas Gregore060e572013-01-25 01:03:03 +00003541bool ASTReader::loadGlobalIndex() {
3542 if (GlobalIndex)
3543 return false;
3544
3545 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3546 !Context.getLangOpts().Modules)
3547 return true;
3548
3549 // Try to load the global index.
3550 TriedLoadingGlobalIndex = true;
3551 StringRef ModuleCachePath
3552 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3553 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003554 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003555 if (!Result.first)
3556 return true;
3557
3558 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003559 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003560 return false;
3561}
3562
3563bool ASTReader::isGlobalIndexUnavailable() const {
3564 return Context.getLangOpts().Modules && UseGlobalIndex &&
3565 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3566}
3567
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003568static void updateModuleTimestamp(ModuleFile &MF) {
3569 // Overwrite the timestamp file contents so that file's mtime changes.
3570 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003571 std::error_code EC;
3572 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3573 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003574 return;
3575 OS << "Timestamp file\n";
3576}
3577
Guy Benyei11169dd2012-12-18 14:30:41 +00003578ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3579 ModuleKind Type,
3580 SourceLocation ImportLoc,
3581 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003582 llvm::SaveAndRestore<SourceLocation>
3583 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3584
Richard Smithd1c46742014-04-30 02:24:17 +00003585 // Defer any pending actions until we get to the end of reading the AST file.
3586 Deserializing AnASTFile(this);
3587
Guy Benyei11169dd2012-12-18 14:30:41 +00003588 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003589 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003590
3591 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003592 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003593 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003594 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003595 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003596 ClientLoadCapabilities)) {
3597 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003598 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003599 case OutOfDate:
3600 case VersionMismatch:
3601 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003602 case HadErrors: {
3603 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3604 for (const ImportedModule &IM : Loaded)
3605 LoadedSet.insert(IM.Mod);
3606
Douglas Gregor7029ce12013-03-19 00:28:20 +00003607 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003608 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003609 Context.getLangOpts().Modules
3610 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003611 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003612
3613 // If we find that any modules are unusable, the global index is going
3614 // to be out-of-date. Just remove it.
3615 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003616 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003617 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003618 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003619 case Success:
3620 break;
3621 }
3622
3623 // Here comes stuff that we only do once the entire chain is loaded.
3624
3625 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003626 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3627 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003628 M != MEnd; ++M) {
3629 ModuleFile &F = *M->Mod;
3630
3631 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003632 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3633 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003634
3635 // Once read, set the ModuleFile bit base offset and update the size in
3636 // bits of all files we've seen.
3637 F.GlobalBitOffset = TotalModulesSizeInBits;
3638 TotalModulesSizeInBits += F.SizeInBits;
3639 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3640
3641 // Preload SLocEntries.
3642 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3643 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3644 // Load it through the SourceManager and don't call ReadSLocEntry()
3645 // directly because the entry may have already been loaded in which case
3646 // calling ReadSLocEntry() directly would trigger an assertion in
3647 // SourceManager.
3648 SourceMgr.getLoadedSLocEntryByID(Index);
3649 }
3650 }
3651
Douglas Gregor603cd862013-03-22 18:50:14 +00003652 // Setup the import locations and notify the module manager that we've
3653 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003654 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3655 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003656 M != MEnd; ++M) {
3657 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003658
3659 ModuleMgr.moduleFileAccepted(&F);
3660
3661 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003662 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003663 if (!M->ImportedBy)
3664 F.ImportLoc = M->ImportLoc;
3665 else
3666 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3667 M->ImportLoc.getRawEncoding());
3668 }
3669
3670 // Mark all of the identifiers in the identifier table as being out of date,
3671 // so that various accessors know to check the loaded modules when the
3672 // identifier is used.
3673 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3674 IdEnd = PP.getIdentifierTable().end();
3675 Id != IdEnd; ++Id)
3676 Id->second->setOutOfDate(true);
3677
3678 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003679 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3680 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003681 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3682 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003683
3684 switch (Unresolved.Kind) {
3685 case UnresolvedModuleRef::Conflict:
3686 if (ResolvedMod) {
3687 Module::Conflict Conflict;
3688 Conflict.Other = ResolvedMod;
3689 Conflict.Message = Unresolved.String.str();
3690 Unresolved.Mod->Conflicts.push_back(Conflict);
3691 }
3692 continue;
3693
3694 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003695 if (ResolvedMod)
3696 Unresolved.Mod->Imports.push_back(ResolvedMod);
3697 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003698
Douglas Gregorfb912652013-03-20 21:10:35 +00003699 case UnresolvedModuleRef::Export:
3700 if (ResolvedMod || Unresolved.IsWildcard)
3701 Unresolved.Mod->Exports.push_back(
3702 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3703 continue;
3704 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003705 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003706 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003707
3708 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3709 // Might be unnecessary as use declarations are only used to build the
3710 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003711
3712 InitializeContext();
3713
Richard Smith3d8e97e2013-10-18 06:54:39 +00003714 if (SemaObj)
3715 UpdateSema();
3716
Guy Benyei11169dd2012-12-18 14:30:41 +00003717 if (DeserializationListener)
3718 DeserializationListener->ReaderInitialized(this);
3719
3720 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3721 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3722 PrimaryModule.OriginalSourceFileID
3723 = FileID::get(PrimaryModule.SLocEntryBaseID
3724 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3725
3726 // If this AST file is a precompiled preamble, then set the
3727 // preamble file ID of the source manager to the file source file
3728 // from which the preamble was built.
3729 if (Type == MK_Preamble) {
3730 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3731 } else if (Type == MK_MainFile) {
3732 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3733 }
3734 }
3735
3736 // For any Objective-C class definitions we have already loaded, make sure
3737 // that we load any additional categories.
3738 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3739 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3740 ObjCClassesLoaded[I],
3741 PreviousGeneration);
3742 }
Douglas Gregore060e572013-01-25 01:03:03 +00003743
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003744 if (PP.getHeaderSearchInfo()
3745 .getHeaderSearchOpts()
3746 .ModulesValidateOncePerBuildSession) {
3747 // Now we are certain that the module and all modules it depends on are
3748 // up to date. Create or update timestamp files for modules that are
3749 // located in the module cache (not for PCH files that could be anywhere
3750 // in the filesystem).
3751 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3752 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003753 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003754 updateModuleTimestamp(*M.Mod);
3755 }
3756 }
3757 }
3758
Guy Benyei11169dd2012-12-18 14:30:41 +00003759 return Success;
3760}
3761
Ben Langmuir487ea142014-10-23 18:05:36 +00003762static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3763
Ben Langmuir70a1b812015-03-24 04:43:52 +00003764/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3765static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3766 return Stream.Read(8) == 'C' &&
3767 Stream.Read(8) == 'P' &&
3768 Stream.Read(8) == 'C' &&
3769 Stream.Read(8) == 'H';
3770}
3771
Guy Benyei11169dd2012-12-18 14:30:41 +00003772ASTReader::ASTReadResult
3773ASTReader::ReadASTCore(StringRef FileName,
3774 ModuleKind Type,
3775 SourceLocation ImportLoc,
3776 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003777 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003778 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003779 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003780 unsigned ClientLoadCapabilities) {
3781 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003782 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003783 ModuleManager::AddModuleResult AddResult
3784 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003785 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003786 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003787 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003788
Douglas Gregor7029ce12013-03-19 00:28:20 +00003789 switch (AddResult) {
3790 case ModuleManager::AlreadyLoaded:
3791 return Success;
3792
3793 case ModuleManager::NewlyLoaded:
3794 // Load module file below.
3795 break;
3796
3797 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003798 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003799 // it.
3800 if (ClientLoadCapabilities & ARR_Missing)
3801 return Missing;
3802
3803 // Otherwise, return an error.
3804 {
3805 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3806 + ErrorStr;
3807 Error(Msg);
3808 }
3809 return Failure;
3810
3811 case ModuleManager::OutOfDate:
3812 // We couldn't load the module file because it is out-of-date. If the
3813 // client can handle out-of-date, return it.
3814 if (ClientLoadCapabilities & ARR_OutOfDate)
3815 return OutOfDate;
3816
3817 // Otherwise, return an error.
3818 {
3819 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3820 + ErrorStr;
3821 Error(Msg);
3822 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003823 return Failure;
3824 }
3825
Douglas Gregor7029ce12013-03-19 00:28:20 +00003826 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003827
3828 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3829 // module?
3830 if (FileName != "-") {
3831 CurrentDir = llvm::sys::path::parent_path(FileName);
3832 if (CurrentDir.empty()) CurrentDir = ".";
3833 }
3834
3835 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003836 BitstreamCursor &Stream = F.Stream;
Rafael Espindolafd832392014-11-12 14:48:44 +00003837 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003838 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3839
Guy Benyei11169dd2012-12-18 14:30:41 +00003840 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003841 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003842 Diag(diag::err_not_a_pch_file) << FileName;
3843 return Failure;
3844 }
3845
3846 // This is used for compatibility with older PCH formats.
3847 bool HaveReadControlBlock = false;
3848
Chris Lattnerefa77172013-01-20 00:00:22 +00003849 while (1) {
3850 llvm::BitstreamEntry Entry = Stream.advance();
3851
3852 switch (Entry.Kind) {
3853 case llvm::BitstreamEntry::Error:
3854 case llvm::BitstreamEntry::EndBlock:
3855 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003856 Error("invalid record at top-level of AST file");
3857 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003858
3859 case llvm::BitstreamEntry::SubBlock:
3860 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003861 }
3862
Guy Benyei11169dd2012-12-18 14:30:41 +00003863 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003864 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003865 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3866 if (Stream.ReadBlockInfoBlock()) {
3867 Error("malformed BlockInfoBlock in AST file");
3868 return Failure;
3869 }
3870 break;
3871 case CONTROL_BLOCK_ID:
3872 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003873 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003874 case Success:
3875 break;
3876
3877 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003878 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003879 case OutOfDate: return OutOfDate;
3880 case VersionMismatch: return VersionMismatch;
3881 case ConfigurationMismatch: return ConfigurationMismatch;
3882 case HadErrors: return HadErrors;
3883 }
3884 break;
3885 case AST_BLOCK_ID:
3886 if (!HaveReadControlBlock) {
3887 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003888 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003889 return VersionMismatch;
3890 }
3891
3892 // Record that we've loaded this module.
3893 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3894 return Success;
3895
3896 default:
3897 if (Stream.SkipBlock()) {
3898 Error("malformed block record in AST file");
3899 return Failure;
3900 }
3901 break;
3902 }
3903 }
3904
3905 return Success;
3906}
3907
3908void ASTReader::InitializeContext() {
3909 // If there's a listener, notify them that we "read" the translation unit.
3910 if (DeserializationListener)
3911 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3912 Context.getTranslationUnitDecl());
3913
Guy Benyei11169dd2012-12-18 14:30:41 +00003914 // FIXME: Find a better way to deal with collisions between these
3915 // built-in types. Right now, we just ignore the problem.
3916
3917 // Load the special types.
3918 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3919 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3920 if (!Context.CFConstantStringTypeDecl)
3921 Context.setCFConstantStringType(GetType(String));
3922 }
3923
3924 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3925 QualType FileType = GetType(File);
3926 if (FileType.isNull()) {
3927 Error("FILE type is NULL");
3928 return;
3929 }
3930
3931 if (!Context.FILEDecl) {
3932 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3933 Context.setFILEDecl(Typedef->getDecl());
3934 else {
3935 const TagType *Tag = FileType->getAs<TagType>();
3936 if (!Tag) {
3937 Error("Invalid FILE type in AST file");
3938 return;
3939 }
3940 Context.setFILEDecl(Tag->getDecl());
3941 }
3942 }
3943 }
3944
3945 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3946 QualType Jmp_bufType = GetType(Jmp_buf);
3947 if (Jmp_bufType.isNull()) {
3948 Error("jmp_buf type is NULL");
3949 return;
3950 }
3951
3952 if (!Context.jmp_bufDecl) {
3953 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3954 Context.setjmp_bufDecl(Typedef->getDecl());
3955 else {
3956 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3957 if (!Tag) {
3958 Error("Invalid jmp_buf type in AST file");
3959 return;
3960 }
3961 Context.setjmp_bufDecl(Tag->getDecl());
3962 }
3963 }
3964 }
3965
3966 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3967 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3968 if (Sigjmp_bufType.isNull()) {
3969 Error("sigjmp_buf type is NULL");
3970 return;
3971 }
3972
3973 if (!Context.sigjmp_bufDecl) {
3974 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3975 Context.setsigjmp_bufDecl(Typedef->getDecl());
3976 else {
3977 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3978 assert(Tag && "Invalid sigjmp_buf type in AST file");
3979 Context.setsigjmp_bufDecl(Tag->getDecl());
3980 }
3981 }
3982 }
3983
3984 if (unsigned ObjCIdRedef
3985 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3986 if (Context.ObjCIdRedefinitionType.isNull())
3987 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3988 }
3989
3990 if (unsigned ObjCClassRedef
3991 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3992 if (Context.ObjCClassRedefinitionType.isNull())
3993 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3994 }
3995
3996 if (unsigned ObjCSelRedef
3997 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3998 if (Context.ObjCSelRedefinitionType.isNull())
3999 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4000 }
4001
4002 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4003 QualType Ucontext_tType = GetType(Ucontext_t);
4004 if (Ucontext_tType.isNull()) {
4005 Error("ucontext_t type is NULL");
4006 return;
4007 }
4008
4009 if (!Context.ucontext_tDecl) {
4010 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4011 Context.setucontext_tDecl(Typedef->getDecl());
4012 else {
4013 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4014 assert(Tag && "Invalid ucontext_t type in AST file");
4015 Context.setucontext_tDecl(Tag->getDecl());
4016 }
4017 }
4018 }
4019 }
4020
4021 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4022
4023 // If there were any CUDA special declarations, deserialize them.
4024 if (!CUDASpecialDeclRefs.empty()) {
4025 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4026 Context.setcudaConfigureCallDecl(
4027 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4028 }
Richard Smith56be7542014-03-21 00:33:59 +00004029
Guy Benyei11169dd2012-12-18 14:30:41 +00004030 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00004031 // FIXME: This does not make macro-only imports visible again. It also doesn't
4032 // make #includes mapped to module imports visible.
4033 for (auto &Import : ImportedModules) {
4034 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004035 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00004036 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00004037 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00004038 }
4039 ImportedModules.clear();
4040}
4041
4042void ASTReader::finalizeForWriting() {
Richard Smith57721ac2014-07-21 04:10:40 +00004043 while (!HiddenNamesMap.empty()) {
4044 auto HiddenNames = std::move(*HiddenNamesMap.begin());
4045 HiddenNamesMap.erase(HiddenNamesMap.begin());
4046 makeNamesVisible(HiddenNames.second, HiddenNames.first,
4047 /*FromFinalization*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004048 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004049}
4050
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004051/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
4052/// cursor into the start of the given block ID, returning false on success and
4053/// true on failure.
4054static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004055 while (1) {
4056 llvm::BitstreamEntry Entry = Cursor.advance();
4057 switch (Entry.Kind) {
4058 case llvm::BitstreamEntry::Error:
4059 case llvm::BitstreamEntry::EndBlock:
4060 return true;
4061
4062 case llvm::BitstreamEntry::Record:
4063 // Ignore top-level records.
4064 Cursor.skipRecord(Entry.ID);
4065 break;
4066
4067 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004068 if (Entry.ID == BlockID) {
4069 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004070 return true;
4071 // Found it!
4072 return false;
4073 }
4074
4075 if (Cursor.SkipBlock())
4076 return true;
4077 }
4078 }
4079}
4080
Ben Langmuir70a1b812015-03-24 04:43:52 +00004081/// \brief Reads and return the signature record from \p StreamFile's control
4082/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00004083static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4084 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004085 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004086 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004087
4088 // Scan for the CONTROL_BLOCK_ID block.
4089 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4090 return 0;
4091
4092 // Scan for SIGNATURE inside the control block.
4093 ASTReader::RecordData Record;
4094 while (1) {
4095 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4096 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4097 Entry.Kind != llvm::BitstreamEntry::Record)
4098 return 0;
4099
4100 Record.clear();
4101 StringRef Blob;
4102 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4103 return Record[0];
4104 }
4105}
4106
Guy Benyei11169dd2012-12-18 14:30:41 +00004107/// \brief Retrieve the name of the original source file name
4108/// directly from the AST file, without actually loading the AST
4109/// file.
4110std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
4111 FileManager &FileMgr,
4112 DiagnosticsEngine &Diags) {
4113 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004114 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004115 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004116 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4117 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004118 return std::string();
4119 }
4120
4121 // Initialize the stream
4122 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004123 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4124 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004125 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004126
4127 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004128 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004129 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4130 return std::string();
4131 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004132
Chris Lattnere7b154b2013-01-19 21:39:22 +00004133 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004134 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004135 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4136 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004137 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004138
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004139 // Scan for ORIGINAL_FILE inside the control block.
4140 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004141 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004142 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004143 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4144 return std::string();
4145
4146 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4147 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4148 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004149 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004150
Guy Benyei11169dd2012-12-18 14:30:41 +00004151 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004152 StringRef Blob;
4153 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4154 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004155 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004156}
4157
4158namespace {
4159 class SimplePCHValidator : public ASTReaderListener {
4160 const LangOptions &ExistingLangOpts;
4161 const TargetOptions &ExistingTargetOpts;
4162 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004163 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004164 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004165
Guy Benyei11169dd2012-12-18 14:30:41 +00004166 public:
4167 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4168 const TargetOptions &ExistingTargetOpts,
4169 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004170 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004171 FileManager &FileMgr)
4172 : ExistingLangOpts(ExistingLangOpts),
4173 ExistingTargetOpts(ExistingTargetOpts),
4174 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004175 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004176 FileMgr(FileMgr)
4177 {
4178 }
4179
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004180 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4181 bool AllowCompatibleDifferences) override {
4182 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4183 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004184 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004185 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4186 bool AllowCompatibleDifferences) override {
4187 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4188 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004189 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004190 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4191 StringRef SpecificModuleCachePath,
4192 bool Complain) override {
4193 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4194 ExistingModuleCachePath,
4195 nullptr, ExistingLangOpts);
4196 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004197 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4198 bool Complain,
4199 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004200 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004201 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004202 }
4203 };
4204}
4205
4206bool ASTReader::readASTFileControlBlock(StringRef Filename,
4207 FileManager &FileMgr,
4208 ASTReaderListener &Listener) {
4209 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004210 // FIXME: This allows use of the VFS; we do not allow use of the
4211 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004212 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 if (!Buffer) {
4214 return true;
4215 }
4216
4217 // Initialize the stream
4218 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004219 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4220 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004221 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004222
4223 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004224 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004225 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004226
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004227 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004228 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004229 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004230
4231 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004232 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004233 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004234 BitstreamCursor InputFilesCursor;
4235 if (NeedsInputFiles) {
4236 InputFilesCursor = Stream;
4237 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4238 return true;
4239
4240 // Read the abbreviations
4241 while (true) {
4242 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4243 unsigned Code = InputFilesCursor.ReadCode();
4244
4245 // We expect all abbrevs to be at the start of the block.
4246 if (Code != llvm::bitc::DEFINE_ABBREV) {
4247 InputFilesCursor.JumpToBit(Offset);
4248 break;
4249 }
4250 InputFilesCursor.ReadAbbrevRecord();
4251 }
4252 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004253
4254 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004255 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004256 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004257 while (1) {
4258 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4259 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4260 return false;
4261
4262 if (Entry.Kind != llvm::BitstreamEntry::Record)
4263 return true;
4264
Guy Benyei11169dd2012-12-18 14:30:41 +00004265 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004266 StringRef Blob;
4267 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004268 switch ((ControlRecordTypes)RecCode) {
4269 case METADATA: {
4270 if (Record[0] != VERSION_MAJOR)
4271 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004272
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004273 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004274 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004275
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004276 break;
4277 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004278 case MODULE_NAME:
4279 Listener.ReadModuleName(Blob);
4280 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004281 case MODULE_DIRECTORY:
4282 ModuleDir = Blob;
4283 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004284 case MODULE_MAP_FILE: {
4285 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004286 auto Path = ReadString(Record, Idx);
4287 ResolveImportedPath(Path, ModuleDir);
4288 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004289 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004290 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004291 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004292 if (ParseLanguageOptions(Record, false, Listener,
4293 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004294 return true;
4295 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004296
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004297 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004298 if (ParseTargetOptions(Record, false, Listener,
4299 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004300 return true;
4301 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004302
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004303 case DIAGNOSTIC_OPTIONS:
4304 if (ParseDiagnosticOptions(Record, false, Listener))
4305 return true;
4306 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004307
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004308 case FILE_SYSTEM_OPTIONS:
4309 if (ParseFileSystemOptions(Record, false, Listener))
4310 return true;
4311 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004312
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004313 case HEADER_SEARCH_OPTIONS:
4314 if (ParseHeaderSearchOptions(Record, false, Listener))
4315 return true;
4316 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004317
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004318 case PREPROCESSOR_OPTIONS: {
4319 std::string IgnoredSuggestedPredefines;
4320 if (ParsePreprocessorOptions(Record, false, Listener,
4321 IgnoredSuggestedPredefines))
4322 return true;
4323 break;
4324 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004325
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004326 case INPUT_FILE_OFFSETS: {
4327 if (!NeedsInputFiles)
4328 break;
4329
4330 unsigned NumInputFiles = Record[0];
4331 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004332 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004333 for (unsigned I = 0; I != NumInputFiles; ++I) {
4334 // Go find this input file.
4335 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004336
4337 if (isSystemFile && !NeedsSystemInputFiles)
4338 break; // the rest are system input files
4339
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004340 BitstreamCursor &Cursor = InputFilesCursor;
4341 SavedStreamPosition SavedPosition(Cursor);
4342 Cursor.JumpToBit(InputFileOffs[I]);
4343
4344 unsigned Code = Cursor.ReadCode();
4345 RecordData Record;
4346 StringRef Blob;
4347 bool shouldContinue = false;
4348 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4349 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004350 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004351 std::string Filename = Blob;
4352 ResolveImportedPath(Filename, ModuleDir);
4353 shouldContinue =
4354 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004355 break;
4356 }
4357 if (!shouldContinue)
4358 break;
4359 }
4360 break;
4361 }
4362
Richard Smithd4b230b2014-10-27 23:01:16 +00004363 case IMPORTS: {
4364 if (!NeedsImports)
4365 break;
4366
4367 unsigned Idx = 0, N = Record.size();
4368 while (Idx < N) {
4369 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004370 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004371 std::string Filename = ReadString(Record, Idx);
4372 ResolveImportedPath(Filename, ModuleDir);
4373 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004374 }
4375 break;
4376 }
4377
Richard Smith7f330cd2015-03-18 01:42:29 +00004378 case KNOWN_MODULE_FILES: {
4379 // Known-but-not-technically-used module files are treated as imports.
4380 if (!NeedsImports)
4381 break;
4382
4383 unsigned Idx = 0, N = Record.size();
4384 while (Idx < N) {
4385 std::string Filename = ReadString(Record, Idx);
4386 ResolveImportedPath(Filename, ModuleDir);
4387 Listener.visitImport(Filename);
4388 }
4389 break;
4390 }
4391
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004392 default:
4393 // No other validation to perform.
4394 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004395 }
4396 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004397}
4398
4399
4400bool ASTReader::isAcceptableASTFile(StringRef Filename,
4401 FileManager &FileMgr,
4402 const LangOptions &LangOpts,
4403 const TargetOptions &TargetOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004404 const PreprocessorOptions &PPOpts,
4405 std::string ExistingModuleCachePath) {
4406 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4407 ExistingModuleCachePath, FileMgr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004408 return !readASTFileControlBlock(Filename, FileMgr, validator);
4409}
4410
Ben Langmuir2c9af442014-04-10 17:57:43 +00004411ASTReader::ASTReadResult
4412ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004413 // Enter the submodule block.
4414 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4415 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004416 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004417 }
4418
4419 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4420 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004421 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004422 RecordData Record;
4423 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004424 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4425
4426 switch (Entry.Kind) {
4427 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4428 case llvm::BitstreamEntry::Error:
4429 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004430 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004431 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004432 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004433 case llvm::BitstreamEntry::Record:
4434 // The interesting case.
4435 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004436 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004437
Guy Benyei11169dd2012-12-18 14:30:41 +00004438 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004439 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004440 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004441 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4442
4443 if ((Kind == SUBMODULE_METADATA) != First) {
4444 Error("submodule metadata record should be at beginning of block");
4445 return Failure;
4446 }
4447 First = false;
4448
4449 // Submodule information is only valid if we have a current module.
4450 // FIXME: Should we error on these cases?
4451 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4452 Kind != SUBMODULE_DEFINITION)
4453 continue;
4454
4455 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004456 default: // Default behavior: ignore.
4457 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004458
Richard Smith03478d92014-10-23 22:12:14 +00004459 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004460 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004461 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004462 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004463 }
Richard Smith03478d92014-10-23 22:12:14 +00004464
Chris Lattner0e6c9402013-01-20 02:38:54 +00004465 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004466 unsigned Idx = 0;
4467 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4468 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4469 bool IsFramework = Record[Idx++];
4470 bool IsExplicit = Record[Idx++];
4471 bool IsSystem = Record[Idx++];
4472 bool IsExternC = Record[Idx++];
4473 bool InferSubmodules = Record[Idx++];
4474 bool InferExplicitSubmodules = Record[Idx++];
4475 bool InferExportWildcard = Record[Idx++];
4476 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004477
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004478 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004479 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004480 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004481
Guy Benyei11169dd2012-12-18 14:30:41 +00004482 // Retrieve this (sub)module from the module map, creating it if
4483 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004484 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004485 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004486
4487 // FIXME: set the definition loc for CurrentModule, or call
4488 // ModMap.setInferredModuleAllowedBy()
4489
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4491 if (GlobalIndex >= SubmodulesLoaded.size() ||
4492 SubmodulesLoaded[GlobalIndex]) {
4493 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004494 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004496
Douglas Gregor7029ce12013-03-19 00:28:20 +00004497 if (!ParentModule) {
4498 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4499 if (CurFile != F.File) {
4500 if (!Diags.isDiagnosticInFlight()) {
4501 Diag(diag::err_module_file_conflict)
4502 << CurrentModule->getTopLevelModuleName()
4503 << CurFile->getName()
4504 << F.File->getName();
4505 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004506 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004507 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004508 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004509
4510 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004511 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004512
Guy Benyei11169dd2012-12-18 14:30:41 +00004513 CurrentModule->IsFromModuleFile = true;
4514 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004515 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004516 CurrentModule->InferSubmodules = InferSubmodules;
4517 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4518 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004519 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 if (DeserializationListener)
4521 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4522
4523 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004524
Douglas Gregorfb912652013-03-20 21:10:35 +00004525 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004526 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004527 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004528 CurrentModule->UnresolvedConflicts.clear();
4529 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004530 break;
4531 }
4532
4533 case SUBMODULE_UMBRELLA_HEADER: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004534 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004535 if (!CurrentModule->getUmbrellaHeader())
4536 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4537 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004538 // This can be a spurious difference caused by changing the VFS to
4539 // point to a different copy of the file, and it is too late to
4540 // to rebuild safely.
4541 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4542 // after input file validation only real problems would remain and we
4543 // could just error. For now, assume it's okay.
4544 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 }
4546 }
4547 break;
4548 }
4549
Richard Smith202210b2014-10-24 20:23:01 +00004550 case SUBMODULE_HEADER:
4551 case SUBMODULE_EXCLUDED_HEADER:
4552 case SUBMODULE_PRIVATE_HEADER:
4553 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004554 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4555 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004556 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004557
Richard Smith202210b2014-10-24 20:23:01 +00004558 case SUBMODULE_TEXTUAL_HEADER:
4559 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4560 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4561 // them here.
4562 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004563
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004565 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 break;
4567 }
4568
4569 case SUBMODULE_UMBRELLA_DIR: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004570 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004571 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004572 if (!CurrentModule->getUmbrellaDir())
4573 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4574 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004575 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4576 Error("mismatched umbrella directories in submodule");
4577 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004578 }
4579 }
4580 break;
4581 }
4582
4583 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 F.BaseSubmoduleID = getTotalNumSubmodules();
4585 F.LocalNumSubmodules = Record[0];
4586 unsigned LocalBaseSubmoduleID = Record[1];
4587 if (F.LocalNumSubmodules > 0) {
4588 // Introduce the global -> local mapping for submodules within this
4589 // module.
4590 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4591
4592 // Introduce the local -> global mapping for submodules within this
4593 // module.
4594 F.SubmoduleRemap.insertOrReplace(
4595 std::make_pair(LocalBaseSubmoduleID,
4596 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004597
Ben Langmuir52ca6782014-10-20 16:27:32 +00004598 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4599 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004600 break;
4601 }
4602
4603 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004604 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004605 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 Unresolved.File = &F;
4607 Unresolved.Mod = CurrentModule;
4608 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004609 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004610 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004611 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004612 }
4613 break;
4614 }
4615
4616 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004618 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 Unresolved.File = &F;
4620 Unresolved.Mod = CurrentModule;
4621 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004622 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004623 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004624 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 }
4626
4627 // Once we've loaded the set of exports, there's no reason to keep
4628 // the parsed, unresolved exports around.
4629 CurrentModule->UnresolvedExports.clear();
4630 break;
4631 }
4632 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004633 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004634 Context.getTargetInfo());
4635 break;
4636 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004637
4638 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004639 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004640 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004641 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004642
4643 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004644 CurrentModule->ConfigMacros.push_back(Blob.str());
4645 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004646
4647 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004648 UnresolvedModuleRef Unresolved;
4649 Unresolved.File = &F;
4650 Unresolved.Mod = CurrentModule;
4651 Unresolved.ID = Record[0];
4652 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4653 Unresolved.IsWildcard = false;
4654 Unresolved.String = Blob;
4655 UnresolvedModuleRefs.push_back(Unresolved);
4656 break;
4657 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004658 }
4659 }
4660}
4661
4662/// \brief Parse the record that corresponds to a LangOptions data
4663/// structure.
4664///
4665/// This routine parses the language options from the AST file and then gives
4666/// them to the AST listener if one is set.
4667///
4668/// \returns true if the listener deems the file unacceptable, false otherwise.
4669bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4670 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004671 ASTReaderListener &Listener,
4672 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004673 LangOptions LangOpts;
4674 unsigned Idx = 0;
4675#define LANGOPT(Name, Bits, Default, Description) \
4676 LangOpts.Name = Record[Idx++];
4677#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4678 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4679#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004680#define SANITIZER(NAME, ID) \
4681 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004682#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004683
4684 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4685 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4686 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4687
4688 unsigned Length = Record[Idx++];
4689 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4690 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004691
4692 Idx += Length;
4693
4694 // Comment options.
4695 for (unsigned N = Record[Idx++]; N; --N) {
4696 LangOpts.CommentOpts.BlockCommandNames.push_back(
4697 ReadString(Record, Idx));
4698 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004699 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004700
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004701 return Listener.ReadLanguageOptions(LangOpts, Complain,
4702 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004703}
4704
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004705bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4706 ASTReaderListener &Listener,
4707 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004708 unsigned Idx = 0;
4709 TargetOptions TargetOpts;
4710 TargetOpts.Triple = ReadString(Record, Idx);
4711 TargetOpts.CPU = ReadString(Record, Idx);
4712 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004713 for (unsigned N = Record[Idx++]; N; --N) {
4714 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4715 }
4716 for (unsigned N = Record[Idx++]; N; --N) {
4717 TargetOpts.Features.push_back(ReadString(Record, Idx));
4718 }
4719
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004720 return Listener.ReadTargetOptions(TargetOpts, Complain,
4721 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004722}
4723
4724bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4725 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004726 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004727 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004728#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004729#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004730 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004731#include "clang/Basic/DiagnosticOptions.def"
4732
Richard Smith3be1cb22014-08-07 00:24:21 +00004733 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004734 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004735 for (unsigned N = Record[Idx++]; N; --N)
4736 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004737
4738 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4739}
4740
4741bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4742 ASTReaderListener &Listener) {
4743 FileSystemOptions FSOpts;
4744 unsigned Idx = 0;
4745 FSOpts.WorkingDir = ReadString(Record, Idx);
4746 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4747}
4748
4749bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4750 bool Complain,
4751 ASTReaderListener &Listener) {
4752 HeaderSearchOptions HSOpts;
4753 unsigned Idx = 0;
4754 HSOpts.Sysroot = ReadString(Record, Idx);
4755
4756 // Include entries.
4757 for (unsigned N = Record[Idx++]; N; --N) {
4758 std::string Path = ReadString(Record, Idx);
4759 frontend::IncludeDirGroup Group
4760 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004761 bool IsFramework = Record[Idx++];
4762 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004763 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004764 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004765 }
4766
4767 // System header prefixes.
4768 for (unsigned N = Record[Idx++]; N; --N) {
4769 std::string Prefix = ReadString(Record, Idx);
4770 bool IsSystemHeader = Record[Idx++];
4771 HSOpts.SystemHeaderPrefixes.push_back(
4772 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4773 }
4774
4775 HSOpts.ResourceDir = ReadString(Record, Idx);
4776 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004777 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004778 HSOpts.DisableModuleHash = Record[Idx++];
4779 HSOpts.UseBuiltinIncludes = Record[Idx++];
4780 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4781 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4782 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004783 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004784
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004785 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4786 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004787}
4788
4789bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4790 bool Complain,
4791 ASTReaderListener &Listener,
4792 std::string &SuggestedPredefines) {
4793 PreprocessorOptions PPOpts;
4794 unsigned Idx = 0;
4795
4796 // Macro definitions/undefs
4797 for (unsigned N = Record[Idx++]; N; --N) {
4798 std::string Macro = ReadString(Record, Idx);
4799 bool IsUndef = Record[Idx++];
4800 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4801 }
4802
4803 // Includes
4804 for (unsigned N = Record[Idx++]; N; --N) {
4805 PPOpts.Includes.push_back(ReadString(Record, Idx));
4806 }
4807
4808 // Macro Includes
4809 for (unsigned N = Record[Idx++]; N; --N) {
4810 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4811 }
4812
4813 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004814 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004815 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4816 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4817 PPOpts.ObjCXXARCStandardLibrary =
4818 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4819 SuggestedPredefines.clear();
4820 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4821 SuggestedPredefines);
4822}
4823
4824std::pair<ModuleFile *, unsigned>
4825ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4826 GlobalPreprocessedEntityMapType::iterator
4827 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4828 assert(I != GlobalPreprocessedEntityMap.end() &&
4829 "Corrupted global preprocessed entity map");
4830 ModuleFile *M = I->second;
4831 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4832 return std::make_pair(M, LocalIndex);
4833}
4834
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004835llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004836ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4837 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4838 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4839 Mod.NumPreprocessedEntities);
4840
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004841 return llvm::make_range(PreprocessingRecord::iterator(),
4842 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004843}
4844
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004845llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004846ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004847 return llvm::make_range(
4848 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4849 ModuleDeclIterator(this, &Mod,
4850 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004851}
4852
4853PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4854 PreprocessedEntityID PPID = Index+1;
4855 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4856 ModuleFile &M = *PPInfo.first;
4857 unsigned LocalIndex = PPInfo.second;
4858 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4859
Guy Benyei11169dd2012-12-18 14:30:41 +00004860 if (!PP.getPreprocessingRecord()) {
4861 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004862 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004863 }
4864
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004865 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4866 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4867
4868 llvm::BitstreamEntry Entry =
4869 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4870 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004871 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004872
Guy Benyei11169dd2012-12-18 14:30:41 +00004873 // Read the record.
4874 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4875 ReadSourceLocation(M, PPOffs.End));
4876 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004877 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004878 RecordData Record;
4879 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004880 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4881 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004882 switch (RecType) {
4883 case PPD_MACRO_EXPANSION: {
4884 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004885 IdentifierInfo *Name = nullptr;
4886 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004887 if (isBuiltin)
4888 Name = getLocalIdentifier(M, Record[1]);
4889 else {
4890 PreprocessedEntityID
4891 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4892 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4893 }
4894
4895 MacroExpansion *ME;
4896 if (isBuiltin)
4897 ME = new (PPRec) MacroExpansion(Name, Range);
4898 else
4899 ME = new (PPRec) MacroExpansion(Def, Range);
4900
4901 return ME;
4902 }
4903
4904 case PPD_MACRO_DEFINITION: {
4905 // Decode the identifier info and then check again; if the macro is
4906 // still defined and associated with the identifier,
4907 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4908 MacroDefinition *MD
4909 = new (PPRec) MacroDefinition(II, Range);
4910
4911 if (DeserializationListener)
4912 DeserializationListener->MacroDefinitionRead(PPID, MD);
4913
4914 return MD;
4915 }
4916
4917 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004918 const char *FullFileNameStart = Blob.data() + Record[0];
4919 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004920 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004921 if (!FullFileName.empty())
4922 File = PP.getFileManager().getFile(FullFileName);
4923
4924 // FIXME: Stable encoding
4925 InclusionDirective::InclusionKind Kind
4926 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4927 InclusionDirective *ID
4928 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004929 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004930 Record[1], Record[3],
4931 File,
4932 Range);
4933 return ID;
4934 }
4935 }
4936
4937 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4938}
4939
4940/// \brief \arg SLocMapI points at a chunk of a module that contains no
4941/// preprocessed entities or the entities it contains are not the ones we are
4942/// looking for. Find the next module that contains entities and return the ID
4943/// of the first entry.
4944PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4945 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4946 ++SLocMapI;
4947 for (GlobalSLocOffsetMapType::const_iterator
4948 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4949 ModuleFile &M = *SLocMapI->second;
4950 if (M.NumPreprocessedEntities)
4951 return M.BasePreprocessedEntityID;
4952 }
4953
4954 return getTotalNumPreprocessedEntities();
4955}
4956
4957namespace {
4958
4959template <unsigned PPEntityOffset::*PPLoc>
4960struct PPEntityComp {
4961 const ASTReader &Reader;
4962 ModuleFile &M;
4963
4964 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4965
4966 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4967 SourceLocation LHS = getLoc(L);
4968 SourceLocation RHS = getLoc(R);
4969 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4970 }
4971
4972 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4973 SourceLocation LHS = getLoc(L);
4974 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4975 }
4976
4977 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4978 SourceLocation RHS = getLoc(R);
4979 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4980 }
4981
4982 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4983 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4984 }
4985};
4986
4987}
4988
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004989PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4990 bool EndsAfter) const {
4991 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004992 return getTotalNumPreprocessedEntities();
4993
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004994 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4995 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004996 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4997 "Corrupted global sloc offset map");
4998
4999 if (SLocMapI->second->NumPreprocessedEntities == 0)
5000 return findNextPreprocessedEntity(SLocMapI);
5001
5002 ModuleFile &M = *SLocMapI->second;
5003 typedef const PPEntityOffset *pp_iterator;
5004 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5005 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5006
5007 size_t Count = M.NumPreprocessedEntities;
5008 size_t Half;
5009 pp_iterator First = pp_begin;
5010 pp_iterator PPI;
5011
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005012 if (EndsAfter) {
5013 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5014 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
5015 } else {
5016 // Do a binary search manually instead of using std::lower_bound because
5017 // The end locations of entities may be unordered (when a macro expansion
5018 // is inside another macro argument), but for this case it is not important
5019 // whether we get the first macro expansion or its containing macro.
5020 while (Count > 0) {
5021 Half = Count / 2;
5022 PPI = First;
5023 std::advance(PPI, Half);
5024 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
5025 Loc)) {
5026 First = PPI;
5027 ++First;
5028 Count = Count - Half - 1;
5029 } else
5030 Count = Half;
5031 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005032 }
5033
5034 if (PPI == pp_end)
5035 return findNextPreprocessedEntity(SLocMapI);
5036
5037 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5038}
5039
Guy Benyei11169dd2012-12-18 14:30:41 +00005040/// \brief Returns a pair of [Begin, End) indices of preallocated
5041/// preprocessed entities that \arg Range encompasses.
5042std::pair<unsigned, unsigned>
5043 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5044 if (Range.isInvalid())
5045 return std::make_pair(0,0);
5046 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5047
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005048 PreprocessedEntityID BeginID =
5049 findPreprocessedEntity(Range.getBegin(), false);
5050 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 return std::make_pair(BeginID, EndID);
5052}
5053
5054/// \brief Optionally returns true or false if the preallocated preprocessed
5055/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005056Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 FileID FID) {
5058 if (FID.isInvalid())
5059 return false;
5060
5061 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5062 ModuleFile &M = *PPInfo.first;
5063 unsigned LocalIndex = PPInfo.second;
5064 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5065
5066 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5067 if (Loc.isInvalid())
5068 return false;
5069
5070 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5071 return true;
5072 else
5073 return false;
5074}
5075
5076namespace {
5077 /// \brief Visitor used to search for information about a header file.
5078 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 const FileEntry *FE;
5080
David Blaikie05785d12013-02-20 22:23:23 +00005081 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005082
5083 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005084 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5085 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00005086
5087 static bool visit(ModuleFile &M, void *UserData) {
5088 HeaderFileInfoVisitor *This
5089 = static_cast<HeaderFileInfoVisitor *>(UserData);
5090
Guy Benyei11169dd2012-12-18 14:30:41 +00005091 HeaderFileInfoLookupTable *Table
5092 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5093 if (!Table)
5094 return false;
5095
5096 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00005097 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005098 if (Pos == Table->end())
5099 return false;
5100
5101 This->HFI = *Pos;
5102 return true;
5103 }
5104
David Blaikie05785d12013-02-20 22:23:23 +00005105 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 };
5107}
5108
5109HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005110 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005112 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005114
5115 return HeaderFileInfo();
5116}
5117
5118void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5119 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005120 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5122 ModuleFile &F = *(*I);
5123 unsigned Idx = 0;
5124 DiagStates.clear();
5125 assert(!Diag.DiagStates.empty());
5126 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5127 while (Idx < F.PragmaDiagMappings.size()) {
5128 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5129 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5130 if (DiagStateID != 0) {
5131 Diag.DiagStatePoints.push_back(
5132 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5133 FullSourceLoc(Loc, SourceMgr)));
5134 continue;
5135 }
5136
5137 assert(DiagStateID == 0);
5138 // A new DiagState was created here.
5139 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5140 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5141 DiagStates.push_back(NewState);
5142 Diag.DiagStatePoints.push_back(
5143 DiagnosticsEngine::DiagStatePoint(NewState,
5144 FullSourceLoc(Loc, SourceMgr)));
5145 while (1) {
5146 assert(Idx < F.PragmaDiagMappings.size() &&
5147 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5148 if (Idx >= F.PragmaDiagMappings.size()) {
5149 break; // Something is messed up but at least avoid infinite loop in
5150 // release build.
5151 }
5152 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5153 if (DiagID == (unsigned)-1) {
5154 break; // no more diag/map pairs for this location.
5155 }
Alp Tokerc726c362014-06-10 09:31:37 +00005156 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5157 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5158 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 }
5160 }
5161 }
5162}
5163
5164/// \brief Get the correct cursor and offset for loading a type.
5165ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5166 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5167 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5168 ModuleFile *M = I->second;
5169 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5170}
5171
5172/// \brief Read and return the type with the given index..
5173///
5174/// The index is the type ID, shifted and minus the number of predefs. This
5175/// routine actually reads the record corresponding to the type at the given
5176/// location. It is a helper routine for GetType, which deals with reading type
5177/// IDs.
5178QualType ASTReader::readTypeRecord(unsigned Index) {
5179 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005180 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005181
5182 // Keep track of where we are in the stream, then jump back there
5183 // after reading this type.
5184 SavedStreamPosition SavedPosition(DeclsCursor);
5185
5186 ReadingKindTracker ReadingKind(Read_Type, *this);
5187
5188 // Note that we are loading a type record.
5189 Deserializing AType(this);
5190
5191 unsigned Idx = 0;
5192 DeclsCursor.JumpToBit(Loc.Offset);
5193 RecordData Record;
5194 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005195 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005196 case TYPE_EXT_QUAL: {
5197 if (Record.size() != 2) {
5198 Error("Incorrect encoding of extended qualifier type");
5199 return QualType();
5200 }
5201 QualType Base = readType(*Loc.F, Record, Idx);
5202 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5203 return Context.getQualifiedType(Base, Quals);
5204 }
5205
5206 case TYPE_COMPLEX: {
5207 if (Record.size() != 1) {
5208 Error("Incorrect encoding of complex type");
5209 return QualType();
5210 }
5211 QualType ElemType = readType(*Loc.F, Record, Idx);
5212 return Context.getComplexType(ElemType);
5213 }
5214
5215 case TYPE_POINTER: {
5216 if (Record.size() != 1) {
5217 Error("Incorrect encoding of pointer type");
5218 return QualType();
5219 }
5220 QualType PointeeType = readType(*Loc.F, Record, Idx);
5221 return Context.getPointerType(PointeeType);
5222 }
5223
Reid Kleckner8a365022013-06-24 17:51:48 +00005224 case TYPE_DECAYED: {
5225 if (Record.size() != 1) {
5226 Error("Incorrect encoding of decayed type");
5227 return QualType();
5228 }
5229 QualType OriginalType = readType(*Loc.F, Record, Idx);
5230 QualType DT = Context.getAdjustedParameterType(OriginalType);
5231 if (!isa<DecayedType>(DT))
5232 Error("Decayed type does not decay");
5233 return DT;
5234 }
5235
Reid Kleckner0503a872013-12-05 01:23:43 +00005236 case TYPE_ADJUSTED: {
5237 if (Record.size() != 2) {
5238 Error("Incorrect encoding of adjusted type");
5239 return QualType();
5240 }
5241 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5242 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5243 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5244 }
5245
Guy Benyei11169dd2012-12-18 14:30:41 +00005246 case TYPE_BLOCK_POINTER: {
5247 if (Record.size() != 1) {
5248 Error("Incorrect encoding of block pointer type");
5249 return QualType();
5250 }
5251 QualType PointeeType = readType(*Loc.F, Record, Idx);
5252 return Context.getBlockPointerType(PointeeType);
5253 }
5254
5255 case TYPE_LVALUE_REFERENCE: {
5256 if (Record.size() != 2) {
5257 Error("Incorrect encoding of lvalue reference type");
5258 return QualType();
5259 }
5260 QualType PointeeType = readType(*Loc.F, Record, Idx);
5261 return Context.getLValueReferenceType(PointeeType, Record[1]);
5262 }
5263
5264 case TYPE_RVALUE_REFERENCE: {
5265 if (Record.size() != 1) {
5266 Error("Incorrect encoding of rvalue reference type");
5267 return QualType();
5268 }
5269 QualType PointeeType = readType(*Loc.F, Record, Idx);
5270 return Context.getRValueReferenceType(PointeeType);
5271 }
5272
5273 case TYPE_MEMBER_POINTER: {
5274 if (Record.size() != 2) {
5275 Error("Incorrect encoding of member pointer type");
5276 return QualType();
5277 }
5278 QualType PointeeType = readType(*Loc.F, Record, Idx);
5279 QualType ClassType = readType(*Loc.F, Record, Idx);
5280 if (PointeeType.isNull() || ClassType.isNull())
5281 return QualType();
5282
5283 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5284 }
5285
5286 case TYPE_CONSTANT_ARRAY: {
5287 QualType ElementType = readType(*Loc.F, Record, Idx);
5288 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5289 unsigned IndexTypeQuals = Record[2];
5290 unsigned Idx = 3;
5291 llvm::APInt Size = ReadAPInt(Record, Idx);
5292 return Context.getConstantArrayType(ElementType, Size,
5293 ASM, IndexTypeQuals);
5294 }
5295
5296 case TYPE_INCOMPLETE_ARRAY: {
5297 QualType ElementType = readType(*Loc.F, Record, Idx);
5298 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5299 unsigned IndexTypeQuals = Record[2];
5300 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5301 }
5302
5303 case TYPE_VARIABLE_ARRAY: {
5304 QualType ElementType = readType(*Loc.F, Record, Idx);
5305 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5306 unsigned IndexTypeQuals = Record[2];
5307 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5308 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5309 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5310 ASM, IndexTypeQuals,
5311 SourceRange(LBLoc, RBLoc));
5312 }
5313
5314 case TYPE_VECTOR: {
5315 if (Record.size() != 3) {
5316 Error("incorrect encoding of vector type in AST file");
5317 return QualType();
5318 }
5319
5320 QualType ElementType = readType(*Loc.F, Record, Idx);
5321 unsigned NumElements = Record[1];
5322 unsigned VecKind = Record[2];
5323 return Context.getVectorType(ElementType, NumElements,
5324 (VectorType::VectorKind)VecKind);
5325 }
5326
5327 case TYPE_EXT_VECTOR: {
5328 if (Record.size() != 3) {
5329 Error("incorrect encoding of extended vector type in AST file");
5330 return QualType();
5331 }
5332
5333 QualType ElementType = readType(*Loc.F, Record, Idx);
5334 unsigned NumElements = Record[1];
5335 return Context.getExtVectorType(ElementType, NumElements);
5336 }
5337
5338 case TYPE_FUNCTION_NO_PROTO: {
5339 if (Record.size() != 6) {
5340 Error("incorrect encoding of no-proto function type");
5341 return QualType();
5342 }
5343 QualType ResultType = readType(*Loc.F, Record, Idx);
5344 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5345 (CallingConv)Record[4], Record[5]);
5346 return Context.getFunctionNoProtoType(ResultType, Info);
5347 }
5348
5349 case TYPE_FUNCTION_PROTO: {
5350 QualType ResultType = readType(*Loc.F, Record, Idx);
5351
5352 FunctionProtoType::ExtProtoInfo EPI;
5353 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5354 /*hasregparm*/ Record[2],
5355 /*regparm*/ Record[3],
5356 static_cast<CallingConv>(Record[4]),
5357 /*produces*/ Record[5]);
5358
5359 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005360
5361 EPI.Variadic = Record[Idx++];
5362 EPI.HasTrailingReturn = Record[Idx++];
5363 EPI.TypeQuals = Record[Idx++];
5364 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005365 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005366 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005367
5368 unsigned NumParams = Record[Idx++];
5369 SmallVector<QualType, 16> ParamTypes;
5370 for (unsigned I = 0; I != NumParams; ++I)
5371 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5372
Jordan Rose5c382722013-03-08 21:51:21 +00005373 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005374 }
5375
5376 case TYPE_UNRESOLVED_USING: {
5377 unsigned Idx = 0;
5378 return Context.getTypeDeclType(
5379 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5380 }
5381
5382 case TYPE_TYPEDEF: {
5383 if (Record.size() != 2) {
5384 Error("incorrect encoding of typedef type");
5385 return QualType();
5386 }
5387 unsigned Idx = 0;
5388 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5389 QualType Canonical = readType(*Loc.F, Record, Idx);
5390 if (!Canonical.isNull())
5391 Canonical = Context.getCanonicalType(Canonical);
5392 return Context.getTypedefType(Decl, Canonical);
5393 }
5394
5395 case TYPE_TYPEOF_EXPR:
5396 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5397
5398 case TYPE_TYPEOF: {
5399 if (Record.size() != 1) {
5400 Error("incorrect encoding of typeof(type) in AST file");
5401 return QualType();
5402 }
5403 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5404 return Context.getTypeOfType(UnderlyingType);
5405 }
5406
5407 case TYPE_DECLTYPE: {
5408 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5409 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5410 }
5411
5412 case TYPE_UNARY_TRANSFORM: {
5413 QualType BaseType = readType(*Loc.F, Record, Idx);
5414 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5415 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5416 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5417 }
5418
Richard Smith74aeef52013-04-26 16:15:35 +00005419 case TYPE_AUTO: {
5420 QualType Deduced = readType(*Loc.F, Record, Idx);
5421 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005422 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005423 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005424 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005425
5426 case TYPE_RECORD: {
5427 if (Record.size() != 2) {
5428 Error("incorrect encoding of record type");
5429 return QualType();
5430 }
5431 unsigned Idx = 0;
5432 bool IsDependent = Record[Idx++];
5433 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5434 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5435 QualType T = Context.getRecordType(RD);
5436 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5437 return T;
5438 }
5439
5440 case TYPE_ENUM: {
5441 if (Record.size() != 2) {
5442 Error("incorrect encoding of enum type");
5443 return QualType();
5444 }
5445 unsigned Idx = 0;
5446 bool IsDependent = Record[Idx++];
5447 QualType T
5448 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5449 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5450 return T;
5451 }
5452
5453 case TYPE_ATTRIBUTED: {
5454 if (Record.size() != 3) {
5455 Error("incorrect encoding of attributed type");
5456 return QualType();
5457 }
5458 QualType modifiedType = readType(*Loc.F, Record, Idx);
5459 QualType equivalentType = readType(*Loc.F, Record, Idx);
5460 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5461 return Context.getAttributedType(kind, modifiedType, equivalentType);
5462 }
5463
5464 case TYPE_PAREN: {
5465 if (Record.size() != 1) {
5466 Error("incorrect encoding of paren type");
5467 return QualType();
5468 }
5469 QualType InnerType = readType(*Loc.F, Record, Idx);
5470 return Context.getParenType(InnerType);
5471 }
5472
5473 case TYPE_PACK_EXPANSION: {
5474 if (Record.size() != 2) {
5475 Error("incorrect encoding of pack expansion type");
5476 return QualType();
5477 }
5478 QualType Pattern = readType(*Loc.F, Record, Idx);
5479 if (Pattern.isNull())
5480 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005481 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005482 if (Record[1])
5483 NumExpansions = Record[1] - 1;
5484 return Context.getPackExpansionType(Pattern, NumExpansions);
5485 }
5486
5487 case TYPE_ELABORATED: {
5488 unsigned Idx = 0;
5489 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5490 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5491 QualType NamedType = readType(*Loc.F, Record, Idx);
5492 return Context.getElaboratedType(Keyword, NNS, NamedType);
5493 }
5494
5495 case TYPE_OBJC_INTERFACE: {
5496 unsigned Idx = 0;
5497 ObjCInterfaceDecl *ItfD
5498 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5499 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5500 }
5501
5502 case TYPE_OBJC_OBJECT: {
5503 unsigned Idx = 0;
5504 QualType Base = readType(*Loc.F, Record, Idx);
5505 unsigned NumProtos = Record[Idx++];
5506 SmallVector<ObjCProtocolDecl*, 4> Protos;
5507 for (unsigned I = 0; I != NumProtos; ++I)
5508 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5509 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5510 }
5511
5512 case TYPE_OBJC_OBJECT_POINTER: {
5513 unsigned Idx = 0;
5514 QualType Pointee = readType(*Loc.F, Record, Idx);
5515 return Context.getObjCObjectPointerType(Pointee);
5516 }
5517
5518 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5519 unsigned Idx = 0;
5520 QualType Parm = readType(*Loc.F, Record, Idx);
5521 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005522 return Context.getSubstTemplateTypeParmType(
5523 cast<TemplateTypeParmType>(Parm),
5524 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005525 }
5526
5527 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5528 unsigned Idx = 0;
5529 QualType Parm = readType(*Loc.F, Record, Idx);
5530 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5531 return Context.getSubstTemplateTypeParmPackType(
5532 cast<TemplateTypeParmType>(Parm),
5533 ArgPack);
5534 }
5535
5536 case TYPE_INJECTED_CLASS_NAME: {
5537 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5538 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5539 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5540 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005541 const Type *T = nullptr;
5542 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5543 if (const Type *Existing = DI->getTypeForDecl()) {
5544 T = Existing;
5545 break;
5546 }
5547 }
5548 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005549 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005550 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5551 DI->setTypeForDecl(T);
5552 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005553 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005554 }
5555
5556 case TYPE_TEMPLATE_TYPE_PARM: {
5557 unsigned Idx = 0;
5558 unsigned Depth = Record[Idx++];
5559 unsigned Index = Record[Idx++];
5560 bool Pack = Record[Idx++];
5561 TemplateTypeParmDecl *D
5562 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5563 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5564 }
5565
5566 case TYPE_DEPENDENT_NAME: {
5567 unsigned Idx = 0;
5568 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5569 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5570 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5571 QualType Canon = readType(*Loc.F, Record, Idx);
5572 if (!Canon.isNull())
5573 Canon = Context.getCanonicalType(Canon);
5574 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5575 }
5576
5577 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5578 unsigned Idx = 0;
5579 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5580 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5581 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5582 unsigned NumArgs = Record[Idx++];
5583 SmallVector<TemplateArgument, 8> Args;
5584 Args.reserve(NumArgs);
5585 while (NumArgs--)
5586 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5587 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5588 Args.size(), Args.data());
5589 }
5590
5591 case TYPE_DEPENDENT_SIZED_ARRAY: {
5592 unsigned Idx = 0;
5593
5594 // ArrayType
5595 QualType ElementType = readType(*Loc.F, Record, Idx);
5596 ArrayType::ArraySizeModifier ASM
5597 = (ArrayType::ArraySizeModifier)Record[Idx++];
5598 unsigned IndexTypeQuals = Record[Idx++];
5599
5600 // DependentSizedArrayType
5601 Expr *NumElts = ReadExpr(*Loc.F);
5602 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5603
5604 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5605 IndexTypeQuals, Brackets);
5606 }
5607
5608 case TYPE_TEMPLATE_SPECIALIZATION: {
5609 unsigned Idx = 0;
5610 bool IsDependent = Record[Idx++];
5611 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5612 SmallVector<TemplateArgument, 8> Args;
5613 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5614 QualType Underlying = readType(*Loc.F, Record, Idx);
5615 QualType T;
5616 if (Underlying.isNull())
5617 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5618 Args.size());
5619 else
5620 T = Context.getTemplateSpecializationType(Name, Args.data(),
5621 Args.size(), Underlying);
5622 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5623 return T;
5624 }
5625
5626 case TYPE_ATOMIC: {
5627 if (Record.size() != 1) {
5628 Error("Incorrect encoding of atomic type");
5629 return QualType();
5630 }
5631 QualType ValueType = readType(*Loc.F, Record, Idx);
5632 return Context.getAtomicType(ValueType);
5633 }
5634 }
5635 llvm_unreachable("Invalid TypeCode!");
5636}
5637
Richard Smith564417a2014-03-20 21:47:22 +00005638void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5639 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005640 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005641 const RecordData &Record, unsigned &Idx) {
5642 ExceptionSpecificationType EST =
5643 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005644 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005645 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005646 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005647 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005648 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005649 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005650 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005651 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005652 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5653 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005654 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005655 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005656 }
5657}
5658
Guy Benyei11169dd2012-12-18 14:30:41 +00005659class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5660 ASTReader &Reader;
5661 ModuleFile &F;
5662 const ASTReader::RecordData &Record;
5663 unsigned &Idx;
5664
5665 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5666 unsigned &I) {
5667 return Reader.ReadSourceLocation(F, R, I);
5668 }
5669
5670 template<typename T>
5671 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5672 return Reader.ReadDeclAs<T>(F, Record, Idx);
5673 }
5674
5675public:
5676 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5677 const ASTReader::RecordData &Record, unsigned &Idx)
5678 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5679 { }
5680
5681 // We want compile-time assurance that we've enumerated all of
5682 // these, so unfortunately we have to declare them first, then
5683 // define them out-of-line.
5684#define ABSTRACT_TYPELOC(CLASS, PARENT)
5685#define TYPELOC(CLASS, PARENT) \
5686 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5687#include "clang/AST/TypeLocNodes.def"
5688
5689 void VisitFunctionTypeLoc(FunctionTypeLoc);
5690 void VisitArrayTypeLoc(ArrayTypeLoc);
5691};
5692
5693void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5694 // nothing to do
5695}
5696void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5697 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5698 if (TL.needsExtraLocalData()) {
5699 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5700 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5701 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5702 TL.setModeAttr(Record[Idx++]);
5703 }
5704}
5705void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5706 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5707}
5708void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5709 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5710}
Reid Kleckner8a365022013-06-24 17:51:48 +00005711void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5712 // nothing to do
5713}
Reid Kleckner0503a872013-12-05 01:23:43 +00005714void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5715 // nothing to do
5716}
Guy Benyei11169dd2012-12-18 14:30:41 +00005717void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5718 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5719}
5720void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5721 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5722}
5723void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5724 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5725}
5726void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5727 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5728 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5729}
5730void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5731 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5732 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5733 if (Record[Idx++])
5734 TL.setSizeExpr(Reader.ReadExpr(F));
5735 else
Craig Toppera13603a2014-05-22 05:54:18 +00005736 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005737}
5738void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5739 VisitArrayTypeLoc(TL);
5740}
5741void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5742 VisitArrayTypeLoc(TL);
5743}
5744void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5745 VisitArrayTypeLoc(TL);
5746}
5747void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5748 DependentSizedArrayTypeLoc TL) {
5749 VisitArrayTypeLoc(TL);
5750}
5751void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5752 DependentSizedExtVectorTypeLoc TL) {
5753 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5754}
5755void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5756 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5757}
5758void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5759 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5760}
5761void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5762 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5763 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5764 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5765 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005766 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5767 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005768 }
5769}
5770void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5771 VisitFunctionTypeLoc(TL);
5772}
5773void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5774 VisitFunctionTypeLoc(TL);
5775}
5776void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5777 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5778}
5779void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5780 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5781}
5782void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5783 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5784 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5785 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5786}
5787void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5788 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5789 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5790 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5791 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5792}
5793void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5794 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5795}
5796void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5797 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5798 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5799 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5800 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5801}
5802void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5803 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5804}
5805void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5806 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5807}
5808void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5809 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5810}
5811void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5812 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5813 if (TL.hasAttrOperand()) {
5814 SourceRange range;
5815 range.setBegin(ReadSourceLocation(Record, Idx));
5816 range.setEnd(ReadSourceLocation(Record, Idx));
5817 TL.setAttrOperandParensRange(range);
5818 }
5819 if (TL.hasAttrExprOperand()) {
5820 if (Record[Idx++])
5821 TL.setAttrExprOperand(Reader.ReadExpr(F));
5822 else
Craig Toppera13603a2014-05-22 05:54:18 +00005823 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005824 } else if (TL.hasAttrEnumOperand())
5825 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5826}
5827void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5828 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5829}
5830void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5831 SubstTemplateTypeParmTypeLoc TL) {
5832 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5833}
5834void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5835 SubstTemplateTypeParmPackTypeLoc TL) {
5836 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5837}
5838void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5839 TemplateSpecializationTypeLoc TL) {
5840 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5841 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5842 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5843 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5844 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5845 TL.setArgLocInfo(i,
5846 Reader.GetTemplateArgumentLocInfo(F,
5847 TL.getTypePtr()->getArg(i).getKind(),
5848 Record, Idx));
5849}
5850void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5851 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5852 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5853}
5854void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5855 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5856 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5857}
5858void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5859 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5860}
5861void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5862 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5863 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5864 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5865}
5866void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5867 DependentTemplateSpecializationTypeLoc TL) {
5868 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5869 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5870 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5871 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5872 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5873 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5874 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5875 TL.setArgLocInfo(I,
5876 Reader.GetTemplateArgumentLocInfo(F,
5877 TL.getTypePtr()->getArg(I).getKind(),
5878 Record, Idx));
5879}
5880void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5881 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5882}
5883void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5884 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5885}
5886void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5887 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5888 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5889 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5890 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5891 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5892}
5893void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5894 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5895}
5896void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5897 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5898 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5899 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5900}
5901
5902TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5903 const RecordData &Record,
5904 unsigned &Idx) {
5905 QualType InfoTy = readType(F, Record, Idx);
5906 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005907 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005908
5909 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5910 TypeLocReader TLR(*this, F, Record, Idx);
5911 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5912 TLR.Visit(TL);
5913 return TInfo;
5914}
5915
5916QualType ASTReader::GetType(TypeID ID) {
5917 unsigned FastQuals = ID & Qualifiers::FastMask;
5918 unsigned Index = ID >> Qualifiers::FastWidth;
5919
5920 if (Index < NUM_PREDEF_TYPE_IDS) {
5921 QualType T;
5922 switch ((PredefinedTypeIDs)Index) {
5923 case PREDEF_TYPE_NULL_ID: return QualType();
5924 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5925 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5926
5927 case PREDEF_TYPE_CHAR_U_ID:
5928 case PREDEF_TYPE_CHAR_S_ID:
5929 // FIXME: Check that the signedness of CharTy is correct!
5930 T = Context.CharTy;
5931 break;
5932
5933 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5934 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5935 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5936 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5937 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5938 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5939 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5940 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5941 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5942 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5943 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5944 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5945 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5946 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5947 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5948 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5949 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5950 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5951 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5952 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5953 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5954 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5955 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5956 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5957 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5958 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5959 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5960 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005961 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5962 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5963 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5964 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5965 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5966 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005967 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005968 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005969 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5970
5971 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5972 T = Context.getAutoRRefDeductType();
5973 break;
5974
5975 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5976 T = Context.ARCUnbridgedCastTy;
5977 break;
5978
5979 case PREDEF_TYPE_VA_LIST_TAG:
5980 T = Context.getVaListTagType();
5981 break;
5982
5983 case PREDEF_TYPE_BUILTIN_FN:
5984 T = Context.BuiltinFnTy;
5985 break;
5986 }
5987
5988 assert(!T.isNull() && "Unknown predefined type");
5989 return T.withFastQualifiers(FastQuals);
5990 }
5991
5992 Index -= NUM_PREDEF_TYPE_IDS;
5993 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5994 if (TypesLoaded[Index].isNull()) {
5995 TypesLoaded[Index] = readTypeRecord(Index);
5996 if (TypesLoaded[Index].isNull())
5997 return QualType();
5998
5999 TypesLoaded[Index]->setFromAST();
6000 if (DeserializationListener)
6001 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6002 TypesLoaded[Index]);
6003 }
6004
6005 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6006}
6007
6008QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6009 return GetType(getGlobalTypeID(F, LocalID));
6010}
6011
6012serialization::TypeID
6013ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6014 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6015 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6016
6017 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6018 return LocalID;
6019
6020 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6021 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6022 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6023
6024 unsigned GlobalIndex = LocalIndex + I->second;
6025 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6026}
6027
6028TemplateArgumentLocInfo
6029ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6030 TemplateArgument::ArgKind Kind,
6031 const RecordData &Record,
6032 unsigned &Index) {
6033 switch (Kind) {
6034 case TemplateArgument::Expression:
6035 return ReadExpr(F);
6036 case TemplateArgument::Type:
6037 return GetTypeSourceInfo(F, Record, Index);
6038 case TemplateArgument::Template: {
6039 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6040 Index);
6041 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6042 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6043 SourceLocation());
6044 }
6045 case TemplateArgument::TemplateExpansion: {
6046 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6047 Index);
6048 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6049 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6050 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6051 EllipsisLoc);
6052 }
6053 case TemplateArgument::Null:
6054 case TemplateArgument::Integral:
6055 case TemplateArgument::Declaration:
6056 case TemplateArgument::NullPtr:
6057 case TemplateArgument::Pack:
6058 // FIXME: Is this right?
6059 return TemplateArgumentLocInfo();
6060 }
6061 llvm_unreachable("unexpected template argument loc");
6062}
6063
6064TemplateArgumentLoc
6065ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6066 const RecordData &Record, unsigned &Index) {
6067 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6068
6069 if (Arg.getKind() == TemplateArgument::Expression) {
6070 if (Record[Index++]) // bool InfoHasSameExpr.
6071 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6072 }
6073 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6074 Record, Index));
6075}
6076
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006077const ASTTemplateArgumentListInfo*
6078ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6079 const RecordData &Record,
6080 unsigned &Index) {
6081 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6082 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6083 unsigned NumArgsAsWritten = Record[Index++];
6084 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6085 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6086 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6087 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6088}
6089
Guy Benyei11169dd2012-12-18 14:30:41 +00006090Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6091 return GetDecl(ID);
6092}
6093
Richard Smith50895422015-01-31 03:04:55 +00006094template<typename TemplateSpecializationDecl>
6095static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6096 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6097 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6098}
6099
Richard Smith053f6c62014-05-16 23:01:30 +00006100void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006101 if (NumCurrentElementsDeserializing) {
6102 // We arrange to not care about the complete redeclaration chain while we're
6103 // deserializing. Just remember that the AST has marked this one as complete
6104 // but that it's not actually complete yet, so we know we still need to
6105 // complete it later.
6106 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6107 return;
6108 }
6109
Richard Smith053f6c62014-05-16 23:01:30 +00006110 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6111
Richard Smith053f6c62014-05-16 23:01:30 +00006112 // If this is a named declaration, complete it by looking it up
6113 // within its context.
6114 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006115 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006116 // all mergeable entities within it.
6117 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6118 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6119 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6120 auto *II = Name.getAsIdentifierInfo();
6121 if (isa<TranslationUnitDecl>(DC) && II) {
6122 // Outside of C++, we don't have a lookup table for the TU, so update
6123 // the identifier instead. In C++, either way should work fine.
6124 if (II->isOutOfDate())
6125 updateOutOfDateIdentifier(*II);
6126 } else
6127 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006128 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6129 // FIXME: It'd be nice to do something a bit more targeted here.
6130 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00006131 }
6132 }
Richard Smith50895422015-01-31 03:04:55 +00006133
6134 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6135 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6136 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6137 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6138 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6139 if (auto *Template = FD->getPrimaryTemplate())
6140 Template->LoadLazySpecializations();
6141 }
Richard Smith053f6c62014-05-16 23:01:30 +00006142}
6143
Richard Smithc2bb8182015-03-24 06:36:48 +00006144uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
6145 const RecordData &Record,
6146 unsigned &Idx) {
6147 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
6148 Error("malformed AST file: missing C++ ctor initializers");
6149 return 0;
6150 }
6151
6152 unsigned LocalID = Record[Idx++];
6153 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6154}
6155
6156CXXCtorInitializer **
6157ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6158 RecordLocation Loc = getLocalBitOffset(Offset);
6159 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6160 SavedStreamPosition SavedPosition(Cursor);
6161 Cursor.JumpToBit(Loc.Offset);
6162 ReadingKindTracker ReadingKind(Read_Decl, *this);
6163
6164 RecordData Record;
6165 unsigned Code = Cursor.ReadCode();
6166 unsigned RecCode = Cursor.readRecord(Code, Record);
6167 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6168 Error("malformed AST file: missing C++ ctor initializers");
6169 return nullptr;
6170 }
6171
6172 unsigned Idx = 0;
6173 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6174}
6175
Richard Smithcd45dbc2014-04-19 03:48:30 +00006176uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6177 const RecordData &Record,
6178 unsigned &Idx) {
6179 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6180 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006181 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006182 }
6183
Guy Benyei11169dd2012-12-18 14:30:41 +00006184 unsigned LocalID = Record[Idx++];
6185 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6186}
6187
6188CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6189 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006190 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006191 SavedStreamPosition SavedPosition(Cursor);
6192 Cursor.JumpToBit(Loc.Offset);
6193 ReadingKindTracker ReadingKind(Read_Decl, *this);
6194 RecordData Record;
6195 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006196 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006197 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006198 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006199 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006200 }
6201
6202 unsigned Idx = 0;
6203 unsigned NumBases = Record[Idx++];
6204 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6205 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6206 for (unsigned I = 0; I != NumBases; ++I)
6207 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6208 return Bases;
6209}
6210
6211serialization::DeclID
6212ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6213 if (LocalID < NUM_PREDEF_DECL_IDS)
6214 return LocalID;
6215
6216 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6217 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6218 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6219
6220 return LocalID + I->second;
6221}
6222
6223bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6224 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006225 // Predefined decls aren't from any module.
6226 if (ID < NUM_PREDEF_DECL_IDS)
6227 return false;
6228
Guy Benyei11169dd2012-12-18 14:30:41 +00006229 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6230 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6231 return &M == I->second;
6232}
6233
Douglas Gregor9f782892013-01-21 15:25:38 +00006234ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006235 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006236 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006237 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6238 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6239 return I->second;
6240}
6241
6242SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6243 if (ID < NUM_PREDEF_DECL_IDS)
6244 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006245
Guy Benyei11169dd2012-12-18 14:30:41 +00006246 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6247
6248 if (Index > DeclsLoaded.size()) {
6249 Error("declaration ID out-of-range for AST file");
6250 return SourceLocation();
6251 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006252
Guy Benyei11169dd2012-12-18 14:30:41 +00006253 if (Decl *D = DeclsLoaded[Index])
6254 return D->getLocation();
6255
6256 unsigned RawLocation = 0;
6257 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6258 return ReadSourceLocation(*Rec.F, RawLocation);
6259}
6260
Richard Smithfe620d22015-03-05 23:24:12 +00006261static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6262 switch (ID) {
6263 case PREDEF_DECL_NULL_ID:
6264 return nullptr;
6265
6266 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6267 return Context.getTranslationUnitDecl();
6268
6269 case PREDEF_DECL_OBJC_ID_ID:
6270 return Context.getObjCIdDecl();
6271
6272 case PREDEF_DECL_OBJC_SEL_ID:
6273 return Context.getObjCSelDecl();
6274
6275 case PREDEF_DECL_OBJC_CLASS_ID:
6276 return Context.getObjCClassDecl();
6277
6278 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6279 return Context.getObjCProtocolDecl();
6280
6281 case PREDEF_DECL_INT_128_ID:
6282 return Context.getInt128Decl();
6283
6284 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6285 return Context.getUInt128Decl();
6286
6287 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6288 return Context.getObjCInstanceTypeDecl();
6289
6290 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6291 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006292
6293 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6294 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006295 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006296 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006297}
6298
Richard Smithcd45dbc2014-04-19 03:48:30 +00006299Decl *ASTReader::GetExistingDecl(DeclID ID) {
6300 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006301 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6302 if (D) {
6303 // Track that we have merged the declaration with ID \p ID into the
6304 // pre-existing predefined declaration \p D.
6305 auto &Merged = MergedDecls[D->getCanonicalDecl()];
6306 if (Merged.empty())
6307 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006308 }
Richard Smithfe620d22015-03-05 23:24:12 +00006309 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006310 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006311
Guy Benyei11169dd2012-12-18 14:30:41 +00006312 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6313
6314 if (Index >= DeclsLoaded.size()) {
6315 assert(0 && "declaration ID out-of-range for AST file");
6316 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006317 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006318 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006319
6320 return DeclsLoaded[Index];
6321}
6322
6323Decl *ASTReader::GetDecl(DeclID ID) {
6324 if (ID < NUM_PREDEF_DECL_IDS)
6325 return GetExistingDecl(ID);
6326
6327 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6328
6329 if (Index >= DeclsLoaded.size()) {
6330 assert(0 && "declaration ID out-of-range for AST file");
6331 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006332 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006333 }
6334
Guy Benyei11169dd2012-12-18 14:30:41 +00006335 if (!DeclsLoaded[Index]) {
6336 ReadDeclRecord(ID);
6337 if (DeserializationListener)
6338 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6339 }
6340
6341 return DeclsLoaded[Index];
6342}
6343
6344DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6345 DeclID GlobalID) {
6346 if (GlobalID < NUM_PREDEF_DECL_IDS)
6347 return GlobalID;
6348
6349 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6350 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6351 ModuleFile *Owner = I->second;
6352
6353 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6354 = M.GlobalToLocalDeclIDs.find(Owner);
6355 if (Pos == M.GlobalToLocalDeclIDs.end())
6356 return 0;
6357
6358 return GlobalID - Owner->BaseDeclID + Pos->second;
6359}
6360
6361serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6362 const RecordData &Record,
6363 unsigned &Idx) {
6364 if (Idx >= Record.size()) {
6365 Error("Corrupted AST file");
6366 return 0;
6367 }
6368
6369 return getGlobalDeclID(F, Record[Idx++]);
6370}
6371
6372/// \brief Resolve the offset of a statement into a statement.
6373///
6374/// This operation will read a new statement from the external
6375/// source each time it is called, and is meant to be used via a
6376/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6377Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6378 // Switch case IDs are per Decl.
6379 ClearSwitchCaseIDs();
6380
6381 // Offset here is a global offset across the entire chain.
6382 RecordLocation Loc = getLocalBitOffset(Offset);
6383 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6384 return ReadStmtFromStream(*Loc.F);
6385}
6386
6387namespace {
6388 class FindExternalLexicalDeclsVisitor {
6389 ASTReader &Reader;
6390 const DeclContext *DC;
6391 bool (*isKindWeWant)(Decl::Kind);
6392
6393 SmallVectorImpl<Decl*> &Decls;
6394 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6395
6396 public:
6397 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6398 bool (*isKindWeWant)(Decl::Kind),
6399 SmallVectorImpl<Decl*> &Decls)
6400 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6401 {
6402 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6403 PredefsVisited[I] = false;
6404 }
6405
6406 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6407 if (Preorder)
6408 return false;
6409
6410 FindExternalLexicalDeclsVisitor *This
6411 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6412
6413 ModuleFile::DeclContextInfosMap::iterator Info
6414 = M.DeclContextInfos.find(This->DC);
6415 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6416 return false;
6417
6418 // Load all of the declaration IDs
6419 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6420 *IDE = ID + Info->second.NumLexicalDecls;
6421 ID != IDE; ++ID) {
6422 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6423 continue;
6424
6425 // Don't add predefined declarations to the lexical context more
6426 // than once.
6427 if (ID->second < NUM_PREDEF_DECL_IDS) {
6428 if (This->PredefsVisited[ID->second])
6429 continue;
6430
6431 This->PredefsVisited[ID->second] = true;
6432 }
6433
6434 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6435 if (!This->DC->isDeclInLexicalTraversal(D))
6436 This->Decls.push_back(D);
6437 }
6438 }
6439
6440 return false;
6441 }
6442 };
6443}
6444
6445ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6446 bool (*isKindWeWant)(Decl::Kind),
6447 SmallVectorImpl<Decl*> &Decls) {
6448 // There might be lexical decls in multiple modules, for the TU at
6449 // least. Walk all of the modules in the order they were loaded.
6450 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6451 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6452 ++NumLexicalDeclContextsRead;
6453 return ELR_Success;
6454}
6455
6456namespace {
6457
6458class DeclIDComp {
6459 ASTReader &Reader;
6460 ModuleFile &Mod;
6461
6462public:
6463 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6464
6465 bool operator()(LocalDeclID L, LocalDeclID R) const {
6466 SourceLocation LHS = getLocation(L);
6467 SourceLocation RHS = getLocation(R);
6468 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6469 }
6470
6471 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6472 SourceLocation RHS = getLocation(R);
6473 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6474 }
6475
6476 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6477 SourceLocation LHS = getLocation(L);
6478 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6479 }
6480
6481 SourceLocation getLocation(LocalDeclID ID) const {
6482 return Reader.getSourceManager().getFileLoc(
6483 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6484 }
6485};
6486
6487}
6488
6489void ASTReader::FindFileRegionDecls(FileID File,
6490 unsigned Offset, unsigned Length,
6491 SmallVectorImpl<Decl *> &Decls) {
6492 SourceManager &SM = getSourceManager();
6493
6494 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6495 if (I == FileDeclIDs.end())
6496 return;
6497
6498 FileDeclsInfo &DInfo = I->second;
6499 if (DInfo.Decls.empty())
6500 return;
6501
6502 SourceLocation
6503 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6504 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6505
6506 DeclIDComp DIDComp(*this, *DInfo.Mod);
6507 ArrayRef<serialization::LocalDeclID>::iterator
6508 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6509 BeginLoc, DIDComp);
6510 if (BeginIt != DInfo.Decls.begin())
6511 --BeginIt;
6512
6513 // If we are pointing at a top-level decl inside an objc container, we need
6514 // to backtrack until we find it otherwise we will fail to report that the
6515 // region overlaps with an objc container.
6516 while (BeginIt != DInfo.Decls.begin() &&
6517 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6518 ->isTopLevelDeclInObjCContainer())
6519 --BeginIt;
6520
6521 ArrayRef<serialization::LocalDeclID>::iterator
6522 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6523 EndLoc, DIDComp);
6524 if (EndIt != DInfo.Decls.end())
6525 ++EndIt;
6526
6527 for (ArrayRef<serialization::LocalDeclID>::iterator
6528 DIt = BeginIt; DIt != EndIt; ++DIt)
6529 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6530}
6531
6532namespace {
6533 /// \brief ModuleFile visitor used to perform name lookup into a
6534 /// declaration context.
6535 class DeclContextNameLookupVisitor {
6536 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006537 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006538 DeclarationName Name;
6539 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006540 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006541
6542 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006543 DeclContextNameLookupVisitor(ASTReader &Reader,
6544 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006545 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006546 SmallVectorImpl<NamedDecl *> &Decls,
6547 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
6548 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls),
6549 DeclSet(DeclSet) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006550
6551 static bool visit(ModuleFile &M, void *UserData) {
6552 DeclContextNameLookupVisitor *This
6553 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6554
6555 // Check whether we have any visible declaration information for
6556 // this context in this module.
6557 ModuleFile::DeclContextInfosMap::iterator Info;
6558 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006559 for (auto *DC : This->Contexts) {
6560 Info = M.DeclContextInfos.find(DC);
6561 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006562 Info->second.NameLookupTableData) {
6563 FoundInfo = true;
6564 break;
6565 }
6566 }
6567
6568 if (!FoundInfo)
6569 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006570
Guy Benyei11169dd2012-12-18 14:30:41 +00006571 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006572 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006573 Info->second.NameLookupTableData;
6574 ASTDeclContextNameLookupTable::iterator Pos
6575 = LookupTable->find(This->Name);
6576 if (Pos == LookupTable->end())
6577 return false;
6578
6579 bool FoundAnything = false;
6580 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6581 for (; Data.first != Data.second; ++Data.first) {
6582 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6583 if (!ND)
6584 continue;
6585
6586 if (ND->getDeclName() != This->Name) {
6587 // A name might be null because the decl's redeclarable part is
6588 // currently read before reading its name. The lookup is triggered by
6589 // building that decl (likely indirectly), and so it is later in the
6590 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006591 // FIXME: This should not happen; deserializing declarations should
6592 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006593 continue;
6594 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006595
Guy Benyei11169dd2012-12-18 14:30:41 +00006596 // Record this declaration.
6597 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006598 if (This->DeclSet.insert(ND).second)
6599 This->Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006600 }
6601
6602 return FoundAnything;
6603 }
6604 };
6605}
6606
Douglas Gregor9f782892013-01-21 15:25:38 +00006607/// \brief Retrieve the "definitive" module file for the definition of the
6608/// given declaration context, if there is one.
6609///
6610/// The "definitive" module file is the only place where we need to look to
6611/// find information about the declarations within the given declaration
6612/// context. For example, C++ and Objective-C classes, C structs/unions, and
6613/// Objective-C protocols, categories, and extensions are all defined in a
6614/// single place in the source code, so they have definitive module files
6615/// associated with them. C++ namespaces, on the other hand, can have
6616/// definitions in multiple different module files.
6617///
6618/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6619/// NDEBUG checking.
6620static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6621 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006622 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6623 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006624
Craig Toppera13603a2014-05-22 05:54:18 +00006625 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006626}
6627
Richard Smith9ce12e32013-02-07 03:30:24 +00006628bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006629ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6630 DeclarationName Name) {
6631 assert(DC->hasExternalVisibleStorage() &&
6632 "DeclContext has no visible decls in storage");
6633 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006634 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006635
Richard Smith8c913ec2014-08-14 02:21:01 +00006636 Deserializing LookupResults(this);
6637
Guy Benyei11169dd2012-12-18 14:30:41 +00006638 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006639 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006640
Guy Benyei11169dd2012-12-18 14:30:41 +00006641 // Compute the declaration contexts we need to look into. Multiple such
6642 // declaration contexts occur when two declaration contexts from disjoint
6643 // modules get merged, e.g., when two namespaces with the same name are
6644 // independently defined in separate modules.
6645 SmallVector<const DeclContext *, 2> Contexts;
6646 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006647
Guy Benyei11169dd2012-12-18 14:30:41 +00006648 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006649 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006650 if (Merged != MergedDecls.end()) {
6651 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6652 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6653 }
6654 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006655
6656 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
Richard Smith52874ec2015-02-13 20:17:14 +00006657 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006658
6659 // If we can definitively determine which module file to look into,
6660 // only look there. Otherwise, look in all module files.
6661 ModuleFile *Definitive;
6662 if (Contexts.size() == 1 &&
6663 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6664 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6665 } else {
6666 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6667 }
6668 };
6669
6670 LookUpInContexts(Contexts);
6671
6672 // If this might be an implicit special member function, then also search
6673 // all merged definitions of the surrounding class. We need to search them
6674 // individually, because finding an entity in one of them doesn't imply that
6675 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006676 if (isa<CXXRecordDecl>(DC)) {
Richard Smith02793752015-03-27 21:16:39 +00006677 auto Merged = MergedLookups.find(DC);
6678 if (Merged != MergedLookups.end()) {
6679 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6680 const DeclContext *Context = Merged->second[I];
6681 LookUpInContexts(Context);
6682 // We might have just added some more merged lookups. If so, our
6683 // iterator is now invalid, so grab a fresh one before continuing.
6684 Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006685 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006686 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006687 }
6688
Guy Benyei11169dd2012-12-18 14:30:41 +00006689 ++NumVisibleDeclContextsRead;
6690 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006691 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006692}
6693
6694namespace {
6695 /// \brief ModuleFile visitor used to retrieve all visible names in a
6696 /// declaration context.
6697 class DeclContextAllNamesVisitor {
6698 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006699 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006700 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006701 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006702 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006703
6704 public:
6705 DeclContextAllNamesVisitor(ASTReader &Reader,
6706 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006707 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006708 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006709
6710 static bool visit(ModuleFile &M, void *UserData) {
6711 DeclContextAllNamesVisitor *This
6712 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6713
6714 // Check whether we have any visible declaration information for
6715 // this context in this module.
6716 ModuleFile::DeclContextInfosMap::iterator Info;
6717 bool FoundInfo = false;
6718 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6719 Info = M.DeclContextInfos.find(This->Contexts[I]);
6720 if (Info != M.DeclContextInfos.end() &&
6721 Info->second.NameLookupTableData) {
6722 FoundInfo = true;
6723 break;
6724 }
6725 }
6726
6727 if (!FoundInfo)
6728 return false;
6729
Richard Smith52e3fba2014-03-11 07:17:35 +00006730 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006731 Info->second.NameLookupTableData;
6732 bool FoundAnything = false;
6733 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006734 I = LookupTable->data_begin(), E = LookupTable->data_end();
6735 I != E;
6736 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006737 ASTDeclContextNameLookupTrait::data_type Data = *I;
6738 for (; Data.first != Data.second; ++Data.first) {
6739 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6740 *Data.first);
6741 if (!ND)
6742 continue;
6743
6744 // Record this declaration.
6745 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006746 if (This->DeclSet.insert(ND).second)
6747 This->Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006748 }
6749 }
6750
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006751 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006752 }
6753 };
6754}
6755
6756void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6757 if (!DC->hasExternalVisibleStorage())
6758 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006759 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006760
6761 // Compute the declaration contexts we need to look into. Multiple such
6762 // declaration contexts occur when two declaration contexts from disjoint
6763 // modules get merged, e.g., when two namespaces with the same name are
6764 // independently defined in separate modules.
6765 SmallVector<const DeclContext *, 2> Contexts;
6766 Contexts.push_back(DC);
6767
6768 if (DC->isNamespace()) {
6769 MergedDeclsMap::iterator Merged
6770 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6771 if (Merged != MergedDecls.end()) {
6772 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6773 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6774 }
6775 }
6776
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006777 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6778 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006779 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6780 ++NumVisibleDeclContextsRead;
6781
Craig Topper79be4cd2013-07-05 04:33:53 +00006782 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006783 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6784 }
6785 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6786}
6787
6788/// \brief Under non-PCH compilation the consumer receives the objc methods
6789/// before receiving the implementation, and codegen depends on this.
6790/// We simulate this by deserializing and passing to consumer the methods of the
6791/// implementation before passing the deserialized implementation decl.
6792static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6793 ASTConsumer *Consumer) {
6794 assert(ImplD && Consumer);
6795
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006796 for (auto *I : ImplD->methods())
6797 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006798
6799 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6800}
6801
6802void ASTReader::PassInterestingDeclsToConsumer() {
6803 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006804
6805 if (PassingDeclsToConsumer)
6806 return;
6807
6808 // Guard variable to avoid recursively redoing the process of passing
6809 // decls to consumer.
6810 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6811 true);
6812
Richard Smith9e2341d2015-03-23 03:25:59 +00006813 // Ensure that we've loaded all potentially-interesting declarations
6814 // that need to be eagerly loaded.
6815 for (auto ID : EagerlyDeserializedDecls)
6816 GetDecl(ID);
6817 EagerlyDeserializedDecls.clear();
6818
Guy Benyei11169dd2012-12-18 14:30:41 +00006819 while (!InterestingDecls.empty()) {
6820 Decl *D = InterestingDecls.front();
6821 InterestingDecls.pop_front();
6822
6823 PassInterestingDeclToConsumer(D);
6824 }
6825}
6826
6827void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6828 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6829 PassObjCImplDeclToConsumer(ImplD, Consumer);
6830 else
6831 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6832}
6833
6834void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6835 this->Consumer = Consumer;
6836
Richard Smith9e2341d2015-03-23 03:25:59 +00006837 if (Consumer)
6838 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006839
6840 if (DeserializationListener)
6841 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006842}
6843
6844void ASTReader::PrintStats() {
6845 std::fprintf(stderr, "*** AST File Statistics:\n");
6846
6847 unsigned NumTypesLoaded
6848 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6849 QualType());
6850 unsigned NumDeclsLoaded
6851 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006852 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006853 unsigned NumIdentifiersLoaded
6854 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6855 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006856 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006857 unsigned NumMacrosLoaded
6858 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6859 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006860 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006861 unsigned NumSelectorsLoaded
6862 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6863 SelectorsLoaded.end(),
6864 Selector());
6865
6866 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6867 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6868 NumSLocEntriesRead, TotalNumSLocEntries,
6869 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6870 if (!TypesLoaded.empty())
6871 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6872 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6873 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6874 if (!DeclsLoaded.empty())
6875 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6876 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6877 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6878 if (!IdentifiersLoaded.empty())
6879 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6880 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6881 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6882 if (!MacrosLoaded.empty())
6883 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6884 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6885 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6886 if (!SelectorsLoaded.empty())
6887 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6888 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6889 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6890 if (TotalNumStatements)
6891 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6892 NumStatementsRead, TotalNumStatements,
6893 ((float)NumStatementsRead/TotalNumStatements * 100));
6894 if (TotalNumMacros)
6895 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6896 NumMacrosRead, TotalNumMacros,
6897 ((float)NumMacrosRead/TotalNumMacros * 100));
6898 if (TotalLexicalDeclContexts)
6899 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6900 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6901 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6902 * 100));
6903 if (TotalVisibleDeclContexts)
6904 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6905 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6906 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6907 * 100));
6908 if (TotalNumMethodPoolEntries) {
6909 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6910 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6911 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6912 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006913 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006914 if (NumMethodPoolLookups) {
6915 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6916 NumMethodPoolHits, NumMethodPoolLookups,
6917 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6918 }
6919 if (NumMethodPoolTableLookups) {
6920 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6921 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6922 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6923 * 100.0));
6924 }
6925
Douglas Gregor00a50f72013-01-25 00:38:33 +00006926 if (NumIdentifierLookupHits) {
6927 std::fprintf(stderr,
6928 " %u / %u identifier table lookups succeeded (%f%%)\n",
6929 NumIdentifierLookupHits, NumIdentifierLookups,
6930 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6931 }
6932
Douglas Gregore060e572013-01-25 01:03:03 +00006933 if (GlobalIndex) {
6934 std::fprintf(stderr, "\n");
6935 GlobalIndex->printStats();
6936 }
6937
Guy Benyei11169dd2012-12-18 14:30:41 +00006938 std::fprintf(stderr, "\n");
6939 dump();
6940 std::fprintf(stderr, "\n");
6941}
6942
6943template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6944static void
6945dumpModuleIDMap(StringRef Name,
6946 const ContinuousRangeMap<Key, ModuleFile *,
6947 InitialCapacity> &Map) {
6948 if (Map.begin() == Map.end())
6949 return;
6950
6951 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6952 llvm::errs() << Name << ":\n";
6953 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6954 I != IEnd; ++I) {
6955 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6956 << "\n";
6957 }
6958}
6959
6960void ASTReader::dump() {
6961 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6962 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6963 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6964 dumpModuleIDMap("Global type map", GlobalTypeMap);
6965 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6966 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6967 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6968 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6969 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6970 dumpModuleIDMap("Global preprocessed entity map",
6971 GlobalPreprocessedEntityMap);
6972
6973 llvm::errs() << "\n*** PCH/Modules Loaded:";
6974 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6975 MEnd = ModuleMgr.end();
6976 M != MEnd; ++M)
6977 (*M)->dump();
6978}
6979
6980/// Return the amount of memory used by memory buffers, breaking down
6981/// by heap-backed versus mmap'ed memory.
6982void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6983 for (ModuleConstIterator I = ModuleMgr.begin(),
6984 E = ModuleMgr.end(); I != E; ++I) {
6985 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6986 size_t bytes = buf->getBufferSize();
6987 switch (buf->getBufferKind()) {
6988 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6989 sizes.malloc_bytes += bytes;
6990 break;
6991 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6992 sizes.mmap_bytes += bytes;
6993 break;
6994 }
6995 }
6996 }
6997}
6998
6999void ASTReader::InitializeSema(Sema &S) {
7000 SemaObj = &S;
7001 S.addExternalSource(this);
7002
7003 // Makes sure any declarations that were deserialized "too early"
7004 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007005 for (uint64_t ID : PreloadedDeclIDs) {
7006 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7007 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007008 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007009 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007010
Richard Smith3d8e97e2013-10-18 06:54:39 +00007011 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007012 if (!FPPragmaOptions.empty()) {
7013 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7014 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7015 }
7016
Richard Smith3d8e97e2013-10-18 06:54:39 +00007017 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007018 if (!OpenCLExtensions.empty()) {
7019 unsigned I = 0;
7020#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
7021#include "clang/Basic/OpenCLExtensions.def"
7022
7023 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
7024 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00007025
7026 UpdateSema();
7027}
7028
7029void ASTReader::UpdateSema() {
7030 assert(SemaObj && "no Sema to update");
7031
7032 // Load the offsets of the declarations that Sema references.
7033 // They will be lazily deserialized when needed.
7034 if (!SemaDeclRefs.empty()) {
7035 assert(SemaDeclRefs.size() % 2 == 0);
7036 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
7037 if (!SemaObj->StdNamespace)
7038 SemaObj->StdNamespace = SemaDeclRefs[I];
7039 if (!SemaObj->StdBadAlloc)
7040 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
7041 }
7042 SemaDeclRefs.clear();
7043 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007044
7045 // Update the state of 'pragma clang optimize'. Use the same API as if we had
7046 // encountered the pragma in the source.
7047 if(OptimizeOffPragmaLocation.isValid())
7048 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00007049}
7050
7051IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
7052 // Note that we are loading an identifier.
7053 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007054 StringRef Name(NameStart, NameEnd - NameStart);
7055
7056 // If there is a global index, look there first to determine which modules
7057 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00007058 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00007059 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00007060 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00007061 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7062 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00007063 }
7064 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00007065 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007066 NumIdentifierLookups,
7067 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00007068 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007069 IdentifierInfo *II = Visitor.getIdentifierInfo();
7070 markIdentifierUpToDate(II);
7071 return II;
7072}
7073
7074namespace clang {
7075 /// \brief An identifier-lookup iterator that enumerates all of the
7076 /// identifiers stored within a set of AST files.
7077 class ASTIdentifierIterator : public IdentifierIterator {
7078 /// \brief The AST reader whose identifiers are being enumerated.
7079 const ASTReader &Reader;
7080
7081 /// \brief The current index into the chain of AST files stored in
7082 /// the AST reader.
7083 unsigned Index;
7084
7085 /// \brief The current position within the identifier lookup table
7086 /// of the current AST file.
7087 ASTIdentifierLookupTable::key_iterator Current;
7088
7089 /// \brief The end position within the identifier lookup table of
7090 /// the current AST file.
7091 ASTIdentifierLookupTable::key_iterator End;
7092
7093 public:
7094 explicit ASTIdentifierIterator(const ASTReader &Reader);
7095
Craig Topper3e89dfe2014-03-13 02:13:41 +00007096 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007097 };
7098}
7099
7100ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7101 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7102 ASTIdentifierLookupTable *IdTable
7103 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7104 Current = IdTable->key_begin();
7105 End = IdTable->key_end();
7106}
7107
7108StringRef ASTIdentifierIterator::Next() {
7109 while (Current == End) {
7110 // If we have exhausted all of our AST files, we're done.
7111 if (Index == 0)
7112 return StringRef();
7113
7114 --Index;
7115 ASTIdentifierLookupTable *IdTable
7116 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7117 IdentifierLookupTable;
7118 Current = IdTable->key_begin();
7119 End = IdTable->key_end();
7120 }
7121
7122 // We have any identifiers remaining in the current AST file; return
7123 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007124 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007125 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007126 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007127}
7128
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007129IdentifierIterator *ASTReader::getIdentifiers() {
7130 if (!loadGlobalIndex())
7131 return GlobalIndex->createIdentifierIterator();
7132
Guy Benyei11169dd2012-12-18 14:30:41 +00007133 return new ASTIdentifierIterator(*this);
7134}
7135
7136namespace clang { namespace serialization {
7137 class ReadMethodPoolVisitor {
7138 ASTReader &Reader;
7139 Selector Sel;
7140 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007141 unsigned InstanceBits;
7142 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007143 bool InstanceHasMoreThanOneDecl;
7144 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007145 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7146 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007147
7148 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007149 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007150 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007151 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007152 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7153 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007154
Guy Benyei11169dd2012-12-18 14:30:41 +00007155 static bool visit(ModuleFile &M, void *UserData) {
7156 ReadMethodPoolVisitor *This
7157 = static_cast<ReadMethodPoolVisitor *>(UserData);
7158
7159 if (!M.SelectorLookupTable)
7160 return false;
7161
7162 // If we've already searched this module file, skip it now.
7163 if (M.Generation <= This->PriorGeneration)
7164 return true;
7165
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007166 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007167 ASTSelectorLookupTable *PoolTable
7168 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7169 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
7170 if (Pos == PoolTable->end())
7171 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007172
7173 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007174 ++This->Reader.NumSelectorsRead;
7175 // FIXME: Not quite happy with the statistics here. We probably should
7176 // disable this tracking when called via LoadSelector.
7177 // Also, should entries without methods count as misses?
7178 ++This->Reader.NumMethodPoolEntriesRead;
7179 ASTSelectorLookupTrait::data_type Data = *Pos;
7180 if (This->Reader.DeserializationListener)
7181 This->Reader.DeserializationListener->SelectorRead(Data.ID,
7182 This->Sel);
7183
7184 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7185 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007186 This->InstanceBits = Data.InstanceBits;
7187 This->FactoryBits = Data.FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007188 This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7189 This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007190 return true;
7191 }
7192
7193 /// \brief Retrieve the instance methods found by this visitor.
7194 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7195 return InstanceMethods;
7196 }
7197
7198 /// \brief Retrieve the instance methods found by this visitor.
7199 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7200 return FactoryMethods;
7201 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007202
7203 unsigned getInstanceBits() const { return InstanceBits; }
7204 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007205 bool instanceHasMoreThanOneDecl() const {
7206 return InstanceHasMoreThanOneDecl;
7207 }
7208 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007209 };
7210} } // end namespace clang::serialization
7211
7212/// \brief Add the given set of methods to the method list.
7213static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7214 ObjCMethodList &List) {
7215 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7216 S.addMethodToGlobalList(&List, Methods[I]);
7217 }
7218}
7219
7220void ASTReader::ReadMethodPool(Selector Sel) {
7221 // Get the selector generation and update it to the current generation.
7222 unsigned &Generation = SelectorGeneration[Sel];
7223 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007224 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007225
7226 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007227 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007228 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7229 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7230
7231 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007232 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007233 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007234
7235 ++NumMethodPoolHits;
7236
Guy Benyei11169dd2012-12-18 14:30:41 +00007237 if (!getSema())
7238 return;
7239
7240 Sema &S = *getSema();
7241 Sema::GlobalMethodPool::iterator Pos
7242 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007243
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007244 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007245 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007246 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007247 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007248
7249 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7250 // when building a module we keep every method individually and may need to
7251 // update hasMoreThanOneDecl as we add the methods.
7252 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7253 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007254}
7255
7256void ASTReader::ReadKnownNamespaces(
7257 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7258 Namespaces.clear();
7259
7260 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7261 if (NamespaceDecl *Namespace
7262 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7263 Namespaces.push_back(Namespace);
7264 }
7265}
7266
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007267void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007268 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007269 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7270 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007271 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007272 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007273 Undefined.insert(std::make_pair(D, Loc));
7274 }
7275}
Nick Lewycky8334af82013-01-26 00:35:08 +00007276
Guy Benyei11169dd2012-12-18 14:30:41 +00007277void ASTReader::ReadTentativeDefinitions(
7278 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7279 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7280 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7281 if (Var)
7282 TentativeDefs.push_back(Var);
7283 }
7284 TentativeDefinitions.clear();
7285}
7286
7287void ASTReader::ReadUnusedFileScopedDecls(
7288 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7289 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7290 DeclaratorDecl *D
7291 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7292 if (D)
7293 Decls.push_back(D);
7294 }
7295 UnusedFileScopedDecls.clear();
7296}
7297
7298void ASTReader::ReadDelegatingConstructors(
7299 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7300 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7301 CXXConstructorDecl *D
7302 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7303 if (D)
7304 Decls.push_back(D);
7305 }
7306 DelegatingCtorDecls.clear();
7307}
7308
7309void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7310 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7311 TypedefNameDecl *D
7312 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7313 if (D)
7314 Decls.push_back(D);
7315 }
7316 ExtVectorDecls.clear();
7317}
7318
Nico Weber72889432014-09-06 01:25:55 +00007319void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7320 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7321 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7322 ++I) {
7323 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7324 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7325 if (D)
7326 Decls.insert(D);
7327 }
7328 UnusedLocalTypedefNameCandidates.clear();
7329}
7330
Guy Benyei11169dd2012-12-18 14:30:41 +00007331void ASTReader::ReadReferencedSelectors(
7332 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7333 if (ReferencedSelectorsData.empty())
7334 return;
7335
7336 // If there are @selector references added them to its pool. This is for
7337 // implementation of -Wselector.
7338 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7339 unsigned I = 0;
7340 while (I < DataSize) {
7341 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7342 SourceLocation SelLoc
7343 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7344 Sels.push_back(std::make_pair(Sel, SelLoc));
7345 }
7346 ReferencedSelectorsData.clear();
7347}
7348
7349void ASTReader::ReadWeakUndeclaredIdentifiers(
7350 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7351 if (WeakUndeclaredIdentifiers.empty())
7352 return;
7353
7354 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7355 IdentifierInfo *WeakId
7356 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7357 IdentifierInfo *AliasId
7358 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7359 SourceLocation Loc
7360 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7361 bool Used = WeakUndeclaredIdentifiers[I++];
7362 WeakInfo WI(AliasId, Loc);
7363 WI.setUsed(Used);
7364 WeakIDs.push_back(std::make_pair(WeakId, WI));
7365 }
7366 WeakUndeclaredIdentifiers.clear();
7367}
7368
7369void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7370 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7371 ExternalVTableUse VT;
7372 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7373 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7374 VT.DefinitionRequired = VTableUses[Idx++];
7375 VTables.push_back(VT);
7376 }
7377
7378 VTableUses.clear();
7379}
7380
7381void ASTReader::ReadPendingInstantiations(
7382 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7383 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7384 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7385 SourceLocation Loc
7386 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7387
7388 Pending.push_back(std::make_pair(D, Loc));
7389 }
7390 PendingInstantiations.clear();
7391}
7392
Richard Smithe40f2ba2013-08-07 21:41:30 +00007393void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007394 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007395 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7396 /* In loop */) {
7397 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7398
7399 LateParsedTemplate *LT = new LateParsedTemplate;
7400 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7401
7402 ModuleFile *F = getOwningModuleFile(LT->D);
7403 assert(F && "No module");
7404
7405 unsigned TokN = LateParsedTemplates[Idx++];
7406 LT->Toks.reserve(TokN);
7407 for (unsigned T = 0; T < TokN; ++T)
7408 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7409
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007410 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007411 }
7412
7413 LateParsedTemplates.clear();
7414}
7415
Guy Benyei11169dd2012-12-18 14:30:41 +00007416void ASTReader::LoadSelector(Selector Sel) {
7417 // It would be complicated to avoid reading the methods anyway. So don't.
7418 ReadMethodPool(Sel);
7419}
7420
7421void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7422 assert(ID && "Non-zero identifier ID required");
7423 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7424 IdentifiersLoaded[ID - 1] = II;
7425 if (DeserializationListener)
7426 DeserializationListener->IdentifierRead(ID, II);
7427}
7428
7429/// \brief Set the globally-visible declarations associated with the given
7430/// identifier.
7431///
7432/// If the AST reader is currently in a state where the given declaration IDs
7433/// cannot safely be resolved, they are queued until it is safe to resolve
7434/// them.
7435///
7436/// \param II an IdentifierInfo that refers to one or more globally-visible
7437/// declarations.
7438///
7439/// \param DeclIDs the set of declaration IDs with the name @p II that are
7440/// visible at global scope.
7441///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007442/// \param Decls if non-null, this vector will be populated with the set of
7443/// deserialized declarations. These declarations will not be pushed into
7444/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007445void
7446ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7447 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007448 SmallVectorImpl<Decl *> *Decls) {
7449 if (NumCurrentElementsDeserializing && !Decls) {
7450 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007451 return;
7452 }
7453
7454 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007455 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007456 // Queue this declaration so that it will be added to the
7457 // translation unit scope and identifier's declaration chain
7458 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007459 PreloadedDeclIDs.push_back(DeclIDs[I]);
7460 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007461 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007462
7463 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7464
7465 // If we're simply supposed to record the declarations, do so now.
7466 if (Decls) {
7467 Decls->push_back(D);
7468 continue;
7469 }
7470
7471 // Introduce this declaration into the translation-unit scope
7472 // and add it to the declaration chain for this identifier, so
7473 // that (unqualified) name lookup will find it.
7474 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007475 }
7476}
7477
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007478IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007479 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007480 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007481
7482 if (IdentifiersLoaded.empty()) {
7483 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007484 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007485 }
7486
7487 ID -= 1;
7488 if (!IdentifiersLoaded[ID]) {
7489 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7490 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7491 ModuleFile *M = I->second;
7492 unsigned Index = ID - M->BaseIdentifierID;
7493 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7494
7495 // All of the strings in the AST file are preceded by a 16-bit length.
7496 // Extract that 16-bit length to avoid having to execute strlen().
7497 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7498 // unsigned integers. This is important to avoid integer overflow when
7499 // we cast them to 'unsigned'.
7500 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7501 unsigned StrLen = (((unsigned) StrLenPtr[0])
7502 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007503 IdentifiersLoaded[ID]
7504 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007505 if (DeserializationListener)
7506 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7507 }
7508
7509 return IdentifiersLoaded[ID];
7510}
7511
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007512IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7513 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007514}
7515
7516IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7517 if (LocalID < NUM_PREDEF_IDENT_IDS)
7518 return LocalID;
7519
7520 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7521 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7522 assert(I != M.IdentifierRemap.end()
7523 && "Invalid index into identifier index remap");
7524
7525 return LocalID + I->second;
7526}
7527
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007528MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007529 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007530 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007531
7532 if (MacrosLoaded.empty()) {
7533 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007534 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007535 }
7536
7537 ID -= NUM_PREDEF_MACRO_IDS;
7538 if (!MacrosLoaded[ID]) {
7539 GlobalMacroMapType::iterator I
7540 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7541 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7542 ModuleFile *M = I->second;
7543 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007544 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7545
7546 if (DeserializationListener)
7547 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7548 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007549 }
7550
7551 return MacrosLoaded[ID];
7552}
7553
7554MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7555 if (LocalID < NUM_PREDEF_MACRO_IDS)
7556 return LocalID;
7557
7558 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7559 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7560 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7561
7562 return LocalID + I->second;
7563}
7564
7565serialization::SubmoduleID
7566ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7567 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7568 return LocalID;
7569
7570 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7571 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7572 assert(I != M.SubmoduleRemap.end()
7573 && "Invalid index into submodule index remap");
7574
7575 return LocalID + I->second;
7576}
7577
7578Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7579 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7580 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007581 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007582 }
7583
7584 if (GlobalID > SubmodulesLoaded.size()) {
7585 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007586 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007587 }
7588
7589 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7590}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007591
7592Module *ASTReader::getModule(unsigned ID) {
7593 return getSubmodule(ID);
7594}
7595
Guy Benyei11169dd2012-12-18 14:30:41 +00007596Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7597 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7598}
7599
7600Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7601 if (ID == 0)
7602 return Selector();
7603
7604 if (ID > SelectorsLoaded.size()) {
7605 Error("selector ID out of range in AST file");
7606 return Selector();
7607 }
7608
Craig Toppera13603a2014-05-22 05:54:18 +00007609 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007610 // Load this selector from the selector table.
7611 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7612 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7613 ModuleFile &M = *I->second;
7614 ASTSelectorLookupTrait Trait(*this, M);
7615 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7616 SelectorsLoaded[ID - 1] =
7617 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7618 if (DeserializationListener)
7619 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7620 }
7621
7622 return SelectorsLoaded[ID - 1];
7623}
7624
7625Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7626 return DecodeSelector(ID);
7627}
7628
7629uint32_t ASTReader::GetNumExternalSelectors() {
7630 // ID 0 (the null selector) is considered an external selector.
7631 return getTotalNumSelectors() + 1;
7632}
7633
7634serialization::SelectorID
7635ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7636 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7637 return LocalID;
7638
7639 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7640 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7641 assert(I != M.SelectorRemap.end()
7642 && "Invalid index into selector index remap");
7643
7644 return LocalID + I->second;
7645}
7646
7647DeclarationName
7648ASTReader::ReadDeclarationName(ModuleFile &F,
7649 const RecordData &Record, unsigned &Idx) {
7650 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7651 switch (Kind) {
7652 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007653 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007654
7655 case DeclarationName::ObjCZeroArgSelector:
7656 case DeclarationName::ObjCOneArgSelector:
7657 case DeclarationName::ObjCMultiArgSelector:
7658 return DeclarationName(ReadSelector(F, Record, Idx));
7659
7660 case DeclarationName::CXXConstructorName:
7661 return Context.DeclarationNames.getCXXConstructorName(
7662 Context.getCanonicalType(readType(F, Record, Idx)));
7663
7664 case DeclarationName::CXXDestructorName:
7665 return Context.DeclarationNames.getCXXDestructorName(
7666 Context.getCanonicalType(readType(F, Record, Idx)));
7667
7668 case DeclarationName::CXXConversionFunctionName:
7669 return Context.DeclarationNames.getCXXConversionFunctionName(
7670 Context.getCanonicalType(readType(F, Record, Idx)));
7671
7672 case DeclarationName::CXXOperatorName:
7673 return Context.DeclarationNames.getCXXOperatorName(
7674 (OverloadedOperatorKind)Record[Idx++]);
7675
7676 case DeclarationName::CXXLiteralOperatorName:
7677 return Context.DeclarationNames.getCXXLiteralOperatorName(
7678 GetIdentifierInfo(F, Record, Idx));
7679
7680 case DeclarationName::CXXUsingDirective:
7681 return DeclarationName::getUsingDirectiveName();
7682 }
7683
7684 llvm_unreachable("Invalid NameKind!");
7685}
7686
7687void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7688 DeclarationNameLoc &DNLoc,
7689 DeclarationName Name,
7690 const RecordData &Record, unsigned &Idx) {
7691 switch (Name.getNameKind()) {
7692 case DeclarationName::CXXConstructorName:
7693 case DeclarationName::CXXDestructorName:
7694 case DeclarationName::CXXConversionFunctionName:
7695 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7696 break;
7697
7698 case DeclarationName::CXXOperatorName:
7699 DNLoc.CXXOperatorName.BeginOpNameLoc
7700 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7701 DNLoc.CXXOperatorName.EndOpNameLoc
7702 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7703 break;
7704
7705 case DeclarationName::CXXLiteralOperatorName:
7706 DNLoc.CXXLiteralOperatorName.OpNameLoc
7707 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7708 break;
7709
7710 case DeclarationName::Identifier:
7711 case DeclarationName::ObjCZeroArgSelector:
7712 case DeclarationName::ObjCOneArgSelector:
7713 case DeclarationName::ObjCMultiArgSelector:
7714 case DeclarationName::CXXUsingDirective:
7715 break;
7716 }
7717}
7718
7719void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7720 DeclarationNameInfo &NameInfo,
7721 const RecordData &Record, unsigned &Idx) {
7722 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7723 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7724 DeclarationNameLoc DNLoc;
7725 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7726 NameInfo.setInfo(DNLoc);
7727}
7728
7729void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7730 const RecordData &Record, unsigned &Idx) {
7731 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7732 unsigned NumTPLists = Record[Idx++];
7733 Info.NumTemplParamLists = NumTPLists;
7734 if (NumTPLists) {
7735 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7736 for (unsigned i=0; i != NumTPLists; ++i)
7737 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7738 }
7739}
7740
7741TemplateName
7742ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7743 unsigned &Idx) {
7744 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7745 switch (Kind) {
7746 case TemplateName::Template:
7747 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7748
7749 case TemplateName::OverloadedTemplate: {
7750 unsigned size = Record[Idx++];
7751 UnresolvedSet<8> Decls;
7752 while (size--)
7753 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7754
7755 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7756 }
7757
7758 case TemplateName::QualifiedTemplate: {
7759 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7760 bool hasTemplKeyword = Record[Idx++];
7761 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7762 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7763 }
7764
7765 case TemplateName::DependentTemplate: {
7766 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7767 if (Record[Idx++]) // isIdentifier
7768 return Context.getDependentTemplateName(NNS,
7769 GetIdentifierInfo(F, Record,
7770 Idx));
7771 return Context.getDependentTemplateName(NNS,
7772 (OverloadedOperatorKind)Record[Idx++]);
7773 }
7774
7775 case TemplateName::SubstTemplateTemplateParm: {
7776 TemplateTemplateParmDecl *param
7777 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7778 if (!param) return TemplateName();
7779 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7780 return Context.getSubstTemplateTemplateParm(param, replacement);
7781 }
7782
7783 case TemplateName::SubstTemplateTemplateParmPack: {
7784 TemplateTemplateParmDecl *Param
7785 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7786 if (!Param)
7787 return TemplateName();
7788
7789 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7790 if (ArgPack.getKind() != TemplateArgument::Pack)
7791 return TemplateName();
7792
7793 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7794 }
7795 }
7796
7797 llvm_unreachable("Unhandled template name kind!");
7798}
7799
7800TemplateArgument
7801ASTReader::ReadTemplateArgument(ModuleFile &F,
7802 const RecordData &Record, unsigned &Idx) {
7803 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7804 switch (Kind) {
7805 case TemplateArgument::Null:
7806 return TemplateArgument();
7807 case TemplateArgument::Type:
7808 return TemplateArgument(readType(F, Record, Idx));
7809 case TemplateArgument::Declaration: {
7810 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007811 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007812 }
7813 case TemplateArgument::NullPtr:
7814 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7815 case TemplateArgument::Integral: {
7816 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7817 QualType T = readType(F, Record, Idx);
7818 return TemplateArgument(Context, Value, T);
7819 }
7820 case TemplateArgument::Template:
7821 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7822 case TemplateArgument::TemplateExpansion: {
7823 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007824 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007825 if (unsigned NumExpansions = Record[Idx++])
7826 NumTemplateExpansions = NumExpansions - 1;
7827 return TemplateArgument(Name, NumTemplateExpansions);
7828 }
7829 case TemplateArgument::Expression:
7830 return TemplateArgument(ReadExpr(F));
7831 case TemplateArgument::Pack: {
7832 unsigned NumArgs = Record[Idx++];
7833 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7834 for (unsigned I = 0; I != NumArgs; ++I)
7835 Args[I] = ReadTemplateArgument(F, Record, Idx);
7836 return TemplateArgument(Args, NumArgs);
7837 }
7838 }
7839
7840 llvm_unreachable("Unhandled template argument kind!");
7841}
7842
7843TemplateParameterList *
7844ASTReader::ReadTemplateParameterList(ModuleFile &F,
7845 const RecordData &Record, unsigned &Idx) {
7846 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7847 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7848 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7849
7850 unsigned NumParams = Record[Idx++];
7851 SmallVector<NamedDecl *, 16> Params;
7852 Params.reserve(NumParams);
7853 while (NumParams--)
7854 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7855
7856 TemplateParameterList* TemplateParams =
7857 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7858 Params.data(), Params.size(), RAngleLoc);
7859 return TemplateParams;
7860}
7861
7862void
7863ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007864ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007865 ModuleFile &F, const RecordData &Record,
7866 unsigned &Idx) {
7867 unsigned NumTemplateArgs = Record[Idx++];
7868 TemplArgs.reserve(NumTemplateArgs);
7869 while (NumTemplateArgs--)
7870 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7871}
7872
7873/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007874void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007875 const RecordData &Record, unsigned &Idx) {
7876 unsigned NumDecls = Record[Idx++];
7877 Set.reserve(Context, NumDecls);
7878 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007879 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007880 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007881 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007882 }
7883}
7884
7885CXXBaseSpecifier
7886ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7887 const RecordData &Record, unsigned &Idx) {
7888 bool isVirtual = static_cast<bool>(Record[Idx++]);
7889 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7890 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7891 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7892 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7893 SourceRange Range = ReadSourceRange(F, Record, Idx);
7894 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7895 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7896 EllipsisLoc);
7897 Result.setInheritConstructors(inheritConstructors);
7898 return Result;
7899}
7900
Richard Smithc2bb8182015-03-24 06:36:48 +00007901CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007902ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7903 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007904 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007905 assert(NumInitializers && "wrote ctor initializers but have no inits");
7906 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7907 for (unsigned i = 0; i != NumInitializers; ++i) {
7908 TypeSourceInfo *TInfo = nullptr;
7909 bool IsBaseVirtual = false;
7910 FieldDecl *Member = nullptr;
7911 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007912
Richard Smithc2bb8182015-03-24 06:36:48 +00007913 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7914 switch (Type) {
7915 case CTOR_INITIALIZER_BASE:
7916 TInfo = GetTypeSourceInfo(F, Record, Idx);
7917 IsBaseVirtual = Record[Idx++];
7918 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007919
Richard Smithc2bb8182015-03-24 06:36:48 +00007920 case CTOR_INITIALIZER_DELEGATING:
7921 TInfo = GetTypeSourceInfo(F, Record, Idx);
7922 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007923
Richard Smithc2bb8182015-03-24 06:36:48 +00007924 case CTOR_INITIALIZER_MEMBER:
7925 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7926 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007927
Richard Smithc2bb8182015-03-24 06:36:48 +00007928 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7929 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7930 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007931 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007932
7933 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7934 Expr *Init = ReadExpr(F);
7935 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7936 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7937 bool IsWritten = Record[Idx++];
7938 unsigned SourceOrderOrNumArrayIndices;
7939 SmallVector<VarDecl *, 8> Indices;
7940 if (IsWritten) {
7941 SourceOrderOrNumArrayIndices = Record[Idx++];
7942 } else {
7943 SourceOrderOrNumArrayIndices = Record[Idx++];
7944 Indices.reserve(SourceOrderOrNumArrayIndices);
7945 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7946 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7947 }
7948
7949 CXXCtorInitializer *BOMInit;
7950 if (Type == CTOR_INITIALIZER_BASE) {
7951 BOMInit = new (Context)
7952 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7953 RParenLoc, MemberOrEllipsisLoc);
7954 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7955 BOMInit = new (Context)
7956 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7957 } else if (IsWritten) {
7958 if (Member)
7959 BOMInit = new (Context) CXXCtorInitializer(
7960 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7961 else
7962 BOMInit = new (Context)
7963 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7964 LParenLoc, Init, RParenLoc);
7965 } else {
7966 if (IndirectMember) {
7967 assert(Indices.empty() && "Indirect field improperly initialized");
7968 BOMInit = new (Context)
7969 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7970 LParenLoc, Init, RParenLoc);
7971 } else {
7972 BOMInit = CXXCtorInitializer::Create(
7973 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7974 Indices.data(), Indices.size());
7975 }
7976 }
7977
7978 if (IsWritten)
7979 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7980 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007981 }
7982
Richard Smithc2bb8182015-03-24 06:36:48 +00007983 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007984}
7985
7986NestedNameSpecifier *
7987ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7988 const RecordData &Record, unsigned &Idx) {
7989 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007990 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007991 for (unsigned I = 0; I != N; ++I) {
7992 NestedNameSpecifier::SpecifierKind Kind
7993 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7994 switch (Kind) {
7995 case NestedNameSpecifier::Identifier: {
7996 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7997 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7998 break;
7999 }
8000
8001 case NestedNameSpecifier::Namespace: {
8002 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8003 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8004 break;
8005 }
8006
8007 case NestedNameSpecifier::NamespaceAlias: {
8008 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8009 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8010 break;
8011 }
8012
8013 case NestedNameSpecifier::TypeSpec:
8014 case NestedNameSpecifier::TypeSpecWithTemplate: {
8015 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8016 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008017 return nullptr;
8018
Guy Benyei11169dd2012-12-18 14:30:41 +00008019 bool Template = Record[Idx++];
8020 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8021 break;
8022 }
8023
8024 case NestedNameSpecifier::Global: {
8025 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8026 // No associated value, and there can't be a prefix.
8027 break;
8028 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008029
8030 case NestedNameSpecifier::Super: {
8031 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8032 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8033 break;
8034 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008035 }
8036 Prev = NNS;
8037 }
8038 return NNS;
8039}
8040
8041NestedNameSpecifierLoc
8042ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8043 unsigned &Idx) {
8044 unsigned N = Record[Idx++];
8045 NestedNameSpecifierLocBuilder Builder;
8046 for (unsigned I = 0; I != N; ++I) {
8047 NestedNameSpecifier::SpecifierKind Kind
8048 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8049 switch (Kind) {
8050 case NestedNameSpecifier::Identifier: {
8051 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8052 SourceRange Range = ReadSourceRange(F, Record, Idx);
8053 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8054 break;
8055 }
8056
8057 case NestedNameSpecifier::Namespace: {
8058 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8059 SourceRange Range = ReadSourceRange(F, Record, Idx);
8060 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8061 break;
8062 }
8063
8064 case NestedNameSpecifier::NamespaceAlias: {
8065 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8066 SourceRange Range = ReadSourceRange(F, Record, Idx);
8067 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8068 break;
8069 }
8070
8071 case NestedNameSpecifier::TypeSpec:
8072 case NestedNameSpecifier::TypeSpecWithTemplate: {
8073 bool Template = Record[Idx++];
8074 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8075 if (!T)
8076 return NestedNameSpecifierLoc();
8077 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8078
8079 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8080 Builder.Extend(Context,
8081 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8082 T->getTypeLoc(), ColonColonLoc);
8083 break;
8084 }
8085
8086 case NestedNameSpecifier::Global: {
8087 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8088 Builder.MakeGlobal(Context, ColonColonLoc);
8089 break;
8090 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008091
8092 case NestedNameSpecifier::Super: {
8093 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8094 SourceRange Range = ReadSourceRange(F, Record, Idx);
8095 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8096 break;
8097 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008098 }
8099 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008100
Guy Benyei11169dd2012-12-18 14:30:41 +00008101 return Builder.getWithLocInContext(Context);
8102}
8103
8104SourceRange
8105ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8106 unsigned &Idx) {
8107 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8108 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8109 return SourceRange(beg, end);
8110}
8111
8112/// \brief Read an integral value
8113llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8114 unsigned BitWidth = Record[Idx++];
8115 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8116 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8117 Idx += NumWords;
8118 return Result;
8119}
8120
8121/// \brief Read a signed integral value
8122llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8123 bool isUnsigned = Record[Idx++];
8124 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8125}
8126
8127/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008128llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8129 const llvm::fltSemantics &Sem,
8130 unsigned &Idx) {
8131 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008132}
8133
8134// \brief Read a string
8135std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8136 unsigned Len = Record[Idx++];
8137 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8138 Idx += Len;
8139 return Result;
8140}
8141
Richard Smith7ed1bc92014-12-05 22:42:13 +00008142std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8143 unsigned &Idx) {
8144 std::string Filename = ReadString(Record, Idx);
8145 ResolveImportedPath(F, Filename);
8146 return Filename;
8147}
8148
Guy Benyei11169dd2012-12-18 14:30:41 +00008149VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8150 unsigned &Idx) {
8151 unsigned Major = Record[Idx++];
8152 unsigned Minor = Record[Idx++];
8153 unsigned Subminor = Record[Idx++];
8154 if (Minor == 0)
8155 return VersionTuple(Major);
8156 if (Subminor == 0)
8157 return VersionTuple(Major, Minor - 1);
8158 return VersionTuple(Major, Minor - 1, Subminor - 1);
8159}
8160
8161CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8162 const RecordData &Record,
8163 unsigned &Idx) {
8164 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8165 return CXXTemporary::Create(Context, Decl);
8166}
8167
8168DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008169 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008170}
8171
8172DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8173 return Diags.Report(Loc, DiagID);
8174}
8175
8176/// \brief Retrieve the identifier table associated with the
8177/// preprocessor.
8178IdentifierTable &ASTReader::getIdentifierTable() {
8179 return PP.getIdentifierTable();
8180}
8181
8182/// \brief Record that the given ID maps to the given switch-case
8183/// statement.
8184void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008185 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008186 "Already have a SwitchCase with this ID");
8187 (*CurrSwitchCaseStmts)[ID] = SC;
8188}
8189
8190/// \brief Retrieve the switch-case statement with the given ID.
8191SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008192 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008193 return (*CurrSwitchCaseStmts)[ID];
8194}
8195
8196void ASTReader::ClearSwitchCaseIDs() {
8197 CurrSwitchCaseStmts->clear();
8198}
8199
8200void ASTReader::ReadComments() {
8201 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008202 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008203 serialization::ModuleFile *> >::iterator
8204 I = CommentsCursors.begin(),
8205 E = CommentsCursors.end();
8206 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008207 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008208 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008209 serialization::ModuleFile &F = *I->second;
8210 SavedStreamPosition SavedPosition(Cursor);
8211
8212 RecordData Record;
8213 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008214 llvm::BitstreamEntry Entry =
8215 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008216
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008217 switch (Entry.Kind) {
8218 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8219 case llvm::BitstreamEntry::Error:
8220 Error("malformed block record in AST file");
8221 return;
8222 case llvm::BitstreamEntry::EndBlock:
8223 goto NextCursor;
8224 case llvm::BitstreamEntry::Record:
8225 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008226 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008227 }
8228
8229 // Read a record.
8230 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008231 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008232 case COMMENTS_RAW_COMMENT: {
8233 unsigned Idx = 0;
8234 SourceRange SR = ReadSourceRange(F, Record, Idx);
8235 RawComment::CommentKind Kind =
8236 (RawComment::CommentKind) Record[Idx++];
8237 bool IsTrailingComment = Record[Idx++];
8238 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008239 Comments.push_back(new (Context) RawComment(
8240 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8241 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008242 break;
8243 }
8244 }
8245 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008246 NextCursor:
8247 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008248 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008249}
8250
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008251void ASTReader::getInputFiles(ModuleFile &F,
8252 SmallVectorImpl<serialization::InputFile> &Files) {
8253 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8254 unsigned ID = I+1;
8255 Files.push_back(getInputFile(F, ID));
8256 }
8257}
8258
Richard Smithcd45dbc2014-04-19 03:48:30 +00008259std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8260 // If we know the owning module, use it.
8261 if (Module *M = D->getOwningModule())
8262 return M->getFullModuleName();
8263
8264 // Otherwise, use the name of the top-level module the decl is within.
8265 if (ModuleFile *M = getOwningModuleFile(D))
8266 return M->ModuleName;
8267
8268 // Not from a module.
8269 return "";
8270}
8271
Guy Benyei11169dd2012-12-18 14:30:41 +00008272void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008273 while (!PendingIdentifierInfos.empty() ||
8274 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008275 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008276 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008277 // If any identifiers with corresponding top-level declarations have
8278 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008279 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8280 TopLevelDeclsMap;
8281 TopLevelDeclsMap TopLevelDecls;
8282
Guy Benyei11169dd2012-12-18 14:30:41 +00008283 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008284 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008285 SmallVector<uint32_t, 4> DeclIDs =
8286 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008287 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008288
8289 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008290 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008291
Richard Smith851072e2014-05-19 20:59:20 +00008292 // For each decl chain that we wanted to complete while deserializing, mark
8293 // it as "still needs to be completed".
8294 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8295 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8296 }
8297 PendingIncompleteDeclChains.clear();
8298
Guy Benyei11169dd2012-12-18 14:30:41 +00008299 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008300 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008301 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008302 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008303 }
8304 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008305 PendingDeclChains.clear();
8306
Douglas Gregor6168bd22013-02-18 15:53:43 +00008307 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008308 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8309 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008310 IdentifierInfo *II = TLD->first;
8311 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008312 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008313 }
8314 }
8315
Guy Benyei11169dd2012-12-18 14:30:41 +00008316 // Load any pending macro definitions.
8317 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008318 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8319 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8320 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8321 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008322 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008323 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008324 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008325 if (Info.M->Kind != MK_ImplicitModule &&
8326 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008327 resolvePendingMacro(II, Info);
8328 }
8329 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008330 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008331 ++IDIdx) {
8332 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008333 if (Info.M->Kind == MK_ImplicitModule ||
8334 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008335 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008336 }
8337 }
8338 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008339
8340 // Wire up the DeclContexts for Decls that we delayed setting until
8341 // recursive loading is completed.
8342 while (!PendingDeclContextInfos.empty()) {
8343 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8344 PendingDeclContextInfos.pop_front();
8345 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8346 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8347 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8348 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008349
Richard Smithd1c46742014-04-30 02:24:17 +00008350 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008351 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008352 auto Update = PendingUpdateRecords.pop_back_val();
8353 ReadingKindTracker ReadingKind(Read_Decl, *this);
8354 loadDeclUpdateRecords(Update.first, Update.second);
8355 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008356 }
Richard Smith8a639892015-01-24 01:07:20 +00008357
8358 // At this point, all update records for loaded decls are in place, so any
8359 // fake class definitions should have become real.
8360 assert(PendingFakeDefinitionData.empty() &&
8361 "faked up a class definition but never saw the real one");
8362
Guy Benyei11169dd2012-12-18 14:30:41 +00008363 // If we deserialized any C++ or Objective-C class definitions, any
8364 // Objective-C protocol definitions, or any redeclarable templates, make sure
8365 // that all redeclarations point to the definitions. Note that this can only
8366 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008367 for (Decl *D : PendingDefinitions) {
8368 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008369 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008370 // Make sure that the TagType points at the definition.
8371 const_cast<TagType*>(TagT)->decl = TD;
8372 }
Richard Smith8ce51082015-03-11 01:44:51 +00008373
Craig Topperc6914d02014-08-25 04:15:02 +00008374 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008375 for (auto *R = getMostRecentExistingDecl(RD); R;
8376 R = R->getPreviousDecl()) {
8377 assert((R == D) ==
8378 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008379 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008380 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008381 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008382 }
8383
8384 continue;
8385 }
Richard Smith8ce51082015-03-11 01:44:51 +00008386
Craig Topperc6914d02014-08-25 04:15:02 +00008387 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008388 // Make sure that the ObjCInterfaceType points at the definition.
8389 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8390 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008391
8392 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8393 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8394
Guy Benyei11169dd2012-12-18 14:30:41 +00008395 continue;
8396 }
Richard Smith8ce51082015-03-11 01:44:51 +00008397
Craig Topperc6914d02014-08-25 04:15:02 +00008398 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008399 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8400 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8401
Guy Benyei11169dd2012-12-18 14:30:41 +00008402 continue;
8403 }
Richard Smith8ce51082015-03-11 01:44:51 +00008404
Craig Topperc6914d02014-08-25 04:15:02 +00008405 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008406 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8407 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008408 }
8409 PendingDefinitions.clear();
8410
8411 // Load the bodies of any functions or methods we've encountered. We do
8412 // this now (delayed) so that we can be sure that the declaration chains
8413 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008414 // FIXME: There seems to be no point in delaying this, it does not depend
8415 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008416 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8417 PBEnd = PendingBodies.end();
8418 PB != PBEnd; ++PB) {
8419 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8420 // FIXME: Check for =delete/=default?
8421 // FIXME: Complain about ODR violations here?
8422 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8423 FD->setLazyBody(PB->second);
8424 continue;
8425 }
8426
8427 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8428 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8429 MD->setLazyBody(PB->second);
8430 }
8431 PendingBodies.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008432}
8433
8434void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008435 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8436 return;
8437
Richard Smitha0ce9c42014-07-29 23:23:27 +00008438 // Trigger the import of the full definition of each class that had any
8439 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008440 // These updates may in turn find and diagnose some ODR failures, so take
8441 // ownership of the set first.
8442 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8443 PendingOdrMergeFailures.clear();
8444 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008445 Merge.first->buildLookup();
8446 Merge.first->decls_begin();
8447 Merge.first->bases_begin();
8448 Merge.first->vbases_begin();
8449 for (auto *RD : Merge.second) {
8450 RD->decls_begin();
8451 RD->bases_begin();
8452 RD->vbases_begin();
8453 }
8454 }
8455
8456 // For each declaration from a merged context, check that the canonical
8457 // definition of that context also contains a declaration of the same
8458 // entity.
8459 //
8460 // Caution: this loop does things that might invalidate iterators into
8461 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8462 while (!PendingOdrMergeChecks.empty()) {
8463 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8464
8465 // FIXME: Skip over implicit declarations for now. This matters for things
8466 // like implicitly-declared special member functions. This isn't entirely
8467 // correct; we can end up with multiple unmerged declarations of the same
8468 // implicit entity.
8469 if (D->isImplicit())
8470 continue;
8471
8472 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008473
8474 bool Found = false;
8475 const Decl *DCanon = D->getCanonicalDecl();
8476
Richard Smith01bdb7a2014-08-28 05:44:07 +00008477 for (auto RI : D->redecls()) {
8478 if (RI->getLexicalDeclContext() == CanonDef) {
8479 Found = true;
8480 break;
8481 }
8482 }
8483 if (Found)
8484 continue;
8485
Richard Smitha0ce9c42014-07-29 23:23:27 +00008486 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008487 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008488 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8489 !Found && I != E; ++I) {
8490 for (auto RI : (*I)->redecls()) {
8491 if (RI->getLexicalDeclContext() == CanonDef) {
8492 // This declaration is present in the canonical definition. If it's
8493 // in the same redecl chain, it's the one we're looking for.
8494 if (RI->getCanonicalDecl() == DCanon)
8495 Found = true;
8496 else
8497 Candidates.push_back(cast<NamedDecl>(RI));
8498 break;
8499 }
8500 }
8501 }
8502
8503 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008504 // The AST doesn't like TagDecls becoming invalid after they've been
8505 // completed. We only really need to mark FieldDecls as invalid here.
8506 if (!isa<TagDecl>(D))
8507 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008508
8509 // Ensure we don't accidentally recursively enter deserialization while
8510 // we're producing our diagnostic.
8511 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008512
8513 std::string CanonDefModule =
8514 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8515 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8516 << D << getOwningModuleNameForDiagnostic(D)
8517 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8518
8519 if (Candidates.empty())
8520 Diag(cast<Decl>(CanonDef)->getLocation(),
8521 diag::note_module_odr_violation_no_possible_decls) << D;
8522 else {
8523 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8524 Diag(Candidates[I]->getLocation(),
8525 diag::note_module_odr_violation_possible_decl)
8526 << Candidates[I];
8527 }
8528
8529 DiagnosedOdrMergeFailures.insert(CanonDef);
8530 }
8531 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008532
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008533 if (OdrMergeFailures.empty())
8534 return;
8535
8536 // Ensure we don't accidentally recursively enter deserialization while
8537 // we're producing our diagnostics.
8538 Deserializing RecursionGuard(this);
8539
Richard Smithcd45dbc2014-04-19 03:48:30 +00008540 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008541 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008542 // If we've already pointed out a specific problem with this class, don't
8543 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008544 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008545 continue;
8546
8547 bool Diagnosed = false;
8548 for (auto *RD : Merge.second) {
8549 // Multiple different declarations got merged together; tell the user
8550 // where they came from.
8551 if (Merge.first != RD) {
8552 // FIXME: Walk the definition, figure out what's different,
8553 // and diagnose that.
8554 if (!Diagnosed) {
8555 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8556 Diag(Merge.first->getLocation(),
8557 diag::err_module_odr_violation_different_definitions)
8558 << Merge.first << Module.empty() << Module;
8559 Diagnosed = true;
8560 }
8561
8562 Diag(RD->getLocation(),
8563 diag::note_module_odr_violation_different_definitions)
8564 << getOwningModuleNameForDiagnostic(RD);
8565 }
8566 }
8567
8568 if (!Diagnosed) {
8569 // All definitions are updates to the same declaration. This happens if a
8570 // module instantiates the declaration of a class template specialization
8571 // and two or more other modules instantiate its definition.
8572 //
8573 // FIXME: Indicate which modules had instantiations of this definition.
8574 // FIXME: How can this even happen?
8575 Diag(Merge.first->getLocation(),
8576 diag::err_module_odr_violation_different_instantiations)
8577 << Merge.first;
8578 }
8579 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008580}
8581
8582void ASTReader::FinishedDeserializing() {
8583 assert(NumCurrentElementsDeserializing &&
8584 "FinishedDeserializing not paired with StartedDeserializing");
8585 if (NumCurrentElementsDeserializing == 1) {
8586 // We decrease NumCurrentElementsDeserializing only after pending actions
8587 // are finished, to avoid recursively re-calling finishPendingActions().
8588 finishPendingActions();
8589 }
8590 --NumCurrentElementsDeserializing;
8591
Richard Smitha0ce9c42014-07-29 23:23:27 +00008592 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008593 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008594 while (!PendingExceptionSpecUpdates.empty()) {
8595 auto Updates = std::move(PendingExceptionSpecUpdates);
8596 PendingExceptionSpecUpdates.clear();
8597 for (auto Update : Updates) {
8598 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8599 SemaObj->UpdateExceptionSpec(Update.second,
8600 FPT->getExtProtoInfo().ExceptionSpec);
8601 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008602 }
8603
Richard Smitha0ce9c42014-07-29 23:23:27 +00008604 diagnoseOdrViolations();
8605
Richard Smith04d05b52014-03-23 00:27:18 +00008606 // We are not in recursive loading, so it's safe to pass the "interesting"
8607 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008608 if (Consumer)
8609 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008610 }
8611}
8612
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008613void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008614 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8615 // Remove any fake results before adding any real ones.
8616 auto It = PendingFakeLookupResults.find(II);
8617 if (It != PendingFakeLookupResults.end()) {
8618 for (auto *ND : PendingFakeLookupResults[II])
8619 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008620 // FIXME: this works around module+PCH performance issue.
8621 // Rather than erase the result from the map, which is O(n), just clear
8622 // the vector of NamedDecls.
8623 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008624 }
8625 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008626
8627 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8628 SemaObj->TUScope->AddDecl(D);
8629 } else if (SemaObj->TUScope) {
8630 // Adding the decl to IdResolver may have failed because it was already in
8631 // (even though it was not added in scope). If it is already in, make sure
8632 // it gets in the scope as well.
8633 if (std::find(SemaObj->IdResolver.begin(Name),
8634 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8635 SemaObj->TUScope->AddDecl(D);
8636 }
8637}
8638
Nico Weber824285e2014-05-08 04:26:47 +00008639ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8640 bool DisableValidation, bool AllowASTWithCompilerErrors,
8641 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008642 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008643 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008644 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008645 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8646 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8647 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8648 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008649 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8650 AllowConfigurationMismatch(AllowConfigurationMismatch),
8651 ValidateSystemInputs(ValidateSystemInputs),
8652 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008653 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008654 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8655 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8656 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8657 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8658 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8659 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8660 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8661 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8662 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008663 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008664 SourceMgr.setExternalSLocEntrySource(this);
8665}
8666
8667ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008668 if (OwnsDeserializationListener)
8669 delete DeserializationListener;
8670
Guy Benyei11169dd2012-12-18 14:30:41 +00008671 for (DeclContextVisibleUpdatesPending::iterator
8672 I = PendingVisibleUpdates.begin(),
8673 E = PendingVisibleUpdates.end();
8674 I != E; ++I) {
8675 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8676 F = I->second.end();
8677 J != F; ++J)
8678 delete J->first;
8679 }
8680}