blob: 0e45a2f6fa78d68a7650dd94d0f0566509d40ae1 [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());
1807 llvm::SmallDenseMap<unsigned, ModuleMacro*> Macros;
1808 llvm::SmallVector<ModuleMacro*, 8> Overrides;
1809 for (auto &MMI : ModuleMacros) {
1810 Overrides.clear();
1811 for (unsigned ModID : MMI.Overrides) {
1812 auto *Macro = Macros.lookup(ModID);
1813 assert(Macro && "missing definition for overridden macro");
1814 Overrides.push_back(Macros.lookup(ModID));
1815 }
1816
1817 bool Inserted = false;
1818 Macros[MMI.SubModID] =
1819 PP.addModuleMacro(MMI.SubModID, II, MMI.MI, Overrides, Inserted);
1820 if (!Inserted)
1821 continue;
1822
1823 Module *Owner = getSubmodule(MMI.getSubmoduleID());
1824 if (Owner->NameVisibility == Module::Hidden) {
1825 // Macros in the owning module are hidden. Just remember this macro to
1826 // install if we make this module visible.
1827 HiddenNamesMap[Owner].HiddenMacros.insert(
1828 std::make_pair(II, new ModuleMacroInfo(MMI)));
1829 } else {
1830 installImportedMacro(II, MMI, Owner);
1831 }
Richard Smithd7329392015-04-21 21:46:32 +00001832 }
1833 }
1834
1835 // Don't read the directive history for a module; we don't have anywhere
1836 // to put it.
1837 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1838 return;
1839
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001840 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001841 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001842 unsigned Idx = 0, N = Record.size();
1843 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001844 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001845 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001846 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1847 switch (K) {
1848 case MacroDirective::MD_Define: {
1849 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1850 MacroInfo *MI = getMacro(GMacID);
Richard Smithd7329392015-04-21 21:46:32 +00001851 SubmoduleID ImportedFrom = getGlobalSubmoduleID(M, Record[Idx++]);
Richard Smithdaa69e02014-07-25 04:40:03 +00001852 bool IsAmbiguous = Record[Idx++];
1853 llvm::SmallVector<unsigned, 4> Overrides;
1854 if (ImportedFrom) {
1855 Overrides.insert(Overrides.end(),
1856 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
Richard Smithd7329392015-04-21 21:46:32 +00001857 for (auto &ID : Overrides)
1858 ID = getGlobalSubmoduleID(M, ID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001859 Idx += Overrides.size() + 1;
1860 }
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001861 DefMacroDirective *DefMD =
Richard Smithdaa69e02014-07-25 04:40:03 +00001862 PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
1863 DefMD->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001864 MD = DefMD;
1865 break;
1866 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001867 case MacroDirective::MD_Undefine: {
Richard Smithd7329392015-04-21 21:46:32 +00001868 SubmoduleID ImportedFrom = getGlobalSubmoduleID(M, Record[Idx++]);
Richard Smithdaa69e02014-07-25 04:40:03 +00001869 llvm::SmallVector<unsigned, 4> Overrides;
1870 if (ImportedFrom) {
1871 Overrides.insert(Overrides.end(),
1872 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
Richard Smithd7329392015-04-21 21:46:32 +00001873 for (auto &ID : Overrides)
1874 ID = getGlobalSubmoduleID(M, ID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001875 Idx += Overrides.size() + 1;
1876 }
1877 MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001878 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001879 }
1880 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001881 bool isPublic = Record[Idx++];
1882 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1883 break;
1884 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001885
1886 if (!Latest)
1887 Latest = MD;
1888 if (Earliest)
1889 Earliest->setPrevious(MD);
1890 Earliest = MD;
1891 }
1892
1893 PP.setLoadedMacroDirective(II, Latest);
1894}
1895
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001896/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001897/// modules.
1898static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001899 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001900 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001901 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001902 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1903 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001904 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001905 return false;
Chandler Carruthc2132d82015-03-13 08:29:54 +00001906 SourceManager &SrcMgr = Reader.getSourceManager();
1907 bool PrevInSystem = (PrevOwner && PrevOwner->IsSystem) ||
1908 SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1909 bool NewInSystem = (NewOwner && NewOwner->IsSystem) ||
1910 SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
Douglas Gregor5e461192013-06-07 22:56:11 +00001911 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001912}
1913
Richard Smith49f906a2014-03-01 00:08:04 +00001914void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001915 SourceLocation ImportLoc,
Richard Smith49f906a2014-03-01 00:08:04 +00001916 AmbiguousMacros &Ambig,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001917 ArrayRef<SubmoduleID> Overrides) {
Richard Smith49f906a2014-03-01 00:08:04 +00001918 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1919 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001920
Richard Smith49f906a2014-03-01 00:08:04 +00001921 // If this macro is not yet visible, remove it from the hidden names list.
Richard Smithbb853c72014-08-13 01:23:33 +00001922 // It won't be there if we're in the middle of making the owner visible.
Richard Smith49f906a2014-03-01 00:08:04 +00001923 Module *Owner = getSubmodule(OwnerID);
Richard Smithbb853c72014-08-13 01:23:33 +00001924 auto HiddenIt = HiddenNamesMap.find(Owner);
1925 if (HiddenIt != HiddenNamesMap.end()) {
1926 HiddenNames &Hidden = HiddenIt->second;
1927 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1928 if (HI != Hidden.HiddenMacros.end()) {
1929 // Register the macro now so we don't lose it when we re-export.
1930 PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
Richard Smithdaa69e02014-07-25 04:40:03 +00001931
Richard Smithbb853c72014-08-13 01:23:33 +00001932 auto SubOverrides = HI->second->getOverriddenSubmodules();
1933 Hidden.HiddenMacros.erase(HI);
1934 removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
1935 }
Richard Smith49f906a2014-03-01 00:08:04 +00001936 }
1937
1938 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001939 Ambig.erase(
1940 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1941 return MD->getInfo()->getOwningModuleID() == OwnerID;
1942 }),
1943 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001944 }
1945}
1946
1947ASTReader::AmbiguousMacros *
1948ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001949 SourceLocation ImportLoc,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001950 ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001951 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001952 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00001953 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001954
Craig Toppera13603a2014-05-22 05:54:18 +00001955 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
1956 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001957 if (PrevDef && PrevDef->isAmbiguous()) {
1958 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1959 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1960 Ambig.push_back(PrevDef);
1961
Richard Smithdaa69e02014-07-25 04:40:03 +00001962 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001963
1964 if (!Ambig.empty())
1965 return &Ambig;
1966
1967 AmbiguousMacroDefs.erase(II);
1968 } else {
1969 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001970 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001971 if (PrevDef)
1972 Ambig.push_back(PrevDef);
1973
Richard Smithdaa69e02014-07-25 04:40:03 +00001974 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001975
1976 if (!Ambig.empty()) {
1977 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001978 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001979 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001980 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001981 }
Richard Smith49f906a2014-03-01 00:08:04 +00001982
1983 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00001984 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001985}
1986
Richard Smithe56c8bc2015-04-22 00:26:11 +00001987void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo &MMI,
Richard Smithdaa69e02014-07-25 04:40:03 +00001988 Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00001989 assert(II && Owner);
1990
1991 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smithdaa69e02014-07-25 04:40:03 +00001992 if (ImportLoc.isInvalid()) {
Richard Smith49f906a2014-03-01 00:08:04 +00001993 // FIXME: If we made macros from this module visible but didn't provide a
1994 // source location for the import, we don't have a location for the macro.
1995 // Use the location at which the containing module file was first imported
1996 // for now.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001997 ImportLoc = MMI.F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00001998 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00001999 }
2000
Benjamin Kramer834652a2014-05-03 18:44:26 +00002001 AmbiguousMacros *Prev =
Richard Smithe56c8bc2015-04-22 00:26:11 +00002002 removeOverriddenMacros(II, ImportLoc, MMI.getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00002003
Richard Smith49f906a2014-03-01 00:08:04 +00002004 // Create a synthetic macro definition corresponding to the import (or null
2005 // if this was an undefinition of the macro).
Richard Smithe56c8bc2015-04-22 00:26:11 +00002006 MacroDirective *Imported = MMI.import(PP, ImportLoc);
Richard Smithdaa69e02014-07-25 04:40:03 +00002007 DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002008
2009 // If there's no ambiguity, just install the macro.
2010 if (!Prev) {
Richard Smithdaa69e02014-07-25 04:40:03 +00002011 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002012 return;
2013 }
2014 assert(!Prev->empty());
2015
2016 if (!MD) {
2017 // We imported a #undef that didn't remove all prior definitions. The most
2018 // recent prior definition remains, and we install it in the place of the
Richard Smithdaa69e02014-07-25 04:40:03 +00002019 // imported directive, as if by a local #pragma pop_macro.
Richard Smith49f906a2014-03-01 00:08:04 +00002020 MacroInfo *NewMI = Prev->back()->getInfo();
2021 Prev->pop_back();
Richard Smithdaa69e02014-07-25 04:40:03 +00002022 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
2023
2024 // Install our #undef first so that we don't lose track of it. We'll replace
2025 // this with whichever macro definition ends up winning.
2026 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002027 }
2028
2029 // We're introducing a macro definition that creates or adds to an ambiguity.
2030 // We can resolve that ambiguity if this macro is token-for-token identical to
2031 // all of the existing definitions.
2032 MacroInfo *NewMI = MD->getInfo();
2033 assert(NewMI && "macro definition with no MacroInfo?");
2034 while (!Prev->empty()) {
2035 MacroInfo *PrevMI = Prev->back()->getInfo();
2036 assert(PrevMI && "macro definition with no MacroInfo?");
2037
2038 // Before marking the macros as ambiguous, check if this is a case where
2039 // both macros are in system headers. If so, we trust that the system
2040 // did not get it wrong. This also handles cases where Clang's own
2041 // headers have a different spelling of certain system macros:
2042 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
2043 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2044 //
2045 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2046 // overrides the system limits.h's macros, so there's no conflict here.
2047 if (NewMI != PrevMI &&
2048 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2049 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2050 break;
2051
2052 // The previous definition is the same as this one (or both are defined in
2053 // system modules so we can assume they're equivalent); we don't need to
2054 // track it any more.
2055 Prev->pop_back();
2056 }
2057
2058 if (!Prev->empty())
2059 MD->setAmbiguous(true);
2060
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002061 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002062}
2063
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002064ASTReader::InputFileInfo
2065ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002066 // Go find this input file.
2067 BitstreamCursor &Cursor = F.InputFilesCursor;
2068 SavedStreamPosition SavedPosition(Cursor);
2069 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2070
2071 unsigned Code = Cursor.ReadCode();
2072 RecordData Record;
2073 StringRef Blob;
2074
2075 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2076 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2077 "invalid record type for input file");
2078 (void)Result;
2079
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002080 std::string Filename;
2081 off_t StoredSize;
2082 time_t StoredTime;
2083 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002084
Ben Langmuir198c1682014-03-07 07:27:49 +00002085 assert(Record[0] == ID && "Bogus stored ID or offset");
2086 StoredSize = static_cast<off_t>(Record[1]);
2087 StoredTime = static_cast<time_t>(Record[2]);
2088 Overridden = static_cast<bool>(Record[3]);
2089 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002090 ResolveImportedPath(F, Filename);
2091
Hans Wennborg73945142014-03-14 17:45:06 +00002092 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2093 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002094}
2095
2096std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002097 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002098}
2099
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002100InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002101 // If this ID is bogus, just return an empty input file.
2102 if (ID == 0 || ID > F.InputFilesLoaded.size())
2103 return InputFile();
2104
2105 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002106 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002107 return F.InputFilesLoaded[ID-1];
2108
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002109 if (F.InputFilesLoaded[ID-1].isNotFound())
2110 return InputFile();
2111
Guy Benyei11169dd2012-12-18 14:30:41 +00002112 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002113 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002114 SavedStreamPosition SavedPosition(Cursor);
2115 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2116
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002117 InputFileInfo FI = readInputFileInfo(F, ID);
2118 off_t StoredSize = FI.StoredSize;
2119 time_t StoredTime = FI.StoredTime;
2120 bool Overridden = FI.Overridden;
2121 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002122
Ben Langmuir198c1682014-03-07 07:27:49 +00002123 const FileEntry *File
2124 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2125 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2126
2127 // If we didn't find the file, resolve it relative to the
2128 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002129 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002130 F.OriginalDir != CurrentDir) {
2131 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2132 F.OriginalDir,
2133 CurrentDir);
2134 if (!Resolved.empty())
2135 File = FileMgr.getFile(Resolved);
2136 }
2137
2138 // For an overridden file, create a virtual file with the stored
2139 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002140 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002141 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2142 }
2143
Craig Toppera13603a2014-05-22 05:54:18 +00002144 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002145 if (Complain) {
2146 std::string ErrorStr = "could not find file '";
2147 ErrorStr += Filename;
2148 ErrorStr += "' referenced by AST file";
2149 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002150 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002151 // Record that we didn't find the file.
2152 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2153 return InputFile();
2154 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002155
Ben Langmuir198c1682014-03-07 07:27:49 +00002156 // Check if there was a request to override the contents of the file
2157 // that was part of the precompiled header. Overridding such a file
2158 // can lead to problems when lexing using the source locations from the
2159 // PCH.
2160 SourceManager &SM = getSourceManager();
2161 if (!Overridden && SM.isFileOverridden(File)) {
2162 if (Complain)
2163 Error(diag::err_fe_pch_file_overridden, Filename);
2164 // After emitting the diagnostic, recover by disabling the override so
2165 // that the original file will be used.
2166 SM.disableFileContentsOverride(File);
2167 // The FileEntry is a virtual file entry with the size of the contents
2168 // that would override the original contents. Set it to the original's
2169 // size/time.
2170 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2171 StoredSize, StoredTime);
2172 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002173
Ben Langmuir198c1682014-03-07 07:27:49 +00002174 bool IsOutOfDate = false;
2175
2176 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002177 if (!Overridden && //
2178 (StoredSize != File->getSize() ||
2179#if defined(LLVM_ON_WIN32)
2180 false
2181#else
Ben Langmuir198c1682014-03-07 07:27:49 +00002182 // In our regression testing, the Windows file system seems to
2183 // have inconsistent modification times that sometimes
2184 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00002185 //
2186 // This also happens in networked file systems, so disable this
2187 // check if validation is disabled or if we have an explicitly
2188 // built PCM file.
2189 //
2190 // FIXME: Should we also do this for PCH files? They could also
2191 // reasonably get shared across a network during a distributed build.
2192 (StoredTime != File->getModificationTime() && !DisableValidation &&
2193 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00002194#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002195 )) {
2196 if (Complain) {
2197 // Build a list of the PCH imports that got us here (in reverse).
2198 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2199 while (ImportStack.back()->ImportedBy.size() > 0)
2200 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002201
Ben Langmuir198c1682014-03-07 07:27:49 +00002202 // The top-level PCH is stale.
2203 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2204 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002205
Ben Langmuir198c1682014-03-07 07:27:49 +00002206 // Print the import stack.
2207 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2208 Diag(diag::note_pch_required_by)
2209 << Filename << ImportStack[0]->FileName;
2210 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002211 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002212 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002213 }
2214
Ben Langmuir198c1682014-03-07 07:27:49 +00002215 if (!Diags.isDiagnosticInFlight())
2216 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002217 }
2218
Ben Langmuir198c1682014-03-07 07:27:49 +00002219 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002220 }
2221
Ben Langmuir198c1682014-03-07 07:27:49 +00002222 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2223
2224 // Note that we've loaded this input file.
2225 F.InputFilesLoaded[ID-1] = IF;
2226 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002227}
2228
Richard Smith7ed1bc92014-12-05 22:42:13 +00002229/// \brief If we are loading a relocatable PCH or module file, and the filename
2230/// is not an absolute path, add the system or module root to the beginning of
2231/// the file name.
2232void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2233 // Resolve relative to the base directory, if we have one.
2234 if (!M.BaseDirectory.empty())
2235 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002236}
2237
Richard Smith7ed1bc92014-12-05 22:42:13 +00002238void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002239 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2240 return;
2241
Richard Smith7ed1bc92014-12-05 22:42:13 +00002242 SmallString<128> Buffer;
2243 llvm::sys::path::append(Buffer, Prefix, Filename);
2244 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002245}
2246
2247ASTReader::ASTReadResult
2248ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002249 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002250 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002251 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002252 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002253
2254 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2255 Error("malformed block record in AST file");
2256 return Failure;
2257 }
2258
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002259 // Should we allow the configuration of the module file to differ from the
2260 // configuration of the current translation unit in a compatible way?
2261 //
2262 // FIXME: Allow this for files explicitly specified with -include-pch too.
2263 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2264
Guy Benyei11169dd2012-12-18 14:30:41 +00002265 // Read all of the records and blocks in the control block.
2266 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002267 unsigned NumInputs = 0;
2268 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002269 while (1) {
2270 llvm::BitstreamEntry Entry = Stream.advance();
2271
2272 switch (Entry.Kind) {
2273 case llvm::BitstreamEntry::Error:
2274 Error("malformed block record in AST file");
2275 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002276 case llvm::BitstreamEntry::EndBlock: {
2277 // Validate input files.
2278 const HeaderSearchOptions &HSOpts =
2279 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002280
Richard Smitha1825302014-10-23 22:18:29 +00002281 // All user input files reside at the index range [0, NumUserInputs), and
2282 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002283 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002284 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002285
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002286 // If we are reading a module, we will create a verification timestamp,
2287 // so we verify all input files. Otherwise, verify only user input
2288 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002289
2290 unsigned N = NumUserInputs;
2291 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002292 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002293 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002294 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002295 N = NumInputs;
2296
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002297 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002298 InputFile IF = getInputFile(F, I+1, Complain);
2299 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002300 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002301 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002302 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002303
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002304 if (Listener)
2305 Listener->visitModuleFile(F.FileName);
2306
Ben Langmuircb69b572014-03-07 06:40:32 +00002307 if (Listener && Listener->needsInputFileVisitation()) {
2308 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2309 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002310 for (unsigned I = 0; I < N; ++I) {
2311 bool IsSystem = I >= NumUserInputs;
2312 InputFileInfo FI = readInputFileInfo(F, I+1);
2313 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2314 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002315 }
2316
Guy Benyei11169dd2012-12-18 14:30:41 +00002317 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002318 }
2319
Chris Lattnere7b154b2013-01-19 21:39:22 +00002320 case llvm::BitstreamEntry::SubBlock:
2321 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002322 case INPUT_FILES_BLOCK_ID:
2323 F.InputFilesCursor = Stream;
2324 if (Stream.SkipBlock() || // Skip with the main cursor
2325 // Read the abbreviations
2326 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2327 Error("malformed block record in AST file");
2328 return Failure;
2329 }
2330 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002331
Guy Benyei11169dd2012-12-18 14:30:41 +00002332 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002333 if (Stream.SkipBlock()) {
2334 Error("malformed block record in AST file");
2335 return Failure;
2336 }
2337 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002338 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002339
2340 case llvm::BitstreamEntry::Record:
2341 // The interesting case.
2342 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002343 }
2344
2345 // Read and process a record.
2346 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002347 StringRef Blob;
2348 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002349 case METADATA: {
2350 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2351 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002352 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2353 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002354 return VersionMismatch;
2355 }
2356
2357 bool hasErrors = Record[5];
2358 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2359 Diag(diag::err_pch_with_compiler_errors);
2360 return HadErrors;
2361 }
2362
2363 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002364 // Relative paths in a relocatable PCH are relative to our sysroot.
2365 if (F.RelocatablePCH)
2366 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002367
2368 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002369 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002370 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2371 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002372 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002373 return VersionMismatch;
2374 }
2375 break;
2376 }
2377
Ben Langmuir487ea142014-10-23 18:05:36 +00002378 case SIGNATURE:
2379 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2380 F.Signature = Record[0];
2381 break;
2382
Guy Benyei11169dd2012-12-18 14:30:41 +00002383 case IMPORTS: {
2384 // Load each of the imported PCH files.
2385 unsigned Idx = 0, N = Record.size();
2386 while (Idx < N) {
2387 // Read information about the AST file.
2388 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2389 // The import location will be the local one for now; we will adjust
2390 // all import locations of module imports after the global source
2391 // location info are setup.
2392 SourceLocation ImportLoc =
2393 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002394 off_t StoredSize = (off_t)Record[Idx++];
2395 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002396 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002397 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002398
2399 // Load the AST file.
2400 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002401 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002402 ClientLoadCapabilities)) {
2403 case Failure: return Failure;
2404 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002405 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002406 case OutOfDate: return OutOfDate;
2407 case VersionMismatch: return VersionMismatch;
2408 case ConfigurationMismatch: return ConfigurationMismatch;
2409 case HadErrors: return HadErrors;
2410 case Success: break;
2411 }
2412 }
2413 break;
2414 }
2415
Richard Smith7f330cd2015-03-18 01:42:29 +00002416 case KNOWN_MODULE_FILES:
2417 break;
2418
Guy Benyei11169dd2012-12-18 14:30:41 +00002419 case LANGUAGE_OPTIONS: {
2420 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002421 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002423 ParseLanguageOptions(Record, Complain, *Listener,
2424 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002425 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002426 return ConfigurationMismatch;
2427 break;
2428 }
2429
2430 case TARGET_OPTIONS: {
2431 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2432 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002433 ParseTargetOptions(Record, Complain, *Listener,
2434 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002435 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002436 return ConfigurationMismatch;
2437 break;
2438 }
2439
2440 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002441 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002442 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002443 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002444 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002445 !DisableValidation)
2446 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002447 break;
2448 }
2449
2450 case FILE_SYSTEM_OPTIONS: {
2451 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2452 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002453 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002454 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002455 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002456 return ConfigurationMismatch;
2457 break;
2458 }
2459
2460 case HEADER_SEARCH_OPTIONS: {
2461 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2462 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002463 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002465 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 return ConfigurationMismatch;
2467 break;
2468 }
2469
2470 case PREPROCESSOR_OPTIONS: {
2471 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2472 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002473 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002474 ParsePreprocessorOptions(Record, Complain, *Listener,
2475 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002476 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002477 return ConfigurationMismatch;
2478 break;
2479 }
2480
2481 case ORIGINAL_FILE:
2482 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002483 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002484 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002485 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 break;
2487
2488 case ORIGINAL_FILE_ID:
2489 F.OriginalSourceFileID = FileID::get(Record[0]);
2490 break;
2491
2492 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002493 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002494 break;
2495
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002496 case MODULE_NAME:
2497 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002498 if (Listener)
2499 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002500 break;
2501
Richard Smith223d3f22014-12-06 03:21:08 +00002502 case MODULE_DIRECTORY: {
2503 assert(!F.ModuleName.empty() &&
2504 "MODULE_DIRECTORY found before MODULE_NAME");
2505 // If we've already loaded a module map file covering this module, we may
2506 // have a better path for it (relative to the current build).
2507 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2508 if (M && M->Directory) {
2509 // If we're implicitly loading a module, the base directory can't
2510 // change between the build and use.
2511 if (F.Kind != MK_ExplicitModule) {
2512 const DirectoryEntry *BuildDir =
2513 PP.getFileManager().getDirectory(Blob);
2514 if (!BuildDir || BuildDir != M->Directory) {
2515 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2516 Diag(diag::err_imported_module_relocated)
2517 << F.ModuleName << Blob << M->Directory->getName();
2518 return OutOfDate;
2519 }
2520 }
2521 F.BaseDirectory = M->Directory->getName();
2522 } else {
2523 F.BaseDirectory = Blob;
2524 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002525 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002526 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002527
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002528 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002529 if (ASTReadResult Result =
2530 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2531 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002532 break;
2533
Guy Benyei11169dd2012-12-18 14:30:41 +00002534 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002535 NumInputs = Record[0];
2536 NumUserInputs = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00002537 F.InputFileOffsets = (const uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002538 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 break;
2540 }
2541 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002542}
2543
Ben Langmuir2c9af442014-04-10 17:57:43 +00002544ASTReader::ASTReadResult
2545ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002546 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002547
2548 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2549 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002550 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002551 }
2552
2553 // Read all of the records and blocks for the AST file.
2554 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002555 while (1) {
2556 llvm::BitstreamEntry Entry = Stream.advance();
2557
2558 switch (Entry.Kind) {
2559 case llvm::BitstreamEntry::Error:
2560 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002561 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002562 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002563 // Outside of C++, we do not store a lookup map for the translation unit.
2564 // Instead, mark it as needing a lookup map to be built if this module
2565 // contains any declarations lexically within it (which it always does!).
2566 // This usually has no cost, since we very rarely need the lookup map for
2567 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002569 if (DC->hasExternalLexicalStorage() &&
2570 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002572
Ben Langmuir2c9af442014-04-10 17:57:43 +00002573 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002575 case llvm::BitstreamEntry::SubBlock:
2576 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 case DECLTYPES_BLOCK_ID:
2578 // We lazily load the decls block, but we want to set up the
2579 // DeclsCursor cursor to point into it. Clone our current bitcode
2580 // cursor to it, enter the block and read the abbrevs in that block.
2581 // With the main cursor, we just skip over it.
2582 F.DeclsCursor = Stream;
2583 if (Stream.SkipBlock() || // Skip with the main cursor.
2584 // Read the abbrevs.
2585 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2586 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002587 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 }
2589 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002590
Guy Benyei11169dd2012-12-18 14:30:41 +00002591 case PREPROCESSOR_BLOCK_ID:
2592 F.MacroCursor = Stream;
2593 if (!PP.getExternalSource())
2594 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002595
Guy Benyei11169dd2012-12-18 14:30:41 +00002596 if (Stream.SkipBlock() ||
2597 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2598 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002599 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 }
2601 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2602 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002603
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 case PREPROCESSOR_DETAIL_BLOCK_ID:
2605 F.PreprocessorDetailCursor = Stream;
2606 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002607 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002608 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002609 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002610 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002611 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002613 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2614
Guy Benyei11169dd2012-12-18 14:30:41 +00002615 if (!PP.getPreprocessingRecord())
2616 PP.createPreprocessingRecord();
2617 if (!PP.getPreprocessingRecord()->getExternalSource())
2618 PP.getPreprocessingRecord()->SetExternalSource(*this);
2619 break;
2620
2621 case SOURCE_MANAGER_BLOCK_ID:
2622 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002623 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002625
Guy Benyei11169dd2012-12-18 14:30:41 +00002626 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002627 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2628 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002629 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002630
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002632 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 if (Stream.SkipBlock() ||
2634 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2635 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002636 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 }
2638 CommentsCursors.push_back(std::make_pair(C, &F));
2639 break;
2640 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002641
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002643 if (Stream.SkipBlock()) {
2644 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002645 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002646 }
2647 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002648 }
2649 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002650
2651 case llvm::BitstreamEntry::Record:
2652 // The interesting case.
2653 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 }
2655
2656 // Read and process a record.
2657 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002658 StringRef Blob;
2659 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 default: // Default behavior: ignore.
2661 break;
2662
2663 case TYPE_OFFSET: {
2664 if (F.LocalNumTypes != 0) {
2665 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002666 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002667 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002668 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 F.LocalNumTypes = Record[0];
2670 unsigned LocalBaseTypeIndex = Record[1];
2671 F.BaseTypeIndex = getTotalNumTypes();
2672
2673 if (F.LocalNumTypes > 0) {
2674 // Introduce the global -> local mapping for types within this module.
2675 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2676
2677 // Introduce the local -> global mapping for types within this module.
2678 F.TypeRemap.insertOrReplace(
2679 std::make_pair(LocalBaseTypeIndex,
2680 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002681
2682 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002683 }
2684 break;
2685 }
2686
2687 case DECL_OFFSET: {
2688 if (F.LocalNumDecls != 0) {
2689 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002690 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002692 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 F.LocalNumDecls = Record[0];
2694 unsigned LocalBaseDeclID = Record[1];
2695 F.BaseDeclID = getTotalNumDecls();
2696
2697 if (F.LocalNumDecls > 0) {
2698 // Introduce the global -> local mapping for declarations within this
2699 // module.
2700 GlobalDeclMap.insert(
2701 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2702
2703 // Introduce the local -> global mapping for declarations within this
2704 // module.
2705 F.DeclRemap.insertOrReplace(
2706 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2707
2708 // Introduce the global -> local mapping for declarations within this
2709 // module.
2710 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002711
Ben Langmuir52ca6782014-10-20 16:27:32 +00002712 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2713 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002714 break;
2715 }
2716
2717 case TU_UPDATE_LEXICAL: {
2718 DeclContext *TU = Context.getTranslationUnitDecl();
2719 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002720 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002722 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 TU->setHasExternalLexicalStorage(true);
2724 break;
2725 }
2726
2727 case UPDATE_VISIBLE: {
2728 unsigned Idx = 0;
2729 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2730 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002731 ASTDeclContextNameLookupTable::Create(
2732 (const unsigned char *)Blob.data() + Record[Idx++],
2733 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2734 (const unsigned char *)Blob.data(),
2735 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002736 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002737 auto *DC = cast<DeclContext>(D);
2738 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002739 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2740 delete LookupTable;
2741 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 } else
2743 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2744 break;
2745 }
2746
2747 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002748 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002749 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002750 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2751 (const unsigned char *)F.IdentifierTableData + Record[0],
2752 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2753 (const unsigned char *)F.IdentifierTableData,
2754 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002755
2756 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2757 }
2758 break;
2759
2760 case IDENTIFIER_OFFSET: {
2761 if (F.LocalNumIdentifiers != 0) {
2762 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002763 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002764 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002765 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 F.LocalNumIdentifiers = Record[0];
2767 unsigned LocalBaseIdentifierID = Record[1];
2768 F.BaseIdentifierID = getTotalNumIdentifiers();
2769
2770 if (F.LocalNumIdentifiers > 0) {
2771 // Introduce the global -> local mapping for identifiers within this
2772 // module.
2773 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2774 &F));
2775
2776 // Introduce the local -> global mapping for identifiers within this
2777 // module.
2778 F.IdentifierRemap.insertOrReplace(
2779 std::make_pair(LocalBaseIdentifierID,
2780 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002781
Ben Langmuir52ca6782014-10-20 16:27:32 +00002782 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2783 + F.LocalNumIdentifiers);
2784 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002785 break;
2786 }
2787
Ben Langmuir332aafe2014-01-31 01:06:56 +00002788 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002789 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2790 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002791 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002792 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002793 break;
2794
2795 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002796 if (SpecialTypes.empty()) {
2797 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2798 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2799 break;
2800 }
2801
2802 if (SpecialTypes.size() != Record.size()) {
2803 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002804 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002805 }
2806
2807 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2808 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2809 if (!SpecialTypes[I])
2810 SpecialTypes[I] = ID;
2811 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2812 // merge step?
2813 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002814 break;
2815
2816 case STATISTICS:
2817 TotalNumStatements += Record[0];
2818 TotalNumMacros += Record[1];
2819 TotalLexicalDeclContexts += Record[2];
2820 TotalVisibleDeclContexts += Record[3];
2821 break;
2822
2823 case UNUSED_FILESCOPED_DECLS:
2824 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2825 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2826 break;
2827
2828 case DELEGATING_CTORS:
2829 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2830 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2831 break;
2832
2833 case WEAK_UNDECLARED_IDENTIFIERS:
2834 if (Record.size() % 4 != 0) {
2835 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002836 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002837 }
2838
2839 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2840 // files. This isn't the way to do it :)
2841 WeakUndeclaredIdentifiers.clear();
2842
2843 // Translate the weak, undeclared identifiers into global IDs.
2844 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2845 WeakUndeclaredIdentifiers.push_back(
2846 getGlobalIdentifierID(F, Record[I++]));
2847 WeakUndeclaredIdentifiers.push_back(
2848 getGlobalIdentifierID(F, Record[I++]));
2849 WeakUndeclaredIdentifiers.push_back(
2850 ReadSourceLocation(F, Record, I).getRawEncoding());
2851 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2852 }
2853 break;
2854
Guy Benyei11169dd2012-12-18 14:30:41 +00002855 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002856 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002857 F.LocalNumSelectors = Record[0];
2858 unsigned LocalBaseSelectorID = Record[1];
2859 F.BaseSelectorID = getTotalNumSelectors();
2860
2861 if (F.LocalNumSelectors > 0) {
2862 // Introduce the global -> local mapping for selectors within this
2863 // module.
2864 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2865
2866 // Introduce the local -> global mapping for selectors within this
2867 // module.
2868 F.SelectorRemap.insertOrReplace(
2869 std::make_pair(LocalBaseSelectorID,
2870 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002871
2872 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002873 }
2874 break;
2875 }
2876
2877 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002878 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002879 if (Record[0])
2880 F.SelectorLookupTable
2881 = ASTSelectorLookupTable::Create(
2882 F.SelectorLookupTableData + Record[0],
2883 F.SelectorLookupTableData,
2884 ASTSelectorLookupTrait(*this, F));
2885 TotalNumMethodPoolEntries += Record[1];
2886 break;
2887
2888 case REFERENCED_SELECTOR_POOL:
2889 if (!Record.empty()) {
2890 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2891 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2892 Record[Idx++]));
2893 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2894 getRawEncoding());
2895 }
2896 }
2897 break;
2898
2899 case PP_COUNTER_VALUE:
2900 if (!Record.empty() && Listener)
2901 Listener->ReadCounter(F, Record[0]);
2902 break;
2903
2904 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002905 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002906 F.NumFileSortedDecls = Record[0];
2907 break;
2908
2909 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002910 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002911 F.LocalNumSLocEntries = Record[0];
2912 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002913 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002914 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002915 SLocSpaceSize);
2916 // Make our entry in the range map. BaseID is negative and growing, so
2917 // we invert it. Because we invert it, though, we need the other end of
2918 // the range.
2919 unsigned RangeStart =
2920 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2921 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2922 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2923
2924 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2925 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2926 GlobalSLocOffsetMap.insert(
2927 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2928 - SLocSpaceSize,&F));
2929
2930 // Initialize the remapping table.
2931 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002932 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002934 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002935 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2936
2937 TotalNumSLocEntries += F.LocalNumSLocEntries;
2938 break;
2939 }
2940
2941 case MODULE_OFFSET_MAP: {
2942 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002943 const unsigned char *Data = (const unsigned char*)Blob.data();
2944 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002945
2946 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2947 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2948 F.SLocRemap.insert(std::make_pair(0U, 0));
2949 F.SLocRemap.insert(std::make_pair(2U, 1));
2950 }
2951
Guy Benyei11169dd2012-12-18 14:30:41 +00002952 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002953 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2954 RemapBuilder;
2955 RemapBuilder SLocRemap(F.SLocRemap);
2956 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2957 RemapBuilder MacroRemap(F.MacroRemap);
2958 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2959 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2960 RemapBuilder SelectorRemap(F.SelectorRemap);
2961 RemapBuilder DeclRemap(F.DeclRemap);
2962 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002963
2964 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002965 using namespace llvm::support;
2966 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002967 StringRef Name = StringRef((const char*)Data, Len);
2968 Data += Len;
2969 ModuleFile *OM = ModuleMgr.lookup(Name);
2970 if (!OM) {
2971 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002972 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002973 }
2974
Justin Bogner57ba0b22014-03-28 22:03:24 +00002975 uint32_t SLocOffset =
2976 endian::readNext<uint32_t, little, unaligned>(Data);
2977 uint32_t IdentifierIDOffset =
2978 endian::readNext<uint32_t, little, unaligned>(Data);
2979 uint32_t MacroIDOffset =
2980 endian::readNext<uint32_t, little, unaligned>(Data);
2981 uint32_t PreprocessedEntityIDOffset =
2982 endian::readNext<uint32_t, little, unaligned>(Data);
2983 uint32_t SubmoduleIDOffset =
2984 endian::readNext<uint32_t, little, unaligned>(Data);
2985 uint32_t SelectorIDOffset =
2986 endian::readNext<uint32_t, little, unaligned>(Data);
2987 uint32_t DeclIDOffset =
2988 endian::readNext<uint32_t, little, unaligned>(Data);
2989 uint32_t TypeIndexOffset =
2990 endian::readNext<uint32_t, little, unaligned>(Data);
2991
Ben Langmuir785180e2014-10-20 16:27:30 +00002992 uint32_t None = std::numeric_limits<uint32_t>::max();
2993
2994 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2995 RemapBuilder &Remap) {
2996 if (Offset != None)
2997 Remap.insert(std::make_pair(Offset,
2998 static_cast<int>(BaseOffset - Offset)));
2999 };
3000 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3001 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3002 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3003 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3004 PreprocessedEntityRemap);
3005 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3006 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3007 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3008 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003009
3010 // Global -> local mappings.
3011 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3012 }
3013 break;
3014 }
3015
3016 case SOURCE_MANAGER_LINE_TABLE:
3017 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003018 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003019 break;
3020
3021 case SOURCE_LOCATION_PRELOADS: {
3022 // Need to transform from the local view (1-based IDs) to the global view,
3023 // which is based off F.SLocEntryBaseID.
3024 if (!F.PreloadSLocEntries.empty()) {
3025 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003026 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 }
3028
3029 F.PreloadSLocEntries.swap(Record);
3030 break;
3031 }
3032
3033 case EXT_VECTOR_DECLS:
3034 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3035 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3036 break;
3037
3038 case VTABLE_USES:
3039 if (Record.size() % 3 != 0) {
3040 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003041 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003042 }
3043
3044 // Later tables overwrite earlier ones.
3045 // FIXME: Modules will have some trouble with this. This is clearly not
3046 // the right way to do this.
3047 VTableUses.clear();
3048
3049 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3050 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3051 VTableUses.push_back(
3052 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3053 VTableUses.push_back(Record[Idx++]);
3054 }
3055 break;
3056
Guy Benyei11169dd2012-12-18 14:30:41 +00003057 case PENDING_IMPLICIT_INSTANTIATIONS:
3058 if (PendingInstantiations.size() % 2 != 0) {
3059 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003060 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003061 }
3062
3063 if (Record.size() % 2 != 0) {
3064 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003065 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003066 }
3067
3068 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3069 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3070 PendingInstantiations.push_back(
3071 ReadSourceLocation(F, Record, I).getRawEncoding());
3072 }
3073 break;
3074
3075 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003076 if (Record.size() != 2) {
3077 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003078 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003079 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003080 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3081 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3082 break;
3083
3084 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003085 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3086 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3087 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003088
3089 unsigned LocalBasePreprocessedEntityID = Record[0];
3090
3091 unsigned StartingID;
3092 if (!PP.getPreprocessingRecord())
3093 PP.createPreprocessingRecord();
3094 if (!PP.getPreprocessingRecord()->getExternalSource())
3095 PP.getPreprocessingRecord()->SetExternalSource(*this);
3096 StartingID
3097 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003098 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003099 F.BasePreprocessedEntityID = StartingID;
3100
3101 if (F.NumPreprocessedEntities > 0) {
3102 // Introduce the global -> local mapping for preprocessed entities in
3103 // this module.
3104 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3105
3106 // Introduce the local -> global mapping for preprocessed entities in
3107 // this module.
3108 F.PreprocessedEntityRemap.insertOrReplace(
3109 std::make_pair(LocalBasePreprocessedEntityID,
3110 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3111 }
3112
3113 break;
3114 }
3115
3116 case DECL_UPDATE_OFFSETS: {
3117 if (Record.size() % 2 != 0) {
3118 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003119 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003121 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3122 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3123 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3124
3125 // If we've already loaded the decl, perform the updates when we finish
3126 // loading this block.
3127 if (Decl *D = GetExistingDecl(ID))
3128 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3129 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003130 break;
3131 }
3132
3133 case DECL_REPLACEMENTS: {
3134 if (Record.size() % 3 != 0) {
3135 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003136 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003137 }
3138 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3139 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3140 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3141 break;
3142 }
3143
3144 case OBJC_CATEGORIES_MAP: {
3145 if (F.LocalNumObjCCategoriesInMap != 0) {
3146 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003147 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003148 }
3149
3150 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003151 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 break;
3153 }
3154
3155 case OBJC_CATEGORIES:
3156 F.ObjCCategories.swap(Record);
3157 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003158
Guy Benyei11169dd2012-12-18 14:30:41 +00003159 case CXX_BASE_SPECIFIER_OFFSETS: {
3160 if (F.LocalNumCXXBaseSpecifiers != 0) {
3161 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003162 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003163 }
Richard Smithc2bb8182015-03-24 06:36:48 +00003164
Guy Benyei11169dd2012-12-18 14:30:41 +00003165 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003166 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00003167 break;
3168 }
3169
3170 case CXX_CTOR_INITIALIZERS_OFFSETS: {
3171 if (F.LocalNumCXXCtorInitializers != 0) {
3172 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
3173 return Failure;
3174 }
3175
3176 F.LocalNumCXXCtorInitializers = Record[0];
3177 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003178 break;
3179 }
3180
3181 case DIAG_PRAGMA_MAPPINGS:
3182 if (F.PragmaDiagMappings.empty())
3183 F.PragmaDiagMappings.swap(Record);
3184 else
3185 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3186 Record.begin(), Record.end());
3187 break;
3188
3189 case CUDA_SPECIAL_DECL_REFS:
3190 // Later tables overwrite earlier ones.
3191 // FIXME: Modules will have trouble with this.
3192 CUDASpecialDeclRefs.clear();
3193 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3194 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3195 break;
3196
3197 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003198 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003199 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003200 if (Record[0]) {
3201 F.HeaderFileInfoTable
3202 = HeaderFileInfoLookupTable::Create(
3203 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3204 (const unsigned char *)F.HeaderFileInfoTableData,
3205 HeaderFileInfoTrait(*this, F,
3206 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003207 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003208
3209 PP.getHeaderSearchInfo().SetExternalSource(this);
3210 if (!PP.getHeaderSearchInfo().getExternalLookup())
3211 PP.getHeaderSearchInfo().SetExternalLookup(this);
3212 }
3213 break;
3214 }
3215
3216 case FP_PRAGMA_OPTIONS:
3217 // Later tables overwrite earlier ones.
3218 FPPragmaOptions.swap(Record);
3219 break;
3220
3221 case OPENCL_EXTENSIONS:
3222 // Later tables overwrite earlier ones.
3223 OpenCLExtensions.swap(Record);
3224 break;
3225
3226 case TENTATIVE_DEFINITIONS:
3227 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3228 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3229 break;
3230
3231 case KNOWN_NAMESPACES:
3232 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3233 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3234 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003235
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003236 case UNDEFINED_BUT_USED:
3237 if (UndefinedButUsed.size() % 2 != 0) {
3238 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003239 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003240 }
3241
3242 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003243 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003244 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003245 }
3246 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003247 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3248 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003249 ReadSourceLocation(F, Record, I).getRawEncoding());
3250 }
3251 break;
3252
Guy Benyei11169dd2012-12-18 14:30:41 +00003253 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003254 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003255 // If we aren't loading a module (which has its own exports), make
3256 // all of the imported modules visible.
3257 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003258 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3259 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3260 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3261 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003262 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003263 }
3264 }
3265 break;
3266 }
3267
3268 case LOCAL_REDECLARATIONS: {
3269 F.RedeclarationChains.swap(Record);
3270 break;
3271 }
3272
3273 case LOCAL_REDECLARATIONS_MAP: {
3274 if (F.LocalNumRedeclarationsInMap != 0) {
3275 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003276 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003277 }
3278
3279 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003280 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003281 break;
3282 }
3283
Guy Benyei11169dd2012-12-18 14:30:41 +00003284 case MACRO_OFFSET: {
3285 if (F.LocalNumMacros != 0) {
3286 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003287 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003288 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003289 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003290 F.LocalNumMacros = Record[0];
3291 unsigned LocalBaseMacroID = Record[1];
3292 F.BaseMacroID = getTotalNumMacros();
3293
3294 if (F.LocalNumMacros > 0) {
3295 // Introduce the global -> local mapping for macros within this module.
3296 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3297
3298 // Introduce the local -> global mapping for macros within this module.
3299 F.MacroRemap.insertOrReplace(
3300 std::make_pair(LocalBaseMacroID,
3301 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003302
3303 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003304 }
3305 break;
3306 }
3307
Richard Smithe40f2ba2013-08-07 21:41:30 +00003308 case LATE_PARSED_TEMPLATE: {
3309 LateParsedTemplates.append(Record.begin(), Record.end());
3310 break;
3311 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003312
3313 case OPTIMIZE_PRAGMA_OPTIONS:
3314 if (Record.size() != 1) {
3315 Error("invalid pragma optimize record");
3316 return Failure;
3317 }
3318 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3319 break;
Nico Weber72889432014-09-06 01:25:55 +00003320
3321 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3322 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3323 UnusedLocalTypedefNameCandidates.push_back(
3324 getGlobalDeclID(F, Record[I]));
3325 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003326 }
3327 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003328}
3329
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003330ASTReader::ASTReadResult
3331ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3332 const ModuleFile *ImportedBy,
3333 unsigned ClientLoadCapabilities) {
3334 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003335 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003336
Richard Smithe842a472014-10-22 02:05:46 +00003337 if (F.Kind == MK_ExplicitModule) {
3338 // For an explicitly-loaded module, we don't care whether the original
3339 // module map file exists or matches.
3340 return Success;
3341 }
3342
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003343 // Try to resolve ModuleName in the current header search context and
3344 // verify that it is found in the same module map file as we saved. If the
3345 // top-level AST file is a main file, skip this check because there is no
3346 // usable header search context.
3347 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003348 "MODULE_NAME should come before MODULE_MAP_FILE");
3349 if (F.Kind == MK_ImplicitModule &&
3350 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3351 // An implicitly-loaded module file should have its module listed in some
3352 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003353 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003354 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3355 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3356 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003357 assert(ImportedBy && "top-level import should be verified");
3358 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003359 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3360 << ImportedBy->FileName
3361 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003362 return Missing;
3363 }
3364
Richard Smithe842a472014-10-22 02:05:46 +00003365 assert(M->Name == F.ModuleName && "found module with different name");
3366
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003367 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003368 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003369 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3370 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003371 assert(ImportedBy && "top-level import should be verified");
3372 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3373 Diag(diag::err_imported_module_modmap_changed)
3374 << F.ModuleName << ImportedBy->FileName
3375 << ModMap->getName() << F.ModuleMapPath;
3376 return OutOfDate;
3377 }
3378
3379 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3380 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3381 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003382 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003383 const FileEntry *F =
3384 FileMgr.getFile(Filename, false, false);
3385 if (F == nullptr) {
3386 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3387 Error("could not find file '" + Filename +"' referenced by AST file");
3388 return OutOfDate;
3389 }
3390 AdditionalStoredMaps.insert(F);
3391 }
3392
3393 // Check any additional module map files (e.g. module.private.modulemap)
3394 // that are not in the pcm.
3395 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3396 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3397 // Remove files that match
3398 // Note: SmallPtrSet::erase is really remove
3399 if (!AdditionalStoredMaps.erase(ModMap)) {
3400 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3401 Diag(diag::err_module_different_modmap)
3402 << F.ModuleName << /*new*/0 << ModMap->getName();
3403 return OutOfDate;
3404 }
3405 }
3406 }
3407
3408 // Check any additional module map files that are in the pcm, but not
3409 // found in header search. Cases that match are already removed.
3410 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3411 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3412 Diag(diag::err_module_different_modmap)
3413 << F.ModuleName << /*not new*/1 << ModMap->getName();
3414 return OutOfDate;
3415 }
3416 }
3417
3418 if (Listener)
3419 Listener->ReadModuleMapFile(F.ModuleMapPath);
3420 return Success;
3421}
3422
3423
Douglas Gregorc1489562013-02-12 23:36:21 +00003424/// \brief Move the given method to the back of the global list of methods.
3425static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3426 // Find the entry for this selector in the method pool.
3427 Sema::GlobalMethodPool::iterator Known
3428 = S.MethodPool.find(Method->getSelector());
3429 if (Known == S.MethodPool.end())
3430 return;
3431
3432 // Retrieve the appropriate method list.
3433 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3434 : Known->second.second;
3435 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003436 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003437 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003438 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003439 Found = true;
3440 } else {
3441 // Keep searching.
3442 continue;
3443 }
3444 }
3445
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003446 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003447 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003448 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003449 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003450 }
3451}
3452
Richard Smithe657bbd2014-07-18 22:13:40 +00003453void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3454 bool FromFinalization) {
3455 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith57721ac2014-07-21 04:10:40 +00003456 for (Decl *D : Names.HiddenDecls) {
Richard Smith49f906a2014-03-01 00:08:04 +00003457 bool wasHidden = D->Hidden;
3458 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003459
Richard Smith49f906a2014-03-01 00:08:04 +00003460 if (wasHidden && SemaObj) {
3461 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3462 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003463 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003464 }
3465 }
Richard Smith49f906a2014-03-01 00:08:04 +00003466
Richard Smithe657bbd2014-07-18 22:13:40 +00003467 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3468 "nothing to make visible?");
Richard Smithdaa69e02014-07-25 04:40:03 +00003469 for (const auto &Macro : Names.HiddenMacros) {
3470 if (FromFinalization)
3471 PP.appendMacroDirective(Macro.first,
3472 Macro.second->import(PP, SourceLocation()));
3473 else
Richard Smithe56c8bc2015-04-22 00:26:11 +00003474 installImportedMacro(Macro.first, *Macro.second, Owner);
Richard Smithdaa69e02014-07-25 04:40:03 +00003475 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003476}
3477
Richard Smith49f906a2014-03-01 00:08:04 +00003478void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003479 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003480 SourceLocation ImportLoc,
3481 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003482 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003483 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003484 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003485 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003486 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003487
3488 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003489 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003490 // there is nothing more to do.
3491 continue;
3492 }
Richard Smith49f906a2014-03-01 00:08:04 +00003493
Guy Benyei11169dd2012-12-18 14:30:41 +00003494 if (!Mod->isAvailable()) {
3495 // Modules that aren't available cannot be made visible.
3496 continue;
3497 }
3498
3499 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003500 if (NameVisibility >= Module::MacrosVisible &&
3501 Mod->NameVisibility < Module::MacrosVisible)
3502 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003503 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003504
Guy Benyei11169dd2012-12-18 14:30:41 +00003505 // If we've already deserialized any names from this module,
3506 // mark them as visible.
3507 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3508 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003509 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003510 HiddenNamesMap.erase(Hidden);
Richard Smith57721ac2014-07-21 04:10:40 +00003511 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3512 /*FromFinalization*/false);
3513 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3514 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003515 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003516
Guy Benyei11169dd2012-12-18 14:30:41 +00003517 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003518 SmallVector<Module *, 16> Exports;
3519 Mod->getExportedModules(Exports);
3520 for (SmallVectorImpl<Module *>::iterator
3521 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3522 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003523 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003524 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003525 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003526
3527 // Detect any conflicts.
3528 if (Complain) {
3529 assert(ImportLoc.isValid() && "Missing import location");
3530 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3531 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3532 Diag(ImportLoc, diag::warn_module_conflict)
3533 << Mod->getFullModuleName()
3534 << Mod->Conflicts[I].Other->getFullModuleName()
3535 << Mod->Conflicts[I].Message;
3536 // FIXME: Need note where the other module was imported.
3537 }
3538 }
3539 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003540 }
3541}
3542
Douglas Gregore060e572013-01-25 01:03:03 +00003543bool ASTReader::loadGlobalIndex() {
3544 if (GlobalIndex)
3545 return false;
3546
3547 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3548 !Context.getLangOpts().Modules)
3549 return true;
3550
3551 // Try to load the global index.
3552 TriedLoadingGlobalIndex = true;
3553 StringRef ModuleCachePath
3554 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3555 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003556 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003557 if (!Result.first)
3558 return true;
3559
3560 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003561 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003562 return false;
3563}
3564
3565bool ASTReader::isGlobalIndexUnavailable() const {
3566 return Context.getLangOpts().Modules && UseGlobalIndex &&
3567 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3568}
3569
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003570static void updateModuleTimestamp(ModuleFile &MF) {
3571 // Overwrite the timestamp file contents so that file's mtime changes.
3572 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003573 std::error_code EC;
3574 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3575 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003576 return;
3577 OS << "Timestamp file\n";
3578}
3579
Guy Benyei11169dd2012-12-18 14:30:41 +00003580ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3581 ModuleKind Type,
3582 SourceLocation ImportLoc,
3583 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003584 llvm::SaveAndRestore<SourceLocation>
3585 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3586
Richard Smithd1c46742014-04-30 02:24:17 +00003587 // Defer any pending actions until we get to the end of reading the AST file.
3588 Deserializing AnASTFile(this);
3589
Guy Benyei11169dd2012-12-18 14:30:41 +00003590 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003591 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003592
3593 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003594 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003595 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003596 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003597 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003598 ClientLoadCapabilities)) {
3599 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003600 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003601 case OutOfDate:
3602 case VersionMismatch:
3603 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003604 case HadErrors: {
3605 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3606 for (const ImportedModule &IM : Loaded)
3607 LoadedSet.insert(IM.Mod);
3608
Douglas Gregor7029ce12013-03-19 00:28:20 +00003609 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003610 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003611 Context.getLangOpts().Modules
3612 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003613 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003614
3615 // If we find that any modules are unusable, the global index is going
3616 // to be out-of-date. Just remove it.
3617 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003618 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003619 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003620 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003621 case Success:
3622 break;
3623 }
3624
3625 // Here comes stuff that we only do once the entire chain is loaded.
3626
3627 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003628 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3629 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003630 M != MEnd; ++M) {
3631 ModuleFile &F = *M->Mod;
3632
3633 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003634 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3635 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003636
3637 // Once read, set the ModuleFile bit base offset and update the size in
3638 // bits of all files we've seen.
3639 F.GlobalBitOffset = TotalModulesSizeInBits;
3640 TotalModulesSizeInBits += F.SizeInBits;
3641 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3642
3643 // Preload SLocEntries.
3644 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3645 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3646 // Load it through the SourceManager and don't call ReadSLocEntry()
3647 // directly because the entry may have already been loaded in which case
3648 // calling ReadSLocEntry() directly would trigger an assertion in
3649 // SourceManager.
3650 SourceMgr.getLoadedSLocEntryByID(Index);
3651 }
3652 }
3653
Douglas Gregor603cd862013-03-22 18:50:14 +00003654 // Setup the import locations and notify the module manager that we've
3655 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003656 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3657 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003658 M != MEnd; ++M) {
3659 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003660
3661 ModuleMgr.moduleFileAccepted(&F);
3662
3663 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003664 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003665 if (!M->ImportedBy)
3666 F.ImportLoc = M->ImportLoc;
3667 else
3668 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3669 M->ImportLoc.getRawEncoding());
3670 }
3671
3672 // Mark all of the identifiers in the identifier table as being out of date,
3673 // so that various accessors know to check the loaded modules when the
3674 // identifier is used.
3675 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3676 IdEnd = PP.getIdentifierTable().end();
3677 Id != IdEnd; ++Id)
3678 Id->second->setOutOfDate(true);
3679
3680 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003681 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3682 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003683 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3684 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003685
3686 switch (Unresolved.Kind) {
3687 case UnresolvedModuleRef::Conflict:
3688 if (ResolvedMod) {
3689 Module::Conflict Conflict;
3690 Conflict.Other = ResolvedMod;
3691 Conflict.Message = Unresolved.String.str();
3692 Unresolved.Mod->Conflicts.push_back(Conflict);
3693 }
3694 continue;
3695
3696 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003697 if (ResolvedMod)
3698 Unresolved.Mod->Imports.push_back(ResolvedMod);
3699 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003700
Douglas Gregorfb912652013-03-20 21:10:35 +00003701 case UnresolvedModuleRef::Export:
3702 if (ResolvedMod || Unresolved.IsWildcard)
3703 Unresolved.Mod->Exports.push_back(
3704 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3705 continue;
3706 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003707 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003708 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003709
3710 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3711 // Might be unnecessary as use declarations are only used to build the
3712 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003713
3714 InitializeContext();
3715
Richard Smith3d8e97e2013-10-18 06:54:39 +00003716 if (SemaObj)
3717 UpdateSema();
3718
Guy Benyei11169dd2012-12-18 14:30:41 +00003719 if (DeserializationListener)
3720 DeserializationListener->ReaderInitialized(this);
3721
3722 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3723 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3724 PrimaryModule.OriginalSourceFileID
3725 = FileID::get(PrimaryModule.SLocEntryBaseID
3726 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3727
3728 // If this AST file is a precompiled preamble, then set the
3729 // preamble file ID of the source manager to the file source file
3730 // from which the preamble was built.
3731 if (Type == MK_Preamble) {
3732 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3733 } else if (Type == MK_MainFile) {
3734 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3735 }
3736 }
3737
3738 // For any Objective-C class definitions we have already loaded, make sure
3739 // that we load any additional categories.
3740 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3741 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3742 ObjCClassesLoaded[I],
3743 PreviousGeneration);
3744 }
Douglas Gregore060e572013-01-25 01:03:03 +00003745
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003746 if (PP.getHeaderSearchInfo()
3747 .getHeaderSearchOpts()
3748 .ModulesValidateOncePerBuildSession) {
3749 // Now we are certain that the module and all modules it depends on are
3750 // up to date. Create or update timestamp files for modules that are
3751 // located in the module cache (not for PCH files that could be anywhere
3752 // in the filesystem).
3753 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3754 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003755 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003756 updateModuleTimestamp(*M.Mod);
3757 }
3758 }
3759 }
3760
Guy Benyei11169dd2012-12-18 14:30:41 +00003761 return Success;
3762}
3763
Ben Langmuir487ea142014-10-23 18:05:36 +00003764static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3765
Ben Langmuir70a1b812015-03-24 04:43:52 +00003766/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3767static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3768 return Stream.Read(8) == 'C' &&
3769 Stream.Read(8) == 'P' &&
3770 Stream.Read(8) == 'C' &&
3771 Stream.Read(8) == 'H';
3772}
3773
Guy Benyei11169dd2012-12-18 14:30:41 +00003774ASTReader::ASTReadResult
3775ASTReader::ReadASTCore(StringRef FileName,
3776 ModuleKind Type,
3777 SourceLocation ImportLoc,
3778 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003779 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003780 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003781 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003782 unsigned ClientLoadCapabilities) {
3783 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003784 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003785 ModuleManager::AddModuleResult AddResult
3786 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003787 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003788 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003789 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003790
Douglas Gregor7029ce12013-03-19 00:28:20 +00003791 switch (AddResult) {
3792 case ModuleManager::AlreadyLoaded:
3793 return Success;
3794
3795 case ModuleManager::NewlyLoaded:
3796 // Load module file below.
3797 break;
3798
3799 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003800 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003801 // it.
3802 if (ClientLoadCapabilities & ARR_Missing)
3803 return Missing;
3804
3805 // Otherwise, return an error.
3806 {
3807 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3808 + ErrorStr;
3809 Error(Msg);
3810 }
3811 return Failure;
3812
3813 case ModuleManager::OutOfDate:
3814 // We couldn't load the module file because it is out-of-date. If the
3815 // client can handle out-of-date, return it.
3816 if (ClientLoadCapabilities & ARR_OutOfDate)
3817 return OutOfDate;
3818
3819 // Otherwise, return an error.
3820 {
3821 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3822 + ErrorStr;
3823 Error(Msg);
3824 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003825 return Failure;
3826 }
3827
Douglas Gregor7029ce12013-03-19 00:28:20 +00003828 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003829
3830 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3831 // module?
3832 if (FileName != "-") {
3833 CurrentDir = llvm::sys::path::parent_path(FileName);
3834 if (CurrentDir.empty()) CurrentDir = ".";
3835 }
3836
3837 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003838 BitstreamCursor &Stream = F.Stream;
Rafael Espindolafd832392014-11-12 14:48:44 +00003839 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003840 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3841
Guy Benyei11169dd2012-12-18 14:30:41 +00003842 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003843 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003844 Diag(diag::err_not_a_pch_file) << FileName;
3845 return Failure;
3846 }
3847
3848 // This is used for compatibility with older PCH formats.
3849 bool HaveReadControlBlock = false;
3850
Chris Lattnerefa77172013-01-20 00:00:22 +00003851 while (1) {
3852 llvm::BitstreamEntry Entry = Stream.advance();
3853
3854 switch (Entry.Kind) {
3855 case llvm::BitstreamEntry::Error:
3856 case llvm::BitstreamEntry::EndBlock:
3857 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003858 Error("invalid record at top-level of AST file");
3859 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003860
3861 case llvm::BitstreamEntry::SubBlock:
3862 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003863 }
3864
Guy Benyei11169dd2012-12-18 14:30:41 +00003865 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003866 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003867 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3868 if (Stream.ReadBlockInfoBlock()) {
3869 Error("malformed BlockInfoBlock in AST file");
3870 return Failure;
3871 }
3872 break;
3873 case CONTROL_BLOCK_ID:
3874 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003875 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003876 case Success:
3877 break;
3878
3879 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003880 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003881 case OutOfDate: return OutOfDate;
3882 case VersionMismatch: return VersionMismatch;
3883 case ConfigurationMismatch: return ConfigurationMismatch;
3884 case HadErrors: return HadErrors;
3885 }
3886 break;
3887 case AST_BLOCK_ID:
3888 if (!HaveReadControlBlock) {
3889 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003890 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003891 return VersionMismatch;
3892 }
3893
3894 // Record that we've loaded this module.
3895 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3896 return Success;
3897
3898 default:
3899 if (Stream.SkipBlock()) {
3900 Error("malformed block record in AST file");
3901 return Failure;
3902 }
3903 break;
3904 }
3905 }
3906
3907 return Success;
3908}
3909
3910void ASTReader::InitializeContext() {
3911 // If there's a listener, notify them that we "read" the translation unit.
3912 if (DeserializationListener)
3913 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3914 Context.getTranslationUnitDecl());
3915
Guy Benyei11169dd2012-12-18 14:30:41 +00003916 // FIXME: Find a better way to deal with collisions between these
3917 // built-in types. Right now, we just ignore the problem.
3918
3919 // Load the special types.
3920 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3921 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3922 if (!Context.CFConstantStringTypeDecl)
3923 Context.setCFConstantStringType(GetType(String));
3924 }
3925
3926 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3927 QualType FileType = GetType(File);
3928 if (FileType.isNull()) {
3929 Error("FILE type is NULL");
3930 return;
3931 }
3932
3933 if (!Context.FILEDecl) {
3934 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3935 Context.setFILEDecl(Typedef->getDecl());
3936 else {
3937 const TagType *Tag = FileType->getAs<TagType>();
3938 if (!Tag) {
3939 Error("Invalid FILE type in AST file");
3940 return;
3941 }
3942 Context.setFILEDecl(Tag->getDecl());
3943 }
3944 }
3945 }
3946
3947 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3948 QualType Jmp_bufType = GetType(Jmp_buf);
3949 if (Jmp_bufType.isNull()) {
3950 Error("jmp_buf type is NULL");
3951 return;
3952 }
3953
3954 if (!Context.jmp_bufDecl) {
3955 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3956 Context.setjmp_bufDecl(Typedef->getDecl());
3957 else {
3958 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3959 if (!Tag) {
3960 Error("Invalid jmp_buf type in AST file");
3961 return;
3962 }
3963 Context.setjmp_bufDecl(Tag->getDecl());
3964 }
3965 }
3966 }
3967
3968 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3969 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3970 if (Sigjmp_bufType.isNull()) {
3971 Error("sigjmp_buf type is NULL");
3972 return;
3973 }
3974
3975 if (!Context.sigjmp_bufDecl) {
3976 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3977 Context.setsigjmp_bufDecl(Typedef->getDecl());
3978 else {
3979 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3980 assert(Tag && "Invalid sigjmp_buf type in AST file");
3981 Context.setsigjmp_bufDecl(Tag->getDecl());
3982 }
3983 }
3984 }
3985
3986 if (unsigned ObjCIdRedef
3987 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3988 if (Context.ObjCIdRedefinitionType.isNull())
3989 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3990 }
3991
3992 if (unsigned ObjCClassRedef
3993 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3994 if (Context.ObjCClassRedefinitionType.isNull())
3995 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3996 }
3997
3998 if (unsigned ObjCSelRedef
3999 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4000 if (Context.ObjCSelRedefinitionType.isNull())
4001 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4002 }
4003
4004 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4005 QualType Ucontext_tType = GetType(Ucontext_t);
4006 if (Ucontext_tType.isNull()) {
4007 Error("ucontext_t type is NULL");
4008 return;
4009 }
4010
4011 if (!Context.ucontext_tDecl) {
4012 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4013 Context.setucontext_tDecl(Typedef->getDecl());
4014 else {
4015 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4016 assert(Tag && "Invalid ucontext_t type in AST file");
4017 Context.setucontext_tDecl(Tag->getDecl());
4018 }
4019 }
4020 }
4021 }
4022
4023 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4024
4025 // If there were any CUDA special declarations, deserialize them.
4026 if (!CUDASpecialDeclRefs.empty()) {
4027 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4028 Context.setcudaConfigureCallDecl(
4029 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4030 }
Richard Smith56be7542014-03-21 00:33:59 +00004031
Guy Benyei11169dd2012-12-18 14:30:41 +00004032 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00004033 // FIXME: This does not make macro-only imports visible again. It also doesn't
4034 // make #includes mapped to module imports visible.
4035 for (auto &Import : ImportedModules) {
4036 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004037 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00004038 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00004039 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00004040 }
4041 ImportedModules.clear();
4042}
4043
4044void ASTReader::finalizeForWriting() {
Richard Smith57721ac2014-07-21 04:10:40 +00004045 while (!HiddenNamesMap.empty()) {
4046 auto HiddenNames = std::move(*HiddenNamesMap.begin());
4047 HiddenNamesMap.erase(HiddenNamesMap.begin());
4048 makeNamesVisible(HiddenNames.second, HiddenNames.first,
4049 /*FromFinalization*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004050 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004051}
4052
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004053/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
4054/// cursor into the start of the given block ID, returning false on success and
4055/// true on failure.
4056static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004057 while (1) {
4058 llvm::BitstreamEntry Entry = Cursor.advance();
4059 switch (Entry.Kind) {
4060 case llvm::BitstreamEntry::Error:
4061 case llvm::BitstreamEntry::EndBlock:
4062 return true;
4063
4064 case llvm::BitstreamEntry::Record:
4065 // Ignore top-level records.
4066 Cursor.skipRecord(Entry.ID);
4067 break;
4068
4069 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004070 if (Entry.ID == BlockID) {
4071 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004072 return true;
4073 // Found it!
4074 return false;
4075 }
4076
4077 if (Cursor.SkipBlock())
4078 return true;
4079 }
4080 }
4081}
4082
Ben Langmuir70a1b812015-03-24 04:43:52 +00004083/// \brief Reads and return the signature record from \p StreamFile's control
4084/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00004085static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4086 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004087 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004088 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004089
4090 // Scan for the CONTROL_BLOCK_ID block.
4091 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4092 return 0;
4093
4094 // Scan for SIGNATURE inside the control block.
4095 ASTReader::RecordData Record;
4096 while (1) {
4097 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4098 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4099 Entry.Kind != llvm::BitstreamEntry::Record)
4100 return 0;
4101
4102 Record.clear();
4103 StringRef Blob;
4104 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4105 return Record[0];
4106 }
4107}
4108
Guy Benyei11169dd2012-12-18 14:30:41 +00004109/// \brief Retrieve the name of the original source file name
4110/// directly from the AST file, without actually loading the AST
4111/// file.
4112std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
4113 FileManager &FileMgr,
4114 DiagnosticsEngine &Diags) {
4115 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004116 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004117 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004118 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4119 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004120 return std::string();
4121 }
4122
4123 // Initialize the stream
4124 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004125 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4126 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004127 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004128
4129 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004130 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004131 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4132 return std::string();
4133 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004134
Chris Lattnere7b154b2013-01-19 21:39:22 +00004135 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004136 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004137 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4138 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004139 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004140
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004141 // Scan for ORIGINAL_FILE inside the control block.
4142 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004143 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004144 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004145 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4146 return std::string();
4147
4148 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4149 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4150 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004151 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004152
Guy Benyei11169dd2012-12-18 14:30:41 +00004153 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004154 StringRef Blob;
4155 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4156 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004157 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004158}
4159
4160namespace {
4161 class SimplePCHValidator : public ASTReaderListener {
4162 const LangOptions &ExistingLangOpts;
4163 const TargetOptions &ExistingTargetOpts;
4164 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004165 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004166 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004167
Guy Benyei11169dd2012-12-18 14:30:41 +00004168 public:
4169 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4170 const TargetOptions &ExistingTargetOpts,
4171 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004172 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004173 FileManager &FileMgr)
4174 : ExistingLangOpts(ExistingLangOpts),
4175 ExistingTargetOpts(ExistingTargetOpts),
4176 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004177 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004178 FileMgr(FileMgr)
4179 {
4180 }
4181
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004182 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4183 bool AllowCompatibleDifferences) override {
4184 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4185 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004186 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004187 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4188 bool AllowCompatibleDifferences) override {
4189 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4190 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004191 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004192 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4193 StringRef SpecificModuleCachePath,
4194 bool Complain) override {
4195 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4196 ExistingModuleCachePath,
4197 nullptr, ExistingLangOpts);
4198 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004199 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4200 bool Complain,
4201 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004202 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004203 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004204 }
4205 };
4206}
4207
4208bool ASTReader::readASTFileControlBlock(StringRef Filename,
4209 FileManager &FileMgr,
4210 ASTReaderListener &Listener) {
4211 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004212 // FIXME: This allows use of the VFS; we do not allow use of the
4213 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004214 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004215 if (!Buffer) {
4216 return true;
4217 }
4218
4219 // Initialize the stream
4220 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004221 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4222 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004223 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004224
4225 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004226 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004227 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004228
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004229 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004230 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004231 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004232
4233 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004234 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004235 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004236 BitstreamCursor InputFilesCursor;
4237 if (NeedsInputFiles) {
4238 InputFilesCursor = Stream;
4239 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4240 return true;
4241
4242 // Read the abbreviations
4243 while (true) {
4244 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4245 unsigned Code = InputFilesCursor.ReadCode();
4246
4247 // We expect all abbrevs to be at the start of the block.
4248 if (Code != llvm::bitc::DEFINE_ABBREV) {
4249 InputFilesCursor.JumpToBit(Offset);
4250 break;
4251 }
4252 InputFilesCursor.ReadAbbrevRecord();
4253 }
4254 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004255
4256 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004257 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004258 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004259 while (1) {
4260 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4261 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4262 return false;
4263
4264 if (Entry.Kind != llvm::BitstreamEntry::Record)
4265 return true;
4266
Guy Benyei11169dd2012-12-18 14:30:41 +00004267 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004268 StringRef Blob;
4269 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004270 switch ((ControlRecordTypes)RecCode) {
4271 case METADATA: {
4272 if (Record[0] != VERSION_MAJOR)
4273 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004274
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004275 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004276 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004277
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004278 break;
4279 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004280 case MODULE_NAME:
4281 Listener.ReadModuleName(Blob);
4282 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004283 case MODULE_DIRECTORY:
4284 ModuleDir = Blob;
4285 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004286 case MODULE_MAP_FILE: {
4287 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004288 auto Path = ReadString(Record, Idx);
4289 ResolveImportedPath(Path, ModuleDir);
4290 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004291 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004292 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004293 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004294 if (ParseLanguageOptions(Record, false, Listener,
4295 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004296 return true;
4297 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004298
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004299 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004300 if (ParseTargetOptions(Record, false, Listener,
4301 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004302 return true;
4303 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004304
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004305 case DIAGNOSTIC_OPTIONS:
4306 if (ParseDiagnosticOptions(Record, false, Listener))
4307 return true;
4308 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004309
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004310 case FILE_SYSTEM_OPTIONS:
4311 if (ParseFileSystemOptions(Record, false, Listener))
4312 return true;
4313 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004314
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004315 case HEADER_SEARCH_OPTIONS:
4316 if (ParseHeaderSearchOptions(Record, false, Listener))
4317 return true;
4318 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004319
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004320 case PREPROCESSOR_OPTIONS: {
4321 std::string IgnoredSuggestedPredefines;
4322 if (ParsePreprocessorOptions(Record, false, Listener,
4323 IgnoredSuggestedPredefines))
4324 return true;
4325 break;
4326 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004327
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004328 case INPUT_FILE_OFFSETS: {
4329 if (!NeedsInputFiles)
4330 break;
4331
4332 unsigned NumInputFiles = Record[0];
4333 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004334 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004335 for (unsigned I = 0; I != NumInputFiles; ++I) {
4336 // Go find this input file.
4337 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004338
4339 if (isSystemFile && !NeedsSystemInputFiles)
4340 break; // the rest are system input files
4341
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004342 BitstreamCursor &Cursor = InputFilesCursor;
4343 SavedStreamPosition SavedPosition(Cursor);
4344 Cursor.JumpToBit(InputFileOffs[I]);
4345
4346 unsigned Code = Cursor.ReadCode();
4347 RecordData Record;
4348 StringRef Blob;
4349 bool shouldContinue = false;
4350 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4351 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004352 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004353 std::string Filename = Blob;
4354 ResolveImportedPath(Filename, ModuleDir);
4355 shouldContinue =
4356 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004357 break;
4358 }
4359 if (!shouldContinue)
4360 break;
4361 }
4362 break;
4363 }
4364
Richard Smithd4b230b2014-10-27 23:01:16 +00004365 case IMPORTS: {
4366 if (!NeedsImports)
4367 break;
4368
4369 unsigned Idx = 0, N = Record.size();
4370 while (Idx < N) {
4371 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004372 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004373 std::string Filename = ReadString(Record, Idx);
4374 ResolveImportedPath(Filename, ModuleDir);
4375 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004376 }
4377 break;
4378 }
4379
Richard Smith7f330cd2015-03-18 01:42:29 +00004380 case KNOWN_MODULE_FILES: {
4381 // Known-but-not-technically-used module files are treated as imports.
4382 if (!NeedsImports)
4383 break;
4384
4385 unsigned Idx = 0, N = Record.size();
4386 while (Idx < N) {
4387 std::string Filename = ReadString(Record, Idx);
4388 ResolveImportedPath(Filename, ModuleDir);
4389 Listener.visitImport(Filename);
4390 }
4391 break;
4392 }
4393
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004394 default:
4395 // No other validation to perform.
4396 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004397 }
4398 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004399}
4400
4401
4402bool ASTReader::isAcceptableASTFile(StringRef Filename,
4403 FileManager &FileMgr,
4404 const LangOptions &LangOpts,
4405 const TargetOptions &TargetOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004406 const PreprocessorOptions &PPOpts,
4407 std::string ExistingModuleCachePath) {
4408 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4409 ExistingModuleCachePath, FileMgr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004410 return !readASTFileControlBlock(Filename, FileMgr, validator);
4411}
4412
Ben Langmuir2c9af442014-04-10 17:57:43 +00004413ASTReader::ASTReadResult
4414ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 // Enter the submodule block.
4416 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4417 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004418 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004419 }
4420
4421 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4422 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004423 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004424 RecordData Record;
4425 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004426 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4427
4428 switch (Entry.Kind) {
4429 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4430 case llvm::BitstreamEntry::Error:
4431 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004432 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004433 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004434 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004435 case llvm::BitstreamEntry::Record:
4436 // The interesting case.
4437 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004438 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004439
Guy Benyei11169dd2012-12-18 14:30:41 +00004440 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004441 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004442 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004443 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4444
4445 if ((Kind == SUBMODULE_METADATA) != First) {
4446 Error("submodule metadata record should be at beginning of block");
4447 return Failure;
4448 }
4449 First = false;
4450
4451 // Submodule information is only valid if we have a current module.
4452 // FIXME: Should we error on these cases?
4453 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4454 Kind != SUBMODULE_DEFINITION)
4455 continue;
4456
4457 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 default: // Default behavior: ignore.
4459 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004460
Richard Smith03478d92014-10-23 22:12:14 +00004461 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004462 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004463 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004464 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004465 }
Richard Smith03478d92014-10-23 22:12:14 +00004466
Chris Lattner0e6c9402013-01-20 02:38:54 +00004467 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004468 unsigned Idx = 0;
4469 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4470 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4471 bool IsFramework = Record[Idx++];
4472 bool IsExplicit = Record[Idx++];
4473 bool IsSystem = Record[Idx++];
4474 bool IsExternC = Record[Idx++];
4475 bool InferSubmodules = Record[Idx++];
4476 bool InferExplicitSubmodules = Record[Idx++];
4477 bool InferExportWildcard = Record[Idx++];
4478 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004479
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004480 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004481 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004482 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004483
Guy Benyei11169dd2012-12-18 14:30:41 +00004484 // Retrieve this (sub)module from the module map, creating it if
4485 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004486 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004488
4489 // FIXME: set the definition loc for CurrentModule, or call
4490 // ModMap.setInferredModuleAllowedBy()
4491
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4493 if (GlobalIndex >= SubmodulesLoaded.size() ||
4494 SubmodulesLoaded[GlobalIndex]) {
4495 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004496 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004497 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004498
Douglas Gregor7029ce12013-03-19 00:28:20 +00004499 if (!ParentModule) {
4500 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4501 if (CurFile != F.File) {
4502 if (!Diags.isDiagnosticInFlight()) {
4503 Diag(diag::err_module_file_conflict)
4504 << CurrentModule->getTopLevelModuleName()
4505 << CurFile->getName()
4506 << F.File->getName();
4507 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004508 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004509 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004510 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004511
4512 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004513 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004514
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 CurrentModule->IsFromModuleFile = true;
4516 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004517 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004518 CurrentModule->InferSubmodules = InferSubmodules;
4519 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4520 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004521 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004522 if (DeserializationListener)
4523 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4524
4525 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004526
Douglas Gregorfb912652013-03-20 21:10:35 +00004527 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004528 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004529 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004530 CurrentModule->UnresolvedConflicts.clear();
4531 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004532 break;
4533 }
4534
4535 case SUBMODULE_UMBRELLA_HEADER: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004536 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004537 if (!CurrentModule->getUmbrellaHeader())
4538 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4539 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004540 // This can be a spurious difference caused by changing the VFS to
4541 // point to a different copy of the file, and it is too late to
4542 // to rebuild safely.
4543 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4544 // after input file validation only real problems would remain and we
4545 // could just error. For now, assume it's okay.
4546 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 }
4548 }
4549 break;
4550 }
4551
Richard Smith202210b2014-10-24 20:23:01 +00004552 case SUBMODULE_HEADER:
4553 case SUBMODULE_EXCLUDED_HEADER:
4554 case SUBMODULE_PRIVATE_HEADER:
4555 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004556 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4557 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004558 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004559
Richard Smith202210b2014-10-24 20:23:01 +00004560 case SUBMODULE_TEXTUAL_HEADER:
4561 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4562 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4563 // them here.
4564 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004565
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004567 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004568 break;
4569 }
4570
4571 case SUBMODULE_UMBRELLA_DIR: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004572 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004573 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004574 if (!CurrentModule->getUmbrellaDir())
4575 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4576 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004577 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4578 Error("mismatched umbrella directories in submodule");
4579 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004580 }
4581 }
4582 break;
4583 }
4584
4585 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004586 F.BaseSubmoduleID = getTotalNumSubmodules();
4587 F.LocalNumSubmodules = Record[0];
4588 unsigned LocalBaseSubmoduleID = Record[1];
4589 if (F.LocalNumSubmodules > 0) {
4590 // Introduce the global -> local mapping for submodules within this
4591 // module.
4592 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4593
4594 // Introduce the local -> global mapping for submodules within this
4595 // module.
4596 F.SubmoduleRemap.insertOrReplace(
4597 std::make_pair(LocalBaseSubmoduleID,
4598 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004599
Ben Langmuir52ca6782014-10-20 16:27:32 +00004600 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4601 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004602 break;
4603 }
4604
4605 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004607 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004608 Unresolved.File = &F;
4609 Unresolved.Mod = CurrentModule;
4610 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004611 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004612 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004613 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004614 }
4615 break;
4616 }
4617
4618 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004620 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 Unresolved.File = &F;
4622 Unresolved.Mod = CurrentModule;
4623 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004624 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004626 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 }
4628
4629 // Once we've loaded the set of exports, there's no reason to keep
4630 // the parsed, unresolved exports around.
4631 CurrentModule->UnresolvedExports.clear();
4632 break;
4633 }
4634 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004635 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004636 Context.getTargetInfo());
4637 break;
4638 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004639
4640 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004641 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004642 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004643 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004644
4645 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004646 CurrentModule->ConfigMacros.push_back(Blob.str());
4647 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004648
4649 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004650 UnresolvedModuleRef Unresolved;
4651 Unresolved.File = &F;
4652 Unresolved.Mod = CurrentModule;
4653 Unresolved.ID = Record[0];
4654 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4655 Unresolved.IsWildcard = false;
4656 Unresolved.String = Blob;
4657 UnresolvedModuleRefs.push_back(Unresolved);
4658 break;
4659 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004660 }
4661 }
4662}
4663
4664/// \brief Parse the record that corresponds to a LangOptions data
4665/// structure.
4666///
4667/// This routine parses the language options from the AST file and then gives
4668/// them to the AST listener if one is set.
4669///
4670/// \returns true if the listener deems the file unacceptable, false otherwise.
4671bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4672 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004673 ASTReaderListener &Listener,
4674 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004675 LangOptions LangOpts;
4676 unsigned Idx = 0;
4677#define LANGOPT(Name, Bits, Default, Description) \
4678 LangOpts.Name = Record[Idx++];
4679#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4680 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4681#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004682#define SANITIZER(NAME, ID) \
4683 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004684#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004685
4686 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4687 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4688 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4689
4690 unsigned Length = Record[Idx++];
4691 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4692 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004693
4694 Idx += Length;
4695
4696 // Comment options.
4697 for (unsigned N = Record[Idx++]; N; --N) {
4698 LangOpts.CommentOpts.BlockCommandNames.push_back(
4699 ReadString(Record, Idx));
4700 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004701 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004702
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004703 return Listener.ReadLanguageOptions(LangOpts, Complain,
4704 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004705}
4706
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004707bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4708 ASTReaderListener &Listener,
4709 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004710 unsigned Idx = 0;
4711 TargetOptions TargetOpts;
4712 TargetOpts.Triple = ReadString(Record, Idx);
4713 TargetOpts.CPU = ReadString(Record, Idx);
4714 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 for (unsigned N = Record[Idx++]; N; --N) {
4716 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4717 }
4718 for (unsigned N = Record[Idx++]; N; --N) {
4719 TargetOpts.Features.push_back(ReadString(Record, Idx));
4720 }
4721
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004722 return Listener.ReadTargetOptions(TargetOpts, Complain,
4723 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004724}
4725
4726bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4727 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004728 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004729 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004730#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004731#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004732 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004733#include "clang/Basic/DiagnosticOptions.def"
4734
Richard Smith3be1cb22014-08-07 00:24:21 +00004735 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004736 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004737 for (unsigned N = Record[Idx++]; N; --N)
4738 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004739
4740 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4741}
4742
4743bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4744 ASTReaderListener &Listener) {
4745 FileSystemOptions FSOpts;
4746 unsigned Idx = 0;
4747 FSOpts.WorkingDir = ReadString(Record, Idx);
4748 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4749}
4750
4751bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4752 bool Complain,
4753 ASTReaderListener &Listener) {
4754 HeaderSearchOptions HSOpts;
4755 unsigned Idx = 0;
4756 HSOpts.Sysroot = ReadString(Record, Idx);
4757
4758 // Include entries.
4759 for (unsigned N = Record[Idx++]; N; --N) {
4760 std::string Path = ReadString(Record, Idx);
4761 frontend::IncludeDirGroup Group
4762 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004763 bool IsFramework = Record[Idx++];
4764 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004765 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004766 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004767 }
4768
4769 // System header prefixes.
4770 for (unsigned N = Record[Idx++]; N; --N) {
4771 std::string Prefix = ReadString(Record, Idx);
4772 bool IsSystemHeader = Record[Idx++];
4773 HSOpts.SystemHeaderPrefixes.push_back(
4774 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4775 }
4776
4777 HSOpts.ResourceDir = ReadString(Record, Idx);
4778 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004779 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004780 HSOpts.DisableModuleHash = Record[Idx++];
4781 HSOpts.UseBuiltinIncludes = Record[Idx++];
4782 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4783 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4784 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004785 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004786
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004787 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4788 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004789}
4790
4791bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4792 bool Complain,
4793 ASTReaderListener &Listener,
4794 std::string &SuggestedPredefines) {
4795 PreprocessorOptions PPOpts;
4796 unsigned Idx = 0;
4797
4798 // Macro definitions/undefs
4799 for (unsigned N = Record[Idx++]; N; --N) {
4800 std::string Macro = ReadString(Record, Idx);
4801 bool IsUndef = Record[Idx++];
4802 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4803 }
4804
4805 // Includes
4806 for (unsigned N = Record[Idx++]; N; --N) {
4807 PPOpts.Includes.push_back(ReadString(Record, Idx));
4808 }
4809
4810 // Macro Includes
4811 for (unsigned N = Record[Idx++]; N; --N) {
4812 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4813 }
4814
4815 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004816 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004817 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4818 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4819 PPOpts.ObjCXXARCStandardLibrary =
4820 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4821 SuggestedPredefines.clear();
4822 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4823 SuggestedPredefines);
4824}
4825
4826std::pair<ModuleFile *, unsigned>
4827ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4828 GlobalPreprocessedEntityMapType::iterator
4829 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4830 assert(I != GlobalPreprocessedEntityMap.end() &&
4831 "Corrupted global preprocessed entity map");
4832 ModuleFile *M = I->second;
4833 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4834 return std::make_pair(M, LocalIndex);
4835}
4836
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004837llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004838ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4839 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4840 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4841 Mod.NumPreprocessedEntities);
4842
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004843 return llvm::make_range(PreprocessingRecord::iterator(),
4844 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004845}
4846
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004847llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004848ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004849 return llvm::make_range(
4850 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4851 ModuleDeclIterator(this, &Mod,
4852 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004853}
4854
4855PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4856 PreprocessedEntityID PPID = Index+1;
4857 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4858 ModuleFile &M = *PPInfo.first;
4859 unsigned LocalIndex = PPInfo.second;
4860 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4861
Guy Benyei11169dd2012-12-18 14:30:41 +00004862 if (!PP.getPreprocessingRecord()) {
4863 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004864 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004865 }
4866
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004867 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4868 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4869
4870 llvm::BitstreamEntry Entry =
4871 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4872 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004873 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004874
Guy Benyei11169dd2012-12-18 14:30:41 +00004875 // Read the record.
4876 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4877 ReadSourceLocation(M, PPOffs.End));
4878 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004879 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004880 RecordData Record;
4881 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004882 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4883 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004884 switch (RecType) {
4885 case PPD_MACRO_EXPANSION: {
4886 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004887 IdentifierInfo *Name = nullptr;
4888 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004889 if (isBuiltin)
4890 Name = getLocalIdentifier(M, Record[1]);
4891 else {
4892 PreprocessedEntityID
4893 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4894 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4895 }
4896
4897 MacroExpansion *ME;
4898 if (isBuiltin)
4899 ME = new (PPRec) MacroExpansion(Name, Range);
4900 else
4901 ME = new (PPRec) MacroExpansion(Def, Range);
4902
4903 return ME;
4904 }
4905
4906 case PPD_MACRO_DEFINITION: {
4907 // Decode the identifier info and then check again; if the macro is
4908 // still defined and associated with the identifier,
4909 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4910 MacroDefinition *MD
4911 = new (PPRec) MacroDefinition(II, Range);
4912
4913 if (DeserializationListener)
4914 DeserializationListener->MacroDefinitionRead(PPID, MD);
4915
4916 return MD;
4917 }
4918
4919 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004920 const char *FullFileNameStart = Blob.data() + Record[0];
4921 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004922 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004923 if (!FullFileName.empty())
4924 File = PP.getFileManager().getFile(FullFileName);
4925
4926 // FIXME: Stable encoding
4927 InclusionDirective::InclusionKind Kind
4928 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4929 InclusionDirective *ID
4930 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004931 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004932 Record[1], Record[3],
4933 File,
4934 Range);
4935 return ID;
4936 }
4937 }
4938
4939 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4940}
4941
4942/// \brief \arg SLocMapI points at a chunk of a module that contains no
4943/// preprocessed entities or the entities it contains are not the ones we are
4944/// looking for. Find the next module that contains entities and return the ID
4945/// of the first entry.
4946PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4947 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4948 ++SLocMapI;
4949 for (GlobalSLocOffsetMapType::const_iterator
4950 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4951 ModuleFile &M = *SLocMapI->second;
4952 if (M.NumPreprocessedEntities)
4953 return M.BasePreprocessedEntityID;
4954 }
4955
4956 return getTotalNumPreprocessedEntities();
4957}
4958
4959namespace {
4960
4961template <unsigned PPEntityOffset::*PPLoc>
4962struct PPEntityComp {
4963 const ASTReader &Reader;
4964 ModuleFile &M;
4965
4966 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4967
4968 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4969 SourceLocation LHS = getLoc(L);
4970 SourceLocation RHS = getLoc(R);
4971 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4972 }
4973
4974 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4975 SourceLocation LHS = getLoc(L);
4976 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4977 }
4978
4979 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4980 SourceLocation RHS = getLoc(R);
4981 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4982 }
4983
4984 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4985 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4986 }
4987};
4988
4989}
4990
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004991PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4992 bool EndsAfter) const {
4993 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004994 return getTotalNumPreprocessedEntities();
4995
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004996 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4997 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004998 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4999 "Corrupted global sloc offset map");
5000
5001 if (SLocMapI->second->NumPreprocessedEntities == 0)
5002 return findNextPreprocessedEntity(SLocMapI);
5003
5004 ModuleFile &M = *SLocMapI->second;
5005 typedef const PPEntityOffset *pp_iterator;
5006 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5007 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5008
5009 size_t Count = M.NumPreprocessedEntities;
5010 size_t Half;
5011 pp_iterator First = pp_begin;
5012 pp_iterator PPI;
5013
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005014 if (EndsAfter) {
5015 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5016 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
5017 } else {
5018 // Do a binary search manually instead of using std::lower_bound because
5019 // The end locations of entities may be unordered (when a macro expansion
5020 // is inside another macro argument), but for this case it is not important
5021 // whether we get the first macro expansion or its containing macro.
5022 while (Count > 0) {
5023 Half = Count / 2;
5024 PPI = First;
5025 std::advance(PPI, Half);
5026 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
5027 Loc)) {
5028 First = PPI;
5029 ++First;
5030 Count = Count - Half - 1;
5031 } else
5032 Count = Half;
5033 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 }
5035
5036 if (PPI == pp_end)
5037 return findNextPreprocessedEntity(SLocMapI);
5038
5039 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5040}
5041
Guy Benyei11169dd2012-12-18 14:30:41 +00005042/// \brief Returns a pair of [Begin, End) indices of preallocated
5043/// preprocessed entities that \arg Range encompasses.
5044std::pair<unsigned, unsigned>
5045 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5046 if (Range.isInvalid())
5047 return std::make_pair(0,0);
5048 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5049
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005050 PreprocessedEntityID BeginID =
5051 findPreprocessedEntity(Range.getBegin(), false);
5052 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005053 return std::make_pair(BeginID, EndID);
5054}
5055
5056/// \brief Optionally returns true or false if the preallocated preprocessed
5057/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005058Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005059 FileID FID) {
5060 if (FID.isInvalid())
5061 return false;
5062
5063 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5064 ModuleFile &M = *PPInfo.first;
5065 unsigned LocalIndex = PPInfo.second;
5066 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5067
5068 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5069 if (Loc.isInvalid())
5070 return false;
5071
5072 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5073 return true;
5074 else
5075 return false;
5076}
5077
5078namespace {
5079 /// \brief Visitor used to search for information about a header file.
5080 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 const FileEntry *FE;
5082
David Blaikie05785d12013-02-20 22:23:23 +00005083 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005084
5085 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005086 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5087 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00005088
5089 static bool visit(ModuleFile &M, void *UserData) {
5090 HeaderFileInfoVisitor *This
5091 = static_cast<HeaderFileInfoVisitor *>(UserData);
5092
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 HeaderFileInfoLookupTable *Table
5094 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5095 if (!Table)
5096 return false;
5097
5098 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00005099 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 if (Pos == Table->end())
5101 return false;
5102
5103 This->HFI = *Pos;
5104 return true;
5105 }
5106
David Blaikie05785d12013-02-20 22:23:23 +00005107 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005108 };
5109}
5110
5111HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005112 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005114 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005116
5117 return HeaderFileInfo();
5118}
5119
5120void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5121 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005122 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5124 ModuleFile &F = *(*I);
5125 unsigned Idx = 0;
5126 DiagStates.clear();
5127 assert(!Diag.DiagStates.empty());
5128 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5129 while (Idx < F.PragmaDiagMappings.size()) {
5130 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5131 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5132 if (DiagStateID != 0) {
5133 Diag.DiagStatePoints.push_back(
5134 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5135 FullSourceLoc(Loc, SourceMgr)));
5136 continue;
5137 }
5138
5139 assert(DiagStateID == 0);
5140 // A new DiagState was created here.
5141 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5142 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5143 DiagStates.push_back(NewState);
5144 Diag.DiagStatePoints.push_back(
5145 DiagnosticsEngine::DiagStatePoint(NewState,
5146 FullSourceLoc(Loc, SourceMgr)));
5147 while (1) {
5148 assert(Idx < F.PragmaDiagMappings.size() &&
5149 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5150 if (Idx >= F.PragmaDiagMappings.size()) {
5151 break; // Something is messed up but at least avoid infinite loop in
5152 // release build.
5153 }
5154 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5155 if (DiagID == (unsigned)-1) {
5156 break; // no more diag/map pairs for this location.
5157 }
Alp Tokerc726c362014-06-10 09:31:37 +00005158 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5159 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5160 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005161 }
5162 }
5163 }
5164}
5165
5166/// \brief Get the correct cursor and offset for loading a type.
5167ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5168 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5169 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5170 ModuleFile *M = I->second;
5171 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5172}
5173
5174/// \brief Read and return the type with the given index..
5175///
5176/// The index is the type ID, shifted and minus the number of predefs. This
5177/// routine actually reads the record corresponding to the type at the given
5178/// location. It is a helper routine for GetType, which deals with reading type
5179/// IDs.
5180QualType ASTReader::readTypeRecord(unsigned Index) {
5181 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005182 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005183
5184 // Keep track of where we are in the stream, then jump back there
5185 // after reading this type.
5186 SavedStreamPosition SavedPosition(DeclsCursor);
5187
5188 ReadingKindTracker ReadingKind(Read_Type, *this);
5189
5190 // Note that we are loading a type record.
5191 Deserializing AType(this);
5192
5193 unsigned Idx = 0;
5194 DeclsCursor.JumpToBit(Loc.Offset);
5195 RecordData Record;
5196 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005197 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005198 case TYPE_EXT_QUAL: {
5199 if (Record.size() != 2) {
5200 Error("Incorrect encoding of extended qualifier type");
5201 return QualType();
5202 }
5203 QualType Base = readType(*Loc.F, Record, Idx);
5204 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5205 return Context.getQualifiedType(Base, Quals);
5206 }
5207
5208 case TYPE_COMPLEX: {
5209 if (Record.size() != 1) {
5210 Error("Incorrect encoding of complex type");
5211 return QualType();
5212 }
5213 QualType ElemType = readType(*Loc.F, Record, Idx);
5214 return Context.getComplexType(ElemType);
5215 }
5216
5217 case TYPE_POINTER: {
5218 if (Record.size() != 1) {
5219 Error("Incorrect encoding of pointer type");
5220 return QualType();
5221 }
5222 QualType PointeeType = readType(*Loc.F, Record, Idx);
5223 return Context.getPointerType(PointeeType);
5224 }
5225
Reid Kleckner8a365022013-06-24 17:51:48 +00005226 case TYPE_DECAYED: {
5227 if (Record.size() != 1) {
5228 Error("Incorrect encoding of decayed type");
5229 return QualType();
5230 }
5231 QualType OriginalType = readType(*Loc.F, Record, Idx);
5232 QualType DT = Context.getAdjustedParameterType(OriginalType);
5233 if (!isa<DecayedType>(DT))
5234 Error("Decayed type does not decay");
5235 return DT;
5236 }
5237
Reid Kleckner0503a872013-12-05 01:23:43 +00005238 case TYPE_ADJUSTED: {
5239 if (Record.size() != 2) {
5240 Error("Incorrect encoding of adjusted type");
5241 return QualType();
5242 }
5243 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5244 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5245 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5246 }
5247
Guy Benyei11169dd2012-12-18 14:30:41 +00005248 case TYPE_BLOCK_POINTER: {
5249 if (Record.size() != 1) {
5250 Error("Incorrect encoding of block pointer type");
5251 return QualType();
5252 }
5253 QualType PointeeType = readType(*Loc.F, Record, Idx);
5254 return Context.getBlockPointerType(PointeeType);
5255 }
5256
5257 case TYPE_LVALUE_REFERENCE: {
5258 if (Record.size() != 2) {
5259 Error("Incorrect encoding of lvalue reference type");
5260 return QualType();
5261 }
5262 QualType PointeeType = readType(*Loc.F, Record, Idx);
5263 return Context.getLValueReferenceType(PointeeType, Record[1]);
5264 }
5265
5266 case TYPE_RVALUE_REFERENCE: {
5267 if (Record.size() != 1) {
5268 Error("Incorrect encoding of rvalue reference type");
5269 return QualType();
5270 }
5271 QualType PointeeType = readType(*Loc.F, Record, Idx);
5272 return Context.getRValueReferenceType(PointeeType);
5273 }
5274
5275 case TYPE_MEMBER_POINTER: {
5276 if (Record.size() != 2) {
5277 Error("Incorrect encoding of member pointer type");
5278 return QualType();
5279 }
5280 QualType PointeeType = readType(*Loc.F, Record, Idx);
5281 QualType ClassType = readType(*Loc.F, Record, Idx);
5282 if (PointeeType.isNull() || ClassType.isNull())
5283 return QualType();
5284
5285 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5286 }
5287
5288 case TYPE_CONSTANT_ARRAY: {
5289 QualType ElementType = readType(*Loc.F, Record, Idx);
5290 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5291 unsigned IndexTypeQuals = Record[2];
5292 unsigned Idx = 3;
5293 llvm::APInt Size = ReadAPInt(Record, Idx);
5294 return Context.getConstantArrayType(ElementType, Size,
5295 ASM, IndexTypeQuals);
5296 }
5297
5298 case TYPE_INCOMPLETE_ARRAY: {
5299 QualType ElementType = readType(*Loc.F, Record, Idx);
5300 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5301 unsigned IndexTypeQuals = Record[2];
5302 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5303 }
5304
5305 case TYPE_VARIABLE_ARRAY: {
5306 QualType ElementType = readType(*Loc.F, Record, Idx);
5307 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5308 unsigned IndexTypeQuals = Record[2];
5309 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5310 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5311 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5312 ASM, IndexTypeQuals,
5313 SourceRange(LBLoc, RBLoc));
5314 }
5315
5316 case TYPE_VECTOR: {
5317 if (Record.size() != 3) {
5318 Error("incorrect encoding of vector type in AST file");
5319 return QualType();
5320 }
5321
5322 QualType ElementType = readType(*Loc.F, Record, Idx);
5323 unsigned NumElements = Record[1];
5324 unsigned VecKind = Record[2];
5325 return Context.getVectorType(ElementType, NumElements,
5326 (VectorType::VectorKind)VecKind);
5327 }
5328
5329 case TYPE_EXT_VECTOR: {
5330 if (Record.size() != 3) {
5331 Error("incorrect encoding of extended vector type in AST file");
5332 return QualType();
5333 }
5334
5335 QualType ElementType = readType(*Loc.F, Record, Idx);
5336 unsigned NumElements = Record[1];
5337 return Context.getExtVectorType(ElementType, NumElements);
5338 }
5339
5340 case TYPE_FUNCTION_NO_PROTO: {
5341 if (Record.size() != 6) {
5342 Error("incorrect encoding of no-proto function type");
5343 return QualType();
5344 }
5345 QualType ResultType = readType(*Loc.F, Record, Idx);
5346 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5347 (CallingConv)Record[4], Record[5]);
5348 return Context.getFunctionNoProtoType(ResultType, Info);
5349 }
5350
5351 case TYPE_FUNCTION_PROTO: {
5352 QualType ResultType = readType(*Loc.F, Record, Idx);
5353
5354 FunctionProtoType::ExtProtoInfo EPI;
5355 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5356 /*hasregparm*/ Record[2],
5357 /*regparm*/ Record[3],
5358 static_cast<CallingConv>(Record[4]),
5359 /*produces*/ Record[5]);
5360
5361 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005362
5363 EPI.Variadic = Record[Idx++];
5364 EPI.HasTrailingReturn = Record[Idx++];
5365 EPI.TypeQuals = Record[Idx++];
5366 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005367 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005368 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005369
5370 unsigned NumParams = Record[Idx++];
5371 SmallVector<QualType, 16> ParamTypes;
5372 for (unsigned I = 0; I != NumParams; ++I)
5373 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5374
Jordan Rose5c382722013-03-08 21:51:21 +00005375 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005376 }
5377
5378 case TYPE_UNRESOLVED_USING: {
5379 unsigned Idx = 0;
5380 return Context.getTypeDeclType(
5381 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5382 }
5383
5384 case TYPE_TYPEDEF: {
5385 if (Record.size() != 2) {
5386 Error("incorrect encoding of typedef type");
5387 return QualType();
5388 }
5389 unsigned Idx = 0;
5390 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5391 QualType Canonical = readType(*Loc.F, Record, Idx);
5392 if (!Canonical.isNull())
5393 Canonical = Context.getCanonicalType(Canonical);
5394 return Context.getTypedefType(Decl, Canonical);
5395 }
5396
5397 case TYPE_TYPEOF_EXPR:
5398 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5399
5400 case TYPE_TYPEOF: {
5401 if (Record.size() != 1) {
5402 Error("incorrect encoding of typeof(type) in AST file");
5403 return QualType();
5404 }
5405 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5406 return Context.getTypeOfType(UnderlyingType);
5407 }
5408
5409 case TYPE_DECLTYPE: {
5410 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5411 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5412 }
5413
5414 case TYPE_UNARY_TRANSFORM: {
5415 QualType BaseType = readType(*Loc.F, Record, Idx);
5416 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5417 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5418 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5419 }
5420
Richard Smith74aeef52013-04-26 16:15:35 +00005421 case TYPE_AUTO: {
5422 QualType Deduced = readType(*Loc.F, Record, Idx);
5423 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005424 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005425 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005426 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005427
5428 case TYPE_RECORD: {
5429 if (Record.size() != 2) {
5430 Error("incorrect encoding of record type");
5431 return QualType();
5432 }
5433 unsigned Idx = 0;
5434 bool IsDependent = Record[Idx++];
5435 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5436 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5437 QualType T = Context.getRecordType(RD);
5438 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5439 return T;
5440 }
5441
5442 case TYPE_ENUM: {
5443 if (Record.size() != 2) {
5444 Error("incorrect encoding of enum type");
5445 return QualType();
5446 }
5447 unsigned Idx = 0;
5448 bool IsDependent = Record[Idx++];
5449 QualType T
5450 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5451 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5452 return T;
5453 }
5454
5455 case TYPE_ATTRIBUTED: {
5456 if (Record.size() != 3) {
5457 Error("incorrect encoding of attributed type");
5458 return QualType();
5459 }
5460 QualType modifiedType = readType(*Loc.F, Record, Idx);
5461 QualType equivalentType = readType(*Loc.F, Record, Idx);
5462 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5463 return Context.getAttributedType(kind, modifiedType, equivalentType);
5464 }
5465
5466 case TYPE_PAREN: {
5467 if (Record.size() != 1) {
5468 Error("incorrect encoding of paren type");
5469 return QualType();
5470 }
5471 QualType InnerType = readType(*Loc.F, Record, Idx);
5472 return Context.getParenType(InnerType);
5473 }
5474
5475 case TYPE_PACK_EXPANSION: {
5476 if (Record.size() != 2) {
5477 Error("incorrect encoding of pack expansion type");
5478 return QualType();
5479 }
5480 QualType Pattern = readType(*Loc.F, Record, Idx);
5481 if (Pattern.isNull())
5482 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005483 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005484 if (Record[1])
5485 NumExpansions = Record[1] - 1;
5486 return Context.getPackExpansionType(Pattern, NumExpansions);
5487 }
5488
5489 case TYPE_ELABORATED: {
5490 unsigned Idx = 0;
5491 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5492 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5493 QualType NamedType = readType(*Loc.F, Record, Idx);
5494 return Context.getElaboratedType(Keyword, NNS, NamedType);
5495 }
5496
5497 case TYPE_OBJC_INTERFACE: {
5498 unsigned Idx = 0;
5499 ObjCInterfaceDecl *ItfD
5500 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5501 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5502 }
5503
5504 case TYPE_OBJC_OBJECT: {
5505 unsigned Idx = 0;
5506 QualType Base = readType(*Loc.F, Record, Idx);
5507 unsigned NumProtos = Record[Idx++];
5508 SmallVector<ObjCProtocolDecl*, 4> Protos;
5509 for (unsigned I = 0; I != NumProtos; ++I)
5510 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5511 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5512 }
5513
5514 case TYPE_OBJC_OBJECT_POINTER: {
5515 unsigned Idx = 0;
5516 QualType Pointee = readType(*Loc.F, Record, Idx);
5517 return Context.getObjCObjectPointerType(Pointee);
5518 }
5519
5520 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5521 unsigned Idx = 0;
5522 QualType Parm = readType(*Loc.F, Record, Idx);
5523 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005524 return Context.getSubstTemplateTypeParmType(
5525 cast<TemplateTypeParmType>(Parm),
5526 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005527 }
5528
5529 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5530 unsigned Idx = 0;
5531 QualType Parm = readType(*Loc.F, Record, Idx);
5532 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5533 return Context.getSubstTemplateTypeParmPackType(
5534 cast<TemplateTypeParmType>(Parm),
5535 ArgPack);
5536 }
5537
5538 case TYPE_INJECTED_CLASS_NAME: {
5539 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5540 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5541 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5542 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005543 const Type *T = nullptr;
5544 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5545 if (const Type *Existing = DI->getTypeForDecl()) {
5546 T = Existing;
5547 break;
5548 }
5549 }
5550 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005551 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005552 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5553 DI->setTypeForDecl(T);
5554 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005555 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005556 }
5557
5558 case TYPE_TEMPLATE_TYPE_PARM: {
5559 unsigned Idx = 0;
5560 unsigned Depth = Record[Idx++];
5561 unsigned Index = Record[Idx++];
5562 bool Pack = Record[Idx++];
5563 TemplateTypeParmDecl *D
5564 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5565 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5566 }
5567
5568 case TYPE_DEPENDENT_NAME: {
5569 unsigned Idx = 0;
5570 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5571 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5572 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5573 QualType Canon = readType(*Loc.F, Record, Idx);
5574 if (!Canon.isNull())
5575 Canon = Context.getCanonicalType(Canon);
5576 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5577 }
5578
5579 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5580 unsigned Idx = 0;
5581 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5582 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5583 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5584 unsigned NumArgs = Record[Idx++];
5585 SmallVector<TemplateArgument, 8> Args;
5586 Args.reserve(NumArgs);
5587 while (NumArgs--)
5588 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5589 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5590 Args.size(), Args.data());
5591 }
5592
5593 case TYPE_DEPENDENT_SIZED_ARRAY: {
5594 unsigned Idx = 0;
5595
5596 // ArrayType
5597 QualType ElementType = readType(*Loc.F, Record, Idx);
5598 ArrayType::ArraySizeModifier ASM
5599 = (ArrayType::ArraySizeModifier)Record[Idx++];
5600 unsigned IndexTypeQuals = Record[Idx++];
5601
5602 // DependentSizedArrayType
5603 Expr *NumElts = ReadExpr(*Loc.F);
5604 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5605
5606 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5607 IndexTypeQuals, Brackets);
5608 }
5609
5610 case TYPE_TEMPLATE_SPECIALIZATION: {
5611 unsigned Idx = 0;
5612 bool IsDependent = Record[Idx++];
5613 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5614 SmallVector<TemplateArgument, 8> Args;
5615 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5616 QualType Underlying = readType(*Loc.F, Record, Idx);
5617 QualType T;
5618 if (Underlying.isNull())
5619 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5620 Args.size());
5621 else
5622 T = Context.getTemplateSpecializationType(Name, Args.data(),
5623 Args.size(), Underlying);
5624 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5625 return T;
5626 }
5627
5628 case TYPE_ATOMIC: {
5629 if (Record.size() != 1) {
5630 Error("Incorrect encoding of atomic type");
5631 return QualType();
5632 }
5633 QualType ValueType = readType(*Loc.F, Record, Idx);
5634 return Context.getAtomicType(ValueType);
5635 }
5636 }
5637 llvm_unreachable("Invalid TypeCode!");
5638}
5639
Richard Smith564417a2014-03-20 21:47:22 +00005640void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5641 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005642 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005643 const RecordData &Record, unsigned &Idx) {
5644 ExceptionSpecificationType EST =
5645 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005646 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005647 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005648 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005649 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005650 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005651 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005652 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005653 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005654 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5655 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005656 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005657 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005658 }
5659}
5660
Guy Benyei11169dd2012-12-18 14:30:41 +00005661class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5662 ASTReader &Reader;
5663 ModuleFile &F;
5664 const ASTReader::RecordData &Record;
5665 unsigned &Idx;
5666
5667 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5668 unsigned &I) {
5669 return Reader.ReadSourceLocation(F, R, I);
5670 }
5671
5672 template<typename T>
5673 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5674 return Reader.ReadDeclAs<T>(F, Record, Idx);
5675 }
5676
5677public:
5678 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5679 const ASTReader::RecordData &Record, unsigned &Idx)
5680 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5681 { }
5682
5683 // We want compile-time assurance that we've enumerated all of
5684 // these, so unfortunately we have to declare them first, then
5685 // define them out-of-line.
5686#define ABSTRACT_TYPELOC(CLASS, PARENT)
5687#define TYPELOC(CLASS, PARENT) \
5688 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5689#include "clang/AST/TypeLocNodes.def"
5690
5691 void VisitFunctionTypeLoc(FunctionTypeLoc);
5692 void VisitArrayTypeLoc(ArrayTypeLoc);
5693};
5694
5695void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5696 // nothing to do
5697}
5698void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5699 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5700 if (TL.needsExtraLocalData()) {
5701 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5702 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5703 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5704 TL.setModeAttr(Record[Idx++]);
5705 }
5706}
5707void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5708 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5709}
5710void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5711 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5712}
Reid Kleckner8a365022013-06-24 17:51:48 +00005713void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5714 // nothing to do
5715}
Reid Kleckner0503a872013-12-05 01:23:43 +00005716void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5717 // nothing to do
5718}
Guy Benyei11169dd2012-12-18 14:30:41 +00005719void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5720 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5721}
5722void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5723 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5724}
5725void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5726 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5727}
5728void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5729 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5730 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5731}
5732void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5733 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5734 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5735 if (Record[Idx++])
5736 TL.setSizeExpr(Reader.ReadExpr(F));
5737 else
Craig Toppera13603a2014-05-22 05:54:18 +00005738 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005739}
5740void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5741 VisitArrayTypeLoc(TL);
5742}
5743void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5744 VisitArrayTypeLoc(TL);
5745}
5746void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5747 VisitArrayTypeLoc(TL);
5748}
5749void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5750 DependentSizedArrayTypeLoc TL) {
5751 VisitArrayTypeLoc(TL);
5752}
5753void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5754 DependentSizedExtVectorTypeLoc TL) {
5755 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5756}
5757void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5758 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5759}
5760void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5761 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5762}
5763void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5764 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5765 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5766 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5767 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005768 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5769 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005770 }
5771}
5772void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5773 VisitFunctionTypeLoc(TL);
5774}
5775void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5776 VisitFunctionTypeLoc(TL);
5777}
5778void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5779 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5780}
5781void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5782 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5783}
5784void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5785 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5786 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5787 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5788}
5789void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5790 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5791 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5792 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5793 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5794}
5795void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5796 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5797}
5798void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5799 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5800 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5801 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5802 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5803}
5804void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5805 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5806}
5807void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5808 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5809}
5810void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5811 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5812}
5813void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5814 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5815 if (TL.hasAttrOperand()) {
5816 SourceRange range;
5817 range.setBegin(ReadSourceLocation(Record, Idx));
5818 range.setEnd(ReadSourceLocation(Record, Idx));
5819 TL.setAttrOperandParensRange(range);
5820 }
5821 if (TL.hasAttrExprOperand()) {
5822 if (Record[Idx++])
5823 TL.setAttrExprOperand(Reader.ReadExpr(F));
5824 else
Craig Toppera13603a2014-05-22 05:54:18 +00005825 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005826 } else if (TL.hasAttrEnumOperand())
5827 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5828}
5829void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5830 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5831}
5832void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5833 SubstTemplateTypeParmTypeLoc TL) {
5834 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5835}
5836void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5837 SubstTemplateTypeParmPackTypeLoc TL) {
5838 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5839}
5840void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5841 TemplateSpecializationTypeLoc TL) {
5842 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5843 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5844 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5845 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5846 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5847 TL.setArgLocInfo(i,
5848 Reader.GetTemplateArgumentLocInfo(F,
5849 TL.getTypePtr()->getArg(i).getKind(),
5850 Record, Idx));
5851}
5852void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5853 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5854 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5855}
5856void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5857 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5858 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5859}
5860void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5861 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5862}
5863void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5864 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5865 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5866 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5867}
5868void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5869 DependentTemplateSpecializationTypeLoc TL) {
5870 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5871 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5872 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5873 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5874 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5875 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5876 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5877 TL.setArgLocInfo(I,
5878 Reader.GetTemplateArgumentLocInfo(F,
5879 TL.getTypePtr()->getArg(I).getKind(),
5880 Record, Idx));
5881}
5882void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5883 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5884}
5885void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5886 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5887}
5888void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5889 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5890 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5891 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5892 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5893 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5894}
5895void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5896 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5897}
5898void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5899 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5900 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5901 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5902}
5903
5904TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5905 const RecordData &Record,
5906 unsigned &Idx) {
5907 QualType InfoTy = readType(F, Record, Idx);
5908 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005909 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005910
5911 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5912 TypeLocReader TLR(*this, F, Record, Idx);
5913 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5914 TLR.Visit(TL);
5915 return TInfo;
5916}
5917
5918QualType ASTReader::GetType(TypeID ID) {
5919 unsigned FastQuals = ID & Qualifiers::FastMask;
5920 unsigned Index = ID >> Qualifiers::FastWidth;
5921
5922 if (Index < NUM_PREDEF_TYPE_IDS) {
5923 QualType T;
5924 switch ((PredefinedTypeIDs)Index) {
5925 case PREDEF_TYPE_NULL_ID: return QualType();
5926 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5927 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5928
5929 case PREDEF_TYPE_CHAR_U_ID:
5930 case PREDEF_TYPE_CHAR_S_ID:
5931 // FIXME: Check that the signedness of CharTy is correct!
5932 T = Context.CharTy;
5933 break;
5934
5935 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5936 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5937 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5938 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5939 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5940 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5941 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5942 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5943 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5944 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5945 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5946 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5947 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5948 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5949 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5950 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5951 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5952 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5953 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5954 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5955 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5956 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5957 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5958 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5959 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5960 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5961 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5962 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005963 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5964 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5965 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5966 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5967 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5968 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005969 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005970 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005971 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5972
5973 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5974 T = Context.getAutoRRefDeductType();
5975 break;
5976
5977 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5978 T = Context.ARCUnbridgedCastTy;
5979 break;
5980
5981 case PREDEF_TYPE_VA_LIST_TAG:
5982 T = Context.getVaListTagType();
5983 break;
5984
5985 case PREDEF_TYPE_BUILTIN_FN:
5986 T = Context.BuiltinFnTy;
5987 break;
5988 }
5989
5990 assert(!T.isNull() && "Unknown predefined type");
5991 return T.withFastQualifiers(FastQuals);
5992 }
5993
5994 Index -= NUM_PREDEF_TYPE_IDS;
5995 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5996 if (TypesLoaded[Index].isNull()) {
5997 TypesLoaded[Index] = readTypeRecord(Index);
5998 if (TypesLoaded[Index].isNull())
5999 return QualType();
6000
6001 TypesLoaded[Index]->setFromAST();
6002 if (DeserializationListener)
6003 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6004 TypesLoaded[Index]);
6005 }
6006
6007 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6008}
6009
6010QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6011 return GetType(getGlobalTypeID(F, LocalID));
6012}
6013
6014serialization::TypeID
6015ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6016 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6017 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6018
6019 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6020 return LocalID;
6021
6022 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6023 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6024 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6025
6026 unsigned GlobalIndex = LocalIndex + I->second;
6027 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6028}
6029
6030TemplateArgumentLocInfo
6031ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6032 TemplateArgument::ArgKind Kind,
6033 const RecordData &Record,
6034 unsigned &Index) {
6035 switch (Kind) {
6036 case TemplateArgument::Expression:
6037 return ReadExpr(F);
6038 case TemplateArgument::Type:
6039 return GetTypeSourceInfo(F, Record, Index);
6040 case TemplateArgument::Template: {
6041 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6042 Index);
6043 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6044 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6045 SourceLocation());
6046 }
6047 case TemplateArgument::TemplateExpansion: {
6048 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6049 Index);
6050 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6051 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6052 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6053 EllipsisLoc);
6054 }
6055 case TemplateArgument::Null:
6056 case TemplateArgument::Integral:
6057 case TemplateArgument::Declaration:
6058 case TemplateArgument::NullPtr:
6059 case TemplateArgument::Pack:
6060 // FIXME: Is this right?
6061 return TemplateArgumentLocInfo();
6062 }
6063 llvm_unreachable("unexpected template argument loc");
6064}
6065
6066TemplateArgumentLoc
6067ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6068 const RecordData &Record, unsigned &Index) {
6069 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6070
6071 if (Arg.getKind() == TemplateArgument::Expression) {
6072 if (Record[Index++]) // bool InfoHasSameExpr.
6073 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6074 }
6075 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6076 Record, Index));
6077}
6078
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006079const ASTTemplateArgumentListInfo*
6080ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6081 const RecordData &Record,
6082 unsigned &Index) {
6083 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6084 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6085 unsigned NumArgsAsWritten = Record[Index++];
6086 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6087 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6088 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6089 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6090}
6091
Guy Benyei11169dd2012-12-18 14:30:41 +00006092Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6093 return GetDecl(ID);
6094}
6095
Richard Smith50895422015-01-31 03:04:55 +00006096template<typename TemplateSpecializationDecl>
6097static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6098 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6099 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6100}
6101
Richard Smith053f6c62014-05-16 23:01:30 +00006102void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006103 if (NumCurrentElementsDeserializing) {
6104 // We arrange to not care about the complete redeclaration chain while we're
6105 // deserializing. Just remember that the AST has marked this one as complete
6106 // but that it's not actually complete yet, so we know we still need to
6107 // complete it later.
6108 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6109 return;
6110 }
6111
Richard Smith053f6c62014-05-16 23:01:30 +00006112 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6113
Richard Smith053f6c62014-05-16 23:01:30 +00006114 // If this is a named declaration, complete it by looking it up
6115 // within its context.
6116 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006117 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006118 // all mergeable entities within it.
6119 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6120 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6121 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6122 auto *II = Name.getAsIdentifierInfo();
6123 if (isa<TranslationUnitDecl>(DC) && II) {
6124 // Outside of C++, we don't have a lookup table for the TU, so update
6125 // the identifier instead. In C++, either way should work fine.
6126 if (II->isOutOfDate())
6127 updateOutOfDateIdentifier(*II);
6128 } else
6129 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006130 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6131 // FIXME: It'd be nice to do something a bit more targeted here.
6132 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00006133 }
6134 }
Richard Smith50895422015-01-31 03:04:55 +00006135
6136 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6137 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6138 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6139 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6140 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6141 if (auto *Template = FD->getPrimaryTemplate())
6142 Template->LoadLazySpecializations();
6143 }
Richard Smith053f6c62014-05-16 23:01:30 +00006144}
6145
Richard Smithc2bb8182015-03-24 06:36:48 +00006146uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
6147 const RecordData &Record,
6148 unsigned &Idx) {
6149 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
6150 Error("malformed AST file: missing C++ ctor initializers");
6151 return 0;
6152 }
6153
6154 unsigned LocalID = Record[Idx++];
6155 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6156}
6157
6158CXXCtorInitializer **
6159ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6160 RecordLocation Loc = getLocalBitOffset(Offset);
6161 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6162 SavedStreamPosition SavedPosition(Cursor);
6163 Cursor.JumpToBit(Loc.Offset);
6164 ReadingKindTracker ReadingKind(Read_Decl, *this);
6165
6166 RecordData Record;
6167 unsigned Code = Cursor.ReadCode();
6168 unsigned RecCode = Cursor.readRecord(Code, Record);
6169 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6170 Error("malformed AST file: missing C++ ctor initializers");
6171 return nullptr;
6172 }
6173
6174 unsigned Idx = 0;
6175 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6176}
6177
Richard Smithcd45dbc2014-04-19 03:48:30 +00006178uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6179 const RecordData &Record,
6180 unsigned &Idx) {
6181 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6182 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006183 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006184 }
6185
Guy Benyei11169dd2012-12-18 14:30:41 +00006186 unsigned LocalID = Record[Idx++];
6187 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6188}
6189
6190CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6191 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006192 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006193 SavedStreamPosition SavedPosition(Cursor);
6194 Cursor.JumpToBit(Loc.Offset);
6195 ReadingKindTracker ReadingKind(Read_Decl, *this);
6196 RecordData Record;
6197 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006198 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006199 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006200 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006201 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006202 }
6203
6204 unsigned Idx = 0;
6205 unsigned NumBases = Record[Idx++];
6206 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6207 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6208 for (unsigned I = 0; I != NumBases; ++I)
6209 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6210 return Bases;
6211}
6212
6213serialization::DeclID
6214ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6215 if (LocalID < NUM_PREDEF_DECL_IDS)
6216 return LocalID;
6217
6218 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6219 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6220 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6221
6222 return LocalID + I->second;
6223}
6224
6225bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6226 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006227 // Predefined decls aren't from any module.
6228 if (ID < NUM_PREDEF_DECL_IDS)
6229 return false;
6230
Guy Benyei11169dd2012-12-18 14:30:41 +00006231 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6232 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6233 return &M == I->second;
6234}
6235
Douglas Gregor9f782892013-01-21 15:25:38 +00006236ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006237 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006238 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006239 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6240 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6241 return I->second;
6242}
6243
6244SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6245 if (ID < NUM_PREDEF_DECL_IDS)
6246 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006247
Guy Benyei11169dd2012-12-18 14:30:41 +00006248 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6249
6250 if (Index > DeclsLoaded.size()) {
6251 Error("declaration ID out-of-range for AST file");
6252 return SourceLocation();
6253 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006254
Guy Benyei11169dd2012-12-18 14:30:41 +00006255 if (Decl *D = DeclsLoaded[Index])
6256 return D->getLocation();
6257
6258 unsigned RawLocation = 0;
6259 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6260 return ReadSourceLocation(*Rec.F, RawLocation);
6261}
6262
Richard Smithfe620d22015-03-05 23:24:12 +00006263static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6264 switch (ID) {
6265 case PREDEF_DECL_NULL_ID:
6266 return nullptr;
6267
6268 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6269 return Context.getTranslationUnitDecl();
6270
6271 case PREDEF_DECL_OBJC_ID_ID:
6272 return Context.getObjCIdDecl();
6273
6274 case PREDEF_DECL_OBJC_SEL_ID:
6275 return Context.getObjCSelDecl();
6276
6277 case PREDEF_DECL_OBJC_CLASS_ID:
6278 return Context.getObjCClassDecl();
6279
6280 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6281 return Context.getObjCProtocolDecl();
6282
6283 case PREDEF_DECL_INT_128_ID:
6284 return Context.getInt128Decl();
6285
6286 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6287 return Context.getUInt128Decl();
6288
6289 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6290 return Context.getObjCInstanceTypeDecl();
6291
6292 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6293 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006294
6295 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6296 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006297 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006298 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006299}
6300
Richard Smithcd45dbc2014-04-19 03:48:30 +00006301Decl *ASTReader::GetExistingDecl(DeclID ID) {
6302 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006303 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6304 if (D) {
6305 // Track that we have merged the declaration with ID \p ID into the
6306 // pre-existing predefined declaration \p D.
6307 auto &Merged = MergedDecls[D->getCanonicalDecl()];
6308 if (Merged.empty())
6309 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006310 }
Richard Smithfe620d22015-03-05 23:24:12 +00006311 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006312 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006313
Guy Benyei11169dd2012-12-18 14:30:41 +00006314 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6315
6316 if (Index >= DeclsLoaded.size()) {
6317 assert(0 && "declaration ID out-of-range for AST file");
6318 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006319 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006320 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006321
6322 return DeclsLoaded[Index];
6323}
6324
6325Decl *ASTReader::GetDecl(DeclID ID) {
6326 if (ID < NUM_PREDEF_DECL_IDS)
6327 return GetExistingDecl(ID);
6328
6329 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6330
6331 if (Index >= DeclsLoaded.size()) {
6332 assert(0 && "declaration ID out-of-range for AST file");
6333 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006334 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006335 }
6336
Guy Benyei11169dd2012-12-18 14:30:41 +00006337 if (!DeclsLoaded[Index]) {
6338 ReadDeclRecord(ID);
6339 if (DeserializationListener)
6340 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6341 }
6342
6343 return DeclsLoaded[Index];
6344}
6345
6346DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6347 DeclID GlobalID) {
6348 if (GlobalID < NUM_PREDEF_DECL_IDS)
6349 return GlobalID;
6350
6351 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6352 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6353 ModuleFile *Owner = I->second;
6354
6355 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6356 = M.GlobalToLocalDeclIDs.find(Owner);
6357 if (Pos == M.GlobalToLocalDeclIDs.end())
6358 return 0;
6359
6360 return GlobalID - Owner->BaseDeclID + Pos->second;
6361}
6362
6363serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6364 const RecordData &Record,
6365 unsigned &Idx) {
6366 if (Idx >= Record.size()) {
6367 Error("Corrupted AST file");
6368 return 0;
6369 }
6370
6371 return getGlobalDeclID(F, Record[Idx++]);
6372}
6373
6374/// \brief Resolve the offset of a statement into a statement.
6375///
6376/// This operation will read a new statement from the external
6377/// source each time it is called, and is meant to be used via a
6378/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6379Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6380 // Switch case IDs are per Decl.
6381 ClearSwitchCaseIDs();
6382
6383 // Offset here is a global offset across the entire chain.
6384 RecordLocation Loc = getLocalBitOffset(Offset);
6385 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6386 return ReadStmtFromStream(*Loc.F);
6387}
6388
6389namespace {
6390 class FindExternalLexicalDeclsVisitor {
6391 ASTReader &Reader;
6392 const DeclContext *DC;
6393 bool (*isKindWeWant)(Decl::Kind);
6394
6395 SmallVectorImpl<Decl*> &Decls;
6396 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6397
6398 public:
6399 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6400 bool (*isKindWeWant)(Decl::Kind),
6401 SmallVectorImpl<Decl*> &Decls)
6402 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6403 {
6404 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6405 PredefsVisited[I] = false;
6406 }
6407
6408 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6409 if (Preorder)
6410 return false;
6411
6412 FindExternalLexicalDeclsVisitor *This
6413 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6414
6415 ModuleFile::DeclContextInfosMap::iterator Info
6416 = M.DeclContextInfos.find(This->DC);
6417 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6418 return false;
6419
6420 // Load all of the declaration IDs
6421 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6422 *IDE = ID + Info->second.NumLexicalDecls;
6423 ID != IDE; ++ID) {
6424 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6425 continue;
6426
6427 // Don't add predefined declarations to the lexical context more
6428 // than once.
6429 if (ID->second < NUM_PREDEF_DECL_IDS) {
6430 if (This->PredefsVisited[ID->second])
6431 continue;
6432
6433 This->PredefsVisited[ID->second] = true;
6434 }
6435
6436 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6437 if (!This->DC->isDeclInLexicalTraversal(D))
6438 This->Decls.push_back(D);
6439 }
6440 }
6441
6442 return false;
6443 }
6444 };
6445}
6446
6447ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6448 bool (*isKindWeWant)(Decl::Kind),
6449 SmallVectorImpl<Decl*> &Decls) {
6450 // There might be lexical decls in multiple modules, for the TU at
6451 // least. Walk all of the modules in the order they were loaded.
6452 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6453 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6454 ++NumLexicalDeclContextsRead;
6455 return ELR_Success;
6456}
6457
6458namespace {
6459
6460class DeclIDComp {
6461 ASTReader &Reader;
6462 ModuleFile &Mod;
6463
6464public:
6465 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6466
6467 bool operator()(LocalDeclID L, LocalDeclID R) const {
6468 SourceLocation LHS = getLocation(L);
6469 SourceLocation RHS = getLocation(R);
6470 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6471 }
6472
6473 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6474 SourceLocation RHS = getLocation(R);
6475 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6476 }
6477
6478 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6479 SourceLocation LHS = getLocation(L);
6480 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6481 }
6482
6483 SourceLocation getLocation(LocalDeclID ID) const {
6484 return Reader.getSourceManager().getFileLoc(
6485 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6486 }
6487};
6488
6489}
6490
6491void ASTReader::FindFileRegionDecls(FileID File,
6492 unsigned Offset, unsigned Length,
6493 SmallVectorImpl<Decl *> &Decls) {
6494 SourceManager &SM = getSourceManager();
6495
6496 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6497 if (I == FileDeclIDs.end())
6498 return;
6499
6500 FileDeclsInfo &DInfo = I->second;
6501 if (DInfo.Decls.empty())
6502 return;
6503
6504 SourceLocation
6505 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6506 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6507
6508 DeclIDComp DIDComp(*this, *DInfo.Mod);
6509 ArrayRef<serialization::LocalDeclID>::iterator
6510 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6511 BeginLoc, DIDComp);
6512 if (BeginIt != DInfo.Decls.begin())
6513 --BeginIt;
6514
6515 // If we are pointing at a top-level decl inside an objc container, we need
6516 // to backtrack until we find it otherwise we will fail to report that the
6517 // region overlaps with an objc container.
6518 while (BeginIt != DInfo.Decls.begin() &&
6519 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6520 ->isTopLevelDeclInObjCContainer())
6521 --BeginIt;
6522
6523 ArrayRef<serialization::LocalDeclID>::iterator
6524 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6525 EndLoc, DIDComp);
6526 if (EndIt != DInfo.Decls.end())
6527 ++EndIt;
6528
6529 for (ArrayRef<serialization::LocalDeclID>::iterator
6530 DIt = BeginIt; DIt != EndIt; ++DIt)
6531 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6532}
6533
6534namespace {
6535 /// \brief ModuleFile visitor used to perform name lookup into a
6536 /// declaration context.
6537 class DeclContextNameLookupVisitor {
6538 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006539 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006540 DeclarationName Name;
6541 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006542 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006543
6544 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006545 DeclContextNameLookupVisitor(ASTReader &Reader,
6546 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006547 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006548 SmallVectorImpl<NamedDecl *> &Decls,
6549 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
6550 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls),
6551 DeclSet(DeclSet) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006552
6553 static bool visit(ModuleFile &M, void *UserData) {
6554 DeclContextNameLookupVisitor *This
6555 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6556
6557 // Check whether we have any visible declaration information for
6558 // this context in this module.
6559 ModuleFile::DeclContextInfosMap::iterator Info;
6560 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006561 for (auto *DC : This->Contexts) {
6562 Info = M.DeclContextInfos.find(DC);
6563 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006564 Info->second.NameLookupTableData) {
6565 FoundInfo = true;
6566 break;
6567 }
6568 }
6569
6570 if (!FoundInfo)
6571 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006572
Guy Benyei11169dd2012-12-18 14:30:41 +00006573 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006574 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006575 Info->second.NameLookupTableData;
6576 ASTDeclContextNameLookupTable::iterator Pos
6577 = LookupTable->find(This->Name);
6578 if (Pos == LookupTable->end())
6579 return false;
6580
6581 bool FoundAnything = false;
6582 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6583 for (; Data.first != Data.second; ++Data.first) {
6584 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6585 if (!ND)
6586 continue;
6587
6588 if (ND->getDeclName() != This->Name) {
6589 // A name might be null because the decl's redeclarable part is
6590 // currently read before reading its name. The lookup is triggered by
6591 // building that decl (likely indirectly), and so it is later in the
6592 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006593 // FIXME: This should not happen; deserializing declarations should
6594 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006595 continue;
6596 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006597
Guy Benyei11169dd2012-12-18 14:30:41 +00006598 // Record this declaration.
6599 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006600 if (This->DeclSet.insert(ND).second)
6601 This->Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006602 }
6603
6604 return FoundAnything;
6605 }
6606 };
6607}
6608
Douglas Gregor9f782892013-01-21 15:25:38 +00006609/// \brief Retrieve the "definitive" module file for the definition of the
6610/// given declaration context, if there is one.
6611///
6612/// The "definitive" module file is the only place where we need to look to
6613/// find information about the declarations within the given declaration
6614/// context. For example, C++ and Objective-C classes, C structs/unions, and
6615/// Objective-C protocols, categories, and extensions are all defined in a
6616/// single place in the source code, so they have definitive module files
6617/// associated with them. C++ namespaces, on the other hand, can have
6618/// definitions in multiple different module files.
6619///
6620/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6621/// NDEBUG checking.
6622static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6623 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006624 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6625 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006626
Craig Toppera13603a2014-05-22 05:54:18 +00006627 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006628}
6629
Richard Smith9ce12e32013-02-07 03:30:24 +00006630bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006631ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6632 DeclarationName Name) {
6633 assert(DC->hasExternalVisibleStorage() &&
6634 "DeclContext has no visible decls in storage");
6635 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006636 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006637
Richard Smith8c913ec2014-08-14 02:21:01 +00006638 Deserializing LookupResults(this);
6639
Guy Benyei11169dd2012-12-18 14:30:41 +00006640 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006641 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006642
Guy Benyei11169dd2012-12-18 14:30:41 +00006643 // Compute the declaration contexts we need to look into. Multiple such
6644 // declaration contexts occur when two declaration contexts from disjoint
6645 // modules get merged, e.g., when two namespaces with the same name are
6646 // independently defined in separate modules.
6647 SmallVector<const DeclContext *, 2> Contexts;
6648 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006649
Guy Benyei11169dd2012-12-18 14:30:41 +00006650 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006651 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006652 if (Merged != MergedDecls.end()) {
6653 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6654 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6655 }
6656 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006657
6658 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
Richard Smith52874ec2015-02-13 20:17:14 +00006659 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006660
6661 // If we can definitively determine which module file to look into,
6662 // only look there. Otherwise, look in all module files.
6663 ModuleFile *Definitive;
6664 if (Contexts.size() == 1 &&
6665 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6666 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6667 } else {
6668 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6669 }
6670 };
6671
6672 LookUpInContexts(Contexts);
6673
6674 // If this might be an implicit special member function, then also search
6675 // all merged definitions of the surrounding class. We need to search them
6676 // individually, because finding an entity in one of them doesn't imply that
6677 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006678 if (isa<CXXRecordDecl>(DC)) {
Richard Smith02793752015-03-27 21:16:39 +00006679 auto Merged = MergedLookups.find(DC);
6680 if (Merged != MergedLookups.end()) {
6681 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6682 const DeclContext *Context = Merged->second[I];
6683 LookUpInContexts(Context);
6684 // We might have just added some more merged lookups. If so, our
6685 // iterator is now invalid, so grab a fresh one before continuing.
6686 Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006687 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006688 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006689 }
6690
Guy Benyei11169dd2012-12-18 14:30:41 +00006691 ++NumVisibleDeclContextsRead;
6692 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006693 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006694}
6695
6696namespace {
6697 /// \brief ModuleFile visitor used to retrieve all visible names in a
6698 /// declaration context.
6699 class DeclContextAllNamesVisitor {
6700 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006701 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006702 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006703 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006704 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006705
6706 public:
6707 DeclContextAllNamesVisitor(ASTReader &Reader,
6708 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006709 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006710 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006711
6712 static bool visit(ModuleFile &M, void *UserData) {
6713 DeclContextAllNamesVisitor *This
6714 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6715
6716 // Check whether we have any visible declaration information for
6717 // this context in this module.
6718 ModuleFile::DeclContextInfosMap::iterator Info;
6719 bool FoundInfo = false;
6720 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6721 Info = M.DeclContextInfos.find(This->Contexts[I]);
6722 if (Info != M.DeclContextInfos.end() &&
6723 Info->second.NameLookupTableData) {
6724 FoundInfo = true;
6725 break;
6726 }
6727 }
6728
6729 if (!FoundInfo)
6730 return false;
6731
Richard Smith52e3fba2014-03-11 07:17:35 +00006732 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006733 Info->second.NameLookupTableData;
6734 bool FoundAnything = false;
6735 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006736 I = LookupTable->data_begin(), E = LookupTable->data_end();
6737 I != E;
6738 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006739 ASTDeclContextNameLookupTrait::data_type Data = *I;
6740 for (; Data.first != Data.second; ++Data.first) {
6741 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6742 *Data.first);
6743 if (!ND)
6744 continue;
6745
6746 // Record this declaration.
6747 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006748 if (This->DeclSet.insert(ND).second)
6749 This->Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006750 }
6751 }
6752
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006753 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006754 }
6755 };
6756}
6757
6758void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6759 if (!DC->hasExternalVisibleStorage())
6760 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006761 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006762
6763 // Compute the declaration contexts we need to look into. Multiple such
6764 // declaration contexts occur when two declaration contexts from disjoint
6765 // modules get merged, e.g., when two namespaces with the same name are
6766 // independently defined in separate modules.
6767 SmallVector<const DeclContext *, 2> Contexts;
6768 Contexts.push_back(DC);
6769
6770 if (DC->isNamespace()) {
6771 MergedDeclsMap::iterator Merged
6772 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6773 if (Merged != MergedDecls.end()) {
6774 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6775 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6776 }
6777 }
6778
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006779 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6780 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006781 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6782 ++NumVisibleDeclContextsRead;
6783
Craig Topper79be4cd2013-07-05 04:33:53 +00006784 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006785 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6786 }
6787 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6788}
6789
6790/// \brief Under non-PCH compilation the consumer receives the objc methods
6791/// before receiving the implementation, and codegen depends on this.
6792/// We simulate this by deserializing and passing to consumer the methods of the
6793/// implementation before passing the deserialized implementation decl.
6794static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6795 ASTConsumer *Consumer) {
6796 assert(ImplD && Consumer);
6797
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006798 for (auto *I : ImplD->methods())
6799 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006800
6801 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6802}
6803
6804void ASTReader::PassInterestingDeclsToConsumer() {
6805 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006806
6807 if (PassingDeclsToConsumer)
6808 return;
6809
6810 // Guard variable to avoid recursively redoing the process of passing
6811 // decls to consumer.
6812 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6813 true);
6814
Richard Smith9e2341d2015-03-23 03:25:59 +00006815 // Ensure that we've loaded all potentially-interesting declarations
6816 // that need to be eagerly loaded.
6817 for (auto ID : EagerlyDeserializedDecls)
6818 GetDecl(ID);
6819 EagerlyDeserializedDecls.clear();
6820
Guy Benyei11169dd2012-12-18 14:30:41 +00006821 while (!InterestingDecls.empty()) {
6822 Decl *D = InterestingDecls.front();
6823 InterestingDecls.pop_front();
6824
6825 PassInterestingDeclToConsumer(D);
6826 }
6827}
6828
6829void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6830 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6831 PassObjCImplDeclToConsumer(ImplD, Consumer);
6832 else
6833 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6834}
6835
6836void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6837 this->Consumer = Consumer;
6838
Richard Smith9e2341d2015-03-23 03:25:59 +00006839 if (Consumer)
6840 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006841
6842 if (DeserializationListener)
6843 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006844}
6845
6846void ASTReader::PrintStats() {
6847 std::fprintf(stderr, "*** AST File Statistics:\n");
6848
6849 unsigned NumTypesLoaded
6850 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6851 QualType());
6852 unsigned NumDeclsLoaded
6853 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006854 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006855 unsigned NumIdentifiersLoaded
6856 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6857 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006858 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006859 unsigned NumMacrosLoaded
6860 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6861 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006862 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006863 unsigned NumSelectorsLoaded
6864 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6865 SelectorsLoaded.end(),
6866 Selector());
6867
6868 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6869 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6870 NumSLocEntriesRead, TotalNumSLocEntries,
6871 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6872 if (!TypesLoaded.empty())
6873 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6874 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6875 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6876 if (!DeclsLoaded.empty())
6877 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6878 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6879 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6880 if (!IdentifiersLoaded.empty())
6881 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6882 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6883 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6884 if (!MacrosLoaded.empty())
6885 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6886 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6887 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6888 if (!SelectorsLoaded.empty())
6889 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6890 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6891 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6892 if (TotalNumStatements)
6893 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6894 NumStatementsRead, TotalNumStatements,
6895 ((float)NumStatementsRead/TotalNumStatements * 100));
6896 if (TotalNumMacros)
6897 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6898 NumMacrosRead, TotalNumMacros,
6899 ((float)NumMacrosRead/TotalNumMacros * 100));
6900 if (TotalLexicalDeclContexts)
6901 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6902 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6903 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6904 * 100));
6905 if (TotalVisibleDeclContexts)
6906 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6907 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6908 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6909 * 100));
6910 if (TotalNumMethodPoolEntries) {
6911 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6912 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6913 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6914 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006915 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006916 if (NumMethodPoolLookups) {
6917 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6918 NumMethodPoolHits, NumMethodPoolLookups,
6919 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6920 }
6921 if (NumMethodPoolTableLookups) {
6922 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6923 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6924 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6925 * 100.0));
6926 }
6927
Douglas Gregor00a50f72013-01-25 00:38:33 +00006928 if (NumIdentifierLookupHits) {
6929 std::fprintf(stderr,
6930 " %u / %u identifier table lookups succeeded (%f%%)\n",
6931 NumIdentifierLookupHits, NumIdentifierLookups,
6932 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6933 }
6934
Douglas Gregore060e572013-01-25 01:03:03 +00006935 if (GlobalIndex) {
6936 std::fprintf(stderr, "\n");
6937 GlobalIndex->printStats();
6938 }
6939
Guy Benyei11169dd2012-12-18 14:30:41 +00006940 std::fprintf(stderr, "\n");
6941 dump();
6942 std::fprintf(stderr, "\n");
6943}
6944
6945template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6946static void
6947dumpModuleIDMap(StringRef Name,
6948 const ContinuousRangeMap<Key, ModuleFile *,
6949 InitialCapacity> &Map) {
6950 if (Map.begin() == Map.end())
6951 return;
6952
6953 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6954 llvm::errs() << Name << ":\n";
6955 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6956 I != IEnd; ++I) {
6957 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6958 << "\n";
6959 }
6960}
6961
6962void ASTReader::dump() {
6963 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6964 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6965 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6966 dumpModuleIDMap("Global type map", GlobalTypeMap);
6967 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6968 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6969 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6970 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6971 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6972 dumpModuleIDMap("Global preprocessed entity map",
6973 GlobalPreprocessedEntityMap);
6974
6975 llvm::errs() << "\n*** PCH/Modules Loaded:";
6976 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6977 MEnd = ModuleMgr.end();
6978 M != MEnd; ++M)
6979 (*M)->dump();
6980}
6981
6982/// Return the amount of memory used by memory buffers, breaking down
6983/// by heap-backed versus mmap'ed memory.
6984void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6985 for (ModuleConstIterator I = ModuleMgr.begin(),
6986 E = ModuleMgr.end(); I != E; ++I) {
6987 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6988 size_t bytes = buf->getBufferSize();
6989 switch (buf->getBufferKind()) {
6990 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6991 sizes.malloc_bytes += bytes;
6992 break;
6993 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6994 sizes.mmap_bytes += bytes;
6995 break;
6996 }
6997 }
6998 }
6999}
7000
7001void ASTReader::InitializeSema(Sema &S) {
7002 SemaObj = &S;
7003 S.addExternalSource(this);
7004
7005 // Makes sure any declarations that were deserialized "too early"
7006 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007007 for (uint64_t ID : PreloadedDeclIDs) {
7008 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7009 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007010 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007011 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007012
Richard Smith3d8e97e2013-10-18 06:54:39 +00007013 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007014 if (!FPPragmaOptions.empty()) {
7015 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7016 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7017 }
7018
Richard Smith3d8e97e2013-10-18 06:54:39 +00007019 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007020 if (!OpenCLExtensions.empty()) {
7021 unsigned I = 0;
7022#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
7023#include "clang/Basic/OpenCLExtensions.def"
7024
7025 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
7026 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00007027
7028 UpdateSema();
7029}
7030
7031void ASTReader::UpdateSema() {
7032 assert(SemaObj && "no Sema to update");
7033
7034 // Load the offsets of the declarations that Sema references.
7035 // They will be lazily deserialized when needed.
7036 if (!SemaDeclRefs.empty()) {
7037 assert(SemaDeclRefs.size() % 2 == 0);
7038 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
7039 if (!SemaObj->StdNamespace)
7040 SemaObj->StdNamespace = SemaDeclRefs[I];
7041 if (!SemaObj->StdBadAlloc)
7042 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
7043 }
7044 SemaDeclRefs.clear();
7045 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007046
7047 // Update the state of 'pragma clang optimize'. Use the same API as if we had
7048 // encountered the pragma in the source.
7049 if(OptimizeOffPragmaLocation.isValid())
7050 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00007051}
7052
7053IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
7054 // Note that we are loading an identifier.
7055 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007056 StringRef Name(NameStart, NameEnd - NameStart);
7057
7058 // If there is a global index, look there first to determine which modules
7059 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00007060 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00007061 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00007062 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00007063 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7064 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00007065 }
7066 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00007067 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007068 NumIdentifierLookups,
7069 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00007070 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007071 IdentifierInfo *II = Visitor.getIdentifierInfo();
7072 markIdentifierUpToDate(II);
7073 return II;
7074}
7075
7076namespace clang {
7077 /// \brief An identifier-lookup iterator that enumerates all of the
7078 /// identifiers stored within a set of AST files.
7079 class ASTIdentifierIterator : public IdentifierIterator {
7080 /// \brief The AST reader whose identifiers are being enumerated.
7081 const ASTReader &Reader;
7082
7083 /// \brief The current index into the chain of AST files stored in
7084 /// the AST reader.
7085 unsigned Index;
7086
7087 /// \brief The current position within the identifier lookup table
7088 /// of the current AST file.
7089 ASTIdentifierLookupTable::key_iterator Current;
7090
7091 /// \brief The end position within the identifier lookup table of
7092 /// the current AST file.
7093 ASTIdentifierLookupTable::key_iterator End;
7094
7095 public:
7096 explicit ASTIdentifierIterator(const ASTReader &Reader);
7097
Craig Topper3e89dfe2014-03-13 02:13:41 +00007098 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007099 };
7100}
7101
7102ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7103 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7104 ASTIdentifierLookupTable *IdTable
7105 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7106 Current = IdTable->key_begin();
7107 End = IdTable->key_end();
7108}
7109
7110StringRef ASTIdentifierIterator::Next() {
7111 while (Current == End) {
7112 // If we have exhausted all of our AST files, we're done.
7113 if (Index == 0)
7114 return StringRef();
7115
7116 --Index;
7117 ASTIdentifierLookupTable *IdTable
7118 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7119 IdentifierLookupTable;
7120 Current = IdTable->key_begin();
7121 End = IdTable->key_end();
7122 }
7123
7124 // We have any identifiers remaining in the current AST file; return
7125 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007126 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007127 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007128 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007129}
7130
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007131IdentifierIterator *ASTReader::getIdentifiers() {
7132 if (!loadGlobalIndex())
7133 return GlobalIndex->createIdentifierIterator();
7134
Guy Benyei11169dd2012-12-18 14:30:41 +00007135 return new ASTIdentifierIterator(*this);
7136}
7137
7138namespace clang { namespace serialization {
7139 class ReadMethodPoolVisitor {
7140 ASTReader &Reader;
7141 Selector Sel;
7142 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007143 unsigned InstanceBits;
7144 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007145 bool InstanceHasMoreThanOneDecl;
7146 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007147 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7148 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007149
7150 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007151 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007152 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007153 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007154 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7155 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007156
Guy Benyei11169dd2012-12-18 14:30:41 +00007157 static bool visit(ModuleFile &M, void *UserData) {
7158 ReadMethodPoolVisitor *This
7159 = static_cast<ReadMethodPoolVisitor *>(UserData);
7160
7161 if (!M.SelectorLookupTable)
7162 return false;
7163
7164 // If we've already searched this module file, skip it now.
7165 if (M.Generation <= This->PriorGeneration)
7166 return true;
7167
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007168 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007169 ASTSelectorLookupTable *PoolTable
7170 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7171 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
7172 if (Pos == PoolTable->end())
7173 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007174
7175 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007176 ++This->Reader.NumSelectorsRead;
7177 // FIXME: Not quite happy with the statistics here. We probably should
7178 // disable this tracking when called via LoadSelector.
7179 // Also, should entries without methods count as misses?
7180 ++This->Reader.NumMethodPoolEntriesRead;
7181 ASTSelectorLookupTrait::data_type Data = *Pos;
7182 if (This->Reader.DeserializationListener)
7183 This->Reader.DeserializationListener->SelectorRead(Data.ID,
7184 This->Sel);
7185
7186 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7187 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007188 This->InstanceBits = Data.InstanceBits;
7189 This->FactoryBits = Data.FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007190 This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7191 This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007192 return true;
7193 }
7194
7195 /// \brief Retrieve the instance methods found by this visitor.
7196 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7197 return InstanceMethods;
7198 }
7199
7200 /// \brief Retrieve the instance methods found by this visitor.
7201 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7202 return FactoryMethods;
7203 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007204
7205 unsigned getInstanceBits() const { return InstanceBits; }
7206 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007207 bool instanceHasMoreThanOneDecl() const {
7208 return InstanceHasMoreThanOneDecl;
7209 }
7210 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007211 };
7212} } // end namespace clang::serialization
7213
7214/// \brief Add the given set of methods to the method list.
7215static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7216 ObjCMethodList &List) {
7217 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7218 S.addMethodToGlobalList(&List, Methods[I]);
7219 }
7220}
7221
7222void ASTReader::ReadMethodPool(Selector Sel) {
7223 // Get the selector generation and update it to the current generation.
7224 unsigned &Generation = SelectorGeneration[Sel];
7225 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007226 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007227
7228 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007229 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007230 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7231 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7232
7233 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007234 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007235 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007236
7237 ++NumMethodPoolHits;
7238
Guy Benyei11169dd2012-12-18 14:30:41 +00007239 if (!getSema())
7240 return;
7241
7242 Sema &S = *getSema();
7243 Sema::GlobalMethodPool::iterator Pos
7244 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007245
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007246 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007247 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007248 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007249 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007250
7251 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7252 // when building a module we keep every method individually and may need to
7253 // update hasMoreThanOneDecl as we add the methods.
7254 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7255 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007256}
7257
7258void ASTReader::ReadKnownNamespaces(
7259 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7260 Namespaces.clear();
7261
7262 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7263 if (NamespaceDecl *Namespace
7264 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7265 Namespaces.push_back(Namespace);
7266 }
7267}
7268
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007269void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007270 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007271 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7272 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007273 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007274 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007275 Undefined.insert(std::make_pair(D, Loc));
7276 }
7277}
Nick Lewycky8334af82013-01-26 00:35:08 +00007278
Guy Benyei11169dd2012-12-18 14:30:41 +00007279void ASTReader::ReadTentativeDefinitions(
7280 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7281 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7282 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7283 if (Var)
7284 TentativeDefs.push_back(Var);
7285 }
7286 TentativeDefinitions.clear();
7287}
7288
7289void ASTReader::ReadUnusedFileScopedDecls(
7290 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7291 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7292 DeclaratorDecl *D
7293 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7294 if (D)
7295 Decls.push_back(D);
7296 }
7297 UnusedFileScopedDecls.clear();
7298}
7299
7300void ASTReader::ReadDelegatingConstructors(
7301 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7302 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7303 CXXConstructorDecl *D
7304 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7305 if (D)
7306 Decls.push_back(D);
7307 }
7308 DelegatingCtorDecls.clear();
7309}
7310
7311void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7312 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7313 TypedefNameDecl *D
7314 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7315 if (D)
7316 Decls.push_back(D);
7317 }
7318 ExtVectorDecls.clear();
7319}
7320
Nico Weber72889432014-09-06 01:25:55 +00007321void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7322 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7323 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7324 ++I) {
7325 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7326 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7327 if (D)
7328 Decls.insert(D);
7329 }
7330 UnusedLocalTypedefNameCandidates.clear();
7331}
7332
Guy Benyei11169dd2012-12-18 14:30:41 +00007333void ASTReader::ReadReferencedSelectors(
7334 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7335 if (ReferencedSelectorsData.empty())
7336 return;
7337
7338 // If there are @selector references added them to its pool. This is for
7339 // implementation of -Wselector.
7340 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7341 unsigned I = 0;
7342 while (I < DataSize) {
7343 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7344 SourceLocation SelLoc
7345 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7346 Sels.push_back(std::make_pair(Sel, SelLoc));
7347 }
7348 ReferencedSelectorsData.clear();
7349}
7350
7351void ASTReader::ReadWeakUndeclaredIdentifiers(
7352 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7353 if (WeakUndeclaredIdentifiers.empty())
7354 return;
7355
7356 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7357 IdentifierInfo *WeakId
7358 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7359 IdentifierInfo *AliasId
7360 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7361 SourceLocation Loc
7362 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7363 bool Used = WeakUndeclaredIdentifiers[I++];
7364 WeakInfo WI(AliasId, Loc);
7365 WI.setUsed(Used);
7366 WeakIDs.push_back(std::make_pair(WeakId, WI));
7367 }
7368 WeakUndeclaredIdentifiers.clear();
7369}
7370
7371void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7372 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7373 ExternalVTableUse VT;
7374 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7375 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7376 VT.DefinitionRequired = VTableUses[Idx++];
7377 VTables.push_back(VT);
7378 }
7379
7380 VTableUses.clear();
7381}
7382
7383void ASTReader::ReadPendingInstantiations(
7384 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7385 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7386 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7387 SourceLocation Loc
7388 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7389
7390 Pending.push_back(std::make_pair(D, Loc));
7391 }
7392 PendingInstantiations.clear();
7393}
7394
Richard Smithe40f2ba2013-08-07 21:41:30 +00007395void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007396 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007397 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7398 /* In loop */) {
7399 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7400
7401 LateParsedTemplate *LT = new LateParsedTemplate;
7402 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7403
7404 ModuleFile *F = getOwningModuleFile(LT->D);
7405 assert(F && "No module");
7406
7407 unsigned TokN = LateParsedTemplates[Idx++];
7408 LT->Toks.reserve(TokN);
7409 for (unsigned T = 0; T < TokN; ++T)
7410 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7411
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007412 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007413 }
7414
7415 LateParsedTemplates.clear();
7416}
7417
Guy Benyei11169dd2012-12-18 14:30:41 +00007418void ASTReader::LoadSelector(Selector Sel) {
7419 // It would be complicated to avoid reading the methods anyway. So don't.
7420 ReadMethodPool(Sel);
7421}
7422
7423void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7424 assert(ID && "Non-zero identifier ID required");
7425 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7426 IdentifiersLoaded[ID - 1] = II;
7427 if (DeserializationListener)
7428 DeserializationListener->IdentifierRead(ID, II);
7429}
7430
7431/// \brief Set the globally-visible declarations associated with the given
7432/// identifier.
7433///
7434/// If the AST reader is currently in a state where the given declaration IDs
7435/// cannot safely be resolved, they are queued until it is safe to resolve
7436/// them.
7437///
7438/// \param II an IdentifierInfo that refers to one or more globally-visible
7439/// declarations.
7440///
7441/// \param DeclIDs the set of declaration IDs with the name @p II that are
7442/// visible at global scope.
7443///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007444/// \param Decls if non-null, this vector will be populated with the set of
7445/// deserialized declarations. These declarations will not be pushed into
7446/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007447void
7448ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7449 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007450 SmallVectorImpl<Decl *> *Decls) {
7451 if (NumCurrentElementsDeserializing && !Decls) {
7452 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007453 return;
7454 }
7455
7456 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007457 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007458 // Queue this declaration so that it will be added to the
7459 // translation unit scope and identifier's declaration chain
7460 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007461 PreloadedDeclIDs.push_back(DeclIDs[I]);
7462 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007463 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007464
7465 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7466
7467 // If we're simply supposed to record the declarations, do so now.
7468 if (Decls) {
7469 Decls->push_back(D);
7470 continue;
7471 }
7472
7473 // Introduce this declaration into the translation-unit scope
7474 // and add it to the declaration chain for this identifier, so
7475 // that (unqualified) name lookup will find it.
7476 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007477 }
7478}
7479
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007480IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007481 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007482 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007483
7484 if (IdentifiersLoaded.empty()) {
7485 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007486 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007487 }
7488
7489 ID -= 1;
7490 if (!IdentifiersLoaded[ID]) {
7491 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7492 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7493 ModuleFile *M = I->second;
7494 unsigned Index = ID - M->BaseIdentifierID;
7495 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7496
7497 // All of the strings in the AST file are preceded by a 16-bit length.
7498 // Extract that 16-bit length to avoid having to execute strlen().
7499 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7500 // unsigned integers. This is important to avoid integer overflow when
7501 // we cast them to 'unsigned'.
7502 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7503 unsigned StrLen = (((unsigned) StrLenPtr[0])
7504 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007505 IdentifiersLoaded[ID]
7506 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007507 if (DeserializationListener)
7508 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7509 }
7510
7511 return IdentifiersLoaded[ID];
7512}
7513
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007514IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7515 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007516}
7517
7518IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7519 if (LocalID < NUM_PREDEF_IDENT_IDS)
7520 return LocalID;
7521
7522 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7523 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7524 assert(I != M.IdentifierRemap.end()
7525 && "Invalid index into identifier index remap");
7526
7527 return LocalID + I->second;
7528}
7529
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007530MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007531 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007532 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007533
7534 if (MacrosLoaded.empty()) {
7535 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007536 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007537 }
7538
7539 ID -= NUM_PREDEF_MACRO_IDS;
7540 if (!MacrosLoaded[ID]) {
7541 GlobalMacroMapType::iterator I
7542 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7543 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7544 ModuleFile *M = I->second;
7545 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007546 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7547
7548 if (DeserializationListener)
7549 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7550 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007551 }
7552
7553 return MacrosLoaded[ID];
7554}
7555
7556MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7557 if (LocalID < NUM_PREDEF_MACRO_IDS)
7558 return LocalID;
7559
7560 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7561 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7562 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7563
7564 return LocalID + I->second;
7565}
7566
7567serialization::SubmoduleID
7568ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7569 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7570 return LocalID;
7571
7572 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7573 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7574 assert(I != M.SubmoduleRemap.end()
7575 && "Invalid index into submodule index remap");
7576
7577 return LocalID + I->second;
7578}
7579
7580Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7581 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7582 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007583 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007584 }
7585
7586 if (GlobalID > SubmodulesLoaded.size()) {
7587 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007588 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007589 }
7590
7591 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7592}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007593
7594Module *ASTReader::getModule(unsigned ID) {
7595 return getSubmodule(ID);
7596}
7597
Guy Benyei11169dd2012-12-18 14:30:41 +00007598Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7599 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7600}
7601
7602Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7603 if (ID == 0)
7604 return Selector();
7605
7606 if (ID > SelectorsLoaded.size()) {
7607 Error("selector ID out of range in AST file");
7608 return Selector();
7609 }
7610
Craig Toppera13603a2014-05-22 05:54:18 +00007611 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007612 // Load this selector from the selector table.
7613 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7614 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7615 ModuleFile &M = *I->second;
7616 ASTSelectorLookupTrait Trait(*this, M);
7617 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7618 SelectorsLoaded[ID - 1] =
7619 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7620 if (DeserializationListener)
7621 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7622 }
7623
7624 return SelectorsLoaded[ID - 1];
7625}
7626
7627Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7628 return DecodeSelector(ID);
7629}
7630
7631uint32_t ASTReader::GetNumExternalSelectors() {
7632 // ID 0 (the null selector) is considered an external selector.
7633 return getTotalNumSelectors() + 1;
7634}
7635
7636serialization::SelectorID
7637ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7638 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7639 return LocalID;
7640
7641 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7642 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7643 assert(I != M.SelectorRemap.end()
7644 && "Invalid index into selector index remap");
7645
7646 return LocalID + I->second;
7647}
7648
7649DeclarationName
7650ASTReader::ReadDeclarationName(ModuleFile &F,
7651 const RecordData &Record, unsigned &Idx) {
7652 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7653 switch (Kind) {
7654 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007655 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007656
7657 case DeclarationName::ObjCZeroArgSelector:
7658 case DeclarationName::ObjCOneArgSelector:
7659 case DeclarationName::ObjCMultiArgSelector:
7660 return DeclarationName(ReadSelector(F, Record, Idx));
7661
7662 case DeclarationName::CXXConstructorName:
7663 return Context.DeclarationNames.getCXXConstructorName(
7664 Context.getCanonicalType(readType(F, Record, Idx)));
7665
7666 case DeclarationName::CXXDestructorName:
7667 return Context.DeclarationNames.getCXXDestructorName(
7668 Context.getCanonicalType(readType(F, Record, Idx)));
7669
7670 case DeclarationName::CXXConversionFunctionName:
7671 return Context.DeclarationNames.getCXXConversionFunctionName(
7672 Context.getCanonicalType(readType(F, Record, Idx)));
7673
7674 case DeclarationName::CXXOperatorName:
7675 return Context.DeclarationNames.getCXXOperatorName(
7676 (OverloadedOperatorKind)Record[Idx++]);
7677
7678 case DeclarationName::CXXLiteralOperatorName:
7679 return Context.DeclarationNames.getCXXLiteralOperatorName(
7680 GetIdentifierInfo(F, Record, Idx));
7681
7682 case DeclarationName::CXXUsingDirective:
7683 return DeclarationName::getUsingDirectiveName();
7684 }
7685
7686 llvm_unreachable("Invalid NameKind!");
7687}
7688
7689void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7690 DeclarationNameLoc &DNLoc,
7691 DeclarationName Name,
7692 const RecordData &Record, unsigned &Idx) {
7693 switch (Name.getNameKind()) {
7694 case DeclarationName::CXXConstructorName:
7695 case DeclarationName::CXXDestructorName:
7696 case DeclarationName::CXXConversionFunctionName:
7697 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7698 break;
7699
7700 case DeclarationName::CXXOperatorName:
7701 DNLoc.CXXOperatorName.BeginOpNameLoc
7702 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7703 DNLoc.CXXOperatorName.EndOpNameLoc
7704 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7705 break;
7706
7707 case DeclarationName::CXXLiteralOperatorName:
7708 DNLoc.CXXLiteralOperatorName.OpNameLoc
7709 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7710 break;
7711
7712 case DeclarationName::Identifier:
7713 case DeclarationName::ObjCZeroArgSelector:
7714 case DeclarationName::ObjCOneArgSelector:
7715 case DeclarationName::ObjCMultiArgSelector:
7716 case DeclarationName::CXXUsingDirective:
7717 break;
7718 }
7719}
7720
7721void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7722 DeclarationNameInfo &NameInfo,
7723 const RecordData &Record, unsigned &Idx) {
7724 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7725 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7726 DeclarationNameLoc DNLoc;
7727 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7728 NameInfo.setInfo(DNLoc);
7729}
7730
7731void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7732 const RecordData &Record, unsigned &Idx) {
7733 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7734 unsigned NumTPLists = Record[Idx++];
7735 Info.NumTemplParamLists = NumTPLists;
7736 if (NumTPLists) {
7737 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7738 for (unsigned i=0; i != NumTPLists; ++i)
7739 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7740 }
7741}
7742
7743TemplateName
7744ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7745 unsigned &Idx) {
7746 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7747 switch (Kind) {
7748 case TemplateName::Template:
7749 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7750
7751 case TemplateName::OverloadedTemplate: {
7752 unsigned size = Record[Idx++];
7753 UnresolvedSet<8> Decls;
7754 while (size--)
7755 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7756
7757 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7758 }
7759
7760 case TemplateName::QualifiedTemplate: {
7761 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7762 bool hasTemplKeyword = Record[Idx++];
7763 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7764 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7765 }
7766
7767 case TemplateName::DependentTemplate: {
7768 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7769 if (Record[Idx++]) // isIdentifier
7770 return Context.getDependentTemplateName(NNS,
7771 GetIdentifierInfo(F, Record,
7772 Idx));
7773 return Context.getDependentTemplateName(NNS,
7774 (OverloadedOperatorKind)Record[Idx++]);
7775 }
7776
7777 case TemplateName::SubstTemplateTemplateParm: {
7778 TemplateTemplateParmDecl *param
7779 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7780 if (!param) return TemplateName();
7781 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7782 return Context.getSubstTemplateTemplateParm(param, replacement);
7783 }
7784
7785 case TemplateName::SubstTemplateTemplateParmPack: {
7786 TemplateTemplateParmDecl *Param
7787 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7788 if (!Param)
7789 return TemplateName();
7790
7791 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7792 if (ArgPack.getKind() != TemplateArgument::Pack)
7793 return TemplateName();
7794
7795 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7796 }
7797 }
7798
7799 llvm_unreachable("Unhandled template name kind!");
7800}
7801
7802TemplateArgument
7803ASTReader::ReadTemplateArgument(ModuleFile &F,
7804 const RecordData &Record, unsigned &Idx) {
7805 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7806 switch (Kind) {
7807 case TemplateArgument::Null:
7808 return TemplateArgument();
7809 case TemplateArgument::Type:
7810 return TemplateArgument(readType(F, Record, Idx));
7811 case TemplateArgument::Declaration: {
7812 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007813 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007814 }
7815 case TemplateArgument::NullPtr:
7816 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7817 case TemplateArgument::Integral: {
7818 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7819 QualType T = readType(F, Record, Idx);
7820 return TemplateArgument(Context, Value, T);
7821 }
7822 case TemplateArgument::Template:
7823 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7824 case TemplateArgument::TemplateExpansion: {
7825 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007826 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007827 if (unsigned NumExpansions = Record[Idx++])
7828 NumTemplateExpansions = NumExpansions - 1;
7829 return TemplateArgument(Name, NumTemplateExpansions);
7830 }
7831 case TemplateArgument::Expression:
7832 return TemplateArgument(ReadExpr(F));
7833 case TemplateArgument::Pack: {
7834 unsigned NumArgs = Record[Idx++];
7835 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7836 for (unsigned I = 0; I != NumArgs; ++I)
7837 Args[I] = ReadTemplateArgument(F, Record, Idx);
7838 return TemplateArgument(Args, NumArgs);
7839 }
7840 }
7841
7842 llvm_unreachable("Unhandled template argument kind!");
7843}
7844
7845TemplateParameterList *
7846ASTReader::ReadTemplateParameterList(ModuleFile &F,
7847 const RecordData &Record, unsigned &Idx) {
7848 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7849 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7850 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7851
7852 unsigned NumParams = Record[Idx++];
7853 SmallVector<NamedDecl *, 16> Params;
7854 Params.reserve(NumParams);
7855 while (NumParams--)
7856 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7857
7858 TemplateParameterList* TemplateParams =
7859 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7860 Params.data(), Params.size(), RAngleLoc);
7861 return TemplateParams;
7862}
7863
7864void
7865ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007866ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007867 ModuleFile &F, const RecordData &Record,
7868 unsigned &Idx) {
7869 unsigned NumTemplateArgs = Record[Idx++];
7870 TemplArgs.reserve(NumTemplateArgs);
7871 while (NumTemplateArgs--)
7872 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7873}
7874
7875/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007876void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007877 const RecordData &Record, unsigned &Idx) {
7878 unsigned NumDecls = Record[Idx++];
7879 Set.reserve(Context, NumDecls);
7880 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007881 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007882 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007883 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007884 }
7885}
7886
7887CXXBaseSpecifier
7888ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7889 const RecordData &Record, unsigned &Idx) {
7890 bool isVirtual = static_cast<bool>(Record[Idx++]);
7891 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7892 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7893 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7894 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7895 SourceRange Range = ReadSourceRange(F, Record, Idx);
7896 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7897 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7898 EllipsisLoc);
7899 Result.setInheritConstructors(inheritConstructors);
7900 return Result;
7901}
7902
Richard Smithc2bb8182015-03-24 06:36:48 +00007903CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007904ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7905 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007906 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007907 assert(NumInitializers && "wrote ctor initializers but have no inits");
7908 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7909 for (unsigned i = 0; i != NumInitializers; ++i) {
7910 TypeSourceInfo *TInfo = nullptr;
7911 bool IsBaseVirtual = false;
7912 FieldDecl *Member = nullptr;
7913 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007914
Richard Smithc2bb8182015-03-24 06:36:48 +00007915 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7916 switch (Type) {
7917 case CTOR_INITIALIZER_BASE:
7918 TInfo = GetTypeSourceInfo(F, Record, Idx);
7919 IsBaseVirtual = Record[Idx++];
7920 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007921
Richard Smithc2bb8182015-03-24 06:36:48 +00007922 case CTOR_INITIALIZER_DELEGATING:
7923 TInfo = GetTypeSourceInfo(F, Record, Idx);
7924 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007925
Richard Smithc2bb8182015-03-24 06:36:48 +00007926 case CTOR_INITIALIZER_MEMBER:
7927 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7928 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007929
Richard Smithc2bb8182015-03-24 06:36:48 +00007930 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7931 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7932 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007933 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007934
7935 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7936 Expr *Init = ReadExpr(F);
7937 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7938 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7939 bool IsWritten = Record[Idx++];
7940 unsigned SourceOrderOrNumArrayIndices;
7941 SmallVector<VarDecl *, 8> Indices;
7942 if (IsWritten) {
7943 SourceOrderOrNumArrayIndices = Record[Idx++];
7944 } else {
7945 SourceOrderOrNumArrayIndices = Record[Idx++];
7946 Indices.reserve(SourceOrderOrNumArrayIndices);
7947 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7948 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7949 }
7950
7951 CXXCtorInitializer *BOMInit;
7952 if (Type == CTOR_INITIALIZER_BASE) {
7953 BOMInit = new (Context)
7954 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7955 RParenLoc, MemberOrEllipsisLoc);
7956 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7957 BOMInit = new (Context)
7958 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7959 } else if (IsWritten) {
7960 if (Member)
7961 BOMInit = new (Context) CXXCtorInitializer(
7962 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7963 else
7964 BOMInit = new (Context)
7965 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7966 LParenLoc, Init, RParenLoc);
7967 } else {
7968 if (IndirectMember) {
7969 assert(Indices.empty() && "Indirect field improperly initialized");
7970 BOMInit = new (Context)
7971 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7972 LParenLoc, Init, RParenLoc);
7973 } else {
7974 BOMInit = CXXCtorInitializer::Create(
7975 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7976 Indices.data(), Indices.size());
7977 }
7978 }
7979
7980 if (IsWritten)
7981 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7982 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007983 }
7984
Richard Smithc2bb8182015-03-24 06:36:48 +00007985 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007986}
7987
7988NestedNameSpecifier *
7989ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7990 const RecordData &Record, unsigned &Idx) {
7991 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007992 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007993 for (unsigned I = 0; I != N; ++I) {
7994 NestedNameSpecifier::SpecifierKind Kind
7995 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7996 switch (Kind) {
7997 case NestedNameSpecifier::Identifier: {
7998 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7999 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8000 break;
8001 }
8002
8003 case NestedNameSpecifier::Namespace: {
8004 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8005 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8006 break;
8007 }
8008
8009 case NestedNameSpecifier::NamespaceAlias: {
8010 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8011 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8012 break;
8013 }
8014
8015 case NestedNameSpecifier::TypeSpec:
8016 case NestedNameSpecifier::TypeSpecWithTemplate: {
8017 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8018 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008019 return nullptr;
8020
Guy Benyei11169dd2012-12-18 14:30:41 +00008021 bool Template = Record[Idx++];
8022 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8023 break;
8024 }
8025
8026 case NestedNameSpecifier::Global: {
8027 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8028 // No associated value, and there can't be a prefix.
8029 break;
8030 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008031
8032 case NestedNameSpecifier::Super: {
8033 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8034 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8035 break;
8036 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008037 }
8038 Prev = NNS;
8039 }
8040 return NNS;
8041}
8042
8043NestedNameSpecifierLoc
8044ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8045 unsigned &Idx) {
8046 unsigned N = Record[Idx++];
8047 NestedNameSpecifierLocBuilder Builder;
8048 for (unsigned I = 0; I != N; ++I) {
8049 NestedNameSpecifier::SpecifierKind Kind
8050 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8051 switch (Kind) {
8052 case NestedNameSpecifier::Identifier: {
8053 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8054 SourceRange Range = ReadSourceRange(F, Record, Idx);
8055 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8056 break;
8057 }
8058
8059 case NestedNameSpecifier::Namespace: {
8060 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8061 SourceRange Range = ReadSourceRange(F, Record, Idx);
8062 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8063 break;
8064 }
8065
8066 case NestedNameSpecifier::NamespaceAlias: {
8067 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8068 SourceRange Range = ReadSourceRange(F, Record, Idx);
8069 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8070 break;
8071 }
8072
8073 case NestedNameSpecifier::TypeSpec:
8074 case NestedNameSpecifier::TypeSpecWithTemplate: {
8075 bool Template = Record[Idx++];
8076 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8077 if (!T)
8078 return NestedNameSpecifierLoc();
8079 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8080
8081 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8082 Builder.Extend(Context,
8083 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8084 T->getTypeLoc(), ColonColonLoc);
8085 break;
8086 }
8087
8088 case NestedNameSpecifier::Global: {
8089 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8090 Builder.MakeGlobal(Context, ColonColonLoc);
8091 break;
8092 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008093
8094 case NestedNameSpecifier::Super: {
8095 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8096 SourceRange Range = ReadSourceRange(F, Record, Idx);
8097 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8098 break;
8099 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008100 }
8101 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008102
Guy Benyei11169dd2012-12-18 14:30:41 +00008103 return Builder.getWithLocInContext(Context);
8104}
8105
8106SourceRange
8107ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8108 unsigned &Idx) {
8109 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8110 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8111 return SourceRange(beg, end);
8112}
8113
8114/// \brief Read an integral value
8115llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8116 unsigned BitWidth = Record[Idx++];
8117 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8118 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8119 Idx += NumWords;
8120 return Result;
8121}
8122
8123/// \brief Read a signed integral value
8124llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8125 bool isUnsigned = Record[Idx++];
8126 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8127}
8128
8129/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008130llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8131 const llvm::fltSemantics &Sem,
8132 unsigned &Idx) {
8133 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008134}
8135
8136// \brief Read a string
8137std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8138 unsigned Len = Record[Idx++];
8139 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8140 Idx += Len;
8141 return Result;
8142}
8143
Richard Smith7ed1bc92014-12-05 22:42:13 +00008144std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8145 unsigned &Idx) {
8146 std::string Filename = ReadString(Record, Idx);
8147 ResolveImportedPath(F, Filename);
8148 return Filename;
8149}
8150
Guy Benyei11169dd2012-12-18 14:30:41 +00008151VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8152 unsigned &Idx) {
8153 unsigned Major = Record[Idx++];
8154 unsigned Minor = Record[Idx++];
8155 unsigned Subminor = Record[Idx++];
8156 if (Minor == 0)
8157 return VersionTuple(Major);
8158 if (Subminor == 0)
8159 return VersionTuple(Major, Minor - 1);
8160 return VersionTuple(Major, Minor - 1, Subminor - 1);
8161}
8162
8163CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8164 const RecordData &Record,
8165 unsigned &Idx) {
8166 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8167 return CXXTemporary::Create(Context, Decl);
8168}
8169
8170DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008171 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008172}
8173
8174DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8175 return Diags.Report(Loc, DiagID);
8176}
8177
8178/// \brief Retrieve the identifier table associated with the
8179/// preprocessor.
8180IdentifierTable &ASTReader::getIdentifierTable() {
8181 return PP.getIdentifierTable();
8182}
8183
8184/// \brief Record that the given ID maps to the given switch-case
8185/// statement.
8186void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008187 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008188 "Already have a SwitchCase with this ID");
8189 (*CurrSwitchCaseStmts)[ID] = SC;
8190}
8191
8192/// \brief Retrieve the switch-case statement with the given ID.
8193SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008194 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008195 return (*CurrSwitchCaseStmts)[ID];
8196}
8197
8198void ASTReader::ClearSwitchCaseIDs() {
8199 CurrSwitchCaseStmts->clear();
8200}
8201
8202void ASTReader::ReadComments() {
8203 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008204 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008205 serialization::ModuleFile *> >::iterator
8206 I = CommentsCursors.begin(),
8207 E = CommentsCursors.end();
8208 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008209 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008210 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008211 serialization::ModuleFile &F = *I->second;
8212 SavedStreamPosition SavedPosition(Cursor);
8213
8214 RecordData Record;
8215 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008216 llvm::BitstreamEntry Entry =
8217 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008218
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008219 switch (Entry.Kind) {
8220 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8221 case llvm::BitstreamEntry::Error:
8222 Error("malformed block record in AST file");
8223 return;
8224 case llvm::BitstreamEntry::EndBlock:
8225 goto NextCursor;
8226 case llvm::BitstreamEntry::Record:
8227 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008228 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008229 }
8230
8231 // Read a record.
8232 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008233 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008234 case COMMENTS_RAW_COMMENT: {
8235 unsigned Idx = 0;
8236 SourceRange SR = ReadSourceRange(F, Record, Idx);
8237 RawComment::CommentKind Kind =
8238 (RawComment::CommentKind) Record[Idx++];
8239 bool IsTrailingComment = Record[Idx++];
8240 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008241 Comments.push_back(new (Context) RawComment(
8242 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8243 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008244 break;
8245 }
8246 }
8247 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008248 NextCursor:
8249 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008250 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008251}
8252
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008253void ASTReader::getInputFiles(ModuleFile &F,
8254 SmallVectorImpl<serialization::InputFile> &Files) {
8255 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8256 unsigned ID = I+1;
8257 Files.push_back(getInputFile(F, ID));
8258 }
8259}
8260
Richard Smithcd45dbc2014-04-19 03:48:30 +00008261std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8262 // If we know the owning module, use it.
8263 if (Module *M = D->getOwningModule())
8264 return M->getFullModuleName();
8265
8266 // Otherwise, use the name of the top-level module the decl is within.
8267 if (ModuleFile *M = getOwningModuleFile(D))
8268 return M->ModuleName;
8269
8270 // Not from a module.
8271 return "";
8272}
8273
Guy Benyei11169dd2012-12-18 14:30:41 +00008274void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008275 while (!PendingIdentifierInfos.empty() ||
8276 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008277 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008278 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008279 // If any identifiers with corresponding top-level declarations have
8280 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008281 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8282 TopLevelDeclsMap;
8283 TopLevelDeclsMap TopLevelDecls;
8284
Guy Benyei11169dd2012-12-18 14:30:41 +00008285 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008286 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008287 SmallVector<uint32_t, 4> DeclIDs =
8288 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008289 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008290
8291 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008292 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008293
Richard Smith851072e2014-05-19 20:59:20 +00008294 // For each decl chain that we wanted to complete while deserializing, mark
8295 // it as "still needs to be completed".
8296 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8297 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8298 }
8299 PendingIncompleteDeclChains.clear();
8300
Guy Benyei11169dd2012-12-18 14:30:41 +00008301 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008302 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008303 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008304 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008305 }
8306 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008307 PendingDeclChains.clear();
8308
Douglas Gregor6168bd22013-02-18 15:53:43 +00008309 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008310 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8311 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008312 IdentifierInfo *II = TLD->first;
8313 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008314 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008315 }
8316 }
8317
Guy Benyei11169dd2012-12-18 14:30:41 +00008318 // Load any pending macro definitions.
8319 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008320 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8321 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8322 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8323 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008324 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008325 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008326 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008327 if (Info.M->Kind != MK_ImplicitModule &&
8328 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008329 resolvePendingMacro(II, Info);
8330 }
8331 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008332 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008333 ++IDIdx) {
8334 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008335 if (Info.M->Kind == MK_ImplicitModule ||
8336 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008337 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008338 }
8339 }
8340 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008341
8342 // Wire up the DeclContexts for Decls that we delayed setting until
8343 // recursive loading is completed.
8344 while (!PendingDeclContextInfos.empty()) {
8345 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8346 PendingDeclContextInfos.pop_front();
8347 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8348 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8349 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8350 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008351
Richard Smithd1c46742014-04-30 02:24:17 +00008352 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008353 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008354 auto Update = PendingUpdateRecords.pop_back_val();
8355 ReadingKindTracker ReadingKind(Read_Decl, *this);
8356 loadDeclUpdateRecords(Update.first, Update.second);
8357 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008358 }
Richard Smith8a639892015-01-24 01:07:20 +00008359
8360 // At this point, all update records for loaded decls are in place, so any
8361 // fake class definitions should have become real.
8362 assert(PendingFakeDefinitionData.empty() &&
8363 "faked up a class definition but never saw the real one");
8364
Guy Benyei11169dd2012-12-18 14:30:41 +00008365 // If we deserialized any C++ or Objective-C class definitions, any
8366 // Objective-C protocol definitions, or any redeclarable templates, make sure
8367 // that all redeclarations point to the definitions. Note that this can only
8368 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008369 for (Decl *D : PendingDefinitions) {
8370 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008371 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008372 // Make sure that the TagType points at the definition.
8373 const_cast<TagType*>(TagT)->decl = TD;
8374 }
Richard Smith8ce51082015-03-11 01:44:51 +00008375
Craig Topperc6914d02014-08-25 04:15:02 +00008376 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008377 for (auto *R = getMostRecentExistingDecl(RD); R;
8378 R = R->getPreviousDecl()) {
8379 assert((R == D) ==
8380 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008381 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008382 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008383 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008384 }
8385
8386 continue;
8387 }
Richard Smith8ce51082015-03-11 01:44:51 +00008388
Craig Topperc6914d02014-08-25 04:15:02 +00008389 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008390 // Make sure that the ObjCInterfaceType points at the definition.
8391 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8392 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008393
8394 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8395 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8396
Guy Benyei11169dd2012-12-18 14:30:41 +00008397 continue;
8398 }
Richard Smith8ce51082015-03-11 01:44:51 +00008399
Craig Topperc6914d02014-08-25 04:15:02 +00008400 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008401 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8402 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8403
Guy Benyei11169dd2012-12-18 14:30:41 +00008404 continue;
8405 }
Richard Smith8ce51082015-03-11 01:44:51 +00008406
Craig Topperc6914d02014-08-25 04:15:02 +00008407 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008408 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8409 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008410 }
8411 PendingDefinitions.clear();
8412
8413 // Load the bodies of any functions or methods we've encountered. We do
8414 // this now (delayed) so that we can be sure that the declaration chains
8415 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008416 // FIXME: There seems to be no point in delaying this, it does not depend
8417 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008418 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8419 PBEnd = PendingBodies.end();
8420 PB != PBEnd; ++PB) {
8421 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8422 // FIXME: Check for =delete/=default?
8423 // FIXME: Complain about ODR violations here?
8424 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8425 FD->setLazyBody(PB->second);
8426 continue;
8427 }
8428
8429 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8430 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8431 MD->setLazyBody(PB->second);
8432 }
8433 PendingBodies.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008434}
8435
8436void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008437 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8438 return;
8439
Richard Smitha0ce9c42014-07-29 23:23:27 +00008440 // Trigger the import of the full definition of each class that had any
8441 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008442 // These updates may in turn find and diagnose some ODR failures, so take
8443 // ownership of the set first.
8444 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8445 PendingOdrMergeFailures.clear();
8446 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008447 Merge.first->buildLookup();
8448 Merge.first->decls_begin();
8449 Merge.first->bases_begin();
8450 Merge.first->vbases_begin();
8451 for (auto *RD : Merge.second) {
8452 RD->decls_begin();
8453 RD->bases_begin();
8454 RD->vbases_begin();
8455 }
8456 }
8457
8458 // For each declaration from a merged context, check that the canonical
8459 // definition of that context also contains a declaration of the same
8460 // entity.
8461 //
8462 // Caution: this loop does things that might invalidate iterators into
8463 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8464 while (!PendingOdrMergeChecks.empty()) {
8465 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8466
8467 // FIXME: Skip over implicit declarations for now. This matters for things
8468 // like implicitly-declared special member functions. This isn't entirely
8469 // correct; we can end up with multiple unmerged declarations of the same
8470 // implicit entity.
8471 if (D->isImplicit())
8472 continue;
8473
8474 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008475
8476 bool Found = false;
8477 const Decl *DCanon = D->getCanonicalDecl();
8478
Richard Smith01bdb7a2014-08-28 05:44:07 +00008479 for (auto RI : D->redecls()) {
8480 if (RI->getLexicalDeclContext() == CanonDef) {
8481 Found = true;
8482 break;
8483 }
8484 }
8485 if (Found)
8486 continue;
8487
Richard Smitha0ce9c42014-07-29 23:23:27 +00008488 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008489 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008490 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8491 !Found && I != E; ++I) {
8492 for (auto RI : (*I)->redecls()) {
8493 if (RI->getLexicalDeclContext() == CanonDef) {
8494 // This declaration is present in the canonical definition. If it's
8495 // in the same redecl chain, it's the one we're looking for.
8496 if (RI->getCanonicalDecl() == DCanon)
8497 Found = true;
8498 else
8499 Candidates.push_back(cast<NamedDecl>(RI));
8500 break;
8501 }
8502 }
8503 }
8504
8505 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008506 // The AST doesn't like TagDecls becoming invalid after they've been
8507 // completed. We only really need to mark FieldDecls as invalid here.
8508 if (!isa<TagDecl>(D))
8509 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008510
8511 // Ensure we don't accidentally recursively enter deserialization while
8512 // we're producing our diagnostic.
8513 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008514
8515 std::string CanonDefModule =
8516 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8517 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8518 << D << getOwningModuleNameForDiagnostic(D)
8519 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8520
8521 if (Candidates.empty())
8522 Diag(cast<Decl>(CanonDef)->getLocation(),
8523 diag::note_module_odr_violation_no_possible_decls) << D;
8524 else {
8525 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8526 Diag(Candidates[I]->getLocation(),
8527 diag::note_module_odr_violation_possible_decl)
8528 << Candidates[I];
8529 }
8530
8531 DiagnosedOdrMergeFailures.insert(CanonDef);
8532 }
8533 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008534
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008535 if (OdrMergeFailures.empty())
8536 return;
8537
8538 // Ensure we don't accidentally recursively enter deserialization while
8539 // we're producing our diagnostics.
8540 Deserializing RecursionGuard(this);
8541
Richard Smithcd45dbc2014-04-19 03:48:30 +00008542 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008543 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008544 // If we've already pointed out a specific problem with this class, don't
8545 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008546 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008547 continue;
8548
8549 bool Diagnosed = false;
8550 for (auto *RD : Merge.second) {
8551 // Multiple different declarations got merged together; tell the user
8552 // where they came from.
8553 if (Merge.first != RD) {
8554 // FIXME: Walk the definition, figure out what's different,
8555 // and diagnose that.
8556 if (!Diagnosed) {
8557 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8558 Diag(Merge.first->getLocation(),
8559 diag::err_module_odr_violation_different_definitions)
8560 << Merge.first << Module.empty() << Module;
8561 Diagnosed = true;
8562 }
8563
8564 Diag(RD->getLocation(),
8565 diag::note_module_odr_violation_different_definitions)
8566 << getOwningModuleNameForDiagnostic(RD);
8567 }
8568 }
8569
8570 if (!Diagnosed) {
8571 // All definitions are updates to the same declaration. This happens if a
8572 // module instantiates the declaration of a class template specialization
8573 // and two or more other modules instantiate its definition.
8574 //
8575 // FIXME: Indicate which modules had instantiations of this definition.
8576 // FIXME: How can this even happen?
8577 Diag(Merge.first->getLocation(),
8578 diag::err_module_odr_violation_different_instantiations)
8579 << Merge.first;
8580 }
8581 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008582}
8583
8584void ASTReader::FinishedDeserializing() {
8585 assert(NumCurrentElementsDeserializing &&
8586 "FinishedDeserializing not paired with StartedDeserializing");
8587 if (NumCurrentElementsDeserializing == 1) {
8588 // We decrease NumCurrentElementsDeserializing only after pending actions
8589 // are finished, to avoid recursively re-calling finishPendingActions().
8590 finishPendingActions();
8591 }
8592 --NumCurrentElementsDeserializing;
8593
Richard Smitha0ce9c42014-07-29 23:23:27 +00008594 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008595 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008596 while (!PendingExceptionSpecUpdates.empty()) {
8597 auto Updates = std::move(PendingExceptionSpecUpdates);
8598 PendingExceptionSpecUpdates.clear();
8599 for (auto Update : Updates) {
8600 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8601 SemaObj->UpdateExceptionSpec(Update.second,
8602 FPT->getExtProtoInfo().ExceptionSpec);
8603 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008604 }
8605
Richard Smitha0ce9c42014-07-29 23:23:27 +00008606 diagnoseOdrViolations();
8607
Richard Smith04d05b52014-03-23 00:27:18 +00008608 // We are not in recursive loading, so it's safe to pass the "interesting"
8609 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008610 if (Consumer)
8611 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008612 }
8613}
8614
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008615void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008616 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8617 // Remove any fake results before adding any real ones.
8618 auto It = PendingFakeLookupResults.find(II);
8619 if (It != PendingFakeLookupResults.end()) {
8620 for (auto *ND : PendingFakeLookupResults[II])
8621 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008622 // FIXME: this works around module+PCH performance issue.
8623 // Rather than erase the result from the map, which is O(n), just clear
8624 // the vector of NamedDecls.
8625 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008626 }
8627 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008628
8629 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8630 SemaObj->TUScope->AddDecl(D);
8631 } else if (SemaObj->TUScope) {
8632 // Adding the decl to IdResolver may have failed because it was already in
8633 // (even though it was not added in scope). If it is already in, make sure
8634 // it gets in the scope as well.
8635 if (std::find(SemaObj->IdResolver.begin(Name),
8636 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8637 SemaObj->TUScope->AddDecl(D);
8638 }
8639}
8640
Nico Weber824285e2014-05-08 04:26:47 +00008641ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8642 bool DisableValidation, bool AllowASTWithCompilerErrors,
8643 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008644 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008645 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008646 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008647 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8648 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8649 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8650 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008651 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8652 AllowConfigurationMismatch(AllowConfigurationMismatch),
8653 ValidateSystemInputs(ValidateSystemInputs),
8654 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008655 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008656 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8657 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8658 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8659 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8660 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8661 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8662 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8663 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8664 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008665 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008666 SourceMgr.setExternalSLocEntrySource(this);
8667}
8668
8669ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008670 if (OwnsDeserializationListener)
8671 delete DeserializationListener;
8672
Guy Benyei11169dd2012-12-18 14:30:41 +00008673 for (DeclContextVisibleUpdatesPending::iterator
8674 I = PendingVisibleUpdates.begin(),
8675 E = PendingVisibleUpdates.end();
8676 I != E; ++I) {
8677 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8678 F = I->second.end();
8679 J != F; ++J)
8680 delete J->first;
8681 }
8682}