blob: 3de1159e78aef8323c4c1459a28761471ba8d68c [file] [log] [blame]
Richard Smith9e2341d2015-03-23 03:25:59 +00001//===-- ASTReader.cpp - AST File Reader ----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
Adrian Prantlbb165fb2015-06-20 18:53:08 +000022#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000023#include "clang/AST/NestedNameSpecifier.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000026#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/SourceManagerInternals.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Basic/TargetOptions.h"
32#include "clang/Basic/Version.h"
33#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000034#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/HeaderSearchOptions.h"
37#include "clang/Lex/MacroInfo.h"
38#include "clang/Lex/PreprocessingRecord.h"
39#include "clang/Lex/Preprocessor.h"
40#include "clang/Lex/PreprocessorOptions.h"
41#include "clang/Sema/Scope.h"
42#include "clang/Sema/Sema.h"
43#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000044#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000045#include "clang/Serialization/ModuleManager.h"
46#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000047#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "llvm/ADT/StringExtras.h"
49#include "llvm/Bitcode/BitstreamReader.h"
50#include "llvm/Support/ErrorHandling.h"
51#include "llvm/Support/FileSystem.h"
52#include "llvm/Support/MemoryBuffer.h"
53#include "llvm/Support/Path.h"
54#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000055#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000056#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000057#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000058#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000059#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000060
61using namespace clang;
62using namespace clang::serialization;
63using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000064using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000065
Ben Langmuircb69b572014-03-07 06:40:32 +000066
67//===----------------------------------------------------------------------===//
68// ChainedASTReaderListener implementation
69//===----------------------------------------------------------------------===//
70
71bool
72ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
73 return First->ReadFullVersionInformation(FullVersion) ||
74 Second->ReadFullVersionInformation(FullVersion);
75}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000076void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
77 First->ReadModuleName(ModuleName);
78 Second->ReadModuleName(ModuleName);
79}
80void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
81 First->ReadModuleMapFile(ModuleMapPath);
82 Second->ReadModuleMapFile(ModuleMapPath);
83}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000084bool
85ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
86 bool Complain,
87 bool AllowCompatibleDifferences) {
88 return First->ReadLanguageOptions(LangOpts, Complain,
89 AllowCompatibleDifferences) ||
90 Second->ReadLanguageOptions(LangOpts, Complain,
91 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000092}
Chandler Carruth0d745bc2015-03-14 04:47:43 +000093bool ChainedASTReaderListener::ReadTargetOptions(
94 const TargetOptions &TargetOpts, bool Complain,
95 bool AllowCompatibleDifferences) {
96 return First->ReadTargetOptions(TargetOpts, Complain,
97 AllowCompatibleDifferences) ||
98 Second->ReadTargetOptions(TargetOpts, Complain,
99 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000100}
101bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000102 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000103 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
104 Second->ReadDiagnosticOptions(DiagOpts, Complain);
105}
106bool
107ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
108 bool Complain) {
109 return First->ReadFileSystemOptions(FSOpts, Complain) ||
110 Second->ReadFileSystemOptions(FSOpts, Complain);
111}
112
113bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000114 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
115 bool Complain) {
116 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
117 Complain) ||
118 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
119 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000120}
121bool ChainedASTReaderListener::ReadPreprocessorOptions(
122 const PreprocessorOptions &PPOpts, bool Complain,
123 std::string &SuggestedPredefines) {
124 return First->ReadPreprocessorOptions(PPOpts, Complain,
125 SuggestedPredefines) ||
126 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
127}
128void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
129 unsigned Value) {
130 First->ReadCounter(M, Value);
131 Second->ReadCounter(M, Value);
132}
133bool ChainedASTReaderListener::needsInputFileVisitation() {
134 return First->needsInputFileVisitation() ||
135 Second->needsInputFileVisitation();
136}
137bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
138 return First->needsSystemInputFileVisitation() ||
139 Second->needsSystemInputFileVisitation();
140}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000141void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
142 First->visitModuleFile(Filename);
143 Second->visitModuleFile(Filename);
144}
Ben Langmuircb69b572014-03-07 06:40:32 +0000145bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000146 bool isSystem,
147 bool isOverridden) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000148 bool Continue = false;
149 if (First->needsInputFileVisitation() &&
150 (!isSystem || First->needsSystemInputFileVisitation()))
151 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
152 if (Second->needsInputFileVisitation() &&
153 (!isSystem || Second->needsSystemInputFileVisitation()))
154 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
155 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000156}
157
Guy Benyei11169dd2012-12-18 14:30:41 +0000158//===----------------------------------------------------------------------===//
159// PCH validator implementation
160//===----------------------------------------------------------------------===//
161
162ASTReaderListener::~ASTReaderListener() {}
163
164/// \brief Compare the given set of language options against an existing set of
165/// language options.
166///
167/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000168/// \param AllowCompatibleDifferences If true, differences between compatible
169/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000170///
171/// \returns true if the languagae options mis-match, false otherwise.
172static bool checkLanguageOptions(const LangOptions &LangOpts,
173 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000174 DiagnosticsEngine *Diags,
175 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000176#define LANGOPT(Name, Bits, Default, Description) \
177 if (ExistingLangOpts.Name != LangOpts.Name) { \
178 if (Diags) \
179 Diags->Report(diag::err_pch_langopt_mismatch) \
180 << Description << LangOpts.Name << ExistingLangOpts.Name; \
181 return true; \
182 }
183
184#define VALUE_LANGOPT(Name, Bits, Default, Description) \
185 if (ExistingLangOpts.Name != LangOpts.Name) { \
186 if (Diags) \
187 Diags->Report(diag::err_pch_langopt_value_mismatch) \
188 << Description; \
189 return true; \
190 }
191
192#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
193 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
194 if (Diags) \
195 Diags->Report(diag::err_pch_langopt_value_mismatch) \
196 << Description; \
197 return true; \
198 }
199
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000200#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
201 if (!AllowCompatibleDifferences) \
202 LANGOPT(Name, Bits, Default, Description)
203
204#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
205 if (!AllowCompatibleDifferences) \
206 ENUM_LANGOPT(Name, Bits, Default, Description)
207
Guy Benyei11169dd2012-12-18 14:30:41 +0000208#define BENIGN_LANGOPT(Name, Bits, Default, Description)
209#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
210#include "clang/Basic/LangOptions.def"
211
Ben Langmuircd98cb72015-06-23 18:20:18 +0000212 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
213 if (Diags)
214 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
215 return true;
216 }
217
Guy Benyei11169dd2012-12-18 14:30:41 +0000218 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
219 if (Diags)
220 Diags->Report(diag::err_pch_langopt_value_mismatch)
221 << "target Objective-C runtime";
222 return true;
223 }
224
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000225 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
226 LangOpts.CommentOpts.BlockCommandNames) {
227 if (Diags)
228 Diags->Report(diag::err_pch_langopt_value_mismatch)
229 << "block command names";
230 return true;
231 }
232
Guy Benyei11169dd2012-12-18 14:30:41 +0000233 return false;
234}
235
236/// \brief Compare the given set of target options against an existing set of
237/// target options.
238///
239/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
240///
241/// \returns true if the target options mis-match, false otherwise.
242static bool checkTargetOptions(const TargetOptions &TargetOpts,
243 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000244 DiagnosticsEngine *Diags,
245 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000246#define CHECK_TARGET_OPT(Field, Name) \
247 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
248 if (Diags) \
249 Diags->Report(diag::err_pch_targetopt_mismatch) \
250 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
251 return true; \
252 }
253
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000254 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000255 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000256 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000257
258 // We can tolerate different CPUs in many cases, notably when one CPU
259 // supports a strict superset of another. When allowing compatible
260 // differences skip this check.
261 if (!AllowCompatibleDifferences)
262 CHECK_TARGET_OPT(CPU, "target CPU");
263
Guy Benyei11169dd2012-12-18 14:30:41 +0000264#undef CHECK_TARGET_OPT
265
266 // Compare feature sets.
267 SmallVector<StringRef, 4> ExistingFeatures(
268 ExistingTargetOpts.FeaturesAsWritten.begin(),
269 ExistingTargetOpts.FeaturesAsWritten.end());
270 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
271 TargetOpts.FeaturesAsWritten.end());
272 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
273 std::sort(ReadFeatures.begin(), ReadFeatures.end());
274
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000275 // We compute the set difference in both directions explicitly so that we can
276 // diagnose the differences differently.
277 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
278 std::set_difference(
279 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
280 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
281 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
282 ExistingFeatures.begin(), ExistingFeatures.end(),
283 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000284
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000285 // If we are allowing compatible differences and the read feature set is
286 // a strict subset of the existing feature set, there is nothing to diagnose.
287 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
288 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000289
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000290 if (Diags) {
291 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000292 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000293 << /* is-existing-feature */ false << Feature;
294 for (StringRef Feature : UnmatchedExistingFeatures)
295 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
296 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000297 }
298
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000299 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000300}
301
302bool
303PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000304 bool Complain,
305 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000306 const LangOptions &ExistingLangOpts = PP.getLangOpts();
307 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000308 Complain ? &Reader.Diags : nullptr,
309 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000310}
311
312bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000313 bool Complain,
314 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000315 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
316 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000317 Complain ? &Reader.Diags : nullptr,
318 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000319}
320
321namespace {
322 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
323 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000324 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
325 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000326}
327
Ben Langmuirb92de022014-04-29 16:25:26 +0000328static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
329 DiagnosticsEngine &Diags,
330 bool Complain) {
331 typedef DiagnosticsEngine::Level Level;
332
333 // Check current mappings for new -Werror mappings, and the stored mappings
334 // for cases that were explicitly mapped to *not* be errors that are now
335 // errors because of options like -Werror.
336 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
337
338 for (DiagnosticsEngine *MappingSource : MappingSources) {
339 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
340 diag::kind DiagID = DiagIDMappingPair.first;
341 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
342 if (CurLevel < DiagnosticsEngine::Error)
343 continue; // not significant
344 Level StoredLevel =
345 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
346 if (StoredLevel < DiagnosticsEngine::Error) {
347 if (Complain)
348 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
349 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
350 return true;
351 }
352 }
353 }
354
355 return false;
356}
357
Alp Tokerac4e8e52014-06-22 21:58:33 +0000358static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
359 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
360 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
361 return true;
362 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000363}
364
365static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
366 DiagnosticsEngine &Diags,
367 bool IsSystem, bool Complain) {
368 // Top-level options
369 if (IsSystem) {
370 if (Diags.getSuppressSystemWarnings())
371 return false;
372 // If -Wsystem-headers was not enabled before, be conservative
373 if (StoredDiags.getSuppressSystemWarnings()) {
374 if (Complain)
375 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
376 return true;
377 }
378 }
379
380 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
381 if (Complain)
382 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
383 return true;
384 }
385
386 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
387 !StoredDiags.getEnableAllWarnings()) {
388 if (Complain)
389 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
390 return true;
391 }
392
393 if (isExtHandlingFromDiagsError(Diags) &&
394 !isExtHandlingFromDiagsError(StoredDiags)) {
395 if (Complain)
396 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
397 return true;
398 }
399
400 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
401}
402
403bool PCHValidator::ReadDiagnosticOptions(
404 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
405 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
406 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
407 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000408 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000409 // This should never fail, because we would have processed these options
410 // before writing them to an ASTFile.
411 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
412
413 ModuleManager &ModuleMgr = Reader.getModuleManager();
414 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
415
416 // If the original import came from a file explicitly generated by the user,
417 // don't check the diagnostic mappings.
418 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000419 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000420 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
421 // the transitive closure of its imports, since unrelated modules cannot be
422 // imported until after this module finishes validation.
423 ModuleFile *TopImport = *ModuleMgr.rbegin();
424 while (!TopImport->ImportedBy.empty())
425 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000426 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000427 return false;
428
429 StringRef ModuleName = TopImport->ModuleName;
430 assert(!ModuleName.empty() && "diagnostic options read before module name");
431
432 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
433 assert(M && "missing module");
434
435 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
436 // contains the union of their flags.
437 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
438}
439
Guy Benyei11169dd2012-12-18 14:30:41 +0000440/// \brief Collect the macro definitions provided by the given preprocessor
441/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000442static void
443collectMacroDefinitions(const PreprocessorOptions &PPOpts,
444 MacroDefinitionsMap &Macros,
445 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000446 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
447 StringRef Macro = PPOpts.Macros[I].first;
448 bool IsUndef = PPOpts.Macros[I].second;
449
450 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
451 StringRef MacroName = MacroPair.first;
452 StringRef MacroBody = MacroPair.second;
453
454 // For an #undef'd macro, we only care about the name.
455 if (IsUndef) {
456 if (MacroNames && !Macros.count(MacroName))
457 MacroNames->push_back(MacroName);
458
459 Macros[MacroName] = std::make_pair("", true);
460 continue;
461 }
462
463 // For a #define'd macro, figure out the actual definition.
464 if (MacroName.size() == Macro.size())
465 MacroBody = "1";
466 else {
467 // Note: GCC drops anything following an end-of-line character.
468 StringRef::size_type End = MacroBody.find_first_of("\n\r");
469 MacroBody = MacroBody.substr(0, End);
470 }
471
472 if (MacroNames && !Macros.count(MacroName))
473 MacroNames->push_back(MacroName);
474 Macros[MacroName] = std::make_pair(MacroBody, false);
475 }
476}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000477
Guy Benyei11169dd2012-12-18 14:30:41 +0000478/// \brief Check the preprocessor options deserialized from the control block
479/// against the preprocessor options in an existing preprocessor.
480///
481/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
482static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
483 const PreprocessorOptions &ExistingPPOpts,
484 DiagnosticsEngine *Diags,
485 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000486 std::string &SuggestedPredefines,
487 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000488 // Check macro definitions.
489 MacroDefinitionsMap ASTFileMacros;
490 collectMacroDefinitions(PPOpts, ASTFileMacros);
491 MacroDefinitionsMap ExistingMacros;
492 SmallVector<StringRef, 4> ExistingMacroNames;
493 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
494
495 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
496 // Dig out the macro definition in the existing preprocessor options.
497 StringRef MacroName = ExistingMacroNames[I];
498 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
499
500 // Check whether we know anything about this macro name or not.
501 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
502 = ASTFileMacros.find(MacroName);
503 if (Known == ASTFileMacros.end()) {
504 // FIXME: Check whether this identifier was referenced anywhere in the
505 // AST file. If so, we should reject the AST file. Unfortunately, this
506 // information isn't in the control block. What shall we do about it?
507
508 if (Existing.second) {
509 SuggestedPredefines += "#undef ";
510 SuggestedPredefines += MacroName.str();
511 SuggestedPredefines += '\n';
512 } else {
513 SuggestedPredefines += "#define ";
514 SuggestedPredefines += MacroName.str();
515 SuggestedPredefines += ' ';
516 SuggestedPredefines += Existing.first.str();
517 SuggestedPredefines += '\n';
518 }
519 continue;
520 }
521
522 // If the macro was defined in one but undef'd in the other, we have a
523 // conflict.
524 if (Existing.second != Known->second.second) {
525 if (Diags) {
526 Diags->Report(diag::err_pch_macro_def_undef)
527 << MacroName << Known->second.second;
528 }
529 return true;
530 }
531
532 // If the macro was #undef'd in both, or if the macro bodies are identical,
533 // it's fine.
534 if (Existing.second || Existing.first == Known->second.first)
535 continue;
536
537 // The macro bodies differ; complain.
538 if (Diags) {
539 Diags->Report(diag::err_pch_macro_def_conflict)
540 << MacroName << Known->second.first << Existing.first;
541 }
542 return true;
543 }
544
545 // Check whether we're using predefines.
546 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
547 if (Diags) {
548 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
549 }
550 return true;
551 }
552
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000553 // Detailed record is important since it is used for the module cache hash.
554 if (LangOpts.Modules &&
555 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
556 if (Diags) {
557 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
558 }
559 return true;
560 }
561
Guy Benyei11169dd2012-12-18 14:30:41 +0000562 // Compute the #include and #include_macros lines we need.
563 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
564 StringRef File = ExistingPPOpts.Includes[I];
565 if (File == ExistingPPOpts.ImplicitPCHInclude)
566 continue;
567
568 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
569 != PPOpts.Includes.end())
570 continue;
571
572 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000573 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000574 SuggestedPredefines += "\"\n";
575 }
576
577 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
578 StringRef File = ExistingPPOpts.MacroIncludes[I];
579 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
580 File)
581 != PPOpts.MacroIncludes.end())
582 continue;
583
584 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000585 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000586 SuggestedPredefines += "\"\n##\n";
587 }
588
589 return false;
590}
591
592bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
593 bool Complain,
594 std::string &SuggestedPredefines) {
595 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
596
597 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000598 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000599 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000600 SuggestedPredefines,
601 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000602}
603
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000604/// Check the header search options deserialized from the control block
605/// against the header search options in an existing preprocessor.
606///
607/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
608static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
609 StringRef SpecificModuleCachePath,
610 StringRef ExistingModuleCachePath,
611 DiagnosticsEngine *Diags,
612 const LangOptions &LangOpts) {
613 if (LangOpts.Modules) {
614 if (SpecificModuleCachePath != ExistingModuleCachePath) {
615 if (Diags)
616 Diags->Report(diag::err_pch_modulecache_mismatch)
617 << SpecificModuleCachePath << ExistingModuleCachePath;
618 return true;
619 }
620 }
621
622 return false;
623}
624
625bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
626 StringRef SpecificModuleCachePath,
627 bool Complain) {
628 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
629 PP.getHeaderSearchInfo().getModuleCachePath(),
630 Complain ? &Reader.Diags : nullptr,
631 PP.getLangOpts());
632}
633
Guy Benyei11169dd2012-12-18 14:30:41 +0000634void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
635 PP.setCounterValue(Value);
636}
637
638//===----------------------------------------------------------------------===//
639// AST reader implementation
640//===----------------------------------------------------------------------===//
641
Nico Weber824285e2014-05-08 04:26:47 +0000642void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
643 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000644 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000645 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000646}
647
648
649
650unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
651 return serialization::ComputeHash(Sel);
652}
653
654
655std::pair<unsigned, unsigned>
656ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000657 using namespace llvm::support;
658 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
659 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000660 return std::make_pair(KeyLen, DataLen);
661}
662
663ASTSelectorLookupTrait::internal_key_type
664ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000665 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000666 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000667 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
668 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
669 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000670 if (N == 0)
671 return SelTable.getNullarySelector(FirstII);
672 else if (N == 1)
673 return SelTable.getUnarySelector(FirstII);
674
675 SmallVector<IdentifierInfo *, 16> Args;
676 Args.push_back(FirstII);
677 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000678 Args.push_back(Reader.getLocalIdentifier(
679 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000680
681 return SelTable.getSelector(N, Args.data());
682}
683
684ASTSelectorLookupTrait::data_type
685ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
686 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000687 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000688
689 data_type Result;
690
Justin Bogner57ba0b22014-03-28 22:03:24 +0000691 Result.ID = Reader.getGlobalSelectorID(
692 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000693 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
694 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
695 Result.InstanceBits = FullInstanceBits & 0x3;
696 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
697 Result.FactoryBits = FullFactoryBits & 0x3;
698 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
699 unsigned NumInstanceMethods = FullInstanceBits >> 3;
700 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000701
702 // Load instance methods
703 for (unsigned I = 0; I != NumInstanceMethods; ++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.Instance.push_back(Method);
707 }
708
709 // Load factory methods
710 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000711 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
712 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000713 Result.Factory.push_back(Method);
714 }
715
716 return Result;
717}
718
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000719unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
720 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000721}
722
723std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000724ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000725 using namespace llvm::support;
726 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
727 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000728 return std::make_pair(KeyLen, DataLen);
729}
730
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000731ASTIdentifierLookupTraitBase::internal_key_type
732ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000733 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000734 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000735}
736
Douglas Gregordcf25082013-02-11 18:16:18 +0000737/// \brief Whether the given identifier is "interesting".
738static bool isInterestingIdentifier(IdentifierInfo &II) {
739 return II.isPoisoned() ||
740 II.isExtensionToken() ||
741 II.getObjCOrBuiltinID() ||
742 II.hasRevertedTokenIDToIdentifier() ||
743 II.hadMacroDefinition() ||
744 II.getFETokenInfo<void>();
745}
746
Guy Benyei11169dd2012-12-18 14:30:41 +0000747IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
748 const unsigned char* d,
749 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000750 using namespace llvm::support;
751 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000752 bool IsInteresting = RawID & 0x01;
753
754 // Wipe out the "is interesting" bit.
755 RawID = RawID >> 1;
756
757 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
758 if (!IsInteresting) {
759 // For uninteresting identifiers, just build the IdentifierInfo
760 // and associate it with the persistent ID.
761 IdentifierInfo *II = KnownII;
762 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000763 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000764 KnownII = II;
765 }
766 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000767 if (!II->isFromAST()) {
768 bool WasInteresting = isInterestingIdentifier(*II);
769 II->setIsFromAST();
770 if (WasInteresting)
771 II->setChangedSinceDeserialization();
772 }
773 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000774 return II;
775 }
776
Justin Bogner57ba0b22014-03-28 22:03:24 +0000777 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
778 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000779 bool CPlusPlusOperatorKeyword = Bits & 0x01;
780 Bits >>= 1;
781 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
782 Bits >>= 1;
783 bool Poisoned = Bits & 0x01;
784 Bits >>= 1;
785 bool ExtensionToken = Bits & 0x01;
786 Bits >>= 1;
787 bool hadMacroDefinition = Bits & 0x01;
788 Bits >>= 1;
789
790 assert(Bits == 0 && "Extra bits in the identifier?");
791 DataLen -= 8;
792
793 // Build the IdentifierInfo itself and link the identifier ID with
794 // the new IdentifierInfo.
795 IdentifierInfo *II = KnownII;
796 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000797 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000798 KnownII = II;
799 }
800 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000801 if (!II->isFromAST()) {
802 bool WasInteresting = isInterestingIdentifier(*II);
803 II->setIsFromAST();
804 if (WasInteresting)
805 II->setChangedSinceDeserialization();
806 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000807
808 // Set or check the various bits in the IdentifierInfo structure.
809 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000810 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000811 II->RevertTokenIDToIdentifier();
812 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
813 assert(II->isExtensionToken() == ExtensionToken &&
814 "Incorrect extension token flag");
815 (void)ExtensionToken;
816 if (Poisoned)
817 II->setIsPoisoned(true);
818 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
819 "Incorrect C++ operator keyword flag");
820 (void)CPlusPlusOperatorKeyword;
821
822 // If this identifier is a macro, deserialize the macro
823 // definition.
824 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000825 uint32_t MacroDirectivesOffset =
826 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000827 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000828
Richard Smithd7329392015-04-21 21:46:32 +0000829 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000830 }
831
832 Reader.SetIdentifierInfo(ID, II);
833
834 // Read all of the declarations visible at global scope with this
835 // name.
836 if (DataLen > 0) {
837 SmallVector<uint32_t, 4> DeclIDs;
838 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000839 DeclIDs.push_back(Reader.getGlobalDeclID(
840 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000841 Reader.SetGloballyVisibleDecls(II, DeclIDs);
842 }
843
844 return II;
845}
846
847unsigned
848ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
849 llvm::FoldingSetNodeID ID;
850 ID.AddInteger(Key.Kind);
851
852 switch (Key.Kind) {
853 case DeclarationName::Identifier:
854 case DeclarationName::CXXLiteralOperatorName:
855 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
856 break;
857 case DeclarationName::ObjCZeroArgSelector:
858 case DeclarationName::ObjCOneArgSelector:
859 case DeclarationName::ObjCMultiArgSelector:
860 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
861 break;
862 case DeclarationName::CXXOperatorName:
863 ID.AddInteger((OverloadedOperatorKind)Key.Data);
864 break;
865 case DeclarationName::CXXConstructorName:
866 case DeclarationName::CXXDestructorName:
867 case DeclarationName::CXXConversionFunctionName:
868 case DeclarationName::CXXUsingDirective:
869 break;
870 }
871
872 return ID.ComputeHash();
873}
874
875ASTDeclContextNameLookupTrait::internal_key_type
876ASTDeclContextNameLookupTrait::GetInternalKey(
877 const external_key_type& Name) const {
878 DeclNameKey Key;
879 Key.Kind = Name.getNameKind();
880 switch (Name.getNameKind()) {
881 case DeclarationName::Identifier:
882 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
883 break;
884 case DeclarationName::ObjCZeroArgSelector:
885 case DeclarationName::ObjCOneArgSelector:
886 case DeclarationName::ObjCMultiArgSelector:
887 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
888 break;
889 case DeclarationName::CXXOperatorName:
890 Key.Data = Name.getCXXOverloadedOperator();
891 break;
892 case DeclarationName::CXXLiteralOperatorName:
893 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
894 break;
895 case DeclarationName::CXXConstructorName:
896 case DeclarationName::CXXDestructorName:
897 case DeclarationName::CXXConversionFunctionName:
898 case DeclarationName::CXXUsingDirective:
899 Key.Data = 0;
900 break;
901 }
902
903 return Key;
904}
905
906std::pair<unsigned, unsigned>
907ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000908 using namespace llvm::support;
909 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
910 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000911 return std::make_pair(KeyLen, DataLen);
912}
913
914ASTDeclContextNameLookupTrait::internal_key_type
915ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000916 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000917
918 DeclNameKey Key;
919 Key.Kind = (DeclarationName::NameKind)*d++;
920 switch (Key.Kind) {
921 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000922 Key.Data = (uint64_t)Reader.getLocalIdentifier(
923 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000924 break;
925 case DeclarationName::ObjCZeroArgSelector:
926 case DeclarationName::ObjCOneArgSelector:
927 case DeclarationName::ObjCMultiArgSelector:
928 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000929 (uint64_t)Reader.getLocalSelector(
930 F, endian::readNext<uint32_t, little, unaligned>(
931 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000932 break;
933 case DeclarationName::CXXOperatorName:
934 Key.Data = *d++; // OverloadedOperatorKind
935 break;
936 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000937 Key.Data = (uint64_t)Reader.getLocalIdentifier(
938 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000939 break;
940 case DeclarationName::CXXConstructorName:
941 case DeclarationName::CXXDestructorName:
942 case DeclarationName::CXXConversionFunctionName:
943 case DeclarationName::CXXUsingDirective:
944 Key.Data = 0;
945 break;
946 }
947
948 return Key;
949}
950
951ASTDeclContextNameLookupTrait::data_type
952ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
953 const unsigned char* d,
954 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000955 using namespace llvm::support;
956 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000957 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
958 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000959 return std::make_pair(Start, Start + NumDecls);
960}
961
962bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000963 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000964 const std::pair<uint64_t, uint64_t> &Offsets,
965 DeclContextInfo &Info) {
966 SavedStreamPosition SavedPosition(Cursor);
967 // First the lexical decls.
968 if (Offsets.first != 0) {
969 Cursor.JumpToBit(Offsets.first);
970
971 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000972 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000973 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000974 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000975 if (RecCode != DECL_CONTEXT_LEXICAL) {
976 Error("Expected lexical block");
977 return true;
978 }
979
Chris Lattner0e6c9402013-01-20 02:38:54 +0000980 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
981 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000982 }
983
984 // Now the lookup table.
985 if (Offsets.second != 0) {
986 Cursor.JumpToBit(Offsets.second);
987
988 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000989 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000990 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000991 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000992 if (RecCode != DECL_CONTEXT_VISIBLE) {
993 Error("Expected visible lookup table block");
994 return true;
995 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000996 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
997 (const unsigned char *)Blob.data() + Record[0],
998 (const unsigned char *)Blob.data() + sizeof(uint32_t),
999 (const unsigned char *)Blob.data(),
1000 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +00001001 }
1002
1003 return false;
1004}
1005
1006void ASTReader::Error(StringRef Msg) {
1007 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001008 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1009 Diag(diag::note_module_cache_path)
1010 << PP.getHeaderSearchInfo().getModuleCachePath();
1011 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001012}
1013
1014void ASTReader::Error(unsigned DiagID,
1015 StringRef Arg1, StringRef Arg2) {
1016 if (Diags.isDiagnosticInFlight())
1017 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1018 else
1019 Diag(DiagID) << Arg1 << Arg2;
1020}
1021
1022//===----------------------------------------------------------------------===//
1023// Source Manager Deserialization
1024//===----------------------------------------------------------------------===//
1025
1026/// \brief Read the line table in the source manager block.
1027/// \returns true if there was an error.
1028bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001029 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001030 unsigned Idx = 0;
1031 LineTableInfo &LineTable = SourceMgr.getLineTable();
1032
1033 // Parse the file names
1034 std::map<int, int> FileIDs;
1035 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1036 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001037 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001038 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1039 }
1040
1041 // Parse the line entries
1042 std::vector<LineEntry> Entries;
1043 while (Idx < Record.size()) {
1044 int FID = Record[Idx++];
1045 assert(FID >= 0 && "Serialized line entries for non-local file.");
1046 // Remap FileID from 1-based old view.
1047 FID += F.SLocEntryBaseID - 1;
1048
1049 // Extract the line entries
1050 unsigned NumEntries = Record[Idx++];
1051 assert(NumEntries && "Numentries is 00000");
1052 Entries.clear();
1053 Entries.reserve(NumEntries);
1054 for (unsigned I = 0; I != NumEntries; ++I) {
1055 unsigned FileOffset = Record[Idx++];
1056 unsigned LineNo = Record[Idx++];
1057 int FilenameID = FileIDs[Record[Idx++]];
1058 SrcMgr::CharacteristicKind FileKind
1059 = (SrcMgr::CharacteristicKind)Record[Idx++];
1060 unsigned IncludeOffset = Record[Idx++];
1061 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1062 FileKind, IncludeOffset));
1063 }
1064 LineTable.AddEntry(FileID::get(FID), Entries);
1065 }
1066
1067 return false;
1068}
1069
1070/// \brief Read a source manager block
1071bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1072 using namespace SrcMgr;
1073
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001074 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001075
1076 // Set the source-location entry cursor to the current position in
1077 // the stream. This cursor will be used to read the contents of the
1078 // source manager block initially, and then lazily read
1079 // source-location entries as needed.
1080 SLocEntryCursor = F.Stream;
1081
1082 // The stream itself is going to skip over the source manager block.
1083 if (F.Stream.SkipBlock()) {
1084 Error("malformed block record in AST file");
1085 return true;
1086 }
1087
1088 // Enter the source manager block.
1089 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1090 Error("malformed source manager block record in AST file");
1091 return true;
1092 }
1093
1094 RecordData Record;
1095 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001096 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1097
1098 switch (E.Kind) {
1099 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1100 case llvm::BitstreamEntry::Error:
1101 Error("malformed block record in AST file");
1102 return true;
1103 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001105 case llvm::BitstreamEntry::Record:
1106 // The interesting case.
1107 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001108 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001109
Guy Benyei11169dd2012-12-18 14:30:41 +00001110 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001111 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001112 StringRef Blob;
1113 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001114 default: // Default behavior: ignore.
1115 break;
1116
1117 case SM_SLOC_FILE_ENTRY:
1118 case SM_SLOC_BUFFER_ENTRY:
1119 case SM_SLOC_EXPANSION_ENTRY:
1120 // Once we hit one of the source location entries, we're done.
1121 return false;
1122 }
1123 }
1124}
1125
1126/// \brief If a header file is not found at the path that we expect it to be
1127/// and the PCH file was moved from its original location, try to resolve the
1128/// file by assuming that header+PCH were moved together and the header is in
1129/// the same place relative to the PCH.
1130static std::string
1131resolveFileRelativeToOriginalDir(const std::string &Filename,
1132 const std::string &OriginalDir,
1133 const std::string &CurrDir) {
1134 assert(OriginalDir != CurrDir &&
1135 "No point trying to resolve the file if the PCH dir didn't change");
1136 using namespace llvm::sys;
1137 SmallString<128> filePath(Filename);
1138 fs::make_absolute(filePath);
1139 assert(path::is_absolute(OriginalDir));
1140 SmallString<128> currPCHPath(CurrDir);
1141
1142 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1143 fileDirE = path::end(path::parent_path(filePath));
1144 path::const_iterator origDirI = path::begin(OriginalDir),
1145 origDirE = path::end(OriginalDir);
1146 // Skip the common path components from filePath and OriginalDir.
1147 while (fileDirI != fileDirE && origDirI != origDirE &&
1148 *fileDirI == *origDirI) {
1149 ++fileDirI;
1150 ++origDirI;
1151 }
1152 for (; origDirI != origDirE; ++origDirI)
1153 path::append(currPCHPath, "..");
1154 path::append(currPCHPath, fileDirI, fileDirE);
1155 path::append(currPCHPath, path::filename(Filename));
1156 return currPCHPath.str();
1157}
1158
1159bool ASTReader::ReadSLocEntry(int ID) {
1160 if (ID == 0)
1161 return false;
1162
1163 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1164 Error("source location entry ID out-of-range for AST file");
1165 return true;
1166 }
1167
1168 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1169 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001170 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001171 unsigned BaseOffset = F->SLocEntryBaseOffset;
1172
1173 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001174 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1175 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001176 Error("incorrectly-formatted source location entry in AST file");
1177 return true;
1178 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001179
Guy Benyei11169dd2012-12-18 14:30:41 +00001180 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001181 StringRef Blob;
1182 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001183 default:
1184 Error("incorrectly-formatted source location entry in AST file");
1185 return true;
1186
1187 case SM_SLOC_FILE_ENTRY: {
1188 // We will detect whether a file changed and return 'Failure' for it, but
1189 // we will also try to fail gracefully by setting up the SLocEntry.
1190 unsigned InputID = Record[4];
1191 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001192 const FileEntry *File = IF.getFile();
1193 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001194
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001195 // Note that we only check if a File was returned. If it was out-of-date
1196 // we have complained but we will continue creating a FileID to recover
1197 // gracefully.
1198 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001199 return true;
1200
1201 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1202 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1203 // This is the module's main file.
1204 IncludeLoc = getImportLocation(F);
1205 }
1206 SrcMgr::CharacteristicKind
1207 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1208 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1209 ID, BaseOffset + Record[0]);
1210 SrcMgr::FileInfo &FileInfo =
1211 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1212 FileInfo.NumCreatedFIDs = Record[5];
1213 if (Record[3])
1214 FileInfo.setHasLineDirectives();
1215
1216 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1217 unsigned NumFileDecls = Record[7];
1218 if (NumFileDecls) {
1219 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1220 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1221 NumFileDecls));
1222 }
1223
1224 const SrcMgr::ContentCache *ContentCache
1225 = SourceMgr.getOrCreateContentCache(File,
1226 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1227 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1228 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1229 unsigned Code = SLocEntryCursor.ReadCode();
1230 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001231 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001232
1233 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1234 Error("AST record has invalid code");
1235 return true;
1236 }
1237
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001238 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001239 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001240 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001241 }
1242
1243 break;
1244 }
1245
1246 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001247 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001248 unsigned Offset = Record[0];
1249 SrcMgr::CharacteristicKind
1250 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1251 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001252 if (IncludeLoc.isInvalid() &&
1253 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001254 IncludeLoc = getImportLocation(F);
1255 }
1256 unsigned Code = SLocEntryCursor.ReadCode();
1257 Record.clear();
1258 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001259 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001260
1261 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1262 Error("AST record has invalid code");
1263 return true;
1264 }
1265
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001266 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1267 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001268 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001269 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001270 break;
1271 }
1272
1273 case SM_SLOC_EXPANSION_ENTRY: {
1274 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1275 SourceMgr.createExpansionLoc(SpellingLoc,
1276 ReadSourceLocation(*F, Record[2]),
1277 ReadSourceLocation(*F, Record[3]),
1278 Record[4],
1279 ID,
1280 BaseOffset + Record[0]);
1281 break;
1282 }
1283 }
1284
1285 return false;
1286}
1287
1288std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1289 if (ID == 0)
1290 return std::make_pair(SourceLocation(), "");
1291
1292 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1293 Error("source location entry ID out-of-range for AST file");
1294 return std::make_pair(SourceLocation(), "");
1295 }
1296
1297 // Find which module file this entry lands in.
1298 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001299 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001300 return std::make_pair(SourceLocation(), "");
1301
1302 // FIXME: Can we map this down to a particular submodule? That would be
1303 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001304 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001305}
1306
1307/// \brief Find the location where the module F is imported.
1308SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1309 if (F->ImportLoc.isValid())
1310 return F->ImportLoc;
1311
1312 // Otherwise we have a PCH. It's considered to be "imported" at the first
1313 // location of its includer.
1314 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001315 // Main file is the importer.
1316 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1317 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001318 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001319 return F->ImportedBy[0]->FirstLoc;
1320}
1321
1322/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1323/// specified cursor. Read the abbreviations that are at the top of the block
1324/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001325bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001326 if (Cursor.EnterSubBlock(BlockID)) {
1327 Error("malformed block record in AST file");
1328 return Failure;
1329 }
1330
1331 while (true) {
1332 uint64_t Offset = Cursor.GetCurrentBitNo();
1333 unsigned Code = Cursor.ReadCode();
1334
1335 // We expect all abbrevs to be at the start of the block.
1336 if (Code != llvm::bitc::DEFINE_ABBREV) {
1337 Cursor.JumpToBit(Offset);
1338 return false;
1339 }
1340 Cursor.ReadAbbrevRecord();
1341 }
1342}
1343
Richard Smithe40f2ba2013-08-07 21:41:30 +00001344Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001345 unsigned &Idx) {
1346 Token Tok;
1347 Tok.startToken();
1348 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1349 Tok.setLength(Record[Idx++]);
1350 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1351 Tok.setIdentifierInfo(II);
1352 Tok.setKind((tok::TokenKind)Record[Idx++]);
1353 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1354 return Tok;
1355}
1356
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001357MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001358 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001359
1360 // Keep track of where we are in the stream, then jump back there
1361 // after reading this macro.
1362 SavedStreamPosition SavedPosition(Stream);
1363
1364 Stream.JumpToBit(Offset);
1365 RecordData Record;
1366 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001367 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001368
Guy Benyei11169dd2012-12-18 14:30:41 +00001369 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001370 // Advance to the next record, but if we get to the end of the block, don't
1371 // pop it (removing all the abbreviations from the cursor) since we want to
1372 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001373 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001374 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1375
1376 switch (Entry.Kind) {
1377 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1378 case llvm::BitstreamEntry::Error:
1379 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001380 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001381 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001382 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001383 case llvm::BitstreamEntry::Record:
1384 // The interesting case.
1385 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001386 }
1387
1388 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001389 Record.clear();
1390 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001391 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001392 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001393 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001394 case PP_MACRO_DIRECTIVE_HISTORY:
1395 return Macro;
1396
Guy Benyei11169dd2012-12-18 14:30:41 +00001397 case PP_MACRO_OBJECT_LIKE:
1398 case PP_MACRO_FUNCTION_LIKE: {
1399 // If we already have a macro, that means that we've hit the end
1400 // of the definition of the macro we were looking for. We're
1401 // done.
1402 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001403 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001404
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001405 unsigned NextIndex = 1; // Skip identifier ID.
1406 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001407 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001408 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001409 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001410 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001411 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001412
Guy Benyei11169dd2012-12-18 14:30:41 +00001413 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1414 // Decode function-like macro info.
1415 bool isC99VarArgs = Record[NextIndex++];
1416 bool isGNUVarArgs = Record[NextIndex++];
1417 bool hasCommaPasting = Record[NextIndex++];
1418 MacroArgs.clear();
1419 unsigned NumArgs = Record[NextIndex++];
1420 for (unsigned i = 0; i != NumArgs; ++i)
1421 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1422
1423 // Install function-like macro info.
1424 MI->setIsFunctionLike();
1425 if (isC99VarArgs) MI->setIsC99Varargs();
1426 if (isGNUVarArgs) MI->setIsGNUVarargs();
1427 if (hasCommaPasting) MI->setHasCommaPasting();
1428 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1429 PP.getPreprocessorAllocator());
1430 }
1431
Guy Benyei11169dd2012-12-18 14:30:41 +00001432 // Remember that we saw this macro last so that we add the tokens that
1433 // form its body to it.
1434 Macro = MI;
1435
1436 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1437 Record[NextIndex]) {
1438 // We have a macro definition. Register the association
1439 PreprocessedEntityID
1440 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1441 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001442 PreprocessingRecord::PPEntityID PPID =
1443 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1444 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1445 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001446 if (PPDef)
1447 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001448 }
1449
1450 ++NumMacrosRead;
1451 break;
1452 }
1453
1454 case PP_TOKEN: {
1455 // If we see a TOKEN before a PP_MACRO_*, then the file is
1456 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001457 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001458
John McCallf413f5e2013-05-03 00:10:13 +00001459 unsigned Idx = 0;
1460 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001461 Macro->AddTokenToBody(Tok);
1462 break;
1463 }
1464 }
1465 }
1466}
1467
1468PreprocessedEntityID
1469ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1470 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1471 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1472 assert(I != M.PreprocessedEntityRemap.end()
1473 && "Invalid index into preprocessed entity index remap");
1474
1475 return LocalID + I->second;
1476}
1477
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001478unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1479 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001480}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001481
Guy Benyei11169dd2012-12-18 14:30:41 +00001482HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001483HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1484 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001485 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001486 return ikey;
1487}
Guy Benyei11169dd2012-12-18 14:30:41 +00001488
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001489bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1490 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001491 return false;
1492
Richard Smith7ed1bc92014-12-05 22:42:13 +00001493 if (llvm::sys::path::is_absolute(a.Filename) &&
1494 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001495 return true;
1496
Guy Benyei11169dd2012-12-18 14:30:41 +00001497 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001498 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001499 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1500 if (!Key.Imported)
1501 return FileMgr.getFile(Key.Filename);
1502
1503 std::string Resolved = Key.Filename;
1504 Reader.ResolveImportedPath(M, Resolved);
1505 return FileMgr.getFile(Resolved);
1506 };
1507
1508 const FileEntry *FEA = GetFile(a);
1509 const FileEntry *FEB = GetFile(b);
1510 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001511}
1512
1513std::pair<unsigned, unsigned>
1514HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001515 using namespace llvm::support;
1516 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001518 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001519}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001520
1521HeaderFileInfoTrait::internal_key_type
1522HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001523 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001524 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001525 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1526 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001527 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001528 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001529 return ikey;
1530}
1531
Guy Benyei11169dd2012-12-18 14:30:41 +00001532HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001533HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001534 unsigned DataLen) {
1535 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001536 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001537 HeaderFileInfo HFI;
1538 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001539 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1540 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001541 HFI.isImport = (Flags >> 5) & 0x01;
1542 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1543 HFI.DirInfo = (Flags >> 2) & 0x03;
1544 HFI.Resolved = (Flags >> 1) & 0x01;
1545 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001546 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1547 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1548 M, endian::readNext<uint32_t, little, unaligned>(d));
1549 if (unsigned FrameworkOffset =
1550 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001551 // The framework offset is 1 greater than the actual offset,
1552 // since 0 is used as an indicator for "no framework name".
1553 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1554 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1555 }
1556
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001557 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001558 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001559 if (LocalSMID) {
1560 // This header is part of a module. Associate it with the module to enable
1561 // implicit module import.
1562 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1563 Module *Mod = Reader.getSubmodule(GlobalSMID);
1564 HFI.isModuleHeader = true;
1565 FileManager &FileMgr = Reader.getFileManager();
1566 ModuleMap &ModMap =
1567 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001568 // FIXME: This information should be propagated through the
1569 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001570 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001571 std::string Filename = key.Filename;
1572 if (key.Imported)
1573 Reader.ResolveImportedPath(M, Filename);
1574 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001575 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001576 }
1577 }
1578
Guy Benyei11169dd2012-12-18 14:30:41 +00001579 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1580 (void)End;
1581
1582 // This HeaderFileInfo was externally loaded.
1583 HFI.External = true;
1584 return HFI;
1585}
1586
Richard Smithd7329392015-04-21 21:46:32 +00001587void ASTReader::addPendingMacro(IdentifierInfo *II,
1588 ModuleFile *M,
1589 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001590 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1591 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001592}
1593
1594void ASTReader::ReadDefinedMacros() {
1595 // Note that we are loading defined macros.
1596 Deserializing Macros(this);
1597
1598 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1599 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001600 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001601
1602 // If there was no preprocessor block, skip this file.
1603 if (!MacroCursor.getBitStreamReader())
1604 continue;
1605
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001606 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001607 Cursor.JumpToBit((*I)->MacroStartOffset);
1608
1609 RecordData Record;
1610 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001611 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1612
1613 switch (E.Kind) {
1614 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1615 case llvm::BitstreamEntry::Error:
1616 Error("malformed block record in AST file");
1617 return;
1618 case llvm::BitstreamEntry::EndBlock:
1619 goto NextCursor;
1620
1621 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001622 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001623 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001624 default: // Default behavior: ignore.
1625 break;
1626
1627 case PP_MACRO_OBJECT_LIKE:
1628 case PP_MACRO_FUNCTION_LIKE:
1629 getLocalIdentifier(**I, Record[0]);
1630 break;
1631
1632 case PP_TOKEN:
1633 // Ignore tokens.
1634 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001635 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001636 break;
1637 }
1638 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001639 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001640 }
1641}
1642
1643namespace {
1644 /// \brief Visitor class used to look up identifirs in an AST file.
1645 class IdentifierLookupVisitor {
1646 StringRef Name;
1647 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001648 unsigned &NumIdentifierLookups;
1649 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001650 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001651
Guy Benyei11169dd2012-12-18 14:30:41 +00001652 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001653 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1654 unsigned &NumIdentifierLookups,
1655 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001656 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001657 NumIdentifierLookups(NumIdentifierLookups),
1658 NumIdentifierLookupHits(NumIdentifierLookupHits),
1659 Found()
1660 {
1661 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001662
1663 static bool visit(ModuleFile &M, void *UserData) {
1664 IdentifierLookupVisitor *This
1665 = static_cast<IdentifierLookupVisitor *>(UserData);
1666
1667 // If we've already searched this module file, skip it now.
1668 if (M.Generation <= This->PriorGeneration)
1669 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001670
Guy Benyei11169dd2012-12-18 14:30:41 +00001671 ASTIdentifierLookupTable *IdTable
1672 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1673 if (!IdTable)
1674 return false;
1675
1676 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1677 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001678 ++This->NumIdentifierLookups;
1679 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001680 if (Pos == IdTable->end())
1681 return false;
1682
1683 // Dereferencing the iterator has the effect of building the
1684 // IdentifierInfo node and populating it with the various
1685 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001686 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001687 This->Found = *Pos;
1688 return true;
1689 }
1690
1691 // \brief Retrieve the identifier info found within the module
1692 // files.
1693 IdentifierInfo *getIdentifierInfo() const { return Found; }
1694 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001695}
Guy Benyei11169dd2012-12-18 14:30:41 +00001696
1697void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1698 // Note that we are loading an identifier.
1699 Deserializing AnIdentifier(this);
1700
1701 unsigned PriorGeneration = 0;
1702 if (getContext().getLangOpts().Modules)
1703 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001704
1705 // If there is a global index, look there first to determine which modules
1706 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001707 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001708 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001709 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001710 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1711 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001712 }
1713 }
1714
Douglas Gregor7211ac12013-01-25 23:32:03 +00001715 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001716 NumIdentifierLookups,
1717 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001718 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001719 markIdentifierUpToDate(&II);
1720}
1721
1722void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1723 if (!II)
1724 return;
1725
1726 II->setOutOfDate(false);
1727
1728 // Update the generation for this identifier.
1729 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001730 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001731}
1732
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001733void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1734 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001735 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001736
1737 BitstreamCursor &Cursor = M.MacroCursor;
1738 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001739 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001740
Richard Smith713369b2015-04-23 20:40:50 +00001741 struct ModuleMacroRecord {
1742 SubmoduleID SubModID;
1743 MacroInfo *MI;
1744 SmallVector<SubmoduleID, 8> Overrides;
1745 };
1746 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001747
Richard Smithd7329392015-04-21 21:46:32 +00001748 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1749 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1750 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001751 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001752 while (true) {
1753 llvm::BitstreamEntry Entry =
1754 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1755 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1756 Error("malformed block record in AST file");
1757 return;
1758 }
1759
1760 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001761 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001762 case PP_MACRO_DIRECTIVE_HISTORY:
1763 break;
1764
1765 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001766 ModuleMacros.push_back(ModuleMacroRecord());
1767 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001768 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1769 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001770 for (int I = 2, N = Record.size(); I != N; ++I)
1771 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001772 continue;
1773 }
1774
1775 default:
1776 Error("malformed block record in AST file");
1777 return;
1778 }
1779
1780 // We found the macro directive history; that's the last record
1781 // for this macro.
1782 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001783 }
1784
Richard Smithd7329392015-04-21 21:46:32 +00001785 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001786 {
1787 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001788 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001789 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001790 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001791 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001792 Module *Mod = getSubmodule(ModID);
1793 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001794 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001795 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001796 }
1797
1798 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001799 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001800 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001801 }
1802 }
1803
1804 // Don't read the directive history for a module; we don't have anywhere
1805 // to put it.
1806 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1807 return;
1808
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001809 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001810 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001811 unsigned Idx = 0, N = Record.size();
1812 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001813 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001814 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001815 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1816 switch (K) {
1817 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001818 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001819 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001820 break;
1821 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001822 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001823 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001824 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001825 }
1826 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001827 bool isPublic = Record[Idx++];
1828 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1829 break;
1830 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001831
1832 if (!Latest)
1833 Latest = MD;
1834 if (Earliest)
1835 Earliest->setPrevious(MD);
1836 Earliest = MD;
1837 }
1838
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001839 if (Latest)
1840 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001841}
1842
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001843ASTReader::InputFileInfo
1844ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001845 // Go find this input file.
1846 BitstreamCursor &Cursor = F.InputFilesCursor;
1847 SavedStreamPosition SavedPosition(Cursor);
1848 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1849
1850 unsigned Code = Cursor.ReadCode();
1851 RecordData Record;
1852 StringRef Blob;
1853
1854 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1855 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1856 "invalid record type for input file");
1857 (void)Result;
1858
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001859 std::string Filename;
1860 off_t StoredSize;
1861 time_t StoredTime;
1862 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001863
Ben Langmuir198c1682014-03-07 07:27:49 +00001864 assert(Record[0] == ID && "Bogus stored ID or offset");
1865 StoredSize = static_cast<off_t>(Record[1]);
1866 StoredTime = static_cast<time_t>(Record[2]);
1867 Overridden = static_cast<bool>(Record[3]);
1868 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001869 ResolveImportedPath(F, Filename);
1870
Hans Wennborg73945142014-03-14 17:45:06 +00001871 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1872 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001873}
1874
1875std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001876 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00001877}
1878
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001879InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001880 // If this ID is bogus, just return an empty input file.
1881 if (ID == 0 || ID > F.InputFilesLoaded.size())
1882 return InputFile();
1883
1884 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001885 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001886 return F.InputFilesLoaded[ID-1];
1887
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001888 if (F.InputFilesLoaded[ID-1].isNotFound())
1889 return InputFile();
1890
Guy Benyei11169dd2012-12-18 14:30:41 +00001891 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001892 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001893 SavedStreamPosition SavedPosition(Cursor);
1894 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1895
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001896 InputFileInfo FI = readInputFileInfo(F, ID);
1897 off_t StoredSize = FI.StoredSize;
1898 time_t StoredTime = FI.StoredTime;
1899 bool Overridden = FI.Overridden;
1900 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001901
Ben Langmuir198c1682014-03-07 07:27:49 +00001902 const FileEntry *File
1903 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1904 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1905
1906 // If we didn't find the file, resolve it relative to the
1907 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001908 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001909 F.OriginalDir != CurrentDir) {
1910 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1911 F.OriginalDir,
1912 CurrentDir);
1913 if (!Resolved.empty())
1914 File = FileMgr.getFile(Resolved);
1915 }
1916
1917 // For an overridden file, create a virtual file with the stored
1918 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001919 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001920 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1921 }
1922
Craig Toppera13603a2014-05-22 05:54:18 +00001923 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001924 if (Complain) {
1925 std::string ErrorStr = "could not find file '";
1926 ErrorStr += Filename;
1927 ErrorStr += "' referenced by AST file";
1928 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001929 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001930 // Record that we didn't find the file.
1931 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1932 return InputFile();
1933 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001934
Ben Langmuir198c1682014-03-07 07:27:49 +00001935 // Check if there was a request to override the contents of the file
1936 // that was part of the precompiled header. Overridding such a file
1937 // can lead to problems when lexing using the source locations from the
1938 // PCH.
1939 SourceManager &SM = getSourceManager();
1940 if (!Overridden && SM.isFileOverridden(File)) {
1941 if (Complain)
1942 Error(diag::err_fe_pch_file_overridden, Filename);
1943 // After emitting the diagnostic, recover by disabling the override so
1944 // that the original file will be used.
1945 SM.disableFileContentsOverride(File);
1946 // The FileEntry is a virtual file entry with the size of the contents
1947 // that would override the original contents. Set it to the original's
1948 // size/time.
1949 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1950 StoredSize, StoredTime);
1951 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001952
Ben Langmuir198c1682014-03-07 07:27:49 +00001953 bool IsOutOfDate = false;
1954
1955 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001956 if (!Overridden && //
1957 (StoredSize != File->getSize() ||
1958#if defined(LLVM_ON_WIN32)
1959 false
1960#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001961 // In our regression testing, the Windows file system seems to
1962 // have inconsistent modification times that sometimes
1963 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001964 //
1965 // This also happens in networked file systems, so disable this
1966 // check if validation is disabled or if we have an explicitly
1967 // built PCM file.
1968 //
1969 // FIXME: Should we also do this for PCH files? They could also
1970 // reasonably get shared across a network during a distributed build.
1971 (StoredTime != File->getModificationTime() && !DisableValidation &&
1972 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001973#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001974 )) {
1975 if (Complain) {
1976 // Build a list of the PCH imports that got us here (in reverse).
1977 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1978 while (ImportStack.back()->ImportedBy.size() > 0)
1979 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001980
Ben Langmuir198c1682014-03-07 07:27:49 +00001981 // The top-level PCH is stale.
1982 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1983 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00001984
Ben Langmuir198c1682014-03-07 07:27:49 +00001985 // Print the import stack.
1986 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1987 Diag(diag::note_pch_required_by)
1988 << Filename << ImportStack[0]->FileName;
1989 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00001990 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00001991 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00001992 }
1993
Ben Langmuir198c1682014-03-07 07:27:49 +00001994 if (!Diags.isDiagnosticInFlight())
1995 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00001996 }
1997
Ben Langmuir198c1682014-03-07 07:27:49 +00001998 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001999 }
2000
Ben Langmuir198c1682014-03-07 07:27:49 +00002001 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2002
2003 // Note that we've loaded this input file.
2004 F.InputFilesLoaded[ID-1] = IF;
2005 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002006}
2007
Richard Smith7ed1bc92014-12-05 22:42:13 +00002008/// \brief If we are loading a relocatable PCH or module file, and the filename
2009/// is not an absolute path, add the system or module root to the beginning of
2010/// the file name.
2011void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2012 // Resolve relative to the base directory, if we have one.
2013 if (!M.BaseDirectory.empty())
2014 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002015}
2016
Richard Smith7ed1bc92014-12-05 22:42:13 +00002017void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002018 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2019 return;
2020
Richard Smith7ed1bc92014-12-05 22:42:13 +00002021 SmallString<128> Buffer;
2022 llvm::sys::path::append(Buffer, Prefix, Filename);
2023 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002024}
2025
2026ASTReader::ASTReadResult
2027ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002028 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002029 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002030 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002031 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002032
2033 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2034 Error("malformed block record in AST file");
2035 return Failure;
2036 }
2037
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002038 // Should we allow the configuration of the module file to differ from the
2039 // configuration of the current translation unit in a compatible way?
2040 //
2041 // FIXME: Allow this for files explicitly specified with -include-pch too.
2042 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2043
Guy Benyei11169dd2012-12-18 14:30:41 +00002044 // Read all of the records and blocks in the control block.
2045 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002046 unsigned NumInputs = 0;
2047 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002048 while (1) {
2049 llvm::BitstreamEntry Entry = Stream.advance();
2050
2051 switch (Entry.Kind) {
2052 case llvm::BitstreamEntry::Error:
2053 Error("malformed block record in AST file");
2054 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002055 case llvm::BitstreamEntry::EndBlock: {
2056 // Validate input files.
2057 const HeaderSearchOptions &HSOpts =
2058 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002059
Richard Smitha1825302014-10-23 22:18:29 +00002060 // All user input files reside at the index range [0, NumUserInputs), and
2061 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002062 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002063 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002064
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002065 // If we are reading a module, we will create a verification timestamp,
2066 // so we verify all input files. Otherwise, verify only user input
2067 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002068
2069 unsigned N = NumUserInputs;
2070 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002071 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002072 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002073 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002074 N = NumInputs;
2075
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002076 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002077 InputFile IF = getInputFile(F, I+1, Complain);
2078 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002079 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002080 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002081 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002082
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002083 if (Listener)
2084 Listener->visitModuleFile(F.FileName);
2085
Ben Langmuircb69b572014-03-07 06:40:32 +00002086 if (Listener && Listener->needsInputFileVisitation()) {
2087 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2088 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002089 for (unsigned I = 0; I < N; ++I) {
2090 bool IsSystem = I >= NumUserInputs;
2091 InputFileInfo FI = readInputFileInfo(F, I+1);
2092 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2093 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002094 }
2095
Guy Benyei11169dd2012-12-18 14:30:41 +00002096 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002097 }
2098
Chris Lattnere7b154b2013-01-19 21:39:22 +00002099 case llvm::BitstreamEntry::SubBlock:
2100 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002101 case INPUT_FILES_BLOCK_ID:
2102 F.InputFilesCursor = Stream;
2103 if (Stream.SkipBlock() || // Skip with the main cursor
2104 // Read the abbreviations
2105 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2106 Error("malformed block record in AST file");
2107 return Failure;
2108 }
2109 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002110
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002112 if (Stream.SkipBlock()) {
2113 Error("malformed block record in AST file");
2114 return Failure;
2115 }
2116 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002117 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002118
2119 case llvm::BitstreamEntry::Record:
2120 // The interesting case.
2121 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002122 }
2123
2124 // Read and process a record.
2125 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002126 StringRef Blob;
2127 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002128 case METADATA: {
2129 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2130 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002131 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2132 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002133 return VersionMismatch;
2134 }
2135
2136 bool hasErrors = Record[5];
2137 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2138 Diag(diag::err_pch_with_compiler_errors);
2139 return HadErrors;
2140 }
2141
2142 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002143 // Relative paths in a relocatable PCH are relative to our sysroot.
2144 if (F.RelocatablePCH)
2145 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002146
2147 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002148 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002149 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2150 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002151 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002152 return VersionMismatch;
2153 }
2154 break;
2155 }
2156
Ben Langmuir487ea142014-10-23 18:05:36 +00002157 case SIGNATURE:
2158 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2159 F.Signature = Record[0];
2160 break;
2161
Guy Benyei11169dd2012-12-18 14:30:41 +00002162 case IMPORTS: {
2163 // Load each of the imported PCH files.
2164 unsigned Idx = 0, N = Record.size();
2165 while (Idx < N) {
2166 // Read information about the AST file.
2167 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2168 // The import location will be the local one for now; we will adjust
2169 // all import locations of module imports after the global source
2170 // location info are setup.
2171 SourceLocation ImportLoc =
2172 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002173 off_t StoredSize = (off_t)Record[Idx++];
2174 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002175 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002176 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002177
2178 // Load the AST file.
2179 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002180 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002181 ClientLoadCapabilities)) {
2182 case Failure: return Failure;
2183 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002184 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002185 case OutOfDate: return OutOfDate;
2186 case VersionMismatch: return VersionMismatch;
2187 case ConfigurationMismatch: return ConfigurationMismatch;
2188 case HadErrors: return HadErrors;
2189 case Success: break;
2190 }
2191 }
2192 break;
2193 }
2194
Richard Smith7f330cd2015-03-18 01:42:29 +00002195 case KNOWN_MODULE_FILES:
2196 break;
2197
Guy Benyei11169dd2012-12-18 14:30:41 +00002198 case LANGUAGE_OPTIONS: {
2199 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002200 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002201 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002202 ParseLanguageOptions(Record, Complain, *Listener,
2203 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002204 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002205 return ConfigurationMismatch;
2206 break;
2207 }
2208
2209 case TARGET_OPTIONS: {
2210 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2211 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002212 ParseTargetOptions(Record, Complain, *Listener,
2213 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002214 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002215 return ConfigurationMismatch;
2216 break;
2217 }
2218
2219 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002220 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002221 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002222 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002223 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002224 !DisableValidation)
2225 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002226 break;
2227 }
2228
2229 case FILE_SYSTEM_OPTIONS: {
2230 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2231 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002232 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002233 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002234 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002235 return ConfigurationMismatch;
2236 break;
2237 }
2238
2239 case HEADER_SEARCH_OPTIONS: {
2240 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2241 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002242 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002243 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002244 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002245 return ConfigurationMismatch;
2246 break;
2247 }
2248
2249 case PREPROCESSOR_OPTIONS: {
2250 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2251 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002252 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002253 ParsePreprocessorOptions(Record, Complain, *Listener,
2254 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002255 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002256 return ConfigurationMismatch;
2257 break;
2258 }
2259
2260 case ORIGINAL_FILE:
2261 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002262 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002263 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002264 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002265 break;
2266
2267 case ORIGINAL_FILE_ID:
2268 F.OriginalSourceFileID = FileID::get(Record[0]);
2269 break;
2270
2271 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002272 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002273 break;
2274
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002275 case MODULE_NAME:
2276 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002277 if (Listener)
2278 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002279 break;
2280
Richard Smith223d3f22014-12-06 03:21:08 +00002281 case MODULE_DIRECTORY: {
2282 assert(!F.ModuleName.empty() &&
2283 "MODULE_DIRECTORY found before MODULE_NAME");
2284 // If we've already loaded a module map file covering this module, we may
2285 // have a better path for it (relative to the current build).
2286 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2287 if (M && M->Directory) {
2288 // If we're implicitly loading a module, the base directory can't
2289 // change between the build and use.
2290 if (F.Kind != MK_ExplicitModule) {
2291 const DirectoryEntry *BuildDir =
2292 PP.getFileManager().getDirectory(Blob);
2293 if (!BuildDir || BuildDir != M->Directory) {
2294 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2295 Diag(diag::err_imported_module_relocated)
2296 << F.ModuleName << Blob << M->Directory->getName();
2297 return OutOfDate;
2298 }
2299 }
2300 F.BaseDirectory = M->Directory->getName();
2301 } else {
2302 F.BaseDirectory = Blob;
2303 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002304 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002305 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002306
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002307 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002308 if (ASTReadResult Result =
2309 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2310 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002311 break;
2312
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002313 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002314 NumInputs = Record[0];
2315 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002316 F.InputFileOffsets =
2317 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002318 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002319 break;
2320 }
2321 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002322}
2323
Ben Langmuir2c9af442014-04-10 17:57:43 +00002324ASTReader::ASTReadResult
2325ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002326 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002327
2328 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2329 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002330 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002331 }
2332
2333 // Read all of the records and blocks for the AST file.
2334 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002335 while (1) {
2336 llvm::BitstreamEntry Entry = Stream.advance();
2337
2338 switch (Entry.Kind) {
2339 case llvm::BitstreamEntry::Error:
2340 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002341 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002342 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002343 // Outside of C++, we do not store a lookup map for the translation unit.
2344 // Instead, mark it as needing a lookup map to be built if this module
2345 // contains any declarations lexically within it (which it always does!).
2346 // This usually has no cost, since we very rarely need the lookup map for
2347 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002348 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002349 if (DC->hasExternalLexicalStorage() &&
2350 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002351 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002352
Ben Langmuir2c9af442014-04-10 17:57:43 +00002353 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002354 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002355 case llvm::BitstreamEntry::SubBlock:
2356 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002357 case DECLTYPES_BLOCK_ID:
2358 // We lazily load the decls block, but we want to set up the
2359 // DeclsCursor cursor to point into it. Clone our current bitcode
2360 // cursor to it, enter the block and read the abbrevs in that block.
2361 // With the main cursor, we just skip over it.
2362 F.DeclsCursor = Stream;
2363 if (Stream.SkipBlock() || // Skip with the main cursor.
2364 // Read the abbrevs.
2365 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2366 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002367 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 }
2369 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002370
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 case PREPROCESSOR_BLOCK_ID:
2372 F.MacroCursor = Stream;
2373 if (!PP.getExternalSource())
2374 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002375
Guy Benyei11169dd2012-12-18 14:30:41 +00002376 if (Stream.SkipBlock() ||
2377 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2378 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002379 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002380 }
2381 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2382 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002383
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 case PREPROCESSOR_DETAIL_BLOCK_ID:
2385 F.PreprocessorDetailCursor = Stream;
2386 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002387 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002388 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002389 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002390 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002391 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002393 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2394
Guy Benyei11169dd2012-12-18 14:30:41 +00002395 if (!PP.getPreprocessingRecord())
2396 PP.createPreprocessingRecord();
2397 if (!PP.getPreprocessingRecord()->getExternalSource())
2398 PP.getPreprocessingRecord()->SetExternalSource(*this);
2399 break;
2400
2401 case SOURCE_MANAGER_BLOCK_ID:
2402 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002403 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002404 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002405
Guy Benyei11169dd2012-12-18 14:30:41 +00002406 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002407 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2408 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002409 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002410
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002412 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002413 if (Stream.SkipBlock() ||
2414 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2415 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002416 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002417 }
2418 CommentsCursors.push_back(std::make_pair(C, &F));
2419 break;
2420 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002421
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002423 if (Stream.SkipBlock()) {
2424 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002425 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002426 }
2427 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002428 }
2429 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002430
2431 case llvm::BitstreamEntry::Record:
2432 // The interesting case.
2433 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 }
2435
2436 // Read and process a record.
2437 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002438 StringRef Blob;
2439 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002440 default: // Default behavior: ignore.
2441 break;
2442
2443 case TYPE_OFFSET: {
2444 if (F.LocalNumTypes != 0) {
2445 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002446 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002447 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002448 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002449 F.LocalNumTypes = Record[0];
2450 unsigned LocalBaseTypeIndex = Record[1];
2451 F.BaseTypeIndex = getTotalNumTypes();
2452
2453 if (F.LocalNumTypes > 0) {
2454 // Introduce the global -> local mapping for types within this module.
2455 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2456
2457 // Introduce the local -> global mapping for types within this module.
2458 F.TypeRemap.insertOrReplace(
2459 std::make_pair(LocalBaseTypeIndex,
2460 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002461
2462 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 }
2464 break;
2465 }
2466
2467 case DECL_OFFSET: {
2468 if (F.LocalNumDecls != 0) {
2469 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002470 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002472 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002473 F.LocalNumDecls = Record[0];
2474 unsigned LocalBaseDeclID = Record[1];
2475 F.BaseDeclID = getTotalNumDecls();
2476
2477 if (F.LocalNumDecls > 0) {
2478 // Introduce the global -> local mapping for declarations within this
2479 // module.
2480 GlobalDeclMap.insert(
2481 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2482
2483 // Introduce the local -> global mapping for declarations within this
2484 // module.
2485 F.DeclRemap.insertOrReplace(
2486 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2487
2488 // Introduce the global -> local mapping for declarations within this
2489 // module.
2490 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002491
Ben Langmuir52ca6782014-10-20 16:27:32 +00002492 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2493 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002494 break;
2495 }
2496
2497 case TU_UPDATE_LEXICAL: {
2498 DeclContext *TU = Context.getTranslationUnitDecl();
2499 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002500 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002502 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 TU->setHasExternalLexicalStorage(true);
2504 break;
2505 }
2506
2507 case UPDATE_VISIBLE: {
2508 unsigned Idx = 0;
2509 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2510 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002511 ASTDeclContextNameLookupTable::Create(
2512 (const unsigned char *)Blob.data() + Record[Idx++],
2513 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2514 (const unsigned char *)Blob.data(),
2515 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002516 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002517 auto *DC = cast<DeclContext>(D);
2518 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002519 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2520 delete LookupTable;
2521 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 } else
2523 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2524 break;
2525 }
2526
2527 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002528 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002529 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002530 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2531 (const unsigned char *)F.IdentifierTableData + Record[0],
2532 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2533 (const unsigned char *)F.IdentifierTableData,
2534 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002535
2536 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2537 }
2538 break;
2539
2540 case IDENTIFIER_OFFSET: {
2541 if (F.LocalNumIdentifiers != 0) {
2542 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002543 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002544 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002545 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002546 F.LocalNumIdentifiers = Record[0];
2547 unsigned LocalBaseIdentifierID = Record[1];
2548 F.BaseIdentifierID = getTotalNumIdentifiers();
2549
2550 if (F.LocalNumIdentifiers > 0) {
2551 // Introduce the global -> local mapping for identifiers within this
2552 // module.
2553 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2554 &F));
2555
2556 // Introduce the local -> global mapping for identifiers within this
2557 // module.
2558 F.IdentifierRemap.insertOrReplace(
2559 std::make_pair(LocalBaseIdentifierID,
2560 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002561
Ben Langmuir52ca6782014-10-20 16:27:32 +00002562 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2563 + F.LocalNumIdentifiers);
2564 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 break;
2566 }
2567
Ben Langmuir332aafe2014-01-31 01:06:56 +00002568 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002569 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2570 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002572 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 break;
2574
2575 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002576 if (SpecialTypes.empty()) {
2577 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2578 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2579 break;
2580 }
2581
2582 if (SpecialTypes.size() != Record.size()) {
2583 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002584 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002585 }
2586
2587 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2588 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2589 if (!SpecialTypes[I])
2590 SpecialTypes[I] = ID;
2591 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2592 // merge step?
2593 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 break;
2595
2596 case STATISTICS:
2597 TotalNumStatements += Record[0];
2598 TotalNumMacros += Record[1];
2599 TotalLexicalDeclContexts += Record[2];
2600 TotalVisibleDeclContexts += Record[3];
2601 break;
2602
2603 case UNUSED_FILESCOPED_DECLS:
2604 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2605 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2606 break;
2607
2608 case DELEGATING_CTORS:
2609 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2610 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2611 break;
2612
2613 case WEAK_UNDECLARED_IDENTIFIERS:
2614 if (Record.size() % 4 != 0) {
2615 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002616 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002617 }
2618
2619 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2620 // files. This isn't the way to do it :)
2621 WeakUndeclaredIdentifiers.clear();
2622
2623 // Translate the weak, undeclared identifiers into global IDs.
2624 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2625 WeakUndeclaredIdentifiers.push_back(
2626 getGlobalIdentifierID(F, Record[I++]));
2627 WeakUndeclaredIdentifiers.push_back(
2628 getGlobalIdentifierID(F, Record[I++]));
2629 WeakUndeclaredIdentifiers.push_back(
2630 ReadSourceLocation(F, Record, I).getRawEncoding());
2631 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2632 }
2633 break;
2634
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002636 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 F.LocalNumSelectors = Record[0];
2638 unsigned LocalBaseSelectorID = Record[1];
2639 F.BaseSelectorID = getTotalNumSelectors();
2640
2641 if (F.LocalNumSelectors > 0) {
2642 // Introduce the global -> local mapping for selectors within this
2643 // module.
2644 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2645
2646 // Introduce the local -> global mapping for selectors within this
2647 // module.
2648 F.SelectorRemap.insertOrReplace(
2649 std::make_pair(LocalBaseSelectorID,
2650 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002651
2652 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 }
2654 break;
2655 }
2656
2657 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002658 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002659 if (Record[0])
2660 F.SelectorLookupTable
2661 = ASTSelectorLookupTable::Create(
2662 F.SelectorLookupTableData + Record[0],
2663 F.SelectorLookupTableData,
2664 ASTSelectorLookupTrait(*this, F));
2665 TotalNumMethodPoolEntries += Record[1];
2666 break;
2667
2668 case REFERENCED_SELECTOR_POOL:
2669 if (!Record.empty()) {
2670 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2671 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2672 Record[Idx++]));
2673 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2674 getRawEncoding());
2675 }
2676 }
2677 break;
2678
2679 case PP_COUNTER_VALUE:
2680 if (!Record.empty() && Listener)
2681 Listener->ReadCounter(F, Record[0]);
2682 break;
2683
2684 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002685 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 F.NumFileSortedDecls = Record[0];
2687 break;
2688
2689 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002690 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 F.LocalNumSLocEntries = Record[0];
2692 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002693 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002694 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002695 SLocSpaceSize);
2696 // Make our entry in the range map. BaseID is negative and growing, so
2697 // we invert it. Because we invert it, though, we need the other end of
2698 // the range.
2699 unsigned RangeStart =
2700 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2701 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2702 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2703
2704 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2705 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2706 GlobalSLocOffsetMap.insert(
2707 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2708 - SLocSpaceSize,&F));
2709
2710 // Initialize the remapping table.
2711 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002712 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002714 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2716
2717 TotalNumSLocEntries += F.LocalNumSLocEntries;
2718 break;
2719 }
2720
2721 case MODULE_OFFSET_MAP: {
2722 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002723 const unsigned char *Data = (const unsigned char*)Blob.data();
2724 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002725
2726 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2727 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2728 F.SLocRemap.insert(std::make_pair(0U, 0));
2729 F.SLocRemap.insert(std::make_pair(2U, 1));
2730 }
2731
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002733 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2734 RemapBuilder;
2735 RemapBuilder SLocRemap(F.SLocRemap);
2736 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2737 RemapBuilder MacroRemap(F.MacroRemap);
2738 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2739 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2740 RemapBuilder SelectorRemap(F.SelectorRemap);
2741 RemapBuilder DeclRemap(F.DeclRemap);
2742 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002743
2744 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002745 using namespace llvm::support;
2746 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 StringRef Name = StringRef((const char*)Data, Len);
2748 Data += Len;
2749 ModuleFile *OM = ModuleMgr.lookup(Name);
2750 if (!OM) {
2751 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002752 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002753 }
2754
Justin Bogner57ba0b22014-03-28 22:03:24 +00002755 uint32_t SLocOffset =
2756 endian::readNext<uint32_t, little, unaligned>(Data);
2757 uint32_t IdentifierIDOffset =
2758 endian::readNext<uint32_t, little, unaligned>(Data);
2759 uint32_t MacroIDOffset =
2760 endian::readNext<uint32_t, little, unaligned>(Data);
2761 uint32_t PreprocessedEntityIDOffset =
2762 endian::readNext<uint32_t, little, unaligned>(Data);
2763 uint32_t SubmoduleIDOffset =
2764 endian::readNext<uint32_t, little, unaligned>(Data);
2765 uint32_t SelectorIDOffset =
2766 endian::readNext<uint32_t, little, unaligned>(Data);
2767 uint32_t DeclIDOffset =
2768 endian::readNext<uint32_t, little, unaligned>(Data);
2769 uint32_t TypeIndexOffset =
2770 endian::readNext<uint32_t, little, unaligned>(Data);
2771
Ben Langmuir785180e2014-10-20 16:27:30 +00002772 uint32_t None = std::numeric_limits<uint32_t>::max();
2773
2774 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2775 RemapBuilder &Remap) {
2776 if (Offset != None)
2777 Remap.insert(std::make_pair(Offset,
2778 static_cast<int>(BaseOffset - Offset)));
2779 };
2780 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2781 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2782 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2783 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2784 PreprocessedEntityRemap);
2785 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2786 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2787 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2788 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002789
2790 // Global -> local mappings.
2791 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2792 }
2793 break;
2794 }
2795
2796 case SOURCE_MANAGER_LINE_TABLE:
2797 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002798 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002799 break;
2800
2801 case SOURCE_LOCATION_PRELOADS: {
2802 // Need to transform from the local view (1-based IDs) to the global view,
2803 // which is based off F.SLocEntryBaseID.
2804 if (!F.PreloadSLocEntries.empty()) {
2805 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002806 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002807 }
2808
2809 F.PreloadSLocEntries.swap(Record);
2810 break;
2811 }
2812
2813 case EXT_VECTOR_DECLS:
2814 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2815 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2816 break;
2817
2818 case VTABLE_USES:
2819 if (Record.size() % 3 != 0) {
2820 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002821 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002822 }
2823
2824 // Later tables overwrite earlier ones.
2825 // FIXME: Modules will have some trouble with this. This is clearly not
2826 // the right way to do this.
2827 VTableUses.clear();
2828
2829 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2830 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2831 VTableUses.push_back(
2832 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2833 VTableUses.push_back(Record[Idx++]);
2834 }
2835 break;
2836
Guy Benyei11169dd2012-12-18 14:30:41 +00002837 case PENDING_IMPLICIT_INSTANTIATIONS:
2838 if (PendingInstantiations.size() % 2 != 0) {
2839 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002840 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002841 }
2842
2843 if (Record.size() % 2 != 0) {
2844 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002845 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002846 }
2847
2848 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2849 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2850 PendingInstantiations.push_back(
2851 ReadSourceLocation(F, Record, I).getRawEncoding());
2852 }
2853 break;
2854
2855 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002856 if (Record.size() != 2) {
2857 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002858 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002859 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2861 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2862 break;
2863
2864 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002865 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2866 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2867 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002868
2869 unsigned LocalBasePreprocessedEntityID = Record[0];
2870
2871 unsigned StartingID;
2872 if (!PP.getPreprocessingRecord())
2873 PP.createPreprocessingRecord();
2874 if (!PP.getPreprocessingRecord()->getExternalSource())
2875 PP.getPreprocessingRecord()->SetExternalSource(*this);
2876 StartingID
2877 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002878 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002879 F.BasePreprocessedEntityID = StartingID;
2880
2881 if (F.NumPreprocessedEntities > 0) {
2882 // Introduce the global -> local mapping for preprocessed entities in
2883 // this module.
2884 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2885
2886 // Introduce the local -> global mapping for preprocessed entities in
2887 // this module.
2888 F.PreprocessedEntityRemap.insertOrReplace(
2889 std::make_pair(LocalBasePreprocessedEntityID,
2890 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2891 }
2892
2893 break;
2894 }
2895
2896 case DECL_UPDATE_OFFSETS: {
2897 if (Record.size() % 2 != 0) {
2898 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002899 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002900 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002901 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2902 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2903 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2904
2905 // If we've already loaded the decl, perform the updates when we finish
2906 // loading this block.
2907 if (Decl *D = GetExistingDecl(ID))
2908 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2909 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002910 break;
2911 }
2912
2913 case DECL_REPLACEMENTS: {
2914 if (Record.size() % 3 != 0) {
2915 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002916 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002917 }
2918 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2919 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2920 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2921 break;
2922 }
2923
2924 case OBJC_CATEGORIES_MAP: {
2925 if (F.LocalNumObjCCategoriesInMap != 0) {
2926 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002927 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002928 }
2929
2930 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002931 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002932 break;
2933 }
2934
2935 case OBJC_CATEGORIES:
2936 F.ObjCCategories.swap(Record);
2937 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00002938
Guy Benyei11169dd2012-12-18 14:30:41 +00002939 case CXX_BASE_SPECIFIER_OFFSETS: {
2940 if (F.LocalNumCXXBaseSpecifiers != 0) {
2941 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002942 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002943 }
Richard Smithc2bb8182015-03-24 06:36:48 +00002944
Guy Benyei11169dd2012-12-18 14:30:41 +00002945 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002946 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00002947 break;
2948 }
2949
2950 case CXX_CTOR_INITIALIZERS_OFFSETS: {
2951 if (F.LocalNumCXXCtorInitializers != 0) {
2952 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2953 return Failure;
2954 }
2955
2956 F.LocalNumCXXCtorInitializers = Record[0];
2957 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002958 break;
2959 }
2960
2961 case DIAG_PRAGMA_MAPPINGS:
2962 if (F.PragmaDiagMappings.empty())
2963 F.PragmaDiagMappings.swap(Record);
2964 else
2965 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2966 Record.begin(), Record.end());
2967 break;
2968
2969 case CUDA_SPECIAL_DECL_REFS:
2970 // Later tables overwrite earlier ones.
2971 // FIXME: Modules will have trouble with this.
2972 CUDASpecialDeclRefs.clear();
2973 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2974 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2975 break;
2976
2977 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002978 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002979 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002980 if (Record[0]) {
2981 F.HeaderFileInfoTable
2982 = HeaderFileInfoLookupTable::Create(
2983 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2984 (const unsigned char *)F.HeaderFileInfoTableData,
2985 HeaderFileInfoTrait(*this, F,
2986 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002987 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002988
2989 PP.getHeaderSearchInfo().SetExternalSource(this);
2990 if (!PP.getHeaderSearchInfo().getExternalLookup())
2991 PP.getHeaderSearchInfo().SetExternalLookup(this);
2992 }
2993 break;
2994 }
2995
2996 case FP_PRAGMA_OPTIONS:
2997 // Later tables overwrite earlier ones.
2998 FPPragmaOptions.swap(Record);
2999 break;
3000
3001 case OPENCL_EXTENSIONS:
3002 // Later tables overwrite earlier ones.
3003 OpenCLExtensions.swap(Record);
3004 break;
3005
3006 case TENTATIVE_DEFINITIONS:
3007 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3008 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3009 break;
3010
3011 case KNOWN_NAMESPACES:
3012 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3013 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3014 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003015
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003016 case UNDEFINED_BUT_USED:
3017 if (UndefinedButUsed.size() % 2 != 0) {
3018 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003019 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003020 }
3021
3022 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003023 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003024 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003025 }
3026 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003027 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3028 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003029 ReadSourceLocation(F, Record, I).getRawEncoding());
3030 }
3031 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003032 case DELETE_EXPRS_TO_ANALYZE:
3033 for (unsigned I = 0, N = Record.size(); I != N;) {
3034 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3035 const uint64_t Count = Record[I++];
3036 DelayedDeleteExprs.push_back(Count);
3037 for (uint64_t C = 0; C < Count; ++C) {
3038 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3039 bool IsArrayForm = Record[I++] == 1;
3040 DelayedDeleteExprs.push_back(IsArrayForm);
3041 }
3042 }
3043 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003044
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003046 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003047 // If we aren't loading a module (which has its own exports), make
3048 // all of the imported modules visible.
3049 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003050 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3051 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3052 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3053 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003054 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003055 }
3056 }
3057 break;
3058 }
3059
3060 case LOCAL_REDECLARATIONS: {
3061 F.RedeclarationChains.swap(Record);
3062 break;
3063 }
3064
3065 case LOCAL_REDECLARATIONS_MAP: {
3066 if (F.LocalNumRedeclarationsInMap != 0) {
3067 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003068 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003069 }
3070
3071 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003072 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003073 break;
3074 }
3075
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 case MACRO_OFFSET: {
3077 if (F.LocalNumMacros != 0) {
3078 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003079 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003080 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003081 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003082 F.LocalNumMacros = Record[0];
3083 unsigned LocalBaseMacroID = Record[1];
3084 F.BaseMacroID = getTotalNumMacros();
3085
3086 if (F.LocalNumMacros > 0) {
3087 // Introduce the global -> local mapping for macros within this module.
3088 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3089
3090 // Introduce the local -> global mapping for macros within this module.
3091 F.MacroRemap.insertOrReplace(
3092 std::make_pair(LocalBaseMacroID,
3093 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003094
3095 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003096 }
3097 break;
3098 }
3099
Richard Smithe40f2ba2013-08-07 21:41:30 +00003100 case LATE_PARSED_TEMPLATE: {
3101 LateParsedTemplates.append(Record.begin(), Record.end());
3102 break;
3103 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003104
3105 case OPTIMIZE_PRAGMA_OPTIONS:
3106 if (Record.size() != 1) {
3107 Error("invalid pragma optimize record");
3108 return Failure;
3109 }
3110 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3111 break;
Nico Weber72889432014-09-06 01:25:55 +00003112
3113 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3114 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3115 UnusedLocalTypedefNameCandidates.push_back(
3116 getGlobalDeclID(F, Record[I]));
3117 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003118 }
3119 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003120}
3121
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003122ASTReader::ASTReadResult
3123ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3124 const ModuleFile *ImportedBy,
3125 unsigned ClientLoadCapabilities) {
3126 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003127 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003128
Richard Smithe842a472014-10-22 02:05:46 +00003129 if (F.Kind == MK_ExplicitModule) {
3130 // For an explicitly-loaded module, we don't care whether the original
3131 // module map file exists or matches.
3132 return Success;
3133 }
3134
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003135 // Try to resolve ModuleName in the current header search context and
3136 // verify that it is found in the same module map file as we saved. If the
3137 // top-level AST file is a main file, skip this check because there is no
3138 // usable header search context.
3139 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003140 "MODULE_NAME should come before MODULE_MAP_FILE");
3141 if (F.Kind == MK_ImplicitModule &&
3142 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3143 // An implicitly-loaded module file should have its module listed in some
3144 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003145 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003146 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3147 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3148 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003149 assert(ImportedBy && "top-level import should be verified");
3150 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003151 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3152 << ImportedBy->FileName
3153 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003154 return Missing;
3155 }
3156
Richard Smithe842a472014-10-22 02:05:46 +00003157 assert(M->Name == F.ModuleName && "found module with different name");
3158
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003159 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003160 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003161 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3162 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003163 assert(ImportedBy && "top-level import should be verified");
3164 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3165 Diag(diag::err_imported_module_modmap_changed)
3166 << F.ModuleName << ImportedBy->FileName
3167 << ModMap->getName() << F.ModuleMapPath;
3168 return OutOfDate;
3169 }
3170
3171 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3172 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3173 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003174 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003175 const FileEntry *F =
3176 FileMgr.getFile(Filename, false, false);
3177 if (F == nullptr) {
3178 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3179 Error("could not find file '" + Filename +"' referenced by AST file");
3180 return OutOfDate;
3181 }
3182 AdditionalStoredMaps.insert(F);
3183 }
3184
3185 // Check any additional module map files (e.g. module.private.modulemap)
3186 // that are not in the pcm.
3187 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3188 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3189 // Remove files that match
3190 // Note: SmallPtrSet::erase is really remove
3191 if (!AdditionalStoredMaps.erase(ModMap)) {
3192 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3193 Diag(diag::err_module_different_modmap)
3194 << F.ModuleName << /*new*/0 << ModMap->getName();
3195 return OutOfDate;
3196 }
3197 }
3198 }
3199
3200 // Check any additional module map files that are in the pcm, but not
3201 // found in header search. Cases that match are already removed.
3202 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3203 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3204 Diag(diag::err_module_different_modmap)
3205 << F.ModuleName << /*not new*/1 << ModMap->getName();
3206 return OutOfDate;
3207 }
3208 }
3209
3210 if (Listener)
3211 Listener->ReadModuleMapFile(F.ModuleMapPath);
3212 return Success;
3213}
3214
3215
Douglas Gregorc1489562013-02-12 23:36:21 +00003216/// \brief Move the given method to the back of the global list of methods.
3217static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3218 // Find the entry for this selector in the method pool.
3219 Sema::GlobalMethodPool::iterator Known
3220 = S.MethodPool.find(Method->getSelector());
3221 if (Known == S.MethodPool.end())
3222 return;
3223
3224 // Retrieve the appropriate method list.
3225 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3226 : Known->second.second;
3227 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003228 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003229 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003230 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003231 Found = true;
3232 } else {
3233 // Keep searching.
3234 continue;
3235 }
3236 }
3237
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003238 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003239 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003240 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003241 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003242 }
3243}
3244
Richard Smithde711422015-04-23 21:20:19 +00003245void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003246 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003247 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003248 bool wasHidden = D->Hidden;
3249 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003250
Richard Smith49f906a2014-03-01 00:08:04 +00003251 if (wasHidden && SemaObj) {
3252 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3253 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003254 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003255 }
3256 }
3257}
3258
Richard Smith49f906a2014-03-01 00:08:04 +00003259void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003260 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003261 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003262 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003263 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003264 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003265 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003266 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003267
3268 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003269 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003270 // there is nothing more to do.
3271 continue;
3272 }
Richard Smith49f906a2014-03-01 00:08:04 +00003273
Guy Benyei11169dd2012-12-18 14:30:41 +00003274 if (!Mod->isAvailable()) {
3275 // Modules that aren't available cannot be made visible.
3276 continue;
3277 }
3278
3279 // Update the module's name visibility.
3280 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003281
Guy Benyei11169dd2012-12-18 14:30:41 +00003282 // If we've already deserialized any names from this module,
3283 // mark them as visible.
3284 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3285 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003286 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003287 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003288 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003289 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3290 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003291 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003292
Guy Benyei11169dd2012-12-18 14:30:41 +00003293 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003294 SmallVector<Module *, 16> Exports;
3295 Mod->getExportedModules(Exports);
3296 for (SmallVectorImpl<Module *>::iterator
3297 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3298 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003299 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003300 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003301 }
3302 }
3303}
3304
Douglas Gregore060e572013-01-25 01:03:03 +00003305bool ASTReader::loadGlobalIndex() {
3306 if (GlobalIndex)
3307 return false;
3308
3309 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3310 !Context.getLangOpts().Modules)
3311 return true;
3312
3313 // Try to load the global index.
3314 TriedLoadingGlobalIndex = true;
3315 StringRef ModuleCachePath
3316 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3317 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003318 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003319 if (!Result.first)
3320 return true;
3321
3322 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003323 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003324 return false;
3325}
3326
3327bool ASTReader::isGlobalIndexUnavailable() const {
3328 return Context.getLangOpts().Modules && UseGlobalIndex &&
3329 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3330}
3331
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003332static void updateModuleTimestamp(ModuleFile &MF) {
3333 // Overwrite the timestamp file contents so that file's mtime changes.
3334 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003335 std::error_code EC;
3336 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3337 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003338 return;
3339 OS << "Timestamp file\n";
3340}
3341
Guy Benyei11169dd2012-12-18 14:30:41 +00003342ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3343 ModuleKind Type,
3344 SourceLocation ImportLoc,
3345 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003346 llvm::SaveAndRestore<SourceLocation>
3347 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3348
Richard Smithd1c46742014-04-30 02:24:17 +00003349 // Defer any pending actions until we get to the end of reading the AST file.
3350 Deserializing AnASTFile(this);
3351
Guy Benyei11169dd2012-12-18 14:30:41 +00003352 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003353 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003354
3355 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003356 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003357 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003358 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003359 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003360 ClientLoadCapabilities)) {
3361 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003362 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003363 case OutOfDate:
3364 case VersionMismatch:
3365 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003366 case HadErrors: {
3367 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3368 for (const ImportedModule &IM : Loaded)
3369 LoadedSet.insert(IM.Mod);
3370
Douglas Gregor7029ce12013-03-19 00:28:20 +00003371 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003372 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003373 Context.getLangOpts().Modules
3374 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003375 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003376
3377 // If we find that any modules are unusable, the global index is going
3378 // to be out-of-date. Just remove it.
3379 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003380 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003381 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003382 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003383 case Success:
3384 break;
3385 }
3386
3387 // Here comes stuff that we only do once the entire chain is loaded.
3388
3389 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003390 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3391 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003392 M != MEnd; ++M) {
3393 ModuleFile &F = *M->Mod;
3394
3395 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003396 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3397 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003398
3399 // Once read, set the ModuleFile bit base offset and update the size in
3400 // bits of all files we've seen.
3401 F.GlobalBitOffset = TotalModulesSizeInBits;
3402 TotalModulesSizeInBits += F.SizeInBits;
3403 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3404
3405 // Preload SLocEntries.
3406 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3407 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3408 // Load it through the SourceManager and don't call ReadSLocEntry()
3409 // directly because the entry may have already been loaded in which case
3410 // calling ReadSLocEntry() directly would trigger an assertion in
3411 // SourceManager.
3412 SourceMgr.getLoadedSLocEntryByID(Index);
3413 }
3414 }
3415
Douglas Gregor603cd862013-03-22 18:50:14 +00003416 // Setup the import locations and notify the module manager that we've
3417 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003418 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3419 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003420 M != MEnd; ++M) {
3421 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003422
3423 ModuleMgr.moduleFileAccepted(&F);
3424
3425 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003426 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003427 if (!M->ImportedBy)
3428 F.ImportLoc = M->ImportLoc;
3429 else
3430 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3431 M->ImportLoc.getRawEncoding());
3432 }
3433
3434 // Mark all of the identifiers in the identifier table as being out of date,
3435 // so that various accessors know to check the loaded modules when the
3436 // identifier is used.
3437 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3438 IdEnd = PP.getIdentifierTable().end();
3439 Id != IdEnd; ++Id)
3440 Id->second->setOutOfDate(true);
3441
3442 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003443 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3444 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003445 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3446 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003447
3448 switch (Unresolved.Kind) {
3449 case UnresolvedModuleRef::Conflict:
3450 if (ResolvedMod) {
3451 Module::Conflict Conflict;
3452 Conflict.Other = ResolvedMod;
3453 Conflict.Message = Unresolved.String.str();
3454 Unresolved.Mod->Conflicts.push_back(Conflict);
3455 }
3456 continue;
3457
3458 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003459 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003460 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003461 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003462
Douglas Gregorfb912652013-03-20 21:10:35 +00003463 case UnresolvedModuleRef::Export:
3464 if (ResolvedMod || Unresolved.IsWildcard)
3465 Unresolved.Mod->Exports.push_back(
3466 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3467 continue;
3468 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003469 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003470 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003471
3472 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3473 // Might be unnecessary as use declarations are only used to build the
3474 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003475
3476 InitializeContext();
3477
Richard Smith3d8e97e2013-10-18 06:54:39 +00003478 if (SemaObj)
3479 UpdateSema();
3480
Guy Benyei11169dd2012-12-18 14:30:41 +00003481 if (DeserializationListener)
3482 DeserializationListener->ReaderInitialized(this);
3483
3484 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3485 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3486 PrimaryModule.OriginalSourceFileID
3487 = FileID::get(PrimaryModule.SLocEntryBaseID
3488 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3489
3490 // If this AST file is a precompiled preamble, then set the
3491 // preamble file ID of the source manager to the file source file
3492 // from which the preamble was built.
3493 if (Type == MK_Preamble) {
3494 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3495 } else if (Type == MK_MainFile) {
3496 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3497 }
3498 }
3499
3500 // For any Objective-C class definitions we have already loaded, make sure
3501 // that we load any additional categories.
3502 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3503 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3504 ObjCClassesLoaded[I],
3505 PreviousGeneration);
3506 }
Douglas Gregore060e572013-01-25 01:03:03 +00003507
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003508 if (PP.getHeaderSearchInfo()
3509 .getHeaderSearchOpts()
3510 .ModulesValidateOncePerBuildSession) {
3511 // Now we are certain that the module and all modules it depends on are
3512 // up to date. Create or update timestamp files for modules that are
3513 // located in the module cache (not for PCH files that could be anywhere
3514 // in the filesystem).
3515 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3516 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003517 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003518 updateModuleTimestamp(*M.Mod);
3519 }
3520 }
3521 }
3522
Guy Benyei11169dd2012-12-18 14:30:41 +00003523 return Success;
3524}
3525
Ben Langmuir487ea142014-10-23 18:05:36 +00003526static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3527
Ben Langmuir70a1b812015-03-24 04:43:52 +00003528/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3529static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3530 return Stream.Read(8) == 'C' &&
3531 Stream.Read(8) == 'P' &&
3532 Stream.Read(8) == 'C' &&
3533 Stream.Read(8) == 'H';
3534}
3535
Guy Benyei11169dd2012-12-18 14:30:41 +00003536ASTReader::ASTReadResult
3537ASTReader::ReadASTCore(StringRef FileName,
3538 ModuleKind Type,
3539 SourceLocation ImportLoc,
3540 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003541 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003542 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003543 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003544 unsigned ClientLoadCapabilities) {
3545 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003546 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003547 ModuleManager::AddModuleResult AddResult
3548 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003549 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003550 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003551 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003552
Douglas Gregor7029ce12013-03-19 00:28:20 +00003553 switch (AddResult) {
3554 case ModuleManager::AlreadyLoaded:
3555 return Success;
3556
3557 case ModuleManager::NewlyLoaded:
3558 // Load module file below.
3559 break;
3560
3561 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003562 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003563 // it.
3564 if (ClientLoadCapabilities & ARR_Missing)
3565 return Missing;
3566
3567 // Otherwise, return an error.
3568 {
3569 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3570 + ErrorStr;
3571 Error(Msg);
3572 }
3573 return Failure;
3574
3575 case ModuleManager::OutOfDate:
3576 // We couldn't load the module file because it is out-of-date. If the
3577 // client can handle out-of-date, return it.
3578 if (ClientLoadCapabilities & ARR_OutOfDate)
3579 return OutOfDate;
3580
3581 // Otherwise, return an error.
3582 {
3583 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3584 + ErrorStr;
3585 Error(Msg);
3586 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003587 return Failure;
3588 }
3589
Douglas Gregor7029ce12013-03-19 00:28:20 +00003590 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003591
3592 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3593 // module?
3594 if (FileName != "-") {
3595 CurrentDir = llvm::sys::path::parent_path(FileName);
3596 if (CurrentDir.empty()) CurrentDir = ".";
3597 }
3598
3599 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003600 BitstreamCursor &Stream = F.Stream;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003601 PCHContainerOps.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003602 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003603 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3604
Guy Benyei11169dd2012-12-18 14:30:41 +00003605 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003606 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003607 Diag(diag::err_not_a_pch_file) << FileName;
3608 return Failure;
3609 }
3610
3611 // This is used for compatibility with older PCH formats.
3612 bool HaveReadControlBlock = false;
3613
Chris Lattnerefa77172013-01-20 00:00:22 +00003614 while (1) {
3615 llvm::BitstreamEntry Entry = Stream.advance();
3616
3617 switch (Entry.Kind) {
3618 case llvm::BitstreamEntry::Error:
3619 case llvm::BitstreamEntry::EndBlock:
3620 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003621 Error("invalid record at top-level of AST file");
3622 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003623
3624 case llvm::BitstreamEntry::SubBlock:
3625 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003626 }
3627
Guy Benyei11169dd2012-12-18 14:30:41 +00003628 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003629 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003630 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3631 if (Stream.ReadBlockInfoBlock()) {
3632 Error("malformed BlockInfoBlock in AST file");
3633 return Failure;
3634 }
3635 break;
3636 case CONTROL_BLOCK_ID:
3637 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003638 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003639 case Success:
3640 break;
3641
3642 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003643 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003644 case OutOfDate: return OutOfDate;
3645 case VersionMismatch: return VersionMismatch;
3646 case ConfigurationMismatch: return ConfigurationMismatch;
3647 case HadErrors: return HadErrors;
3648 }
3649 break;
3650 case AST_BLOCK_ID:
3651 if (!HaveReadControlBlock) {
3652 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003653 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003654 return VersionMismatch;
3655 }
3656
3657 // Record that we've loaded this module.
3658 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3659 return Success;
3660
3661 default:
3662 if (Stream.SkipBlock()) {
3663 Error("malformed block record in AST file");
3664 return Failure;
3665 }
3666 break;
3667 }
3668 }
3669
3670 return Success;
3671}
3672
Richard Smitha7e2cc62015-05-01 01:53:09 +00003673void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003674 // If there's a listener, notify them that we "read" the translation unit.
3675 if (DeserializationListener)
3676 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3677 Context.getTranslationUnitDecl());
3678
Guy Benyei11169dd2012-12-18 14:30:41 +00003679 // FIXME: Find a better way to deal with collisions between these
3680 // built-in types. Right now, we just ignore the problem.
3681
3682 // Load the special types.
3683 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3684 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3685 if (!Context.CFConstantStringTypeDecl)
3686 Context.setCFConstantStringType(GetType(String));
3687 }
3688
3689 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3690 QualType FileType = GetType(File);
3691 if (FileType.isNull()) {
3692 Error("FILE type is NULL");
3693 return;
3694 }
3695
3696 if (!Context.FILEDecl) {
3697 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3698 Context.setFILEDecl(Typedef->getDecl());
3699 else {
3700 const TagType *Tag = FileType->getAs<TagType>();
3701 if (!Tag) {
3702 Error("Invalid FILE type in AST file");
3703 return;
3704 }
3705 Context.setFILEDecl(Tag->getDecl());
3706 }
3707 }
3708 }
3709
3710 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3711 QualType Jmp_bufType = GetType(Jmp_buf);
3712 if (Jmp_bufType.isNull()) {
3713 Error("jmp_buf type is NULL");
3714 return;
3715 }
3716
3717 if (!Context.jmp_bufDecl) {
3718 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3719 Context.setjmp_bufDecl(Typedef->getDecl());
3720 else {
3721 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3722 if (!Tag) {
3723 Error("Invalid jmp_buf type in AST file");
3724 return;
3725 }
3726 Context.setjmp_bufDecl(Tag->getDecl());
3727 }
3728 }
3729 }
3730
3731 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3732 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3733 if (Sigjmp_bufType.isNull()) {
3734 Error("sigjmp_buf type is NULL");
3735 return;
3736 }
3737
3738 if (!Context.sigjmp_bufDecl) {
3739 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3740 Context.setsigjmp_bufDecl(Typedef->getDecl());
3741 else {
3742 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3743 assert(Tag && "Invalid sigjmp_buf type in AST file");
3744 Context.setsigjmp_bufDecl(Tag->getDecl());
3745 }
3746 }
3747 }
3748
3749 if (unsigned ObjCIdRedef
3750 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3751 if (Context.ObjCIdRedefinitionType.isNull())
3752 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3753 }
3754
3755 if (unsigned ObjCClassRedef
3756 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3757 if (Context.ObjCClassRedefinitionType.isNull())
3758 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3759 }
3760
3761 if (unsigned ObjCSelRedef
3762 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3763 if (Context.ObjCSelRedefinitionType.isNull())
3764 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3765 }
3766
3767 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3768 QualType Ucontext_tType = GetType(Ucontext_t);
3769 if (Ucontext_tType.isNull()) {
3770 Error("ucontext_t type is NULL");
3771 return;
3772 }
3773
3774 if (!Context.ucontext_tDecl) {
3775 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3776 Context.setucontext_tDecl(Typedef->getDecl());
3777 else {
3778 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3779 assert(Tag && "Invalid ucontext_t type in AST file");
3780 Context.setucontext_tDecl(Tag->getDecl());
3781 }
3782 }
3783 }
3784 }
3785
3786 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3787
3788 // If there were any CUDA special declarations, deserialize them.
3789 if (!CUDASpecialDeclRefs.empty()) {
3790 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3791 Context.setcudaConfigureCallDecl(
3792 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3793 }
Richard Smith56be7542014-03-21 00:33:59 +00003794
Guy Benyei11169dd2012-12-18 14:30:41 +00003795 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003796 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003797 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003798 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003799 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003800 /*ImportLoc=*/Import.ImportLoc);
3801 PP.makeModuleVisible(Imported, Import.ImportLoc);
3802 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003803 }
3804 ImportedModules.clear();
3805}
3806
3807void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003808 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003809}
3810
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003811/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3812/// cursor into the start of the given block ID, returning false on success and
3813/// true on failure.
3814static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003815 while (1) {
3816 llvm::BitstreamEntry Entry = Cursor.advance();
3817 switch (Entry.Kind) {
3818 case llvm::BitstreamEntry::Error:
3819 case llvm::BitstreamEntry::EndBlock:
3820 return true;
3821
3822 case llvm::BitstreamEntry::Record:
3823 // Ignore top-level records.
3824 Cursor.skipRecord(Entry.ID);
3825 break;
3826
3827 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003828 if (Entry.ID == BlockID) {
3829 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003830 return true;
3831 // Found it!
3832 return false;
3833 }
3834
3835 if (Cursor.SkipBlock())
3836 return true;
3837 }
3838 }
3839}
3840
Ben Langmuir70a1b812015-03-24 04:43:52 +00003841/// \brief Reads and return the signature record from \p StreamFile's control
3842/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003843static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3844 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003845 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003846 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003847
3848 // Scan for the CONTROL_BLOCK_ID block.
3849 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3850 return 0;
3851
3852 // Scan for SIGNATURE inside the control block.
3853 ASTReader::RecordData Record;
3854 while (1) {
3855 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3856 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3857 Entry.Kind != llvm::BitstreamEntry::Record)
3858 return 0;
3859
3860 Record.clear();
3861 StringRef Blob;
3862 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3863 return Record[0];
3864 }
3865}
3866
Guy Benyei11169dd2012-12-18 14:30:41 +00003867/// \brief Retrieve the name of the original source file name
3868/// directly from the AST file, without actually loading the AST
3869/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003870std::string ASTReader::getOriginalSourceFile(
3871 const std::string &ASTFileName, FileManager &FileMgr,
3872 const PCHContainerOperations &PCHContainerOps, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003873 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00003874 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00003875 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00003876 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3877 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00003878 return std::string();
3879 }
3880
3881 // Initialize the stream
3882 llvm::BitstreamReader StreamFile;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003883 PCHContainerOps.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003884 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003885
3886 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003887 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003888 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3889 return std::string();
3890 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003891
Chris Lattnere7b154b2013-01-19 21:39:22 +00003892 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003893 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003894 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3895 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003896 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003897
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003898 // Scan for ORIGINAL_FILE inside the control block.
3899 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003900 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003901 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003902 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3903 return std::string();
3904
3905 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3906 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3907 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003908 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003909
Guy Benyei11169dd2012-12-18 14:30:41 +00003910 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003911 StringRef Blob;
3912 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3913 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003914 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003915}
3916
3917namespace {
3918 class SimplePCHValidator : public ASTReaderListener {
3919 const LangOptions &ExistingLangOpts;
3920 const TargetOptions &ExistingTargetOpts;
3921 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003922 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00003923 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003924
Guy Benyei11169dd2012-12-18 14:30:41 +00003925 public:
3926 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3927 const TargetOptions &ExistingTargetOpts,
3928 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003929 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00003930 FileManager &FileMgr)
3931 : ExistingLangOpts(ExistingLangOpts),
3932 ExistingTargetOpts(ExistingTargetOpts),
3933 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003934 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00003935 FileMgr(FileMgr)
3936 {
3937 }
3938
Richard Smith1e2cf0d2014-10-31 02:28:58 +00003939 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
3940 bool AllowCompatibleDifferences) override {
3941 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
3942 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003943 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00003944 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
3945 bool AllowCompatibleDifferences) override {
3946 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
3947 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003948 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003949 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
3950 StringRef SpecificModuleCachePath,
3951 bool Complain) override {
3952 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
3953 ExistingModuleCachePath,
3954 nullptr, ExistingLangOpts);
3955 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003956 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3957 bool Complain,
3958 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00003959 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003960 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003961 }
3962 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003963}
Guy Benyei11169dd2012-12-18 14:30:41 +00003964
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003965bool ASTReader::readASTFileControlBlock(
3966 StringRef Filename, FileManager &FileMgr,
3967 const PCHContainerOperations &PCHContainerOps,
3968 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003969 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00003970 // FIXME: This allows use of the VFS; we do not allow use of the
3971 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00003972 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00003973 if (!Buffer) {
3974 return true;
3975 }
3976
3977 // Initialize the stream
3978 llvm::BitstreamReader StreamFile;
Adrian Prantl142ec392015-07-07 23:19:46 +00003979 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
3980 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003981 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003982
3983 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003984 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00003985 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003986
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003987 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003988 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003989 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003990
3991 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00003992 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00003993 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003994 BitstreamCursor InputFilesCursor;
3995 if (NeedsInputFiles) {
3996 InputFilesCursor = Stream;
3997 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
3998 return true;
3999
4000 // Read the abbreviations
4001 while (true) {
4002 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4003 unsigned Code = InputFilesCursor.ReadCode();
4004
4005 // We expect all abbrevs to be at the start of the block.
4006 if (Code != llvm::bitc::DEFINE_ABBREV) {
4007 InputFilesCursor.JumpToBit(Offset);
4008 break;
4009 }
4010 InputFilesCursor.ReadAbbrevRecord();
4011 }
4012 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004013
4014 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004015 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004016 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004017 while (1) {
4018 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4019 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4020 return false;
4021
4022 if (Entry.Kind != llvm::BitstreamEntry::Record)
4023 return true;
4024
Guy Benyei11169dd2012-12-18 14:30:41 +00004025 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004026 StringRef Blob;
4027 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004028 switch ((ControlRecordTypes)RecCode) {
4029 case METADATA: {
4030 if (Record[0] != VERSION_MAJOR)
4031 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004032
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004033 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004034 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004035
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004036 break;
4037 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004038 case MODULE_NAME:
4039 Listener.ReadModuleName(Blob);
4040 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004041 case MODULE_DIRECTORY:
4042 ModuleDir = Blob;
4043 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004044 case MODULE_MAP_FILE: {
4045 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004046 auto Path = ReadString(Record, Idx);
4047 ResolveImportedPath(Path, ModuleDir);
4048 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004049 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004050 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004051 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004052 if (ParseLanguageOptions(Record, false, Listener,
4053 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004054 return true;
4055 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004056
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004057 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004058 if (ParseTargetOptions(Record, false, Listener,
4059 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004060 return true;
4061 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004062
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004063 case DIAGNOSTIC_OPTIONS:
4064 if (ParseDiagnosticOptions(Record, false, Listener))
4065 return true;
4066 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004067
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004068 case FILE_SYSTEM_OPTIONS:
4069 if (ParseFileSystemOptions(Record, false, Listener))
4070 return true;
4071 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004072
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004073 case HEADER_SEARCH_OPTIONS:
4074 if (ParseHeaderSearchOptions(Record, false, Listener))
4075 return true;
4076 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004077
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004078 case PREPROCESSOR_OPTIONS: {
4079 std::string IgnoredSuggestedPredefines;
4080 if (ParsePreprocessorOptions(Record, false, Listener,
4081 IgnoredSuggestedPredefines))
4082 return true;
4083 break;
4084 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004085
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004086 case INPUT_FILE_OFFSETS: {
4087 if (!NeedsInputFiles)
4088 break;
4089
4090 unsigned NumInputFiles = Record[0];
4091 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004092 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004093 for (unsigned I = 0; I != NumInputFiles; ++I) {
4094 // Go find this input file.
4095 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004096
4097 if (isSystemFile && !NeedsSystemInputFiles)
4098 break; // the rest are system input files
4099
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004100 BitstreamCursor &Cursor = InputFilesCursor;
4101 SavedStreamPosition SavedPosition(Cursor);
4102 Cursor.JumpToBit(InputFileOffs[I]);
4103
4104 unsigned Code = Cursor.ReadCode();
4105 RecordData Record;
4106 StringRef Blob;
4107 bool shouldContinue = false;
4108 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4109 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004110 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004111 std::string Filename = Blob;
4112 ResolveImportedPath(Filename, ModuleDir);
4113 shouldContinue =
4114 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004115 break;
4116 }
4117 if (!shouldContinue)
4118 break;
4119 }
4120 break;
4121 }
4122
Richard Smithd4b230b2014-10-27 23:01:16 +00004123 case IMPORTS: {
4124 if (!NeedsImports)
4125 break;
4126
4127 unsigned Idx = 0, N = Record.size();
4128 while (Idx < N) {
4129 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004130 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004131 std::string Filename = ReadString(Record, Idx);
4132 ResolveImportedPath(Filename, ModuleDir);
4133 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004134 }
4135 break;
4136 }
4137
Richard Smith7f330cd2015-03-18 01:42:29 +00004138 case KNOWN_MODULE_FILES: {
4139 // Known-but-not-technically-used module files are treated as imports.
4140 if (!NeedsImports)
4141 break;
4142
4143 unsigned Idx = 0, N = Record.size();
4144 while (Idx < N) {
4145 std::string Filename = ReadString(Record, Idx);
4146 ResolveImportedPath(Filename, ModuleDir);
4147 Listener.visitImport(Filename);
4148 }
4149 break;
4150 }
4151
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004152 default:
4153 // No other validation to perform.
4154 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004155 }
4156 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004157}
4158
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004159bool ASTReader::isAcceptableASTFile(
4160 StringRef Filename, FileManager &FileMgr,
4161 const PCHContainerOperations &PCHContainerOps, const LangOptions &LangOpts,
4162 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4163 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004164 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4165 ExistingModuleCachePath, FileMgr);
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004166 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerOps,
4167 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004168}
4169
Ben Langmuir2c9af442014-04-10 17:57:43 +00004170ASTReader::ASTReadResult
4171ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004172 // Enter the submodule block.
4173 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4174 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004175 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004176 }
4177
4178 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4179 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004180 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004181 RecordData Record;
4182 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004183 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4184
4185 switch (Entry.Kind) {
4186 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4187 case llvm::BitstreamEntry::Error:
4188 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004189 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004190 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004191 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004192 case llvm::BitstreamEntry::Record:
4193 // The interesting case.
4194 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004195 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004196
Guy Benyei11169dd2012-12-18 14:30:41 +00004197 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004198 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004199 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004200 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4201
4202 if ((Kind == SUBMODULE_METADATA) != First) {
4203 Error("submodule metadata record should be at beginning of block");
4204 return Failure;
4205 }
4206 First = false;
4207
4208 // Submodule information is only valid if we have a current module.
4209 // FIXME: Should we error on these cases?
4210 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4211 Kind != SUBMODULE_DEFINITION)
4212 continue;
4213
4214 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004215 default: // Default behavior: ignore.
4216 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004217
Richard Smith03478d92014-10-23 22:12:14 +00004218 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004219 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004220 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004221 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004222 }
Richard Smith03478d92014-10-23 22:12:14 +00004223
Chris Lattner0e6c9402013-01-20 02:38:54 +00004224 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004225 unsigned Idx = 0;
4226 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4227 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4228 bool IsFramework = Record[Idx++];
4229 bool IsExplicit = Record[Idx++];
4230 bool IsSystem = Record[Idx++];
4231 bool IsExternC = Record[Idx++];
4232 bool InferSubmodules = Record[Idx++];
4233 bool InferExplicitSubmodules = Record[Idx++];
4234 bool InferExportWildcard = Record[Idx++];
4235 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004236
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004237 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004238 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004239 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004240
Guy Benyei11169dd2012-12-18 14:30:41 +00004241 // Retrieve this (sub)module from the module map, creating it if
4242 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004243 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004244 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004245
4246 // FIXME: set the definition loc for CurrentModule, or call
4247 // ModMap.setInferredModuleAllowedBy()
4248
Guy Benyei11169dd2012-12-18 14:30:41 +00004249 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4250 if (GlobalIndex >= SubmodulesLoaded.size() ||
4251 SubmodulesLoaded[GlobalIndex]) {
4252 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004253 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004254 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004255
Douglas Gregor7029ce12013-03-19 00:28:20 +00004256 if (!ParentModule) {
4257 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4258 if (CurFile != F.File) {
4259 if (!Diags.isDiagnosticInFlight()) {
4260 Diag(diag::err_module_file_conflict)
4261 << CurrentModule->getTopLevelModuleName()
4262 << CurFile->getName()
4263 << F.File->getName();
4264 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004265 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004266 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004267 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004268
4269 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004270 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004271
Adrian Prantl15bcf702015-06-30 17:39:43 +00004272 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004273 CurrentModule->IsFromModuleFile = true;
4274 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004275 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004276 CurrentModule->InferSubmodules = InferSubmodules;
4277 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4278 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004279 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004280 if (DeserializationListener)
4281 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4282
4283 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004284
Douglas Gregorfb912652013-03-20 21:10:35 +00004285 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004286 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004287 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004288 CurrentModule->UnresolvedConflicts.clear();
4289 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 break;
4291 }
4292
4293 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004294 std::string Filename = Blob;
4295 ResolveImportedPath(F, Filename);
4296 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004297 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004298 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4299 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004300 // This can be a spurious difference caused by changing the VFS to
4301 // point to a different copy of the file, and it is too late to
4302 // to rebuild safely.
4303 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4304 // after input file validation only real problems would remain and we
4305 // could just error. For now, assume it's okay.
4306 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004307 }
4308 }
4309 break;
4310 }
4311
Richard Smith202210b2014-10-24 20:23:01 +00004312 case SUBMODULE_HEADER:
4313 case SUBMODULE_EXCLUDED_HEADER:
4314 case SUBMODULE_PRIVATE_HEADER:
4315 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004316 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4317 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004318 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004319
Richard Smith202210b2014-10-24 20:23:01 +00004320 case SUBMODULE_TEXTUAL_HEADER:
4321 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4322 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4323 // them here.
4324 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004325
Guy Benyei11169dd2012-12-18 14:30:41 +00004326 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004327 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004328 break;
4329 }
4330
4331 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004332 std::string Dirname = Blob;
4333 ResolveImportedPath(F, Dirname);
4334 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004336 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4337 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004338 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4339 Error("mismatched umbrella directories in submodule");
4340 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004341 }
4342 }
4343 break;
4344 }
4345
4346 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 F.BaseSubmoduleID = getTotalNumSubmodules();
4348 F.LocalNumSubmodules = Record[0];
4349 unsigned LocalBaseSubmoduleID = Record[1];
4350 if (F.LocalNumSubmodules > 0) {
4351 // Introduce the global -> local mapping for submodules within this
4352 // module.
4353 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4354
4355 // Introduce the local -> global mapping for submodules within this
4356 // module.
4357 F.SubmoduleRemap.insertOrReplace(
4358 std::make_pair(LocalBaseSubmoduleID,
4359 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004360
Ben Langmuir52ca6782014-10-20 16:27:32 +00004361 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4362 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004363 break;
4364 }
4365
4366 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004368 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004369 Unresolved.File = &F;
4370 Unresolved.Mod = CurrentModule;
4371 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004372 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004374 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004375 }
4376 break;
4377 }
4378
4379 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004380 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004381 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004382 Unresolved.File = &F;
4383 Unresolved.Mod = CurrentModule;
4384 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004385 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004386 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004387 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004388 }
4389
4390 // Once we've loaded the set of exports, there's no reason to keep
4391 // the parsed, unresolved exports around.
4392 CurrentModule->UnresolvedExports.clear();
4393 break;
4394 }
4395 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004396 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004397 Context.getTargetInfo());
4398 break;
4399 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004400
4401 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004402 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004403 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004404 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004405
4406 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004407 CurrentModule->ConfigMacros.push_back(Blob.str());
4408 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004409
4410 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004411 UnresolvedModuleRef Unresolved;
4412 Unresolved.File = &F;
4413 Unresolved.Mod = CurrentModule;
4414 Unresolved.ID = Record[0];
4415 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4416 Unresolved.IsWildcard = false;
4417 Unresolved.String = Blob;
4418 UnresolvedModuleRefs.push_back(Unresolved);
4419 break;
4420 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004421 }
4422 }
4423}
4424
4425/// \brief Parse the record that corresponds to a LangOptions data
4426/// structure.
4427///
4428/// This routine parses the language options from the AST file and then gives
4429/// them to the AST listener if one is set.
4430///
4431/// \returns true if the listener deems the file unacceptable, false otherwise.
4432bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4433 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004434 ASTReaderListener &Listener,
4435 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004436 LangOptions LangOpts;
4437 unsigned Idx = 0;
4438#define LANGOPT(Name, Bits, Default, Description) \
4439 LangOpts.Name = Record[Idx++];
4440#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4441 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4442#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004443#define SANITIZER(NAME, ID) \
4444 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004445#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004446
Ben Langmuircd98cb72015-06-23 18:20:18 +00004447 for (unsigned N = Record[Idx++]; N; --N)
4448 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4449
Guy Benyei11169dd2012-12-18 14:30:41 +00004450 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4451 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4452 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004453
Ben Langmuird4a667a2015-06-23 18:20:23 +00004454 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004455
4456 // Comment options.
4457 for (unsigned N = Record[Idx++]; N; --N) {
4458 LangOpts.CommentOpts.BlockCommandNames.push_back(
4459 ReadString(Record, Idx));
4460 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004461 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004462
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004463 return Listener.ReadLanguageOptions(LangOpts, Complain,
4464 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004465}
4466
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004467bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4468 ASTReaderListener &Listener,
4469 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004470 unsigned Idx = 0;
4471 TargetOptions TargetOpts;
4472 TargetOpts.Triple = ReadString(Record, Idx);
4473 TargetOpts.CPU = ReadString(Record, Idx);
4474 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004475 for (unsigned N = Record[Idx++]; N; --N) {
4476 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4477 }
4478 for (unsigned N = Record[Idx++]; N; --N) {
4479 TargetOpts.Features.push_back(ReadString(Record, Idx));
4480 }
4481
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004482 return Listener.ReadTargetOptions(TargetOpts, Complain,
4483 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004484}
4485
4486bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4487 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004488 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004489 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004490#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004491#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004492 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004493#include "clang/Basic/DiagnosticOptions.def"
4494
Richard Smith3be1cb22014-08-07 00:24:21 +00004495 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004496 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004497 for (unsigned N = Record[Idx++]; N; --N)
4498 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004499
4500 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4501}
4502
4503bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4504 ASTReaderListener &Listener) {
4505 FileSystemOptions FSOpts;
4506 unsigned Idx = 0;
4507 FSOpts.WorkingDir = ReadString(Record, Idx);
4508 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4509}
4510
4511bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4512 bool Complain,
4513 ASTReaderListener &Listener) {
4514 HeaderSearchOptions HSOpts;
4515 unsigned Idx = 0;
4516 HSOpts.Sysroot = ReadString(Record, Idx);
4517
4518 // Include entries.
4519 for (unsigned N = Record[Idx++]; N; --N) {
4520 std::string Path = ReadString(Record, Idx);
4521 frontend::IncludeDirGroup Group
4522 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 bool IsFramework = Record[Idx++];
4524 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004525 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4526 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004527 }
4528
4529 // System header prefixes.
4530 for (unsigned N = Record[Idx++]; N; --N) {
4531 std::string Prefix = ReadString(Record, Idx);
4532 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004533 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004534 }
4535
4536 HSOpts.ResourceDir = ReadString(Record, Idx);
4537 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004538 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 HSOpts.DisableModuleHash = Record[Idx++];
4540 HSOpts.UseBuiltinIncludes = Record[Idx++];
4541 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4542 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4543 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004544 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004545
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004546 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4547 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004548}
4549
4550bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4551 bool Complain,
4552 ASTReaderListener &Listener,
4553 std::string &SuggestedPredefines) {
4554 PreprocessorOptions PPOpts;
4555 unsigned Idx = 0;
4556
4557 // Macro definitions/undefs
4558 for (unsigned N = Record[Idx++]; N; --N) {
4559 std::string Macro = ReadString(Record, Idx);
4560 bool IsUndef = Record[Idx++];
4561 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4562 }
4563
4564 // Includes
4565 for (unsigned N = Record[Idx++]; N; --N) {
4566 PPOpts.Includes.push_back(ReadString(Record, Idx));
4567 }
4568
4569 // Macro Includes
4570 for (unsigned N = Record[Idx++]; N; --N) {
4571 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4572 }
4573
4574 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004575 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004576 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4577 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4578 PPOpts.ObjCXXARCStandardLibrary =
4579 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4580 SuggestedPredefines.clear();
4581 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4582 SuggestedPredefines);
4583}
4584
4585std::pair<ModuleFile *, unsigned>
4586ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4587 GlobalPreprocessedEntityMapType::iterator
4588 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4589 assert(I != GlobalPreprocessedEntityMap.end() &&
4590 "Corrupted global preprocessed entity map");
4591 ModuleFile *M = I->second;
4592 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4593 return std::make_pair(M, LocalIndex);
4594}
4595
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004596llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004597ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4598 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4599 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4600 Mod.NumPreprocessedEntities);
4601
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004602 return llvm::make_range(PreprocessingRecord::iterator(),
4603 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004604}
4605
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004606llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004607ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004608 return llvm::make_range(
4609 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4610 ModuleDeclIterator(this, &Mod,
4611 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004612}
4613
4614PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4615 PreprocessedEntityID PPID = Index+1;
4616 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4617 ModuleFile &M = *PPInfo.first;
4618 unsigned LocalIndex = PPInfo.second;
4619 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4620
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 if (!PP.getPreprocessingRecord()) {
4622 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004623 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004624 }
4625
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004626 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4627 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4628
4629 llvm::BitstreamEntry Entry =
4630 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4631 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004632 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004633
Guy Benyei11169dd2012-12-18 14:30:41 +00004634 // Read the record.
4635 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4636 ReadSourceLocation(M, PPOffs.End));
4637 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004638 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004639 RecordData Record;
4640 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004641 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4642 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004643 switch (RecType) {
4644 case PPD_MACRO_EXPANSION: {
4645 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004646 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004647 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004648 if (isBuiltin)
4649 Name = getLocalIdentifier(M, Record[1]);
4650 else {
Richard Smith66a81862015-05-04 02:25:31 +00004651 PreprocessedEntityID GlobalID =
4652 getGlobalPreprocessedEntityID(M, Record[1]);
4653 Def = cast<MacroDefinitionRecord>(
4654 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004655 }
4656
4657 MacroExpansion *ME;
4658 if (isBuiltin)
4659 ME = new (PPRec) MacroExpansion(Name, Range);
4660 else
4661 ME = new (PPRec) MacroExpansion(Def, Range);
4662
4663 return ME;
4664 }
4665
4666 case PPD_MACRO_DEFINITION: {
4667 // Decode the identifier info and then check again; if the macro is
4668 // still defined and associated with the identifier,
4669 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004670 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004671
4672 if (DeserializationListener)
4673 DeserializationListener->MacroDefinitionRead(PPID, MD);
4674
4675 return MD;
4676 }
4677
4678 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004679 const char *FullFileNameStart = Blob.data() + Record[0];
4680 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004681 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004682 if (!FullFileName.empty())
4683 File = PP.getFileManager().getFile(FullFileName);
4684
4685 // FIXME: Stable encoding
4686 InclusionDirective::InclusionKind Kind
4687 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4688 InclusionDirective *ID
4689 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004690 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004691 Record[1], Record[3],
4692 File,
4693 Range);
4694 return ID;
4695 }
4696 }
4697
4698 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4699}
4700
4701/// \brief \arg SLocMapI points at a chunk of a module that contains no
4702/// preprocessed entities or the entities it contains are not the ones we are
4703/// looking for. Find the next module that contains entities and return the ID
4704/// of the first entry.
4705PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4706 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4707 ++SLocMapI;
4708 for (GlobalSLocOffsetMapType::const_iterator
4709 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4710 ModuleFile &M = *SLocMapI->second;
4711 if (M.NumPreprocessedEntities)
4712 return M.BasePreprocessedEntityID;
4713 }
4714
4715 return getTotalNumPreprocessedEntities();
4716}
4717
4718namespace {
4719
4720template <unsigned PPEntityOffset::*PPLoc>
4721struct PPEntityComp {
4722 const ASTReader &Reader;
4723 ModuleFile &M;
4724
4725 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4726
4727 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4728 SourceLocation LHS = getLoc(L);
4729 SourceLocation RHS = getLoc(R);
4730 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4731 }
4732
4733 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4734 SourceLocation LHS = getLoc(L);
4735 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4736 }
4737
4738 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4739 SourceLocation RHS = getLoc(R);
4740 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4741 }
4742
4743 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4744 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4745 }
4746};
4747
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004748}
Guy Benyei11169dd2012-12-18 14:30:41 +00004749
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004750PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4751 bool EndsAfter) const {
4752 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004753 return getTotalNumPreprocessedEntities();
4754
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004755 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4756 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004757 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4758 "Corrupted global sloc offset map");
4759
4760 if (SLocMapI->second->NumPreprocessedEntities == 0)
4761 return findNextPreprocessedEntity(SLocMapI);
4762
4763 ModuleFile &M = *SLocMapI->second;
4764 typedef const PPEntityOffset *pp_iterator;
4765 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4766 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4767
4768 size_t Count = M.NumPreprocessedEntities;
4769 size_t Half;
4770 pp_iterator First = pp_begin;
4771 pp_iterator PPI;
4772
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004773 if (EndsAfter) {
4774 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4775 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4776 } else {
4777 // Do a binary search manually instead of using std::lower_bound because
4778 // The end locations of entities may be unordered (when a macro expansion
4779 // is inside another macro argument), but for this case it is not important
4780 // whether we get the first macro expansion or its containing macro.
4781 while (Count > 0) {
4782 Half = Count / 2;
4783 PPI = First;
4784 std::advance(PPI, Half);
4785 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4786 Loc)) {
4787 First = PPI;
4788 ++First;
4789 Count = Count - Half - 1;
4790 } else
4791 Count = Half;
4792 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004793 }
4794
4795 if (PPI == pp_end)
4796 return findNextPreprocessedEntity(SLocMapI);
4797
4798 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4799}
4800
Guy Benyei11169dd2012-12-18 14:30:41 +00004801/// \brief Returns a pair of [Begin, End) indices of preallocated
4802/// preprocessed entities that \arg Range encompasses.
4803std::pair<unsigned, unsigned>
4804 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4805 if (Range.isInvalid())
4806 return std::make_pair(0,0);
4807 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4808
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004809 PreprocessedEntityID BeginID =
4810 findPreprocessedEntity(Range.getBegin(), false);
4811 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004812 return std::make_pair(BeginID, EndID);
4813}
4814
4815/// \brief Optionally returns true or false if the preallocated preprocessed
4816/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004817Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004818 FileID FID) {
4819 if (FID.isInvalid())
4820 return false;
4821
4822 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4823 ModuleFile &M = *PPInfo.first;
4824 unsigned LocalIndex = PPInfo.second;
4825 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4826
4827 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4828 if (Loc.isInvalid())
4829 return false;
4830
4831 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4832 return true;
4833 else
4834 return false;
4835}
4836
4837namespace {
4838 /// \brief Visitor used to search for information about a header file.
4839 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004840 const FileEntry *FE;
4841
David Blaikie05785d12013-02-20 22:23:23 +00004842 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004843
4844 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004845 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4846 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004847
4848 static bool visit(ModuleFile &M, void *UserData) {
4849 HeaderFileInfoVisitor *This
4850 = static_cast<HeaderFileInfoVisitor *>(UserData);
4851
Guy Benyei11169dd2012-12-18 14:30:41 +00004852 HeaderFileInfoLookupTable *Table
4853 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4854 if (!Table)
4855 return false;
4856
4857 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004858 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004859 if (Pos == Table->end())
4860 return false;
4861
4862 This->HFI = *Pos;
4863 return true;
4864 }
4865
David Blaikie05785d12013-02-20 22:23:23 +00004866 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004867 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004868}
Guy Benyei11169dd2012-12-18 14:30:41 +00004869
4870HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004871 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004872 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004873 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004874 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004875
4876 return HeaderFileInfo();
4877}
4878
4879void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4880 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004881 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004882 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4883 ModuleFile &F = *(*I);
4884 unsigned Idx = 0;
4885 DiagStates.clear();
4886 assert(!Diag.DiagStates.empty());
4887 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4888 while (Idx < F.PragmaDiagMappings.size()) {
4889 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4890 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4891 if (DiagStateID != 0) {
4892 Diag.DiagStatePoints.push_back(
4893 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4894 FullSourceLoc(Loc, SourceMgr)));
4895 continue;
4896 }
4897
4898 assert(DiagStateID == 0);
4899 // A new DiagState was created here.
4900 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4901 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4902 DiagStates.push_back(NewState);
4903 Diag.DiagStatePoints.push_back(
4904 DiagnosticsEngine::DiagStatePoint(NewState,
4905 FullSourceLoc(Loc, SourceMgr)));
4906 while (1) {
4907 assert(Idx < F.PragmaDiagMappings.size() &&
4908 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4909 if (Idx >= F.PragmaDiagMappings.size()) {
4910 break; // Something is messed up but at least avoid infinite loop in
4911 // release build.
4912 }
4913 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4914 if (DiagID == (unsigned)-1) {
4915 break; // no more diag/map pairs for this location.
4916 }
Alp Tokerc726c362014-06-10 09:31:37 +00004917 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4918 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4919 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00004920 }
4921 }
4922 }
4923}
4924
4925/// \brief Get the correct cursor and offset for loading a type.
4926ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4927 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4928 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4929 ModuleFile *M = I->second;
4930 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4931}
4932
4933/// \brief Read and return the type with the given index..
4934///
4935/// The index is the type ID, shifted and minus the number of predefs. This
4936/// routine actually reads the record corresponding to the type at the given
4937/// location. It is a helper routine for GetType, which deals with reading type
4938/// IDs.
4939QualType ASTReader::readTypeRecord(unsigned Index) {
4940 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004941 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004942
4943 // Keep track of where we are in the stream, then jump back there
4944 // after reading this type.
4945 SavedStreamPosition SavedPosition(DeclsCursor);
4946
4947 ReadingKindTracker ReadingKind(Read_Type, *this);
4948
4949 // Note that we are loading a type record.
4950 Deserializing AType(this);
4951
4952 unsigned Idx = 0;
4953 DeclsCursor.JumpToBit(Loc.Offset);
4954 RecordData Record;
4955 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004956 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004957 case TYPE_EXT_QUAL: {
4958 if (Record.size() != 2) {
4959 Error("Incorrect encoding of extended qualifier type");
4960 return QualType();
4961 }
4962 QualType Base = readType(*Loc.F, Record, Idx);
4963 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4964 return Context.getQualifiedType(Base, Quals);
4965 }
4966
4967 case TYPE_COMPLEX: {
4968 if (Record.size() != 1) {
4969 Error("Incorrect encoding of complex type");
4970 return QualType();
4971 }
4972 QualType ElemType = readType(*Loc.F, Record, Idx);
4973 return Context.getComplexType(ElemType);
4974 }
4975
4976 case TYPE_POINTER: {
4977 if (Record.size() != 1) {
4978 Error("Incorrect encoding of pointer type");
4979 return QualType();
4980 }
4981 QualType PointeeType = readType(*Loc.F, Record, Idx);
4982 return Context.getPointerType(PointeeType);
4983 }
4984
Reid Kleckner8a365022013-06-24 17:51:48 +00004985 case TYPE_DECAYED: {
4986 if (Record.size() != 1) {
4987 Error("Incorrect encoding of decayed type");
4988 return QualType();
4989 }
4990 QualType OriginalType = readType(*Loc.F, Record, Idx);
4991 QualType DT = Context.getAdjustedParameterType(OriginalType);
4992 if (!isa<DecayedType>(DT))
4993 Error("Decayed type does not decay");
4994 return DT;
4995 }
4996
Reid Kleckner0503a872013-12-05 01:23:43 +00004997 case TYPE_ADJUSTED: {
4998 if (Record.size() != 2) {
4999 Error("Incorrect encoding of adjusted type");
5000 return QualType();
5001 }
5002 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5003 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5004 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5005 }
5006
Guy Benyei11169dd2012-12-18 14:30:41 +00005007 case TYPE_BLOCK_POINTER: {
5008 if (Record.size() != 1) {
5009 Error("Incorrect encoding of block pointer type");
5010 return QualType();
5011 }
5012 QualType PointeeType = readType(*Loc.F, Record, Idx);
5013 return Context.getBlockPointerType(PointeeType);
5014 }
5015
5016 case TYPE_LVALUE_REFERENCE: {
5017 if (Record.size() != 2) {
5018 Error("Incorrect encoding of lvalue reference type");
5019 return QualType();
5020 }
5021 QualType PointeeType = readType(*Loc.F, Record, Idx);
5022 return Context.getLValueReferenceType(PointeeType, Record[1]);
5023 }
5024
5025 case TYPE_RVALUE_REFERENCE: {
5026 if (Record.size() != 1) {
5027 Error("Incorrect encoding of rvalue reference type");
5028 return QualType();
5029 }
5030 QualType PointeeType = readType(*Loc.F, Record, Idx);
5031 return Context.getRValueReferenceType(PointeeType);
5032 }
5033
5034 case TYPE_MEMBER_POINTER: {
5035 if (Record.size() != 2) {
5036 Error("Incorrect encoding of member pointer type");
5037 return QualType();
5038 }
5039 QualType PointeeType = readType(*Loc.F, Record, Idx);
5040 QualType ClassType = readType(*Loc.F, Record, Idx);
5041 if (PointeeType.isNull() || ClassType.isNull())
5042 return QualType();
5043
5044 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5045 }
5046
5047 case TYPE_CONSTANT_ARRAY: {
5048 QualType ElementType = readType(*Loc.F, Record, Idx);
5049 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5050 unsigned IndexTypeQuals = Record[2];
5051 unsigned Idx = 3;
5052 llvm::APInt Size = ReadAPInt(Record, Idx);
5053 return Context.getConstantArrayType(ElementType, Size,
5054 ASM, IndexTypeQuals);
5055 }
5056
5057 case TYPE_INCOMPLETE_ARRAY: {
5058 QualType ElementType = readType(*Loc.F, Record, Idx);
5059 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5060 unsigned IndexTypeQuals = Record[2];
5061 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5062 }
5063
5064 case TYPE_VARIABLE_ARRAY: {
5065 QualType ElementType = readType(*Loc.F, Record, Idx);
5066 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5067 unsigned IndexTypeQuals = Record[2];
5068 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5069 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5070 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5071 ASM, IndexTypeQuals,
5072 SourceRange(LBLoc, RBLoc));
5073 }
5074
5075 case TYPE_VECTOR: {
5076 if (Record.size() != 3) {
5077 Error("incorrect encoding of vector type in AST file");
5078 return QualType();
5079 }
5080
5081 QualType ElementType = readType(*Loc.F, Record, Idx);
5082 unsigned NumElements = Record[1];
5083 unsigned VecKind = Record[2];
5084 return Context.getVectorType(ElementType, NumElements,
5085 (VectorType::VectorKind)VecKind);
5086 }
5087
5088 case TYPE_EXT_VECTOR: {
5089 if (Record.size() != 3) {
5090 Error("incorrect encoding of extended vector type in AST file");
5091 return QualType();
5092 }
5093
5094 QualType ElementType = readType(*Loc.F, Record, Idx);
5095 unsigned NumElements = Record[1];
5096 return Context.getExtVectorType(ElementType, NumElements);
5097 }
5098
5099 case TYPE_FUNCTION_NO_PROTO: {
5100 if (Record.size() != 6) {
5101 Error("incorrect encoding of no-proto function type");
5102 return QualType();
5103 }
5104 QualType ResultType = readType(*Loc.F, Record, Idx);
5105 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5106 (CallingConv)Record[4], Record[5]);
5107 return Context.getFunctionNoProtoType(ResultType, Info);
5108 }
5109
5110 case TYPE_FUNCTION_PROTO: {
5111 QualType ResultType = readType(*Loc.F, Record, Idx);
5112
5113 FunctionProtoType::ExtProtoInfo EPI;
5114 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5115 /*hasregparm*/ Record[2],
5116 /*regparm*/ Record[3],
5117 static_cast<CallingConv>(Record[4]),
5118 /*produces*/ Record[5]);
5119
5120 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005121
5122 EPI.Variadic = Record[Idx++];
5123 EPI.HasTrailingReturn = Record[Idx++];
5124 EPI.TypeQuals = Record[Idx++];
5125 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005126 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005127 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005128
5129 unsigned NumParams = Record[Idx++];
5130 SmallVector<QualType, 16> ParamTypes;
5131 for (unsigned I = 0; I != NumParams; ++I)
5132 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5133
Jordan Rose5c382722013-03-08 21:51:21 +00005134 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 }
5136
5137 case TYPE_UNRESOLVED_USING: {
5138 unsigned Idx = 0;
5139 return Context.getTypeDeclType(
5140 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5141 }
5142
5143 case TYPE_TYPEDEF: {
5144 if (Record.size() != 2) {
5145 Error("incorrect encoding of typedef type");
5146 return QualType();
5147 }
5148 unsigned Idx = 0;
5149 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5150 QualType Canonical = readType(*Loc.F, Record, Idx);
5151 if (!Canonical.isNull())
5152 Canonical = Context.getCanonicalType(Canonical);
5153 return Context.getTypedefType(Decl, Canonical);
5154 }
5155
5156 case TYPE_TYPEOF_EXPR:
5157 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5158
5159 case TYPE_TYPEOF: {
5160 if (Record.size() != 1) {
5161 Error("incorrect encoding of typeof(type) in AST file");
5162 return QualType();
5163 }
5164 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5165 return Context.getTypeOfType(UnderlyingType);
5166 }
5167
5168 case TYPE_DECLTYPE: {
5169 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5170 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5171 }
5172
5173 case TYPE_UNARY_TRANSFORM: {
5174 QualType BaseType = readType(*Loc.F, Record, Idx);
5175 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5176 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5177 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5178 }
5179
Richard Smith74aeef52013-04-26 16:15:35 +00005180 case TYPE_AUTO: {
5181 QualType Deduced = readType(*Loc.F, Record, Idx);
5182 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005183 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005184 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005185 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005186
5187 case TYPE_RECORD: {
5188 if (Record.size() != 2) {
5189 Error("incorrect encoding of record type");
5190 return QualType();
5191 }
5192 unsigned Idx = 0;
5193 bool IsDependent = Record[Idx++];
5194 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5195 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5196 QualType T = Context.getRecordType(RD);
5197 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5198 return T;
5199 }
5200
5201 case TYPE_ENUM: {
5202 if (Record.size() != 2) {
5203 Error("incorrect encoding of enum type");
5204 return QualType();
5205 }
5206 unsigned Idx = 0;
5207 bool IsDependent = Record[Idx++];
5208 QualType T
5209 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5210 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5211 return T;
5212 }
5213
5214 case TYPE_ATTRIBUTED: {
5215 if (Record.size() != 3) {
5216 Error("incorrect encoding of attributed type");
5217 return QualType();
5218 }
5219 QualType modifiedType = readType(*Loc.F, Record, Idx);
5220 QualType equivalentType = readType(*Loc.F, Record, Idx);
5221 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5222 return Context.getAttributedType(kind, modifiedType, equivalentType);
5223 }
5224
5225 case TYPE_PAREN: {
5226 if (Record.size() != 1) {
5227 Error("incorrect encoding of paren type");
5228 return QualType();
5229 }
5230 QualType InnerType = readType(*Loc.F, Record, Idx);
5231 return Context.getParenType(InnerType);
5232 }
5233
5234 case TYPE_PACK_EXPANSION: {
5235 if (Record.size() != 2) {
5236 Error("incorrect encoding of pack expansion type");
5237 return QualType();
5238 }
5239 QualType Pattern = readType(*Loc.F, Record, Idx);
5240 if (Pattern.isNull())
5241 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005242 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005243 if (Record[1])
5244 NumExpansions = Record[1] - 1;
5245 return Context.getPackExpansionType(Pattern, NumExpansions);
5246 }
5247
5248 case TYPE_ELABORATED: {
5249 unsigned Idx = 0;
5250 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5251 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5252 QualType NamedType = readType(*Loc.F, Record, Idx);
5253 return Context.getElaboratedType(Keyword, NNS, NamedType);
5254 }
5255
5256 case TYPE_OBJC_INTERFACE: {
5257 unsigned Idx = 0;
5258 ObjCInterfaceDecl *ItfD
5259 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5260 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5261 }
5262
5263 case TYPE_OBJC_OBJECT: {
5264 unsigned Idx = 0;
5265 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005266 unsigned NumTypeArgs = Record[Idx++];
5267 SmallVector<QualType, 4> TypeArgs;
5268 for (unsigned I = 0; I != NumTypeArgs; ++I)
5269 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005270 unsigned NumProtos = Record[Idx++];
5271 SmallVector<ObjCProtocolDecl*, 4> Protos;
5272 for (unsigned I = 0; I != NumProtos; ++I)
5273 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005274 bool IsKindOf = Record[Idx++];
5275 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005276 }
5277
5278 case TYPE_OBJC_OBJECT_POINTER: {
5279 unsigned Idx = 0;
5280 QualType Pointee = readType(*Loc.F, Record, Idx);
5281 return Context.getObjCObjectPointerType(Pointee);
5282 }
5283
5284 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5285 unsigned Idx = 0;
5286 QualType Parm = readType(*Loc.F, Record, Idx);
5287 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005288 return Context.getSubstTemplateTypeParmType(
5289 cast<TemplateTypeParmType>(Parm),
5290 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005291 }
5292
5293 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5294 unsigned Idx = 0;
5295 QualType Parm = readType(*Loc.F, Record, Idx);
5296 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5297 return Context.getSubstTemplateTypeParmPackType(
5298 cast<TemplateTypeParmType>(Parm),
5299 ArgPack);
5300 }
5301
5302 case TYPE_INJECTED_CLASS_NAME: {
5303 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5304 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5305 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5306 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005307 const Type *T = nullptr;
5308 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5309 if (const Type *Existing = DI->getTypeForDecl()) {
5310 T = Existing;
5311 break;
5312 }
5313 }
5314 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005315 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005316 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5317 DI->setTypeForDecl(T);
5318 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005319 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005320 }
5321
5322 case TYPE_TEMPLATE_TYPE_PARM: {
5323 unsigned Idx = 0;
5324 unsigned Depth = Record[Idx++];
5325 unsigned Index = Record[Idx++];
5326 bool Pack = Record[Idx++];
5327 TemplateTypeParmDecl *D
5328 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5329 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5330 }
5331
5332 case TYPE_DEPENDENT_NAME: {
5333 unsigned Idx = 0;
5334 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5335 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5336 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5337 QualType Canon = readType(*Loc.F, Record, Idx);
5338 if (!Canon.isNull())
5339 Canon = Context.getCanonicalType(Canon);
5340 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5341 }
5342
5343 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5344 unsigned Idx = 0;
5345 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5346 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5347 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5348 unsigned NumArgs = Record[Idx++];
5349 SmallVector<TemplateArgument, 8> Args;
5350 Args.reserve(NumArgs);
5351 while (NumArgs--)
5352 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5353 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5354 Args.size(), Args.data());
5355 }
5356
5357 case TYPE_DEPENDENT_SIZED_ARRAY: {
5358 unsigned Idx = 0;
5359
5360 // ArrayType
5361 QualType ElementType = readType(*Loc.F, Record, Idx);
5362 ArrayType::ArraySizeModifier ASM
5363 = (ArrayType::ArraySizeModifier)Record[Idx++];
5364 unsigned IndexTypeQuals = Record[Idx++];
5365
5366 // DependentSizedArrayType
5367 Expr *NumElts = ReadExpr(*Loc.F);
5368 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5369
5370 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5371 IndexTypeQuals, Brackets);
5372 }
5373
5374 case TYPE_TEMPLATE_SPECIALIZATION: {
5375 unsigned Idx = 0;
5376 bool IsDependent = Record[Idx++];
5377 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5378 SmallVector<TemplateArgument, 8> Args;
5379 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5380 QualType Underlying = readType(*Loc.F, Record, Idx);
5381 QualType T;
5382 if (Underlying.isNull())
5383 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5384 Args.size());
5385 else
5386 T = Context.getTemplateSpecializationType(Name, Args.data(),
5387 Args.size(), Underlying);
5388 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5389 return T;
5390 }
5391
5392 case TYPE_ATOMIC: {
5393 if (Record.size() != 1) {
5394 Error("Incorrect encoding of atomic type");
5395 return QualType();
5396 }
5397 QualType ValueType = readType(*Loc.F, Record, Idx);
5398 return Context.getAtomicType(ValueType);
5399 }
5400 }
5401 llvm_unreachable("Invalid TypeCode!");
5402}
5403
Richard Smith564417a2014-03-20 21:47:22 +00005404void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5405 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005406 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005407 const RecordData &Record, unsigned &Idx) {
5408 ExceptionSpecificationType EST =
5409 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005410 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005411 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005412 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005413 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005414 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005415 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005416 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005417 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005418 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5419 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005420 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005421 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005422 }
5423}
5424
Guy Benyei11169dd2012-12-18 14:30:41 +00005425class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5426 ASTReader &Reader;
5427 ModuleFile &F;
5428 const ASTReader::RecordData &Record;
5429 unsigned &Idx;
5430
5431 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5432 unsigned &I) {
5433 return Reader.ReadSourceLocation(F, R, I);
5434 }
5435
5436 template<typename T>
5437 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5438 return Reader.ReadDeclAs<T>(F, Record, Idx);
5439 }
5440
5441public:
5442 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5443 const ASTReader::RecordData &Record, unsigned &Idx)
5444 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5445 { }
5446
5447 // We want compile-time assurance that we've enumerated all of
5448 // these, so unfortunately we have to declare them first, then
5449 // define them out-of-line.
5450#define ABSTRACT_TYPELOC(CLASS, PARENT)
5451#define TYPELOC(CLASS, PARENT) \
5452 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5453#include "clang/AST/TypeLocNodes.def"
5454
5455 void VisitFunctionTypeLoc(FunctionTypeLoc);
5456 void VisitArrayTypeLoc(ArrayTypeLoc);
5457};
5458
5459void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5460 // nothing to do
5461}
5462void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5463 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5464 if (TL.needsExtraLocalData()) {
5465 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5466 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5467 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5468 TL.setModeAttr(Record[Idx++]);
5469 }
5470}
5471void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5472 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5473}
5474void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5475 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5476}
Reid Kleckner8a365022013-06-24 17:51:48 +00005477void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5478 // nothing to do
5479}
Reid Kleckner0503a872013-12-05 01:23:43 +00005480void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5481 // nothing to do
5482}
Guy Benyei11169dd2012-12-18 14:30:41 +00005483void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5484 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5485}
5486void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5487 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5488}
5489void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5490 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5491}
5492void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5493 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5494 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5495}
5496void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5497 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5498 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5499 if (Record[Idx++])
5500 TL.setSizeExpr(Reader.ReadExpr(F));
5501 else
Craig Toppera13603a2014-05-22 05:54:18 +00005502 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005503}
5504void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5505 VisitArrayTypeLoc(TL);
5506}
5507void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5508 VisitArrayTypeLoc(TL);
5509}
5510void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5511 VisitArrayTypeLoc(TL);
5512}
5513void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5514 DependentSizedArrayTypeLoc TL) {
5515 VisitArrayTypeLoc(TL);
5516}
5517void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5518 DependentSizedExtVectorTypeLoc TL) {
5519 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5520}
5521void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5522 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5523}
5524void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5525 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5526}
5527void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5528 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5529 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5530 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5531 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005532 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5533 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005534 }
5535}
5536void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5537 VisitFunctionTypeLoc(TL);
5538}
5539void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5540 VisitFunctionTypeLoc(TL);
5541}
5542void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5543 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5544}
5545void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5546 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5547}
5548void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5549 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5550 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5551 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5552}
5553void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5554 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5555 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5556 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5557 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5558}
5559void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5560 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5561}
5562void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5563 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5564 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5565 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5566 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5567}
5568void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5569 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5570}
5571void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5572 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5573}
5574void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5575 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5576}
5577void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5578 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5579 if (TL.hasAttrOperand()) {
5580 SourceRange range;
5581 range.setBegin(ReadSourceLocation(Record, Idx));
5582 range.setEnd(ReadSourceLocation(Record, Idx));
5583 TL.setAttrOperandParensRange(range);
5584 }
5585 if (TL.hasAttrExprOperand()) {
5586 if (Record[Idx++])
5587 TL.setAttrExprOperand(Reader.ReadExpr(F));
5588 else
Craig Toppera13603a2014-05-22 05:54:18 +00005589 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005590 } else if (TL.hasAttrEnumOperand())
5591 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5592}
5593void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5594 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5595}
5596void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5597 SubstTemplateTypeParmTypeLoc TL) {
5598 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5599}
5600void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5601 SubstTemplateTypeParmPackTypeLoc TL) {
5602 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5603}
5604void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5605 TemplateSpecializationTypeLoc TL) {
5606 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5607 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5608 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5609 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5610 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5611 TL.setArgLocInfo(i,
5612 Reader.GetTemplateArgumentLocInfo(F,
5613 TL.getTypePtr()->getArg(i).getKind(),
5614 Record, Idx));
5615}
5616void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5617 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5618 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5619}
5620void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5621 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5622 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5623}
5624void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5625 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5626}
5627void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5628 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5629 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5630 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5631}
5632void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5633 DependentTemplateSpecializationTypeLoc TL) {
5634 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5635 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5636 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5637 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5638 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5639 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5640 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5641 TL.setArgLocInfo(I,
5642 Reader.GetTemplateArgumentLocInfo(F,
5643 TL.getTypePtr()->getArg(I).getKind(),
5644 Record, Idx));
5645}
5646void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5647 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5648}
5649void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5650 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5651}
5652void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5653 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005654 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5655 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5656 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5657 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5658 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5659 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005660 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5661 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5662}
5663void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5664 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5665}
5666void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5667 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5668 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5669 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5670}
5671
5672TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5673 const RecordData &Record,
5674 unsigned &Idx) {
5675 QualType InfoTy = readType(F, Record, Idx);
5676 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005677 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005678
5679 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5680 TypeLocReader TLR(*this, F, Record, Idx);
5681 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5682 TLR.Visit(TL);
5683 return TInfo;
5684}
5685
5686QualType ASTReader::GetType(TypeID ID) {
5687 unsigned FastQuals = ID & Qualifiers::FastMask;
5688 unsigned Index = ID >> Qualifiers::FastWidth;
5689
5690 if (Index < NUM_PREDEF_TYPE_IDS) {
5691 QualType T;
5692 switch ((PredefinedTypeIDs)Index) {
5693 case PREDEF_TYPE_NULL_ID: return QualType();
5694 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5695 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5696
5697 case PREDEF_TYPE_CHAR_U_ID:
5698 case PREDEF_TYPE_CHAR_S_ID:
5699 // FIXME: Check that the signedness of CharTy is correct!
5700 T = Context.CharTy;
5701 break;
5702
5703 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5704 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5705 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5706 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5707 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5708 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5709 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5710 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5711 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5712 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5713 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5714 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5715 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5716 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5717 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5718 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5719 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5720 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5721 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5722 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5723 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5724 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5725 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5726 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5727 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5728 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5729 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5730 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005731 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5732 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5733 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5734 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5735 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5736 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005737 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005738 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005739 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5740
5741 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5742 T = Context.getAutoRRefDeductType();
5743 break;
5744
5745 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5746 T = Context.ARCUnbridgedCastTy;
5747 break;
5748
5749 case PREDEF_TYPE_VA_LIST_TAG:
5750 T = Context.getVaListTagType();
5751 break;
5752
5753 case PREDEF_TYPE_BUILTIN_FN:
5754 T = Context.BuiltinFnTy;
5755 break;
5756 }
5757
5758 assert(!T.isNull() && "Unknown predefined type");
5759 return T.withFastQualifiers(FastQuals);
5760 }
5761
5762 Index -= NUM_PREDEF_TYPE_IDS;
5763 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5764 if (TypesLoaded[Index].isNull()) {
5765 TypesLoaded[Index] = readTypeRecord(Index);
5766 if (TypesLoaded[Index].isNull())
5767 return QualType();
5768
5769 TypesLoaded[Index]->setFromAST();
5770 if (DeserializationListener)
5771 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5772 TypesLoaded[Index]);
5773 }
5774
5775 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5776}
5777
5778QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5779 return GetType(getGlobalTypeID(F, LocalID));
5780}
5781
5782serialization::TypeID
5783ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5784 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5785 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5786
5787 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5788 return LocalID;
5789
5790 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5791 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5792 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5793
5794 unsigned GlobalIndex = LocalIndex + I->second;
5795 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5796}
5797
5798TemplateArgumentLocInfo
5799ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5800 TemplateArgument::ArgKind Kind,
5801 const RecordData &Record,
5802 unsigned &Index) {
5803 switch (Kind) {
5804 case TemplateArgument::Expression:
5805 return ReadExpr(F);
5806 case TemplateArgument::Type:
5807 return GetTypeSourceInfo(F, Record, Index);
5808 case TemplateArgument::Template: {
5809 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5810 Index);
5811 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5812 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5813 SourceLocation());
5814 }
5815 case TemplateArgument::TemplateExpansion: {
5816 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5817 Index);
5818 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5819 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5820 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5821 EllipsisLoc);
5822 }
5823 case TemplateArgument::Null:
5824 case TemplateArgument::Integral:
5825 case TemplateArgument::Declaration:
5826 case TemplateArgument::NullPtr:
5827 case TemplateArgument::Pack:
5828 // FIXME: Is this right?
5829 return TemplateArgumentLocInfo();
5830 }
5831 llvm_unreachable("unexpected template argument loc");
5832}
5833
5834TemplateArgumentLoc
5835ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5836 const RecordData &Record, unsigned &Index) {
5837 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5838
5839 if (Arg.getKind() == TemplateArgument::Expression) {
5840 if (Record[Index++]) // bool InfoHasSameExpr.
5841 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5842 }
5843 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5844 Record, Index));
5845}
5846
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005847const ASTTemplateArgumentListInfo*
5848ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5849 const RecordData &Record,
5850 unsigned &Index) {
5851 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5852 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5853 unsigned NumArgsAsWritten = Record[Index++];
5854 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5855 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5856 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5857 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5858}
5859
Guy Benyei11169dd2012-12-18 14:30:41 +00005860Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5861 return GetDecl(ID);
5862}
5863
Richard Smith50895422015-01-31 03:04:55 +00005864template<typename TemplateSpecializationDecl>
5865static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5866 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5867 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5868}
5869
Richard Smith053f6c62014-05-16 23:01:30 +00005870void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005871 if (NumCurrentElementsDeserializing) {
5872 // We arrange to not care about the complete redeclaration chain while we're
5873 // deserializing. Just remember that the AST has marked this one as complete
5874 // but that it's not actually complete yet, so we know we still need to
5875 // complete it later.
5876 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5877 return;
5878 }
5879
Richard Smith053f6c62014-05-16 23:01:30 +00005880 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5881
Richard Smith053f6c62014-05-16 23:01:30 +00005882 // If this is a named declaration, complete it by looking it up
5883 // within its context.
5884 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005885 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005886 // all mergeable entities within it.
5887 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5888 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5889 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
5890 auto *II = Name.getAsIdentifierInfo();
5891 if (isa<TranslationUnitDecl>(DC) && II) {
5892 // Outside of C++, we don't have a lookup table for the TU, so update
5893 // the identifier instead. In C++, either way should work fine.
5894 if (II->isOutOfDate())
5895 updateOutOfDateIdentifier(*II);
5896 } else
5897 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005898 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
5899 // FIXME: It'd be nice to do something a bit more targeted here.
5900 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00005901 }
5902 }
Richard Smith50895422015-01-31 03:04:55 +00005903
5904 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5905 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5906 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5907 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5908 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5909 if (auto *Template = FD->getPrimaryTemplate())
5910 Template->LoadLazySpecializations();
5911 }
Richard Smith053f6c62014-05-16 23:01:30 +00005912}
5913
Richard Smithc2bb8182015-03-24 06:36:48 +00005914uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5915 const RecordData &Record,
5916 unsigned &Idx) {
5917 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5918 Error("malformed AST file: missing C++ ctor initializers");
5919 return 0;
5920 }
5921
5922 unsigned LocalID = Record[Idx++];
5923 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
5924}
5925
5926CXXCtorInitializer **
5927ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
5928 RecordLocation Loc = getLocalBitOffset(Offset);
5929 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
5930 SavedStreamPosition SavedPosition(Cursor);
5931 Cursor.JumpToBit(Loc.Offset);
5932 ReadingKindTracker ReadingKind(Read_Decl, *this);
5933
5934 RecordData Record;
5935 unsigned Code = Cursor.ReadCode();
5936 unsigned RecCode = Cursor.readRecord(Code, Record);
5937 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
5938 Error("malformed AST file: missing C++ ctor initializers");
5939 return nullptr;
5940 }
5941
5942 unsigned Idx = 0;
5943 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
5944}
5945
Richard Smithcd45dbc2014-04-19 03:48:30 +00005946uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5947 const RecordData &Record,
5948 unsigned &Idx) {
5949 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5950 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005951 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005952 }
5953
Guy Benyei11169dd2012-12-18 14:30:41 +00005954 unsigned LocalID = Record[Idx++];
5955 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5956}
5957
5958CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5959 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005960 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005961 SavedStreamPosition SavedPosition(Cursor);
5962 Cursor.JumpToBit(Loc.Offset);
5963 ReadingKindTracker ReadingKind(Read_Decl, *this);
5964 RecordData Record;
5965 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005966 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005967 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005968 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00005969 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005970 }
5971
5972 unsigned Idx = 0;
5973 unsigned NumBases = Record[Idx++];
5974 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5975 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5976 for (unsigned I = 0; I != NumBases; ++I)
5977 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5978 return Bases;
5979}
5980
5981serialization::DeclID
5982ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5983 if (LocalID < NUM_PREDEF_DECL_IDS)
5984 return LocalID;
5985
5986 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5987 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5988 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5989
5990 return LocalID + I->second;
5991}
5992
5993bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5994 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00005995 // Predefined decls aren't from any module.
5996 if (ID < NUM_PREDEF_DECL_IDS)
5997 return false;
5998
Guy Benyei11169dd2012-12-18 14:30:41 +00005999 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6000 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6001 return &M == I->second;
6002}
6003
Douglas Gregor9f782892013-01-21 15:25:38 +00006004ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006005 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006006 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006007 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6008 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6009 return I->second;
6010}
6011
6012SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6013 if (ID < NUM_PREDEF_DECL_IDS)
6014 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006015
Guy Benyei11169dd2012-12-18 14:30:41 +00006016 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6017
6018 if (Index > DeclsLoaded.size()) {
6019 Error("declaration ID out-of-range for AST file");
6020 return SourceLocation();
6021 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006022
Guy Benyei11169dd2012-12-18 14:30:41 +00006023 if (Decl *D = DeclsLoaded[Index])
6024 return D->getLocation();
6025
6026 unsigned RawLocation = 0;
6027 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6028 return ReadSourceLocation(*Rec.F, RawLocation);
6029}
6030
Richard Smithfe620d22015-03-05 23:24:12 +00006031static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6032 switch (ID) {
6033 case PREDEF_DECL_NULL_ID:
6034 return nullptr;
6035
6036 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6037 return Context.getTranslationUnitDecl();
6038
6039 case PREDEF_DECL_OBJC_ID_ID:
6040 return Context.getObjCIdDecl();
6041
6042 case PREDEF_DECL_OBJC_SEL_ID:
6043 return Context.getObjCSelDecl();
6044
6045 case PREDEF_DECL_OBJC_CLASS_ID:
6046 return Context.getObjCClassDecl();
6047
6048 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6049 return Context.getObjCProtocolDecl();
6050
6051 case PREDEF_DECL_INT_128_ID:
6052 return Context.getInt128Decl();
6053
6054 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6055 return Context.getUInt128Decl();
6056
6057 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6058 return Context.getObjCInstanceTypeDecl();
6059
6060 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6061 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006062
6063 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6064 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006065 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006066 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006067}
6068
Richard Smithcd45dbc2014-04-19 03:48:30 +00006069Decl *ASTReader::GetExistingDecl(DeclID ID) {
6070 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006071 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6072 if (D) {
6073 // Track that we have merged the declaration with ID \p ID into the
6074 // pre-existing predefined declaration \p D.
6075 auto &Merged = MergedDecls[D->getCanonicalDecl()];
6076 if (Merged.empty())
6077 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006078 }
Richard Smithfe620d22015-03-05 23:24:12 +00006079 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006080 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006081
Guy Benyei11169dd2012-12-18 14:30:41 +00006082 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6083
6084 if (Index >= DeclsLoaded.size()) {
6085 assert(0 && "declaration ID out-of-range for AST file");
6086 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006087 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006088 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006089
6090 return DeclsLoaded[Index];
6091}
6092
6093Decl *ASTReader::GetDecl(DeclID ID) {
6094 if (ID < NUM_PREDEF_DECL_IDS)
6095 return GetExistingDecl(ID);
6096
6097 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6098
6099 if (Index >= DeclsLoaded.size()) {
6100 assert(0 && "declaration ID out-of-range for AST file");
6101 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006102 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006103 }
6104
Guy Benyei11169dd2012-12-18 14:30:41 +00006105 if (!DeclsLoaded[Index]) {
6106 ReadDeclRecord(ID);
6107 if (DeserializationListener)
6108 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6109 }
6110
6111 return DeclsLoaded[Index];
6112}
6113
6114DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6115 DeclID GlobalID) {
6116 if (GlobalID < NUM_PREDEF_DECL_IDS)
6117 return GlobalID;
6118
6119 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6120 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6121 ModuleFile *Owner = I->second;
6122
6123 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6124 = M.GlobalToLocalDeclIDs.find(Owner);
6125 if (Pos == M.GlobalToLocalDeclIDs.end())
6126 return 0;
6127
6128 return GlobalID - Owner->BaseDeclID + Pos->second;
6129}
6130
6131serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6132 const RecordData &Record,
6133 unsigned &Idx) {
6134 if (Idx >= Record.size()) {
6135 Error("Corrupted AST file");
6136 return 0;
6137 }
6138
6139 return getGlobalDeclID(F, Record[Idx++]);
6140}
6141
6142/// \brief Resolve the offset of a statement into a statement.
6143///
6144/// This operation will read a new statement from the external
6145/// source each time it is called, and is meant to be used via a
6146/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6147Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6148 // Switch case IDs are per Decl.
6149 ClearSwitchCaseIDs();
6150
6151 // Offset here is a global offset across the entire chain.
6152 RecordLocation Loc = getLocalBitOffset(Offset);
6153 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6154 return ReadStmtFromStream(*Loc.F);
6155}
6156
6157namespace {
6158 class FindExternalLexicalDeclsVisitor {
6159 ASTReader &Reader;
6160 const DeclContext *DC;
6161 bool (*isKindWeWant)(Decl::Kind);
6162
6163 SmallVectorImpl<Decl*> &Decls;
6164 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6165
6166 public:
6167 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6168 bool (*isKindWeWant)(Decl::Kind),
6169 SmallVectorImpl<Decl*> &Decls)
6170 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6171 {
6172 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6173 PredefsVisited[I] = false;
6174 }
6175
Manuel Klimek9eff8b12015-05-20 10:29:23 +00006176 static bool visitPostorder(ModuleFile &M, void *UserData) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006177 FindExternalLexicalDeclsVisitor *This
6178 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6179
6180 ModuleFile::DeclContextInfosMap::iterator Info
6181 = M.DeclContextInfos.find(This->DC);
6182 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6183 return false;
6184
6185 // Load all of the declaration IDs
6186 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6187 *IDE = ID + Info->second.NumLexicalDecls;
6188 ID != IDE; ++ID) {
6189 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6190 continue;
6191
6192 // Don't add predefined declarations to the lexical context more
6193 // than once.
6194 if (ID->second < NUM_PREDEF_DECL_IDS) {
6195 if (This->PredefsVisited[ID->second])
6196 continue;
6197
6198 This->PredefsVisited[ID->second] = true;
6199 }
6200
6201 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6202 if (!This->DC->isDeclInLexicalTraversal(D))
6203 This->Decls.push_back(D);
6204 }
6205 }
6206
6207 return false;
6208 }
6209 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006210}
Guy Benyei11169dd2012-12-18 14:30:41 +00006211
6212ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6213 bool (*isKindWeWant)(Decl::Kind),
6214 SmallVectorImpl<Decl*> &Decls) {
6215 // There might be lexical decls in multiple modules, for the TU at
6216 // least. Walk all of the modules in the order they were loaded.
6217 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
Manuel Klimek9eff8b12015-05-20 10:29:23 +00006218 ModuleMgr.visitDepthFirst(
6219 nullptr, &FindExternalLexicalDeclsVisitor::visitPostorder, &Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006220 ++NumLexicalDeclContextsRead;
6221 return ELR_Success;
6222}
6223
6224namespace {
6225
6226class DeclIDComp {
6227 ASTReader &Reader;
6228 ModuleFile &Mod;
6229
6230public:
6231 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6232
6233 bool operator()(LocalDeclID L, LocalDeclID R) const {
6234 SourceLocation LHS = getLocation(L);
6235 SourceLocation RHS = getLocation(R);
6236 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6237 }
6238
6239 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6240 SourceLocation RHS = getLocation(R);
6241 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6242 }
6243
6244 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6245 SourceLocation LHS = getLocation(L);
6246 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6247 }
6248
6249 SourceLocation getLocation(LocalDeclID ID) const {
6250 return Reader.getSourceManager().getFileLoc(
6251 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6252 }
6253};
6254
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006255}
Guy Benyei11169dd2012-12-18 14:30:41 +00006256
6257void ASTReader::FindFileRegionDecls(FileID File,
6258 unsigned Offset, unsigned Length,
6259 SmallVectorImpl<Decl *> &Decls) {
6260 SourceManager &SM = getSourceManager();
6261
6262 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6263 if (I == FileDeclIDs.end())
6264 return;
6265
6266 FileDeclsInfo &DInfo = I->second;
6267 if (DInfo.Decls.empty())
6268 return;
6269
6270 SourceLocation
6271 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6272 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6273
6274 DeclIDComp DIDComp(*this, *DInfo.Mod);
6275 ArrayRef<serialization::LocalDeclID>::iterator
6276 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6277 BeginLoc, DIDComp);
6278 if (BeginIt != DInfo.Decls.begin())
6279 --BeginIt;
6280
6281 // If we are pointing at a top-level decl inside an objc container, we need
6282 // to backtrack until we find it otherwise we will fail to report that the
6283 // region overlaps with an objc container.
6284 while (BeginIt != DInfo.Decls.begin() &&
6285 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6286 ->isTopLevelDeclInObjCContainer())
6287 --BeginIt;
6288
6289 ArrayRef<serialization::LocalDeclID>::iterator
6290 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6291 EndLoc, DIDComp);
6292 if (EndIt != DInfo.Decls.end())
6293 ++EndIt;
6294
6295 for (ArrayRef<serialization::LocalDeclID>::iterator
6296 DIt = BeginIt; DIt != EndIt; ++DIt)
6297 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6298}
6299
6300namespace {
6301 /// \brief ModuleFile visitor used to perform name lookup into a
6302 /// declaration context.
6303 class DeclContextNameLookupVisitor {
6304 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006305 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006306 DeclarationName Name;
6307 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006308 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006309
6310 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006311 DeclContextNameLookupVisitor(ASTReader &Reader,
6312 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006313 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006314 SmallVectorImpl<NamedDecl *> &Decls,
6315 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
6316 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls),
6317 DeclSet(DeclSet) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006318
6319 static bool visit(ModuleFile &M, void *UserData) {
6320 DeclContextNameLookupVisitor *This
6321 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6322
6323 // Check whether we have any visible declaration information for
6324 // this context in this module.
6325 ModuleFile::DeclContextInfosMap::iterator Info;
6326 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006327 for (auto *DC : This->Contexts) {
6328 Info = M.DeclContextInfos.find(DC);
6329 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006330 Info->second.NameLookupTableData) {
6331 FoundInfo = true;
6332 break;
6333 }
6334 }
6335
6336 if (!FoundInfo)
6337 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006338
Guy Benyei11169dd2012-12-18 14:30:41 +00006339 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006340 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006341 Info->second.NameLookupTableData;
6342 ASTDeclContextNameLookupTable::iterator Pos
6343 = LookupTable->find(This->Name);
6344 if (Pos == LookupTable->end())
6345 return false;
6346
6347 bool FoundAnything = false;
6348 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6349 for (; Data.first != Data.second; ++Data.first) {
6350 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6351 if (!ND)
6352 continue;
6353
6354 if (ND->getDeclName() != This->Name) {
6355 // A name might be null because the decl's redeclarable part is
6356 // currently read before reading its name. The lookup is triggered by
6357 // building that decl (likely indirectly), and so it is later in the
6358 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006359 // FIXME: This should not happen; deserializing declarations should
6360 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006361 continue;
6362 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006363
Guy Benyei11169dd2012-12-18 14:30:41 +00006364 // Record this declaration.
6365 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006366 if (This->DeclSet.insert(ND).second)
6367 This->Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006368 }
6369
6370 return FoundAnything;
6371 }
6372 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006373}
Guy Benyei11169dd2012-12-18 14:30:41 +00006374
Douglas Gregor9f782892013-01-21 15:25:38 +00006375/// \brief Retrieve the "definitive" module file for the definition of the
6376/// given declaration context, if there is one.
6377///
6378/// The "definitive" module file is the only place where we need to look to
6379/// find information about the declarations within the given declaration
6380/// context. For example, C++ and Objective-C classes, C structs/unions, and
6381/// Objective-C protocols, categories, and extensions are all defined in a
6382/// single place in the source code, so they have definitive module files
6383/// associated with them. C++ namespaces, on the other hand, can have
6384/// definitions in multiple different module files.
6385///
6386/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6387/// NDEBUG checking.
6388static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6389 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006390 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6391 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006392
Craig Toppera13603a2014-05-22 05:54:18 +00006393 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006394}
6395
Richard Smith9ce12e32013-02-07 03:30:24 +00006396bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006397ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6398 DeclarationName Name) {
6399 assert(DC->hasExternalVisibleStorage() &&
6400 "DeclContext has no visible decls in storage");
6401 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006402 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006403
Richard Smith8c913ec2014-08-14 02:21:01 +00006404 Deserializing LookupResults(this);
6405
Guy Benyei11169dd2012-12-18 14:30:41 +00006406 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006407 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006408
Guy Benyei11169dd2012-12-18 14:30:41 +00006409 // Compute the declaration contexts we need to look into. Multiple such
6410 // declaration contexts occur when two declaration contexts from disjoint
6411 // modules get merged, e.g., when two namespaces with the same name are
6412 // independently defined in separate modules.
6413 SmallVector<const DeclContext *, 2> Contexts;
6414 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006415
Guy Benyei11169dd2012-12-18 14:30:41 +00006416 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006417 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006418 if (Merged != MergedDecls.end()) {
6419 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6420 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6421 }
6422 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006423
6424 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
Richard Smith52874ec2015-02-13 20:17:14 +00006425 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006426
6427 // If we can definitively determine which module file to look into,
6428 // only look there. Otherwise, look in all module files.
6429 ModuleFile *Definitive;
6430 if (Contexts.size() == 1 &&
6431 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6432 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6433 } else {
6434 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6435 }
6436 };
6437
6438 LookUpInContexts(Contexts);
6439
6440 // If this might be an implicit special member function, then also search
6441 // all merged definitions of the surrounding class. We need to search them
6442 // individually, because finding an entity in one of them doesn't imply that
6443 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006444 if (isa<CXXRecordDecl>(DC)) {
Richard Smith02793752015-03-27 21:16:39 +00006445 auto Merged = MergedLookups.find(DC);
6446 if (Merged != MergedLookups.end()) {
6447 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6448 const DeclContext *Context = Merged->second[I];
6449 LookUpInContexts(Context);
6450 // We might have just added some more merged lookups. If so, our
6451 // iterator is now invalid, so grab a fresh one before continuing.
6452 Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006453 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006454 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006455 }
6456
Guy Benyei11169dd2012-12-18 14:30:41 +00006457 ++NumVisibleDeclContextsRead;
6458 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006459 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006460}
6461
6462namespace {
6463 /// \brief ModuleFile visitor used to retrieve all visible names in a
6464 /// declaration context.
6465 class DeclContextAllNamesVisitor {
6466 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006467 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006468 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006469 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006470 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006471
6472 public:
6473 DeclContextAllNamesVisitor(ASTReader &Reader,
6474 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006475 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006476 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006477
6478 static bool visit(ModuleFile &M, void *UserData) {
6479 DeclContextAllNamesVisitor *This
6480 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6481
6482 // Check whether we have any visible declaration information for
6483 // this context in this module.
6484 ModuleFile::DeclContextInfosMap::iterator Info;
6485 bool FoundInfo = false;
6486 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6487 Info = M.DeclContextInfos.find(This->Contexts[I]);
6488 if (Info != M.DeclContextInfos.end() &&
6489 Info->second.NameLookupTableData) {
6490 FoundInfo = true;
6491 break;
6492 }
6493 }
6494
6495 if (!FoundInfo)
6496 return false;
6497
Richard Smith52e3fba2014-03-11 07:17:35 +00006498 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006499 Info->second.NameLookupTableData;
6500 bool FoundAnything = false;
6501 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006502 I = LookupTable->data_begin(), E = LookupTable->data_end();
6503 I != E;
6504 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006505 ASTDeclContextNameLookupTrait::data_type Data = *I;
6506 for (; Data.first != Data.second; ++Data.first) {
6507 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6508 *Data.first);
6509 if (!ND)
6510 continue;
6511
6512 // Record this declaration.
6513 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006514 if (This->DeclSet.insert(ND).second)
6515 This->Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006516 }
6517 }
6518
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006519 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006520 }
6521 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006522}
Guy Benyei11169dd2012-12-18 14:30:41 +00006523
6524void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6525 if (!DC->hasExternalVisibleStorage())
6526 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006527 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006528
6529 // Compute the declaration contexts we need to look into. Multiple such
6530 // declaration contexts occur when two declaration contexts from disjoint
6531 // modules get merged, e.g., when two namespaces with the same name are
6532 // independently defined in separate modules.
6533 SmallVector<const DeclContext *, 2> Contexts;
6534 Contexts.push_back(DC);
6535
6536 if (DC->isNamespace()) {
6537 MergedDeclsMap::iterator Merged
6538 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6539 if (Merged != MergedDecls.end()) {
6540 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6541 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6542 }
6543 }
6544
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006545 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6546 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006547 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6548 ++NumVisibleDeclContextsRead;
6549
Craig Topper79be4cd2013-07-05 04:33:53 +00006550 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006551 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6552 }
6553 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6554}
6555
6556/// \brief Under non-PCH compilation the consumer receives the objc methods
6557/// before receiving the implementation, and codegen depends on this.
6558/// We simulate this by deserializing and passing to consumer the methods of the
6559/// implementation before passing the deserialized implementation decl.
6560static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6561 ASTConsumer *Consumer) {
6562 assert(ImplD && Consumer);
6563
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006564 for (auto *I : ImplD->methods())
6565 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006566
6567 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6568}
6569
6570void ASTReader::PassInterestingDeclsToConsumer() {
6571 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006572
6573 if (PassingDeclsToConsumer)
6574 return;
6575
6576 // Guard variable to avoid recursively redoing the process of passing
6577 // decls to consumer.
6578 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6579 true);
6580
Richard Smith9e2341d2015-03-23 03:25:59 +00006581 // Ensure that we've loaded all potentially-interesting declarations
6582 // that need to be eagerly loaded.
6583 for (auto ID : EagerlyDeserializedDecls)
6584 GetDecl(ID);
6585 EagerlyDeserializedDecls.clear();
6586
Guy Benyei11169dd2012-12-18 14:30:41 +00006587 while (!InterestingDecls.empty()) {
6588 Decl *D = InterestingDecls.front();
6589 InterestingDecls.pop_front();
6590
6591 PassInterestingDeclToConsumer(D);
6592 }
6593}
6594
6595void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6596 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6597 PassObjCImplDeclToConsumer(ImplD, Consumer);
6598 else
6599 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6600}
6601
6602void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6603 this->Consumer = Consumer;
6604
Richard Smith9e2341d2015-03-23 03:25:59 +00006605 if (Consumer)
6606 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006607
6608 if (DeserializationListener)
6609 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006610}
6611
6612void ASTReader::PrintStats() {
6613 std::fprintf(stderr, "*** AST File Statistics:\n");
6614
6615 unsigned NumTypesLoaded
6616 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6617 QualType());
6618 unsigned NumDeclsLoaded
6619 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006620 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006621 unsigned NumIdentifiersLoaded
6622 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6623 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006624 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006625 unsigned NumMacrosLoaded
6626 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6627 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006628 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006629 unsigned NumSelectorsLoaded
6630 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6631 SelectorsLoaded.end(),
6632 Selector());
6633
6634 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6635 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6636 NumSLocEntriesRead, TotalNumSLocEntries,
6637 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6638 if (!TypesLoaded.empty())
6639 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6640 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6641 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6642 if (!DeclsLoaded.empty())
6643 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6644 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6645 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6646 if (!IdentifiersLoaded.empty())
6647 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6648 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6649 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6650 if (!MacrosLoaded.empty())
6651 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6652 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6653 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6654 if (!SelectorsLoaded.empty())
6655 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6656 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6657 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6658 if (TotalNumStatements)
6659 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6660 NumStatementsRead, TotalNumStatements,
6661 ((float)NumStatementsRead/TotalNumStatements * 100));
6662 if (TotalNumMacros)
6663 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6664 NumMacrosRead, TotalNumMacros,
6665 ((float)NumMacrosRead/TotalNumMacros * 100));
6666 if (TotalLexicalDeclContexts)
6667 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6668 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6669 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6670 * 100));
6671 if (TotalVisibleDeclContexts)
6672 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6673 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6674 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6675 * 100));
6676 if (TotalNumMethodPoolEntries) {
6677 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6678 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6679 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6680 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006681 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006682 if (NumMethodPoolLookups) {
6683 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6684 NumMethodPoolHits, NumMethodPoolLookups,
6685 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6686 }
6687 if (NumMethodPoolTableLookups) {
6688 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6689 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6690 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6691 * 100.0));
6692 }
6693
Douglas Gregor00a50f72013-01-25 00:38:33 +00006694 if (NumIdentifierLookupHits) {
6695 std::fprintf(stderr,
6696 " %u / %u identifier table lookups succeeded (%f%%)\n",
6697 NumIdentifierLookupHits, NumIdentifierLookups,
6698 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6699 }
6700
Douglas Gregore060e572013-01-25 01:03:03 +00006701 if (GlobalIndex) {
6702 std::fprintf(stderr, "\n");
6703 GlobalIndex->printStats();
6704 }
6705
Guy Benyei11169dd2012-12-18 14:30:41 +00006706 std::fprintf(stderr, "\n");
6707 dump();
6708 std::fprintf(stderr, "\n");
6709}
6710
6711template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6712static void
6713dumpModuleIDMap(StringRef Name,
6714 const ContinuousRangeMap<Key, ModuleFile *,
6715 InitialCapacity> &Map) {
6716 if (Map.begin() == Map.end())
6717 return;
6718
6719 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6720 llvm::errs() << Name << ":\n";
6721 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6722 I != IEnd; ++I) {
6723 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6724 << "\n";
6725 }
6726}
6727
6728void ASTReader::dump() {
6729 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6730 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6731 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6732 dumpModuleIDMap("Global type map", GlobalTypeMap);
6733 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6734 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6735 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6736 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6737 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6738 dumpModuleIDMap("Global preprocessed entity map",
6739 GlobalPreprocessedEntityMap);
6740
6741 llvm::errs() << "\n*** PCH/Modules Loaded:";
6742 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6743 MEnd = ModuleMgr.end();
6744 M != MEnd; ++M)
6745 (*M)->dump();
6746}
6747
6748/// Return the amount of memory used by memory buffers, breaking down
6749/// by heap-backed versus mmap'ed memory.
6750void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6751 for (ModuleConstIterator I = ModuleMgr.begin(),
6752 E = ModuleMgr.end(); I != E; ++I) {
6753 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6754 size_t bytes = buf->getBufferSize();
6755 switch (buf->getBufferKind()) {
6756 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6757 sizes.malloc_bytes += bytes;
6758 break;
6759 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6760 sizes.mmap_bytes += bytes;
6761 break;
6762 }
6763 }
6764 }
6765}
6766
6767void ASTReader::InitializeSema(Sema &S) {
6768 SemaObj = &S;
6769 S.addExternalSource(this);
6770
6771 // Makes sure any declarations that were deserialized "too early"
6772 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006773 for (uint64_t ID : PreloadedDeclIDs) {
6774 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6775 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006776 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006777 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006778
Richard Smith3d8e97e2013-10-18 06:54:39 +00006779 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006780 if (!FPPragmaOptions.empty()) {
6781 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6782 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6783 }
6784
Richard Smith3d8e97e2013-10-18 06:54:39 +00006785 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006786 if (!OpenCLExtensions.empty()) {
6787 unsigned I = 0;
6788#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6789#include "clang/Basic/OpenCLExtensions.def"
6790
6791 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6792 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006793
6794 UpdateSema();
6795}
6796
6797void ASTReader::UpdateSema() {
6798 assert(SemaObj && "no Sema to update");
6799
6800 // Load the offsets of the declarations that Sema references.
6801 // They will be lazily deserialized when needed.
6802 if (!SemaDeclRefs.empty()) {
6803 assert(SemaDeclRefs.size() % 2 == 0);
6804 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6805 if (!SemaObj->StdNamespace)
6806 SemaObj->StdNamespace = SemaDeclRefs[I];
6807 if (!SemaObj->StdBadAlloc)
6808 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6809 }
6810 SemaDeclRefs.clear();
6811 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006812
6813 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6814 // encountered the pragma in the source.
6815 if(OptimizeOffPragmaLocation.isValid())
6816 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006817}
6818
6819IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6820 // Note that we are loading an identifier.
6821 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006822 StringRef Name(NameStart, NameEnd - NameStart);
6823
6824 // If there is a global index, look there first to determine which modules
6825 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006826 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00006827 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00006828 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006829 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6830 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006831 }
6832 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006833 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006834 NumIdentifierLookups,
6835 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006836 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006837 IdentifierInfo *II = Visitor.getIdentifierInfo();
6838 markIdentifierUpToDate(II);
6839 return II;
6840}
6841
6842namespace clang {
6843 /// \brief An identifier-lookup iterator that enumerates all of the
6844 /// identifiers stored within a set of AST files.
6845 class ASTIdentifierIterator : public IdentifierIterator {
6846 /// \brief The AST reader whose identifiers are being enumerated.
6847 const ASTReader &Reader;
6848
6849 /// \brief The current index into the chain of AST files stored in
6850 /// the AST reader.
6851 unsigned Index;
6852
6853 /// \brief The current position within the identifier lookup table
6854 /// of the current AST file.
6855 ASTIdentifierLookupTable::key_iterator Current;
6856
6857 /// \brief The end position within the identifier lookup table of
6858 /// the current AST file.
6859 ASTIdentifierLookupTable::key_iterator End;
6860
6861 public:
6862 explicit ASTIdentifierIterator(const ASTReader &Reader);
6863
Craig Topper3e89dfe2014-03-13 02:13:41 +00006864 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006865 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006866}
Guy Benyei11169dd2012-12-18 14:30:41 +00006867
6868ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6869 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6870 ASTIdentifierLookupTable *IdTable
6871 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6872 Current = IdTable->key_begin();
6873 End = IdTable->key_end();
6874}
6875
6876StringRef ASTIdentifierIterator::Next() {
6877 while (Current == End) {
6878 // If we have exhausted all of our AST files, we're done.
6879 if (Index == 0)
6880 return StringRef();
6881
6882 --Index;
6883 ASTIdentifierLookupTable *IdTable
6884 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6885 IdentifierLookupTable;
6886 Current = IdTable->key_begin();
6887 End = IdTable->key_end();
6888 }
6889
6890 // We have any identifiers remaining in the current AST file; return
6891 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006892 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006893 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006894 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006895}
6896
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006897IdentifierIterator *ASTReader::getIdentifiers() {
6898 if (!loadGlobalIndex())
6899 return GlobalIndex->createIdentifierIterator();
6900
Guy Benyei11169dd2012-12-18 14:30:41 +00006901 return new ASTIdentifierIterator(*this);
6902}
6903
6904namespace clang { namespace serialization {
6905 class ReadMethodPoolVisitor {
6906 ASTReader &Reader;
6907 Selector Sel;
6908 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006909 unsigned InstanceBits;
6910 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006911 bool InstanceHasMoreThanOneDecl;
6912 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006913 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6914 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006915
6916 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006917 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006918 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006919 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006920 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6921 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006922
Guy Benyei11169dd2012-12-18 14:30:41 +00006923 static bool visit(ModuleFile &M, void *UserData) {
6924 ReadMethodPoolVisitor *This
6925 = static_cast<ReadMethodPoolVisitor *>(UserData);
6926
6927 if (!M.SelectorLookupTable)
6928 return false;
6929
6930 // If we've already searched this module file, skip it now.
6931 if (M.Generation <= This->PriorGeneration)
6932 return true;
6933
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006934 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006935 ASTSelectorLookupTable *PoolTable
6936 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6937 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6938 if (Pos == PoolTable->end())
6939 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006940
6941 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006942 ++This->Reader.NumSelectorsRead;
6943 // FIXME: Not quite happy with the statistics here. We probably should
6944 // disable this tracking when called via LoadSelector.
6945 // Also, should entries without methods count as misses?
6946 ++This->Reader.NumMethodPoolEntriesRead;
6947 ASTSelectorLookupTrait::data_type Data = *Pos;
6948 if (This->Reader.DeserializationListener)
6949 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6950 This->Sel);
6951
6952 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6953 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006954 This->InstanceBits = Data.InstanceBits;
6955 This->FactoryBits = Data.FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006956 This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6957 This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006958 return true;
6959 }
6960
6961 /// \brief Retrieve the instance methods found by this visitor.
6962 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6963 return InstanceMethods;
6964 }
6965
6966 /// \brief Retrieve the instance methods found by this visitor.
6967 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6968 return FactoryMethods;
6969 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006970
6971 unsigned getInstanceBits() const { return InstanceBits; }
6972 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006973 bool instanceHasMoreThanOneDecl() const {
6974 return InstanceHasMoreThanOneDecl;
6975 }
6976 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006977 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006978} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00006979
6980/// \brief Add the given set of methods to the method list.
6981static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6982 ObjCMethodList &List) {
6983 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6984 S.addMethodToGlobalList(&List, Methods[I]);
6985 }
6986}
6987
6988void ASTReader::ReadMethodPool(Selector Sel) {
6989 // Get the selector generation and update it to the current generation.
6990 unsigned &Generation = SelectorGeneration[Sel];
6991 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00006992 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00006993
6994 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006995 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006996 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6997 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6998
6999 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007000 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007001 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007002
7003 ++NumMethodPoolHits;
7004
Guy Benyei11169dd2012-12-18 14:30:41 +00007005 if (!getSema())
7006 return;
7007
7008 Sema &S = *getSema();
7009 Sema::GlobalMethodPool::iterator Pos
7010 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007011
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007012 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007013 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007014 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007015 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007016
7017 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7018 // when building a module we keep every method individually and may need to
7019 // update hasMoreThanOneDecl as we add the methods.
7020 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7021 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007022}
7023
7024void ASTReader::ReadKnownNamespaces(
7025 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7026 Namespaces.clear();
7027
7028 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7029 if (NamespaceDecl *Namespace
7030 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7031 Namespaces.push_back(Namespace);
7032 }
7033}
7034
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007035void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007036 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007037 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7038 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007039 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007040 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007041 Undefined.insert(std::make_pair(D, Loc));
7042 }
7043}
Nick Lewycky8334af82013-01-26 00:35:08 +00007044
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007045void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7046 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7047 Exprs) {
7048 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7049 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7050 uint64_t Count = DelayedDeleteExprs[Idx++];
7051 for (uint64_t C = 0; C < Count; ++C) {
7052 SourceLocation DeleteLoc =
7053 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7054 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7055 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7056 }
7057 }
7058}
7059
Guy Benyei11169dd2012-12-18 14:30:41 +00007060void ASTReader::ReadTentativeDefinitions(
7061 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7062 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7063 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7064 if (Var)
7065 TentativeDefs.push_back(Var);
7066 }
7067 TentativeDefinitions.clear();
7068}
7069
7070void ASTReader::ReadUnusedFileScopedDecls(
7071 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7072 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7073 DeclaratorDecl *D
7074 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7075 if (D)
7076 Decls.push_back(D);
7077 }
7078 UnusedFileScopedDecls.clear();
7079}
7080
7081void ASTReader::ReadDelegatingConstructors(
7082 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7083 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7084 CXXConstructorDecl *D
7085 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7086 if (D)
7087 Decls.push_back(D);
7088 }
7089 DelegatingCtorDecls.clear();
7090}
7091
7092void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7093 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7094 TypedefNameDecl *D
7095 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7096 if (D)
7097 Decls.push_back(D);
7098 }
7099 ExtVectorDecls.clear();
7100}
7101
Nico Weber72889432014-09-06 01:25:55 +00007102void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7103 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7104 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7105 ++I) {
7106 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7107 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7108 if (D)
7109 Decls.insert(D);
7110 }
7111 UnusedLocalTypedefNameCandidates.clear();
7112}
7113
Guy Benyei11169dd2012-12-18 14:30:41 +00007114void ASTReader::ReadReferencedSelectors(
7115 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7116 if (ReferencedSelectorsData.empty())
7117 return;
7118
7119 // If there are @selector references added them to its pool. This is for
7120 // implementation of -Wselector.
7121 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7122 unsigned I = 0;
7123 while (I < DataSize) {
7124 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7125 SourceLocation SelLoc
7126 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7127 Sels.push_back(std::make_pair(Sel, SelLoc));
7128 }
7129 ReferencedSelectorsData.clear();
7130}
7131
7132void ASTReader::ReadWeakUndeclaredIdentifiers(
7133 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7134 if (WeakUndeclaredIdentifiers.empty())
7135 return;
7136
7137 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7138 IdentifierInfo *WeakId
7139 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7140 IdentifierInfo *AliasId
7141 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7142 SourceLocation Loc
7143 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7144 bool Used = WeakUndeclaredIdentifiers[I++];
7145 WeakInfo WI(AliasId, Loc);
7146 WI.setUsed(Used);
7147 WeakIDs.push_back(std::make_pair(WeakId, WI));
7148 }
7149 WeakUndeclaredIdentifiers.clear();
7150}
7151
7152void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7153 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7154 ExternalVTableUse VT;
7155 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7156 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7157 VT.DefinitionRequired = VTableUses[Idx++];
7158 VTables.push_back(VT);
7159 }
7160
7161 VTableUses.clear();
7162}
7163
7164void ASTReader::ReadPendingInstantiations(
7165 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7166 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7167 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7168 SourceLocation Loc
7169 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7170
7171 Pending.push_back(std::make_pair(D, Loc));
7172 }
7173 PendingInstantiations.clear();
7174}
7175
Richard Smithe40f2ba2013-08-07 21:41:30 +00007176void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007177 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007178 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7179 /* In loop */) {
7180 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7181
7182 LateParsedTemplate *LT = new LateParsedTemplate;
7183 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7184
7185 ModuleFile *F = getOwningModuleFile(LT->D);
7186 assert(F && "No module");
7187
7188 unsigned TokN = LateParsedTemplates[Idx++];
7189 LT->Toks.reserve(TokN);
7190 for (unsigned T = 0; T < TokN; ++T)
7191 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7192
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007193 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007194 }
7195
7196 LateParsedTemplates.clear();
7197}
7198
Guy Benyei11169dd2012-12-18 14:30:41 +00007199void ASTReader::LoadSelector(Selector Sel) {
7200 // It would be complicated to avoid reading the methods anyway. So don't.
7201 ReadMethodPool(Sel);
7202}
7203
7204void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7205 assert(ID && "Non-zero identifier ID required");
7206 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7207 IdentifiersLoaded[ID - 1] = II;
7208 if (DeserializationListener)
7209 DeserializationListener->IdentifierRead(ID, II);
7210}
7211
7212/// \brief Set the globally-visible declarations associated with the given
7213/// identifier.
7214///
7215/// If the AST reader is currently in a state where the given declaration IDs
7216/// cannot safely be resolved, they are queued until it is safe to resolve
7217/// them.
7218///
7219/// \param II an IdentifierInfo that refers to one or more globally-visible
7220/// declarations.
7221///
7222/// \param DeclIDs the set of declaration IDs with the name @p II that are
7223/// visible at global scope.
7224///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007225/// \param Decls if non-null, this vector will be populated with the set of
7226/// deserialized declarations. These declarations will not be pushed into
7227/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007228void
7229ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7230 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007231 SmallVectorImpl<Decl *> *Decls) {
7232 if (NumCurrentElementsDeserializing && !Decls) {
7233 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007234 return;
7235 }
7236
7237 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007238 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007239 // Queue this declaration so that it will be added to the
7240 // translation unit scope and identifier's declaration chain
7241 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007242 PreloadedDeclIDs.push_back(DeclIDs[I]);
7243 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007244 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007245
7246 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7247
7248 // If we're simply supposed to record the declarations, do so now.
7249 if (Decls) {
7250 Decls->push_back(D);
7251 continue;
7252 }
7253
7254 // Introduce this declaration into the translation-unit scope
7255 // and add it to the declaration chain for this identifier, so
7256 // that (unqualified) name lookup will find it.
7257 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007258 }
7259}
7260
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007261IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007262 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007263 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007264
7265 if (IdentifiersLoaded.empty()) {
7266 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007267 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007268 }
7269
7270 ID -= 1;
7271 if (!IdentifiersLoaded[ID]) {
7272 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7273 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7274 ModuleFile *M = I->second;
7275 unsigned Index = ID - M->BaseIdentifierID;
7276 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7277
7278 // All of the strings in the AST file are preceded by a 16-bit length.
7279 // Extract that 16-bit length to avoid having to execute strlen().
7280 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7281 // unsigned integers. This is important to avoid integer overflow when
7282 // we cast them to 'unsigned'.
7283 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7284 unsigned StrLen = (((unsigned) StrLenPtr[0])
7285 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007286 IdentifiersLoaded[ID]
7287 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007288 if (DeserializationListener)
7289 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7290 }
7291
7292 return IdentifiersLoaded[ID];
7293}
7294
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007295IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7296 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007297}
7298
7299IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7300 if (LocalID < NUM_PREDEF_IDENT_IDS)
7301 return LocalID;
7302
7303 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7304 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7305 assert(I != M.IdentifierRemap.end()
7306 && "Invalid index into identifier index remap");
7307
7308 return LocalID + I->second;
7309}
7310
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007311MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007312 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007313 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007314
7315 if (MacrosLoaded.empty()) {
7316 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007317 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007318 }
7319
7320 ID -= NUM_PREDEF_MACRO_IDS;
7321 if (!MacrosLoaded[ID]) {
7322 GlobalMacroMapType::iterator I
7323 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7324 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7325 ModuleFile *M = I->second;
7326 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007327 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7328
7329 if (DeserializationListener)
7330 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7331 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007332 }
7333
7334 return MacrosLoaded[ID];
7335}
7336
7337MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7338 if (LocalID < NUM_PREDEF_MACRO_IDS)
7339 return LocalID;
7340
7341 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7342 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7343 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7344
7345 return LocalID + I->second;
7346}
7347
7348serialization::SubmoduleID
7349ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7350 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7351 return LocalID;
7352
7353 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7354 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7355 assert(I != M.SubmoduleRemap.end()
7356 && "Invalid index into submodule index remap");
7357
7358 return LocalID + I->second;
7359}
7360
7361Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7362 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7363 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007364 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007365 }
7366
7367 if (GlobalID > SubmodulesLoaded.size()) {
7368 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007369 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007370 }
7371
7372 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7373}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007374
7375Module *ASTReader::getModule(unsigned ID) {
7376 return getSubmodule(ID);
7377}
7378
Adrian Prantl15bcf702015-06-30 17:39:43 +00007379ExternalASTSource::ASTSourceDescriptor
7380ASTReader::getSourceDescriptor(const Module &M) {
7381 StringRef Dir, Filename;
7382 if (M.Directory)
7383 Dir = M.Directory->getName();
7384 if (auto *File = M.getASTFile())
7385 Filename = File->getName();
7386 return ASTReader::ASTSourceDescriptor{
7387 M.getFullModuleName(), Dir, Filename,
7388 M.Signature
7389 };
7390}
7391
7392llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7393ASTReader::getSourceDescriptor(unsigned ID) {
7394 if (const Module *M = getSubmodule(ID))
7395 return getSourceDescriptor(*M);
7396
7397 // If there is only a single PCH, return it instead.
7398 // Chained PCH are not suported.
7399 if (ModuleMgr.size() == 1) {
7400 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7401 return ASTReader::ASTSourceDescriptor{
7402 MF.OriginalSourceFileName, MF.OriginalDir,
7403 MF.FileName,
7404 MF.Signature
7405 };
7406 }
7407 return None;
7408}
7409
Guy Benyei11169dd2012-12-18 14:30:41 +00007410Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7411 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7412}
7413
7414Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7415 if (ID == 0)
7416 return Selector();
7417
7418 if (ID > SelectorsLoaded.size()) {
7419 Error("selector ID out of range in AST file");
7420 return Selector();
7421 }
7422
Craig Toppera13603a2014-05-22 05:54:18 +00007423 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007424 // Load this selector from the selector table.
7425 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7426 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7427 ModuleFile &M = *I->second;
7428 ASTSelectorLookupTrait Trait(*this, M);
7429 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7430 SelectorsLoaded[ID - 1] =
7431 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7432 if (DeserializationListener)
7433 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7434 }
7435
7436 return SelectorsLoaded[ID - 1];
7437}
7438
7439Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7440 return DecodeSelector(ID);
7441}
7442
7443uint32_t ASTReader::GetNumExternalSelectors() {
7444 // ID 0 (the null selector) is considered an external selector.
7445 return getTotalNumSelectors() + 1;
7446}
7447
7448serialization::SelectorID
7449ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7450 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7451 return LocalID;
7452
7453 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7454 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7455 assert(I != M.SelectorRemap.end()
7456 && "Invalid index into selector index remap");
7457
7458 return LocalID + I->second;
7459}
7460
7461DeclarationName
7462ASTReader::ReadDeclarationName(ModuleFile &F,
7463 const RecordData &Record, unsigned &Idx) {
7464 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7465 switch (Kind) {
7466 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007467 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007468
7469 case DeclarationName::ObjCZeroArgSelector:
7470 case DeclarationName::ObjCOneArgSelector:
7471 case DeclarationName::ObjCMultiArgSelector:
7472 return DeclarationName(ReadSelector(F, Record, Idx));
7473
7474 case DeclarationName::CXXConstructorName:
7475 return Context.DeclarationNames.getCXXConstructorName(
7476 Context.getCanonicalType(readType(F, Record, Idx)));
7477
7478 case DeclarationName::CXXDestructorName:
7479 return Context.DeclarationNames.getCXXDestructorName(
7480 Context.getCanonicalType(readType(F, Record, Idx)));
7481
7482 case DeclarationName::CXXConversionFunctionName:
7483 return Context.DeclarationNames.getCXXConversionFunctionName(
7484 Context.getCanonicalType(readType(F, Record, Idx)));
7485
7486 case DeclarationName::CXXOperatorName:
7487 return Context.DeclarationNames.getCXXOperatorName(
7488 (OverloadedOperatorKind)Record[Idx++]);
7489
7490 case DeclarationName::CXXLiteralOperatorName:
7491 return Context.DeclarationNames.getCXXLiteralOperatorName(
7492 GetIdentifierInfo(F, Record, Idx));
7493
7494 case DeclarationName::CXXUsingDirective:
7495 return DeclarationName::getUsingDirectiveName();
7496 }
7497
7498 llvm_unreachable("Invalid NameKind!");
7499}
7500
7501void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7502 DeclarationNameLoc &DNLoc,
7503 DeclarationName Name,
7504 const RecordData &Record, unsigned &Idx) {
7505 switch (Name.getNameKind()) {
7506 case DeclarationName::CXXConstructorName:
7507 case DeclarationName::CXXDestructorName:
7508 case DeclarationName::CXXConversionFunctionName:
7509 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7510 break;
7511
7512 case DeclarationName::CXXOperatorName:
7513 DNLoc.CXXOperatorName.BeginOpNameLoc
7514 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7515 DNLoc.CXXOperatorName.EndOpNameLoc
7516 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7517 break;
7518
7519 case DeclarationName::CXXLiteralOperatorName:
7520 DNLoc.CXXLiteralOperatorName.OpNameLoc
7521 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7522 break;
7523
7524 case DeclarationName::Identifier:
7525 case DeclarationName::ObjCZeroArgSelector:
7526 case DeclarationName::ObjCOneArgSelector:
7527 case DeclarationName::ObjCMultiArgSelector:
7528 case DeclarationName::CXXUsingDirective:
7529 break;
7530 }
7531}
7532
7533void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7534 DeclarationNameInfo &NameInfo,
7535 const RecordData &Record, unsigned &Idx) {
7536 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7537 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7538 DeclarationNameLoc DNLoc;
7539 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7540 NameInfo.setInfo(DNLoc);
7541}
7542
7543void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7544 const RecordData &Record, unsigned &Idx) {
7545 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7546 unsigned NumTPLists = Record[Idx++];
7547 Info.NumTemplParamLists = NumTPLists;
7548 if (NumTPLists) {
7549 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7550 for (unsigned i=0; i != NumTPLists; ++i)
7551 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7552 }
7553}
7554
7555TemplateName
7556ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7557 unsigned &Idx) {
7558 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7559 switch (Kind) {
7560 case TemplateName::Template:
7561 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7562
7563 case TemplateName::OverloadedTemplate: {
7564 unsigned size = Record[Idx++];
7565 UnresolvedSet<8> Decls;
7566 while (size--)
7567 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7568
7569 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7570 }
7571
7572 case TemplateName::QualifiedTemplate: {
7573 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7574 bool hasTemplKeyword = Record[Idx++];
7575 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7576 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7577 }
7578
7579 case TemplateName::DependentTemplate: {
7580 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7581 if (Record[Idx++]) // isIdentifier
7582 return Context.getDependentTemplateName(NNS,
7583 GetIdentifierInfo(F, Record,
7584 Idx));
7585 return Context.getDependentTemplateName(NNS,
7586 (OverloadedOperatorKind)Record[Idx++]);
7587 }
7588
7589 case TemplateName::SubstTemplateTemplateParm: {
7590 TemplateTemplateParmDecl *param
7591 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7592 if (!param) return TemplateName();
7593 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7594 return Context.getSubstTemplateTemplateParm(param, replacement);
7595 }
7596
7597 case TemplateName::SubstTemplateTemplateParmPack: {
7598 TemplateTemplateParmDecl *Param
7599 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7600 if (!Param)
7601 return TemplateName();
7602
7603 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7604 if (ArgPack.getKind() != TemplateArgument::Pack)
7605 return TemplateName();
7606
7607 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7608 }
7609 }
7610
7611 llvm_unreachable("Unhandled template name kind!");
7612}
7613
7614TemplateArgument
7615ASTReader::ReadTemplateArgument(ModuleFile &F,
7616 const RecordData &Record, unsigned &Idx) {
7617 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7618 switch (Kind) {
7619 case TemplateArgument::Null:
7620 return TemplateArgument();
7621 case TemplateArgument::Type:
7622 return TemplateArgument(readType(F, Record, Idx));
7623 case TemplateArgument::Declaration: {
7624 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007625 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007626 }
7627 case TemplateArgument::NullPtr:
7628 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7629 case TemplateArgument::Integral: {
7630 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7631 QualType T = readType(F, Record, Idx);
7632 return TemplateArgument(Context, Value, T);
7633 }
7634 case TemplateArgument::Template:
7635 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7636 case TemplateArgument::TemplateExpansion: {
7637 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007638 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007639 if (unsigned NumExpansions = Record[Idx++])
7640 NumTemplateExpansions = NumExpansions - 1;
7641 return TemplateArgument(Name, NumTemplateExpansions);
7642 }
7643 case TemplateArgument::Expression:
7644 return TemplateArgument(ReadExpr(F));
7645 case TemplateArgument::Pack: {
7646 unsigned NumArgs = Record[Idx++];
7647 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7648 for (unsigned I = 0; I != NumArgs; ++I)
7649 Args[I] = ReadTemplateArgument(F, Record, Idx);
7650 return TemplateArgument(Args, NumArgs);
7651 }
7652 }
7653
7654 llvm_unreachable("Unhandled template argument kind!");
7655}
7656
7657TemplateParameterList *
7658ASTReader::ReadTemplateParameterList(ModuleFile &F,
7659 const RecordData &Record, unsigned &Idx) {
7660 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7661 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7662 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7663
7664 unsigned NumParams = Record[Idx++];
7665 SmallVector<NamedDecl *, 16> Params;
7666 Params.reserve(NumParams);
7667 while (NumParams--)
7668 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7669
7670 TemplateParameterList* TemplateParams =
7671 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7672 Params.data(), Params.size(), RAngleLoc);
7673 return TemplateParams;
7674}
7675
7676void
7677ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007678ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007679 ModuleFile &F, const RecordData &Record,
7680 unsigned &Idx) {
7681 unsigned NumTemplateArgs = Record[Idx++];
7682 TemplArgs.reserve(NumTemplateArgs);
7683 while (NumTemplateArgs--)
7684 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7685}
7686
7687/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007688void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007689 const RecordData &Record, unsigned &Idx) {
7690 unsigned NumDecls = Record[Idx++];
7691 Set.reserve(Context, NumDecls);
7692 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007693 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007694 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007695 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007696 }
7697}
7698
7699CXXBaseSpecifier
7700ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7701 const RecordData &Record, unsigned &Idx) {
7702 bool isVirtual = static_cast<bool>(Record[Idx++]);
7703 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7704 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7705 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7706 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7707 SourceRange Range = ReadSourceRange(F, Record, Idx);
7708 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7709 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7710 EllipsisLoc);
7711 Result.setInheritConstructors(inheritConstructors);
7712 return Result;
7713}
7714
Richard Smithc2bb8182015-03-24 06:36:48 +00007715CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007716ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7717 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007718 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007719 assert(NumInitializers && "wrote ctor initializers but have no inits");
7720 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7721 for (unsigned i = 0; i != NumInitializers; ++i) {
7722 TypeSourceInfo *TInfo = nullptr;
7723 bool IsBaseVirtual = false;
7724 FieldDecl *Member = nullptr;
7725 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007726
Richard Smithc2bb8182015-03-24 06:36:48 +00007727 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7728 switch (Type) {
7729 case CTOR_INITIALIZER_BASE:
7730 TInfo = GetTypeSourceInfo(F, Record, Idx);
7731 IsBaseVirtual = Record[Idx++];
7732 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007733
Richard Smithc2bb8182015-03-24 06:36:48 +00007734 case CTOR_INITIALIZER_DELEGATING:
7735 TInfo = GetTypeSourceInfo(F, Record, Idx);
7736 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007737
Richard Smithc2bb8182015-03-24 06:36:48 +00007738 case CTOR_INITIALIZER_MEMBER:
7739 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7740 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007741
Richard Smithc2bb8182015-03-24 06:36:48 +00007742 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7743 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7744 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007745 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007746
7747 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7748 Expr *Init = ReadExpr(F);
7749 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7750 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7751 bool IsWritten = Record[Idx++];
7752 unsigned SourceOrderOrNumArrayIndices;
7753 SmallVector<VarDecl *, 8> Indices;
7754 if (IsWritten) {
7755 SourceOrderOrNumArrayIndices = Record[Idx++];
7756 } else {
7757 SourceOrderOrNumArrayIndices = Record[Idx++];
7758 Indices.reserve(SourceOrderOrNumArrayIndices);
7759 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7760 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7761 }
7762
7763 CXXCtorInitializer *BOMInit;
7764 if (Type == CTOR_INITIALIZER_BASE) {
7765 BOMInit = new (Context)
7766 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7767 RParenLoc, MemberOrEllipsisLoc);
7768 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7769 BOMInit = new (Context)
7770 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7771 } else if (IsWritten) {
7772 if (Member)
7773 BOMInit = new (Context) CXXCtorInitializer(
7774 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7775 else
7776 BOMInit = new (Context)
7777 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7778 LParenLoc, Init, RParenLoc);
7779 } else {
7780 if (IndirectMember) {
7781 assert(Indices.empty() && "Indirect field improperly initialized");
7782 BOMInit = new (Context)
7783 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7784 LParenLoc, Init, RParenLoc);
7785 } else {
7786 BOMInit = CXXCtorInitializer::Create(
7787 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7788 Indices.data(), Indices.size());
7789 }
7790 }
7791
7792 if (IsWritten)
7793 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7794 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007795 }
7796
Richard Smithc2bb8182015-03-24 06:36:48 +00007797 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007798}
7799
7800NestedNameSpecifier *
7801ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7802 const RecordData &Record, unsigned &Idx) {
7803 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007804 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007805 for (unsigned I = 0; I != N; ++I) {
7806 NestedNameSpecifier::SpecifierKind Kind
7807 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7808 switch (Kind) {
7809 case NestedNameSpecifier::Identifier: {
7810 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7811 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7812 break;
7813 }
7814
7815 case NestedNameSpecifier::Namespace: {
7816 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7817 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7818 break;
7819 }
7820
7821 case NestedNameSpecifier::NamespaceAlias: {
7822 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7823 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7824 break;
7825 }
7826
7827 case NestedNameSpecifier::TypeSpec:
7828 case NestedNameSpecifier::TypeSpecWithTemplate: {
7829 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7830 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007831 return nullptr;
7832
Guy Benyei11169dd2012-12-18 14:30:41 +00007833 bool Template = Record[Idx++];
7834 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7835 break;
7836 }
7837
7838 case NestedNameSpecifier::Global: {
7839 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7840 // No associated value, and there can't be a prefix.
7841 break;
7842 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007843
7844 case NestedNameSpecifier::Super: {
7845 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7846 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7847 break;
7848 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007849 }
7850 Prev = NNS;
7851 }
7852 return NNS;
7853}
7854
7855NestedNameSpecifierLoc
7856ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7857 unsigned &Idx) {
7858 unsigned N = Record[Idx++];
7859 NestedNameSpecifierLocBuilder Builder;
7860 for (unsigned I = 0; I != N; ++I) {
7861 NestedNameSpecifier::SpecifierKind Kind
7862 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7863 switch (Kind) {
7864 case NestedNameSpecifier::Identifier: {
7865 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7866 SourceRange Range = ReadSourceRange(F, Record, Idx);
7867 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7868 break;
7869 }
7870
7871 case NestedNameSpecifier::Namespace: {
7872 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7873 SourceRange Range = ReadSourceRange(F, Record, Idx);
7874 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7875 break;
7876 }
7877
7878 case NestedNameSpecifier::NamespaceAlias: {
7879 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7880 SourceRange Range = ReadSourceRange(F, Record, Idx);
7881 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7882 break;
7883 }
7884
7885 case NestedNameSpecifier::TypeSpec:
7886 case NestedNameSpecifier::TypeSpecWithTemplate: {
7887 bool Template = Record[Idx++];
7888 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7889 if (!T)
7890 return NestedNameSpecifierLoc();
7891 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7892
7893 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7894 Builder.Extend(Context,
7895 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7896 T->getTypeLoc(), ColonColonLoc);
7897 break;
7898 }
7899
7900 case NestedNameSpecifier::Global: {
7901 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7902 Builder.MakeGlobal(Context, ColonColonLoc);
7903 break;
7904 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007905
7906 case NestedNameSpecifier::Super: {
7907 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7908 SourceRange Range = ReadSourceRange(F, Record, Idx);
7909 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7910 break;
7911 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007912 }
7913 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007914
Guy Benyei11169dd2012-12-18 14:30:41 +00007915 return Builder.getWithLocInContext(Context);
7916}
7917
7918SourceRange
7919ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7920 unsigned &Idx) {
7921 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7922 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7923 return SourceRange(beg, end);
7924}
7925
7926/// \brief Read an integral value
7927llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7928 unsigned BitWidth = Record[Idx++];
7929 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7930 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7931 Idx += NumWords;
7932 return Result;
7933}
7934
7935/// \brief Read a signed integral value
7936llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7937 bool isUnsigned = Record[Idx++];
7938 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7939}
7940
7941/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007942llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7943 const llvm::fltSemantics &Sem,
7944 unsigned &Idx) {
7945 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007946}
7947
7948// \brief Read a string
7949std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7950 unsigned Len = Record[Idx++];
7951 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7952 Idx += Len;
7953 return Result;
7954}
7955
Richard Smith7ed1bc92014-12-05 22:42:13 +00007956std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7957 unsigned &Idx) {
7958 std::string Filename = ReadString(Record, Idx);
7959 ResolveImportedPath(F, Filename);
7960 return Filename;
7961}
7962
Guy Benyei11169dd2012-12-18 14:30:41 +00007963VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7964 unsigned &Idx) {
7965 unsigned Major = Record[Idx++];
7966 unsigned Minor = Record[Idx++];
7967 unsigned Subminor = Record[Idx++];
7968 if (Minor == 0)
7969 return VersionTuple(Major);
7970 if (Subminor == 0)
7971 return VersionTuple(Major, Minor - 1);
7972 return VersionTuple(Major, Minor - 1, Subminor - 1);
7973}
7974
7975CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7976 const RecordData &Record,
7977 unsigned &Idx) {
7978 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7979 return CXXTemporary::Create(Context, Decl);
7980}
7981
7982DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007983 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007984}
7985
7986DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7987 return Diags.Report(Loc, DiagID);
7988}
7989
7990/// \brief Retrieve the identifier table associated with the
7991/// preprocessor.
7992IdentifierTable &ASTReader::getIdentifierTable() {
7993 return PP.getIdentifierTable();
7994}
7995
7996/// \brief Record that the given ID maps to the given switch-case
7997/// statement.
7998void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007999 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008000 "Already have a SwitchCase with this ID");
8001 (*CurrSwitchCaseStmts)[ID] = SC;
8002}
8003
8004/// \brief Retrieve the switch-case statement with the given ID.
8005SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008006 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008007 return (*CurrSwitchCaseStmts)[ID];
8008}
8009
8010void ASTReader::ClearSwitchCaseIDs() {
8011 CurrSwitchCaseStmts->clear();
8012}
8013
8014void ASTReader::ReadComments() {
8015 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008016 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008017 serialization::ModuleFile *> >::iterator
8018 I = CommentsCursors.begin(),
8019 E = CommentsCursors.end();
8020 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008021 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008022 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008023 serialization::ModuleFile &F = *I->second;
8024 SavedStreamPosition SavedPosition(Cursor);
8025
8026 RecordData Record;
8027 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008028 llvm::BitstreamEntry Entry =
8029 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008030
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008031 switch (Entry.Kind) {
8032 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8033 case llvm::BitstreamEntry::Error:
8034 Error("malformed block record in AST file");
8035 return;
8036 case llvm::BitstreamEntry::EndBlock:
8037 goto NextCursor;
8038 case llvm::BitstreamEntry::Record:
8039 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008040 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008041 }
8042
8043 // Read a record.
8044 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008045 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008046 case COMMENTS_RAW_COMMENT: {
8047 unsigned Idx = 0;
8048 SourceRange SR = ReadSourceRange(F, Record, Idx);
8049 RawComment::CommentKind Kind =
8050 (RawComment::CommentKind) Record[Idx++];
8051 bool IsTrailingComment = Record[Idx++];
8052 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008053 Comments.push_back(new (Context) RawComment(
8054 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8055 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008056 break;
8057 }
8058 }
8059 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008060 NextCursor:
8061 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008062 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008063}
8064
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008065void ASTReader::getInputFiles(ModuleFile &F,
8066 SmallVectorImpl<serialization::InputFile> &Files) {
8067 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8068 unsigned ID = I+1;
8069 Files.push_back(getInputFile(F, ID));
8070 }
8071}
8072
Richard Smithcd45dbc2014-04-19 03:48:30 +00008073std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8074 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008075 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008076 return M->getFullModuleName();
8077
8078 // Otherwise, use the name of the top-level module the decl is within.
8079 if (ModuleFile *M = getOwningModuleFile(D))
8080 return M->ModuleName;
8081
8082 // Not from a module.
8083 return "";
8084}
8085
Guy Benyei11169dd2012-12-18 14:30:41 +00008086void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008087 while (!PendingIdentifierInfos.empty() ||
8088 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008089 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008090 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008091 // If any identifiers with corresponding top-level declarations have
8092 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008093 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8094 TopLevelDeclsMap;
8095 TopLevelDeclsMap TopLevelDecls;
8096
Guy Benyei11169dd2012-12-18 14:30:41 +00008097 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008098 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008099 SmallVector<uint32_t, 4> DeclIDs =
8100 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008101 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008102
8103 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008104 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008105
Richard Smith851072e2014-05-19 20:59:20 +00008106 // For each decl chain that we wanted to complete while deserializing, mark
8107 // it as "still needs to be completed".
8108 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8109 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8110 }
8111 PendingIncompleteDeclChains.clear();
8112
Guy Benyei11169dd2012-12-18 14:30:41 +00008113 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008114 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008115 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008116 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008117 }
8118 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008119 PendingDeclChains.clear();
8120
Douglas Gregor6168bd22013-02-18 15:53:43 +00008121 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008122 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8123 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008124 IdentifierInfo *II = TLD->first;
8125 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008126 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008127 }
8128 }
8129
Guy Benyei11169dd2012-12-18 14:30:41 +00008130 // Load any pending macro definitions.
8131 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008132 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8133 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8134 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8135 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008136 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008137 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008138 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008139 if (Info.M->Kind != MK_ImplicitModule &&
8140 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008141 resolvePendingMacro(II, Info);
8142 }
8143 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008144 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008145 ++IDIdx) {
8146 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008147 if (Info.M->Kind == MK_ImplicitModule ||
8148 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008149 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008150 }
8151 }
8152 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008153
8154 // Wire up the DeclContexts for Decls that we delayed setting until
8155 // recursive loading is completed.
8156 while (!PendingDeclContextInfos.empty()) {
8157 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8158 PendingDeclContextInfos.pop_front();
8159 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8160 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8161 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8162 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008163
Richard Smithd1c46742014-04-30 02:24:17 +00008164 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008165 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008166 auto Update = PendingUpdateRecords.pop_back_val();
8167 ReadingKindTracker ReadingKind(Read_Decl, *this);
8168 loadDeclUpdateRecords(Update.first, Update.second);
8169 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008170 }
Richard Smith8a639892015-01-24 01:07:20 +00008171
8172 // At this point, all update records for loaded decls are in place, so any
8173 // fake class definitions should have become real.
8174 assert(PendingFakeDefinitionData.empty() &&
8175 "faked up a class definition but never saw the real one");
8176
Guy Benyei11169dd2012-12-18 14:30:41 +00008177 // If we deserialized any C++ or Objective-C class definitions, any
8178 // Objective-C protocol definitions, or any redeclarable templates, make sure
8179 // that all redeclarations point to the definitions. Note that this can only
8180 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008181 for (Decl *D : PendingDefinitions) {
8182 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008183 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008184 // Make sure that the TagType points at the definition.
8185 const_cast<TagType*>(TagT)->decl = TD;
8186 }
Richard Smith8ce51082015-03-11 01:44:51 +00008187
Craig Topperc6914d02014-08-25 04:15:02 +00008188 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008189 for (auto *R = getMostRecentExistingDecl(RD); R;
8190 R = R->getPreviousDecl()) {
8191 assert((R == D) ==
8192 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008193 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008194 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008195 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008196 }
8197
8198 continue;
8199 }
Richard Smith8ce51082015-03-11 01:44:51 +00008200
Craig Topperc6914d02014-08-25 04:15:02 +00008201 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008202 // Make sure that the ObjCInterfaceType points at the definition.
8203 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8204 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008205
8206 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8207 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8208
Guy Benyei11169dd2012-12-18 14:30:41 +00008209 continue;
8210 }
Richard Smith8ce51082015-03-11 01:44:51 +00008211
Craig Topperc6914d02014-08-25 04:15:02 +00008212 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008213 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8214 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8215
Guy Benyei11169dd2012-12-18 14:30:41 +00008216 continue;
8217 }
Richard Smith8ce51082015-03-11 01:44:51 +00008218
Craig Topperc6914d02014-08-25 04:15:02 +00008219 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008220 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8221 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008222 }
8223 PendingDefinitions.clear();
8224
8225 // Load the bodies of any functions or methods we've encountered. We do
8226 // this now (delayed) so that we can be sure that the declaration chains
8227 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008228 // FIXME: There seems to be no point in delaying this, it does not depend
8229 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008230 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8231 PBEnd = PendingBodies.end();
8232 PB != PBEnd; ++PB) {
8233 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8234 // FIXME: Check for =delete/=default?
8235 // FIXME: Complain about ODR violations here?
8236 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8237 FD->setLazyBody(PB->second);
8238 continue;
8239 }
8240
8241 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8242 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8243 MD->setLazyBody(PB->second);
8244 }
8245 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008246
8247 // Do some cleanup.
8248 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8249 getContext().deduplicateMergedDefinitonsFor(ND);
8250 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008251}
8252
8253void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008254 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8255 return;
8256
Richard Smitha0ce9c42014-07-29 23:23:27 +00008257 // Trigger the import of the full definition of each class that had any
8258 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008259 // These updates may in turn find and diagnose some ODR failures, so take
8260 // ownership of the set first.
8261 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8262 PendingOdrMergeFailures.clear();
8263 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008264 Merge.first->buildLookup();
8265 Merge.first->decls_begin();
8266 Merge.first->bases_begin();
8267 Merge.first->vbases_begin();
8268 for (auto *RD : Merge.second) {
8269 RD->decls_begin();
8270 RD->bases_begin();
8271 RD->vbases_begin();
8272 }
8273 }
8274
8275 // For each declaration from a merged context, check that the canonical
8276 // definition of that context also contains a declaration of the same
8277 // entity.
8278 //
8279 // Caution: this loop does things that might invalidate iterators into
8280 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8281 while (!PendingOdrMergeChecks.empty()) {
8282 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8283
8284 // FIXME: Skip over implicit declarations for now. This matters for things
8285 // like implicitly-declared special member functions. This isn't entirely
8286 // correct; we can end up with multiple unmerged declarations of the same
8287 // implicit entity.
8288 if (D->isImplicit())
8289 continue;
8290
8291 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008292
8293 bool Found = false;
8294 const Decl *DCanon = D->getCanonicalDecl();
8295
Richard Smith01bdb7a2014-08-28 05:44:07 +00008296 for (auto RI : D->redecls()) {
8297 if (RI->getLexicalDeclContext() == CanonDef) {
8298 Found = true;
8299 break;
8300 }
8301 }
8302 if (Found)
8303 continue;
8304
Richard Smitha0ce9c42014-07-29 23:23:27 +00008305 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008306 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008307 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8308 !Found && I != E; ++I) {
8309 for (auto RI : (*I)->redecls()) {
8310 if (RI->getLexicalDeclContext() == CanonDef) {
8311 // This declaration is present in the canonical definition. If it's
8312 // in the same redecl chain, it's the one we're looking for.
8313 if (RI->getCanonicalDecl() == DCanon)
8314 Found = true;
8315 else
8316 Candidates.push_back(cast<NamedDecl>(RI));
8317 break;
8318 }
8319 }
8320 }
8321
8322 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008323 // The AST doesn't like TagDecls becoming invalid after they've been
8324 // completed. We only really need to mark FieldDecls as invalid here.
8325 if (!isa<TagDecl>(D))
8326 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008327
8328 // Ensure we don't accidentally recursively enter deserialization while
8329 // we're producing our diagnostic.
8330 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008331
8332 std::string CanonDefModule =
8333 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8334 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8335 << D << getOwningModuleNameForDiagnostic(D)
8336 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8337
8338 if (Candidates.empty())
8339 Diag(cast<Decl>(CanonDef)->getLocation(),
8340 diag::note_module_odr_violation_no_possible_decls) << D;
8341 else {
8342 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8343 Diag(Candidates[I]->getLocation(),
8344 diag::note_module_odr_violation_possible_decl)
8345 << Candidates[I];
8346 }
8347
8348 DiagnosedOdrMergeFailures.insert(CanonDef);
8349 }
8350 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008351
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008352 if (OdrMergeFailures.empty())
8353 return;
8354
8355 // Ensure we don't accidentally recursively enter deserialization while
8356 // we're producing our diagnostics.
8357 Deserializing RecursionGuard(this);
8358
Richard Smithcd45dbc2014-04-19 03:48:30 +00008359 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008360 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008361 // If we've already pointed out a specific problem with this class, don't
8362 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008363 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008364 continue;
8365
8366 bool Diagnosed = false;
8367 for (auto *RD : Merge.second) {
8368 // Multiple different declarations got merged together; tell the user
8369 // where they came from.
8370 if (Merge.first != RD) {
8371 // FIXME: Walk the definition, figure out what's different,
8372 // and diagnose that.
8373 if (!Diagnosed) {
8374 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8375 Diag(Merge.first->getLocation(),
8376 diag::err_module_odr_violation_different_definitions)
8377 << Merge.first << Module.empty() << Module;
8378 Diagnosed = true;
8379 }
8380
8381 Diag(RD->getLocation(),
8382 diag::note_module_odr_violation_different_definitions)
8383 << getOwningModuleNameForDiagnostic(RD);
8384 }
8385 }
8386
8387 if (!Diagnosed) {
8388 // All definitions are updates to the same declaration. This happens if a
8389 // module instantiates the declaration of a class template specialization
8390 // and two or more other modules instantiate its definition.
8391 //
8392 // FIXME: Indicate which modules had instantiations of this definition.
8393 // FIXME: How can this even happen?
8394 Diag(Merge.first->getLocation(),
8395 diag::err_module_odr_violation_different_instantiations)
8396 << Merge.first;
8397 }
8398 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008399}
8400
8401void ASTReader::FinishedDeserializing() {
8402 assert(NumCurrentElementsDeserializing &&
8403 "FinishedDeserializing not paired with StartedDeserializing");
8404 if (NumCurrentElementsDeserializing == 1) {
8405 // We decrease NumCurrentElementsDeserializing only after pending actions
8406 // are finished, to avoid recursively re-calling finishPendingActions().
8407 finishPendingActions();
8408 }
8409 --NumCurrentElementsDeserializing;
8410
Richard Smitha0ce9c42014-07-29 23:23:27 +00008411 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008412 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008413 while (!PendingExceptionSpecUpdates.empty()) {
8414 auto Updates = std::move(PendingExceptionSpecUpdates);
8415 PendingExceptionSpecUpdates.clear();
8416 for (auto Update : Updates) {
8417 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8418 SemaObj->UpdateExceptionSpec(Update.second,
8419 FPT->getExtProtoInfo().ExceptionSpec);
8420 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008421 }
8422
Richard Smitha0ce9c42014-07-29 23:23:27 +00008423 diagnoseOdrViolations();
8424
Richard Smith04d05b52014-03-23 00:27:18 +00008425 // We are not in recursive loading, so it's safe to pass the "interesting"
8426 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008427 if (Consumer)
8428 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008429 }
8430}
8431
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008432void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008433 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8434 // Remove any fake results before adding any real ones.
8435 auto It = PendingFakeLookupResults.find(II);
8436 if (It != PendingFakeLookupResults.end()) {
8437 for (auto *ND : PendingFakeLookupResults[II])
8438 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008439 // FIXME: this works around module+PCH performance issue.
8440 // Rather than erase the result from the map, which is O(n), just clear
8441 // the vector of NamedDecls.
8442 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008443 }
8444 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008445
8446 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8447 SemaObj->TUScope->AddDecl(D);
8448 } else if (SemaObj->TUScope) {
8449 // Adding the decl to IdResolver may have failed because it was already in
8450 // (even though it was not added in scope). If it is already in, make sure
8451 // it gets in the scope as well.
8452 if (std::find(SemaObj->IdResolver.begin(Name),
8453 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8454 SemaObj->TUScope->AddDecl(D);
8455 }
8456}
8457
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008458ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
8459 const PCHContainerOperations &PCHContainerOps,
8460 StringRef isysroot, bool DisableValidation,
8461 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008462 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008463 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008464 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008465 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008466 FileMgr(PP.getFileManager()), PCHContainerOps(PCHContainerOps),
8467 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
8468 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerOps),
8469 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008470 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8471 AllowConfigurationMismatch(AllowConfigurationMismatch),
8472 ValidateSystemInputs(ValidateSystemInputs),
8473 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008474 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8475 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8476 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8477 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008478 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8479 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8480 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8481 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8482 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8483 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008484 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008485 SourceMgr.setExternalSLocEntrySource(this);
8486}
8487
8488ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008489 if (OwnsDeserializationListener)
8490 delete DeserializationListener;
8491
Guy Benyei11169dd2012-12-18 14:30:41 +00008492 for (DeclContextVisibleUpdatesPending::iterator
8493 I = PendingVisibleUpdates.begin(),
8494 E = PendingVisibleUpdates.end();
8495 I != E; ++I) {
8496 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8497 F = I->second.end();
8498 J != F; ++J)
8499 delete J->first;
8500 }
8501}