blob: ad528b0213ab93416e740f2204eb7739bbd5b96e [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".
Richard Smitha534a312015-07-21 23:54:07 +0000738static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
739 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000740 return II.hadMacroDefinition() ||
741 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000742 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000743 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000744 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
745 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000746}
747
Richard Smith76c2f2c2015-07-17 20:09:43 +0000748static bool readBit(unsigned &Bits) {
749 bool Value = Bits & 0x1;
750 Bits >>= 1;
751 return Value;
752}
753
Guy Benyei11169dd2012-12-18 14:30:41 +0000754IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
755 const unsigned char* d,
756 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000757 using namespace llvm::support;
758 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000759 bool IsInteresting = RawID & 0x01;
760
761 // Wipe out the "is interesting" bit.
762 RawID = RawID >> 1;
763
Richard Smith76c2f2c2015-07-17 20:09:43 +0000764 // Build the IdentifierInfo and link the identifier ID with it.
765 IdentifierInfo *II = KnownII;
766 if (!II) {
767 II = &Reader.getIdentifierTable().getOwn(k);
768 KnownII = II;
769 }
770 if (!II->isFromAST()) {
771 II->setIsFromAST();
Richard Smitha534a312015-07-21 23:54:07 +0000772 if (isInterestingIdentifier(Reader, *II, F.isModule()))
Richard Smith76c2f2c2015-07-17 20:09:43 +0000773 II->setChangedSinceDeserialization();
774 }
775 Reader.markIdentifierUpToDate(II);
776
Guy Benyei11169dd2012-12-18 14:30:41 +0000777 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
778 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000779 // For uninteresting identifiers, there's nothing else to do. Just notify
780 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000781 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000782 return II;
783 }
784
Justin Bogner57ba0b22014-03-28 22:03:24 +0000785 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
786 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000787 bool CPlusPlusOperatorKeyword = readBit(Bits);
788 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000789 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000790 bool Poisoned = readBit(Bits);
791 bool ExtensionToken = readBit(Bits);
792 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000793
794 assert(Bits == 0 && "Extra bits in the identifier?");
795 DataLen -= 8;
796
Guy Benyei11169dd2012-12-18 14:30:41 +0000797 // Set or check the various bits in the IdentifierInfo structure.
798 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000799 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000800 II->revertTokenIDToIdentifier();
801 if (!F.isModule())
802 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
803 else if (HasRevertedBuiltin && II->getBuiltinID()) {
804 II->revertBuiltin();
805 assert((II->hasRevertedBuiltin() ||
806 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
807 "Incorrect ObjC keyword or builtin ID");
808 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000809 assert(II->isExtensionToken() == ExtensionToken &&
810 "Incorrect extension token flag");
811 (void)ExtensionToken;
812 if (Poisoned)
813 II->setIsPoisoned(true);
814 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
815 "Incorrect C++ operator keyword flag");
816 (void)CPlusPlusOperatorKeyword;
817
818 // If this identifier is a macro, deserialize the macro
819 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000820 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000821 uint32_t MacroDirectivesOffset =
822 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000823 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000824
Richard Smithd7329392015-04-21 21:46:32 +0000825 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000826 }
827
828 Reader.SetIdentifierInfo(ID, II);
829
830 // Read all of the declarations visible at global scope with this
831 // name.
832 if (DataLen > 0) {
833 SmallVector<uint32_t, 4> DeclIDs;
834 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000835 DeclIDs.push_back(Reader.getGlobalDeclID(
836 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000837 Reader.SetGloballyVisibleDecls(II, DeclIDs);
838 }
839
840 return II;
841}
842
843unsigned
Richard Smith3b637412015-07-14 18:42:41 +0000844ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000845 llvm::FoldingSetNodeID ID;
846 ID.AddInteger(Key.Kind);
847
848 switch (Key.Kind) {
849 case DeclarationName::Identifier:
850 case DeclarationName::CXXLiteralOperatorName:
851 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
852 break;
853 case DeclarationName::ObjCZeroArgSelector:
854 case DeclarationName::ObjCOneArgSelector:
855 case DeclarationName::ObjCMultiArgSelector:
856 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
857 break;
858 case DeclarationName::CXXOperatorName:
859 ID.AddInteger((OverloadedOperatorKind)Key.Data);
860 break;
861 case DeclarationName::CXXConstructorName:
862 case DeclarationName::CXXDestructorName:
863 case DeclarationName::CXXConversionFunctionName:
864 case DeclarationName::CXXUsingDirective:
865 break;
866 }
867
868 return ID.ComputeHash();
869}
870
871ASTDeclContextNameLookupTrait::internal_key_type
872ASTDeclContextNameLookupTrait::GetInternalKey(
Richard Smith3b637412015-07-14 18:42:41 +0000873 const external_key_type& Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000874 DeclNameKey Key;
875 Key.Kind = Name.getNameKind();
876 switch (Name.getNameKind()) {
877 case DeclarationName::Identifier:
878 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
879 break;
880 case DeclarationName::ObjCZeroArgSelector:
881 case DeclarationName::ObjCOneArgSelector:
882 case DeclarationName::ObjCMultiArgSelector:
883 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
884 break;
885 case DeclarationName::CXXOperatorName:
886 Key.Data = Name.getCXXOverloadedOperator();
887 break;
888 case DeclarationName::CXXLiteralOperatorName:
889 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
890 break;
891 case DeclarationName::CXXConstructorName:
892 case DeclarationName::CXXDestructorName:
893 case DeclarationName::CXXConversionFunctionName:
894 case DeclarationName::CXXUsingDirective:
895 Key.Data = 0;
896 break;
897 }
898
899 return Key;
900}
901
902std::pair<unsigned, unsigned>
903ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000904 using namespace llvm::support;
905 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
906 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000907 return std::make_pair(KeyLen, DataLen);
908}
909
910ASTDeclContextNameLookupTrait::internal_key_type
911ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000912 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000913
914 DeclNameKey Key;
915 Key.Kind = (DeclarationName::NameKind)*d++;
916 switch (Key.Kind) {
917 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000918 Key.Data = (uint64_t)Reader.getLocalIdentifier(
919 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000920 break;
921 case DeclarationName::ObjCZeroArgSelector:
922 case DeclarationName::ObjCOneArgSelector:
923 case DeclarationName::ObjCMultiArgSelector:
924 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000925 (uint64_t)Reader.getLocalSelector(
926 F, endian::readNext<uint32_t, little, unaligned>(
927 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000928 break;
929 case DeclarationName::CXXOperatorName:
930 Key.Data = *d++; // OverloadedOperatorKind
931 break;
932 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000933 Key.Data = (uint64_t)Reader.getLocalIdentifier(
934 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000935 break;
936 case DeclarationName::CXXConstructorName:
937 case DeclarationName::CXXDestructorName:
938 case DeclarationName::CXXConversionFunctionName:
939 case DeclarationName::CXXUsingDirective:
940 Key.Data = 0;
941 break;
942 }
943
944 return Key;
945}
946
Richard Smithf02662d2015-07-30 03:17:16 +0000947ASTDeclContextNameLookupTrait::data_type
948ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
949 const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000950 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000951 using namespace llvm::support;
Richard Smithf02662d2015-07-30 03:17:16 +0000952 unsigned NumDecls = DataLen / 4;
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000953 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
954 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000955 return std::make_pair(Start, Start + NumDecls);
956}
957
Richard Smith0f4e2c42015-08-06 04:23:48 +0000958bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
959 BitstreamCursor &Cursor,
960 uint64_t Offset,
961 DeclContext *DC) {
962 assert(Offset != 0);
963
Guy Benyei11169dd2012-12-18 14:30:41 +0000964 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +0000965 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000966
Richard Smith0f4e2c42015-08-06 04:23:48 +0000967 RecordData Record;
968 StringRef Blob;
969 unsigned Code = Cursor.ReadCode();
970 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
971 if (RecCode != DECL_CONTEXT_LEXICAL) {
972 Error("Expected lexical block");
973 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000974 }
975
Richard Smith82f8fcd2015-08-06 22:07:25 +0000976 assert(!isa<TranslationUnitDecl>(DC) &&
977 "expected a TU_UPDATE_LEXICAL record for TU");
978 // FIXME: Once we remove RewriteDecl, assert that we didn't already have
979 // lexical decls for this context.
980 LexicalDecls[DC] = llvm::makeArrayRef(
981 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(Blob.data()),
982 Blob.size() / 4);
Richard Smith0f4e2c42015-08-06 04:23:48 +0000983 DC->setHasExternalLexicalStorage(true);
984 return false;
985}
Guy Benyei11169dd2012-12-18 14:30:41 +0000986
Richard Smith0f4e2c42015-08-06 04:23:48 +0000987bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
988 BitstreamCursor &Cursor,
989 uint64_t Offset,
990 DeclID ID) {
991 assert(Offset != 0);
992
993 SavedStreamPosition SavedPosition(Cursor);
994 Cursor.JumpToBit(Offset);
995
996 RecordData Record;
997 StringRef Blob;
998 unsigned Code = Cursor.ReadCode();
999 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1000 if (RecCode != DECL_CONTEXT_VISIBLE) {
1001 Error("Expected visible lookup table block");
1002 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001003 }
1004
Richard Smith0f4e2c42015-08-06 04:23:48 +00001005 // We can't safely determine the primary context yet, so delay attaching the
1006 // lookup table until we're done with recursive deserialization.
1007 unsigned BucketOffset = Record[0];
1008 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{
1009 &M, (const unsigned char *)Blob.data(), BucketOffset});
Guy Benyei11169dd2012-12-18 14:30:41 +00001010 return false;
1011}
1012
1013void ASTReader::Error(StringRef Msg) {
1014 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001015 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1016 Diag(diag::note_module_cache_path)
1017 << PP.getHeaderSearchInfo().getModuleCachePath();
1018 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001019}
1020
1021void ASTReader::Error(unsigned DiagID,
1022 StringRef Arg1, StringRef Arg2) {
1023 if (Diags.isDiagnosticInFlight())
1024 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1025 else
1026 Diag(DiagID) << Arg1 << Arg2;
1027}
1028
1029//===----------------------------------------------------------------------===//
1030// Source Manager Deserialization
1031//===----------------------------------------------------------------------===//
1032
1033/// \brief Read the line table in the source manager block.
1034/// \returns true if there was an error.
1035bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001036 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001037 unsigned Idx = 0;
1038 LineTableInfo &LineTable = SourceMgr.getLineTable();
1039
1040 // Parse the file names
1041 std::map<int, int> FileIDs;
1042 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1043 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001044 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001045 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1046 }
1047
1048 // Parse the line entries
1049 std::vector<LineEntry> Entries;
1050 while (Idx < Record.size()) {
1051 int FID = Record[Idx++];
1052 assert(FID >= 0 && "Serialized line entries for non-local file.");
1053 // Remap FileID from 1-based old view.
1054 FID += F.SLocEntryBaseID - 1;
1055
1056 // Extract the line entries
1057 unsigned NumEntries = Record[Idx++];
1058 assert(NumEntries && "Numentries is 00000");
1059 Entries.clear();
1060 Entries.reserve(NumEntries);
1061 for (unsigned I = 0; I != NumEntries; ++I) {
1062 unsigned FileOffset = Record[Idx++];
1063 unsigned LineNo = Record[Idx++];
1064 int FilenameID = FileIDs[Record[Idx++]];
1065 SrcMgr::CharacteristicKind FileKind
1066 = (SrcMgr::CharacteristicKind)Record[Idx++];
1067 unsigned IncludeOffset = Record[Idx++];
1068 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1069 FileKind, IncludeOffset));
1070 }
1071 LineTable.AddEntry(FileID::get(FID), Entries);
1072 }
1073
1074 return false;
1075}
1076
1077/// \brief Read a source manager block
1078bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1079 using namespace SrcMgr;
1080
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001081 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001082
1083 // Set the source-location entry cursor to the current position in
1084 // the stream. This cursor will be used to read the contents of the
1085 // source manager block initially, and then lazily read
1086 // source-location entries as needed.
1087 SLocEntryCursor = F.Stream;
1088
1089 // The stream itself is going to skip over the source manager block.
1090 if (F.Stream.SkipBlock()) {
1091 Error("malformed block record in AST file");
1092 return true;
1093 }
1094
1095 // Enter the source manager block.
1096 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1097 Error("malformed source manager block record in AST file");
1098 return true;
1099 }
1100
1101 RecordData Record;
1102 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001103 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1104
1105 switch (E.Kind) {
1106 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1107 case llvm::BitstreamEntry::Error:
1108 Error("malformed block record in AST file");
1109 return true;
1110 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001111 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001112 case llvm::BitstreamEntry::Record:
1113 // The interesting case.
1114 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001115 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001116
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001118 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001119 StringRef Blob;
1120 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001121 default: // Default behavior: ignore.
1122 break;
1123
1124 case SM_SLOC_FILE_ENTRY:
1125 case SM_SLOC_BUFFER_ENTRY:
1126 case SM_SLOC_EXPANSION_ENTRY:
1127 // Once we hit one of the source location entries, we're done.
1128 return false;
1129 }
1130 }
1131}
1132
1133/// \brief If a header file is not found at the path that we expect it to be
1134/// and the PCH file was moved from its original location, try to resolve the
1135/// file by assuming that header+PCH were moved together and the header is in
1136/// the same place relative to the PCH.
1137static std::string
1138resolveFileRelativeToOriginalDir(const std::string &Filename,
1139 const std::string &OriginalDir,
1140 const std::string &CurrDir) {
1141 assert(OriginalDir != CurrDir &&
1142 "No point trying to resolve the file if the PCH dir didn't change");
1143 using namespace llvm::sys;
1144 SmallString<128> filePath(Filename);
1145 fs::make_absolute(filePath);
1146 assert(path::is_absolute(OriginalDir));
1147 SmallString<128> currPCHPath(CurrDir);
1148
1149 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1150 fileDirE = path::end(path::parent_path(filePath));
1151 path::const_iterator origDirI = path::begin(OriginalDir),
1152 origDirE = path::end(OriginalDir);
1153 // Skip the common path components from filePath and OriginalDir.
1154 while (fileDirI != fileDirE && origDirI != origDirE &&
1155 *fileDirI == *origDirI) {
1156 ++fileDirI;
1157 ++origDirI;
1158 }
1159 for (; origDirI != origDirE; ++origDirI)
1160 path::append(currPCHPath, "..");
1161 path::append(currPCHPath, fileDirI, fileDirE);
1162 path::append(currPCHPath, path::filename(Filename));
1163 return currPCHPath.str();
1164}
1165
1166bool ASTReader::ReadSLocEntry(int ID) {
1167 if (ID == 0)
1168 return false;
1169
1170 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1171 Error("source location entry ID out-of-range for AST file");
1172 return true;
1173 }
1174
1175 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1176 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001177 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001178 unsigned BaseOffset = F->SLocEntryBaseOffset;
1179
1180 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001181 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1182 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001183 Error("incorrectly-formatted source location entry in AST file");
1184 return true;
1185 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001186
Guy Benyei11169dd2012-12-18 14:30:41 +00001187 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001188 StringRef Blob;
1189 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001190 default:
1191 Error("incorrectly-formatted source location entry in AST file");
1192 return true;
1193
1194 case SM_SLOC_FILE_ENTRY: {
1195 // We will detect whether a file changed and return 'Failure' for it, but
1196 // we will also try to fail gracefully by setting up the SLocEntry.
1197 unsigned InputID = Record[4];
1198 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001199 const FileEntry *File = IF.getFile();
1200 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001201
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001202 // Note that we only check if a File was returned. If it was out-of-date
1203 // we have complained but we will continue creating a FileID to recover
1204 // gracefully.
1205 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001206 return true;
1207
1208 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1209 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1210 // This is the module's main file.
1211 IncludeLoc = getImportLocation(F);
1212 }
1213 SrcMgr::CharacteristicKind
1214 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1215 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1216 ID, BaseOffset + Record[0]);
1217 SrcMgr::FileInfo &FileInfo =
1218 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1219 FileInfo.NumCreatedFIDs = Record[5];
1220 if (Record[3])
1221 FileInfo.setHasLineDirectives();
1222
1223 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1224 unsigned NumFileDecls = Record[7];
1225 if (NumFileDecls) {
1226 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1227 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1228 NumFileDecls));
1229 }
1230
1231 const SrcMgr::ContentCache *ContentCache
1232 = SourceMgr.getOrCreateContentCache(File,
1233 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1234 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1235 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1236 unsigned Code = SLocEntryCursor.ReadCode();
1237 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001238 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001239
1240 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1241 Error("AST record has invalid code");
1242 return true;
1243 }
1244
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001245 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001246 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001247 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001248 }
1249
1250 break;
1251 }
1252
1253 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001254 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001255 unsigned Offset = Record[0];
1256 SrcMgr::CharacteristicKind
1257 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1258 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001259 if (IncludeLoc.isInvalid() &&
1260 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001261 IncludeLoc = getImportLocation(F);
1262 }
1263 unsigned Code = SLocEntryCursor.ReadCode();
1264 Record.clear();
1265 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001266 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001267
1268 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1269 Error("AST record has invalid code");
1270 return true;
1271 }
1272
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001273 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1274 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001275 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001276 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001277 break;
1278 }
1279
1280 case SM_SLOC_EXPANSION_ENTRY: {
1281 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1282 SourceMgr.createExpansionLoc(SpellingLoc,
1283 ReadSourceLocation(*F, Record[2]),
1284 ReadSourceLocation(*F, Record[3]),
1285 Record[4],
1286 ID,
1287 BaseOffset + Record[0]);
1288 break;
1289 }
1290 }
1291
1292 return false;
1293}
1294
1295std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1296 if (ID == 0)
1297 return std::make_pair(SourceLocation(), "");
1298
1299 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1300 Error("source location entry ID out-of-range for AST file");
1301 return std::make_pair(SourceLocation(), "");
1302 }
1303
1304 // Find which module file this entry lands in.
1305 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001306 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001307 return std::make_pair(SourceLocation(), "");
1308
1309 // FIXME: Can we map this down to a particular submodule? That would be
1310 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001311 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001312}
1313
1314/// \brief Find the location where the module F is imported.
1315SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1316 if (F->ImportLoc.isValid())
1317 return F->ImportLoc;
1318
1319 // Otherwise we have a PCH. It's considered to be "imported" at the first
1320 // location of its includer.
1321 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001322 // Main file is the importer.
1323 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1324 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001325 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001326 return F->ImportedBy[0]->FirstLoc;
1327}
1328
1329/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1330/// specified cursor. Read the abbreviations that are at the top of the block
1331/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001332bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001333 if (Cursor.EnterSubBlock(BlockID)) {
1334 Error("malformed block record in AST file");
1335 return Failure;
1336 }
1337
1338 while (true) {
1339 uint64_t Offset = Cursor.GetCurrentBitNo();
1340 unsigned Code = Cursor.ReadCode();
1341
1342 // We expect all abbrevs to be at the start of the block.
1343 if (Code != llvm::bitc::DEFINE_ABBREV) {
1344 Cursor.JumpToBit(Offset);
1345 return false;
1346 }
1347 Cursor.ReadAbbrevRecord();
1348 }
1349}
1350
Richard Smithe40f2ba2013-08-07 21:41:30 +00001351Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001352 unsigned &Idx) {
1353 Token Tok;
1354 Tok.startToken();
1355 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1356 Tok.setLength(Record[Idx++]);
1357 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1358 Tok.setIdentifierInfo(II);
1359 Tok.setKind((tok::TokenKind)Record[Idx++]);
1360 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1361 return Tok;
1362}
1363
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001364MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001365 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001366
1367 // Keep track of where we are in the stream, then jump back there
1368 // after reading this macro.
1369 SavedStreamPosition SavedPosition(Stream);
1370
1371 Stream.JumpToBit(Offset);
1372 RecordData Record;
1373 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001374 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001375
Guy Benyei11169dd2012-12-18 14:30:41 +00001376 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001377 // Advance to the next record, but if we get to the end of the block, don't
1378 // pop it (removing all the abbreviations from the cursor) since we want to
1379 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001380 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001381 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1382
1383 switch (Entry.Kind) {
1384 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1385 case llvm::BitstreamEntry::Error:
1386 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001387 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001388 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001389 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001390 case llvm::BitstreamEntry::Record:
1391 // The interesting case.
1392 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001393 }
1394
1395 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001396 Record.clear();
1397 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001398 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001399 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001400 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001401 case PP_MACRO_DIRECTIVE_HISTORY:
1402 return Macro;
1403
Guy Benyei11169dd2012-12-18 14:30:41 +00001404 case PP_MACRO_OBJECT_LIKE:
1405 case PP_MACRO_FUNCTION_LIKE: {
1406 // If we already have a macro, that means that we've hit the end
1407 // of the definition of the macro we were looking for. We're
1408 // done.
1409 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001410 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001411
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001412 unsigned NextIndex = 1; // Skip identifier ID.
1413 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001414 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001415 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001416 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001418 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001419
Guy Benyei11169dd2012-12-18 14:30:41 +00001420 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1421 // Decode function-like macro info.
1422 bool isC99VarArgs = Record[NextIndex++];
1423 bool isGNUVarArgs = Record[NextIndex++];
1424 bool hasCommaPasting = Record[NextIndex++];
1425 MacroArgs.clear();
1426 unsigned NumArgs = Record[NextIndex++];
1427 for (unsigned i = 0; i != NumArgs; ++i)
1428 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1429
1430 // Install function-like macro info.
1431 MI->setIsFunctionLike();
1432 if (isC99VarArgs) MI->setIsC99Varargs();
1433 if (isGNUVarArgs) MI->setIsGNUVarargs();
1434 if (hasCommaPasting) MI->setHasCommaPasting();
1435 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1436 PP.getPreprocessorAllocator());
1437 }
1438
Guy Benyei11169dd2012-12-18 14:30:41 +00001439 // Remember that we saw this macro last so that we add the tokens that
1440 // form its body to it.
1441 Macro = MI;
1442
1443 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1444 Record[NextIndex]) {
1445 // We have a macro definition. Register the association
1446 PreprocessedEntityID
1447 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1448 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001449 PreprocessingRecord::PPEntityID PPID =
1450 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1451 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1452 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001453 if (PPDef)
1454 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001455 }
1456
1457 ++NumMacrosRead;
1458 break;
1459 }
1460
1461 case PP_TOKEN: {
1462 // If we see a TOKEN before a PP_MACRO_*, then the file is
1463 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001464 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001465
John McCallf413f5e2013-05-03 00:10:13 +00001466 unsigned Idx = 0;
1467 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001468 Macro->AddTokenToBody(Tok);
1469 break;
1470 }
1471 }
1472 }
1473}
1474
1475PreprocessedEntityID
1476ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1477 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1478 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1479 assert(I != M.PreprocessedEntityRemap.end()
1480 && "Invalid index into preprocessed entity index remap");
1481
1482 return LocalID + I->second;
1483}
1484
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001485unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1486 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001487}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001488
Guy Benyei11169dd2012-12-18 14:30:41 +00001489HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001490HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1491 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001492 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001493 return ikey;
1494}
Guy Benyei11169dd2012-12-18 14:30:41 +00001495
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001496bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1497 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001498 return false;
1499
Richard Smith7ed1bc92014-12-05 22:42:13 +00001500 if (llvm::sys::path::is_absolute(a.Filename) &&
1501 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001502 return true;
1503
Guy Benyei11169dd2012-12-18 14:30:41 +00001504 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001505 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001506 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1507 if (!Key.Imported)
1508 return FileMgr.getFile(Key.Filename);
1509
1510 std::string Resolved = Key.Filename;
1511 Reader.ResolveImportedPath(M, Resolved);
1512 return FileMgr.getFile(Resolved);
1513 };
1514
1515 const FileEntry *FEA = GetFile(a);
1516 const FileEntry *FEB = GetFile(b);
1517 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001518}
1519
1520std::pair<unsigned, unsigned>
1521HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001522 using namespace llvm::support;
1523 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001524 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001525 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001526}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001527
1528HeaderFileInfoTrait::internal_key_type
1529HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001530 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001531 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001532 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1533 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001534 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001535 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001536 return ikey;
1537}
1538
Guy Benyei11169dd2012-12-18 14:30:41 +00001539HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001540HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001541 unsigned DataLen) {
1542 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001543 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001544 HeaderFileInfo HFI;
1545 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001546 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1547 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001548 HFI.isImport = (Flags >> 5) & 0x01;
1549 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1550 HFI.DirInfo = (Flags >> 2) & 0x03;
1551 HFI.Resolved = (Flags >> 1) & 0x01;
1552 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001553 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1554 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1555 M, endian::readNext<uint32_t, little, unaligned>(d));
1556 if (unsigned FrameworkOffset =
1557 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001558 // The framework offset is 1 greater than the actual offset,
1559 // since 0 is used as an indicator for "no framework name".
1560 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1561 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1562 }
1563
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001564 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001565 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001566 if (LocalSMID) {
1567 // This header is part of a module. Associate it with the module to enable
1568 // implicit module import.
1569 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1570 Module *Mod = Reader.getSubmodule(GlobalSMID);
1571 HFI.isModuleHeader = true;
1572 FileManager &FileMgr = Reader.getFileManager();
1573 ModuleMap &ModMap =
1574 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001575 // FIXME: This information should be propagated through the
1576 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001577 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001578 std::string Filename = key.Filename;
1579 if (key.Imported)
1580 Reader.ResolveImportedPath(M, Filename);
1581 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001582 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001583 }
1584 }
1585
Guy Benyei11169dd2012-12-18 14:30:41 +00001586 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1587 (void)End;
1588
1589 // This HeaderFileInfo was externally loaded.
1590 HFI.External = true;
1591 return HFI;
1592}
1593
Richard Smithd7329392015-04-21 21:46:32 +00001594void ASTReader::addPendingMacro(IdentifierInfo *II,
1595 ModuleFile *M,
1596 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001597 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1598 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001599}
1600
1601void ASTReader::ReadDefinedMacros() {
1602 // Note that we are loading defined macros.
1603 Deserializing Macros(this);
1604
Pete Cooper57d3f142015-07-30 17:22:52 +00001605 for (auto &I : llvm::reverse(ModuleMgr)) {
1606 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001607
1608 // If there was no preprocessor block, skip this file.
1609 if (!MacroCursor.getBitStreamReader())
1610 continue;
1611
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001612 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001613 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001614
1615 RecordData Record;
1616 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001617 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1618
1619 switch (E.Kind) {
1620 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1621 case llvm::BitstreamEntry::Error:
1622 Error("malformed block record in AST file");
1623 return;
1624 case llvm::BitstreamEntry::EndBlock:
1625 goto NextCursor;
1626
1627 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001628 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001629 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001630 default: // Default behavior: ignore.
1631 break;
1632
1633 case PP_MACRO_OBJECT_LIKE:
1634 case PP_MACRO_FUNCTION_LIKE:
Pete Cooper57d3f142015-07-30 17:22:52 +00001635 getLocalIdentifier(*I, Record[0]);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001636 break;
1637
1638 case PP_TOKEN:
1639 // Ignore tokens.
1640 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001641 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001642 break;
1643 }
1644 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001645 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001646 }
1647}
1648
1649namespace {
1650 /// \brief Visitor class used to look up identifirs in an AST file.
1651 class IdentifierLookupVisitor {
1652 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001653 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001654 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001655 unsigned &NumIdentifierLookups;
1656 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001657 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001658
Guy Benyei11169dd2012-12-18 14:30:41 +00001659 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001660 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1661 unsigned &NumIdentifierLookups,
1662 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001663 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1664 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001665 NumIdentifierLookups(NumIdentifierLookups),
1666 NumIdentifierLookupHits(NumIdentifierLookupHits),
1667 Found()
1668 {
1669 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001670
1671 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001672 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001673 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001674 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001675
Guy Benyei11169dd2012-12-18 14:30:41 +00001676 ASTIdentifierLookupTable *IdTable
1677 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1678 if (!IdTable)
1679 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001680
1681 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001682 Found);
1683 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001684 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001685 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001686 if (Pos == IdTable->end())
1687 return false;
1688
1689 // Dereferencing the iterator has the effect of building the
1690 // IdentifierInfo node and populating it with the various
1691 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001692 ++NumIdentifierLookupHits;
1693 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001694 return true;
1695 }
1696
1697 // \brief Retrieve the identifier info found within the module
1698 // files.
1699 IdentifierInfo *getIdentifierInfo() const { return Found; }
1700 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001701}
Guy Benyei11169dd2012-12-18 14:30:41 +00001702
1703void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1704 // Note that we are loading an identifier.
1705 Deserializing AnIdentifier(this);
1706
1707 unsigned PriorGeneration = 0;
1708 if (getContext().getLangOpts().Modules)
1709 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001710
1711 // If there is a global index, look there first to determine which modules
1712 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001713 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001714 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001715 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001716 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1717 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001718 }
1719 }
1720
Douglas Gregor7211ac12013-01-25 23:32:03 +00001721 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001722 NumIdentifierLookups,
1723 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001724 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001725 markIdentifierUpToDate(&II);
1726}
1727
1728void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1729 if (!II)
1730 return;
1731
1732 II->setOutOfDate(false);
1733
1734 // Update the generation for this identifier.
1735 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001736 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001737}
1738
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001739void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1740 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001741 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001742
1743 BitstreamCursor &Cursor = M.MacroCursor;
1744 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001745 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001746
Richard Smith713369b2015-04-23 20:40:50 +00001747 struct ModuleMacroRecord {
1748 SubmoduleID SubModID;
1749 MacroInfo *MI;
1750 SmallVector<SubmoduleID, 8> Overrides;
1751 };
1752 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001753
Richard Smithd7329392015-04-21 21:46:32 +00001754 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1755 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1756 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001757 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001758 while (true) {
1759 llvm::BitstreamEntry Entry =
1760 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1761 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1762 Error("malformed block record in AST file");
1763 return;
1764 }
1765
1766 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001767 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001768 case PP_MACRO_DIRECTIVE_HISTORY:
1769 break;
1770
1771 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001772 ModuleMacros.push_back(ModuleMacroRecord());
1773 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001774 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1775 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001776 for (int I = 2, N = Record.size(); I != N; ++I)
1777 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001778 continue;
1779 }
1780
1781 default:
1782 Error("malformed block record in AST file");
1783 return;
1784 }
1785
1786 // We found the macro directive history; that's the last record
1787 // for this macro.
1788 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001789 }
1790
Richard Smithd7329392015-04-21 21:46:32 +00001791 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001792 {
1793 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001794 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001795 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001796 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001797 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001798 Module *Mod = getSubmodule(ModID);
1799 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001800 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001801 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001802 }
1803
1804 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001805 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001806 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001807 }
1808 }
1809
1810 // Don't read the directive history for a module; we don't have anywhere
1811 // to put it.
1812 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1813 return;
1814
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001815 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001816 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001817 unsigned Idx = 0, N = Record.size();
1818 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001819 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001820 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001821 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1822 switch (K) {
1823 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001824 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001825 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001826 break;
1827 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001828 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001829 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001830 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001831 }
1832 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001833 bool isPublic = Record[Idx++];
1834 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1835 break;
1836 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001837
1838 if (!Latest)
1839 Latest = MD;
1840 if (Earliest)
1841 Earliest->setPrevious(MD);
1842 Earliest = MD;
1843 }
1844
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001845 if (Latest)
1846 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001847}
1848
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001849ASTReader::InputFileInfo
1850ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001851 // Go find this input file.
1852 BitstreamCursor &Cursor = F.InputFilesCursor;
1853 SavedStreamPosition SavedPosition(Cursor);
1854 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1855
1856 unsigned Code = Cursor.ReadCode();
1857 RecordData Record;
1858 StringRef Blob;
1859
1860 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1861 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1862 "invalid record type for input file");
1863 (void)Result;
1864
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001865 std::string Filename;
1866 off_t StoredSize;
1867 time_t StoredTime;
1868 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001869
Ben Langmuir198c1682014-03-07 07:27:49 +00001870 assert(Record[0] == ID && "Bogus stored ID or offset");
1871 StoredSize = static_cast<off_t>(Record[1]);
1872 StoredTime = static_cast<time_t>(Record[2]);
1873 Overridden = static_cast<bool>(Record[3]);
1874 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001875 ResolveImportedPath(F, Filename);
1876
Hans Wennborg73945142014-03-14 17:45:06 +00001877 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1878 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001879}
1880
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001881InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001882 // If this ID is bogus, just return an empty input file.
1883 if (ID == 0 || ID > F.InputFilesLoaded.size())
1884 return InputFile();
1885
1886 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001887 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001888 return F.InputFilesLoaded[ID-1];
1889
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001890 if (F.InputFilesLoaded[ID-1].isNotFound())
1891 return InputFile();
1892
Guy Benyei11169dd2012-12-18 14:30:41 +00001893 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001894 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001895 SavedStreamPosition SavedPosition(Cursor);
1896 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1897
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001898 InputFileInfo FI = readInputFileInfo(F, ID);
1899 off_t StoredSize = FI.StoredSize;
1900 time_t StoredTime = FI.StoredTime;
1901 bool Overridden = FI.Overridden;
1902 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001903
Ben Langmuir198c1682014-03-07 07:27:49 +00001904 const FileEntry *File
1905 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1906 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1907
1908 // If we didn't find the file, resolve it relative to the
1909 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001910 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001911 F.OriginalDir != CurrentDir) {
1912 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1913 F.OriginalDir,
1914 CurrentDir);
1915 if (!Resolved.empty())
1916 File = FileMgr.getFile(Resolved);
1917 }
1918
1919 // For an overridden file, create a virtual file with the stored
1920 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001921 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001922 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1923 }
1924
Craig Toppera13603a2014-05-22 05:54:18 +00001925 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001926 if (Complain) {
1927 std::string ErrorStr = "could not find file '";
1928 ErrorStr += Filename;
1929 ErrorStr += "' referenced by AST file";
1930 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001931 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001932 // Record that we didn't find the file.
1933 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1934 return InputFile();
1935 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001936
Ben Langmuir198c1682014-03-07 07:27:49 +00001937 // Check if there was a request to override the contents of the file
1938 // that was part of the precompiled header. Overridding such a file
1939 // can lead to problems when lexing using the source locations from the
1940 // PCH.
1941 SourceManager &SM = getSourceManager();
1942 if (!Overridden && SM.isFileOverridden(File)) {
1943 if (Complain)
1944 Error(diag::err_fe_pch_file_overridden, Filename);
1945 // After emitting the diagnostic, recover by disabling the override so
1946 // that the original file will be used.
1947 SM.disableFileContentsOverride(File);
1948 // The FileEntry is a virtual file entry with the size of the contents
1949 // that would override the original contents. Set it to the original's
1950 // size/time.
1951 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1952 StoredSize, StoredTime);
1953 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001954
Ben Langmuir198c1682014-03-07 07:27:49 +00001955 bool IsOutOfDate = false;
1956
1957 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001958 if (!Overridden && //
1959 (StoredSize != File->getSize() ||
1960#if defined(LLVM_ON_WIN32)
1961 false
1962#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001963 // In our regression testing, the Windows file system seems to
1964 // have inconsistent modification times that sometimes
1965 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001966 //
1967 // This also happens in networked file systems, so disable this
1968 // check if validation is disabled or if we have an explicitly
1969 // built PCM file.
1970 //
1971 // FIXME: Should we also do this for PCH files? They could also
1972 // reasonably get shared across a network during a distributed build.
1973 (StoredTime != File->getModificationTime() && !DisableValidation &&
1974 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001975#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001976 )) {
1977 if (Complain) {
1978 // Build a list of the PCH imports that got us here (in reverse).
1979 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1980 while (ImportStack.back()->ImportedBy.size() > 0)
1981 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001982
Ben Langmuir198c1682014-03-07 07:27:49 +00001983 // The top-level PCH is stale.
1984 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1985 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00001986
Ben Langmuir198c1682014-03-07 07:27:49 +00001987 // Print the import stack.
1988 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1989 Diag(diag::note_pch_required_by)
1990 << Filename << ImportStack[0]->FileName;
1991 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00001992 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00001993 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00001994 }
1995
Ben Langmuir198c1682014-03-07 07:27:49 +00001996 if (!Diags.isDiagnosticInFlight())
1997 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00001998 }
1999
Ben Langmuir198c1682014-03-07 07:27:49 +00002000 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002001 }
2002
Ben Langmuir198c1682014-03-07 07:27:49 +00002003 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2004
2005 // Note that we've loaded this input file.
2006 F.InputFilesLoaded[ID-1] = IF;
2007 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002008}
2009
Richard Smith7ed1bc92014-12-05 22:42:13 +00002010/// \brief If we are loading a relocatable PCH or module file, and the filename
2011/// is not an absolute path, add the system or module root to the beginning of
2012/// the file name.
2013void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2014 // Resolve relative to the base directory, if we have one.
2015 if (!M.BaseDirectory.empty())
2016 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002017}
2018
Richard Smith7ed1bc92014-12-05 22:42:13 +00002019void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002020 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2021 return;
2022
Richard Smith7ed1bc92014-12-05 22:42:13 +00002023 SmallString<128> Buffer;
2024 llvm::sys::path::append(Buffer, Prefix, Filename);
2025 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002026}
2027
Richard Smith0f99d6a2015-08-09 08:48:41 +00002028static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2029 switch (ARR) {
2030 case ASTReader::Failure: return true;
2031 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2032 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2033 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2034 case ASTReader::ConfigurationMismatch:
2035 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2036 case ASTReader::HadErrors: return true;
2037 case ASTReader::Success: return false;
2038 }
2039
2040 llvm_unreachable("unknown ASTReadResult");
2041}
2042
Guy Benyei11169dd2012-12-18 14:30:41 +00002043ASTReader::ASTReadResult
2044ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002045 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002046 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002047 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002048 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002049
2050 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2051 Error("malformed block record in AST file");
2052 return Failure;
2053 }
2054
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002055 // Should we allow the configuration of the module file to differ from the
2056 // configuration of the current translation unit in a compatible way?
2057 //
2058 // FIXME: Allow this for files explicitly specified with -include-pch too.
2059 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2060
Guy Benyei11169dd2012-12-18 14:30:41 +00002061 // Read all of the records and blocks in the control block.
2062 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002063 unsigned NumInputs = 0;
2064 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002065 while (1) {
2066 llvm::BitstreamEntry Entry = Stream.advance();
2067
2068 switch (Entry.Kind) {
2069 case llvm::BitstreamEntry::Error:
2070 Error("malformed block record in AST file");
2071 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002072 case llvm::BitstreamEntry::EndBlock: {
2073 // Validate input files.
2074 const HeaderSearchOptions &HSOpts =
2075 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002076
Richard Smitha1825302014-10-23 22:18:29 +00002077 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002078 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2079 // loaded module files, ignore missing inputs.
2080 if (!DisableValidation && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002081 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002082
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002083 // If we are reading a module, we will create a verification timestamp,
2084 // so we verify all input files. Otherwise, verify only user input
2085 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002086
2087 unsigned N = NumUserInputs;
2088 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002089 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002090 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002091 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002092 N = NumInputs;
2093
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002094 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002095 InputFile IF = getInputFile(F, I+1, Complain);
2096 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002097 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002098 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002099 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002100
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002101 if (Listener)
2102 Listener->visitModuleFile(F.FileName);
2103
Ben Langmuircb69b572014-03-07 06:40:32 +00002104 if (Listener && Listener->needsInputFileVisitation()) {
2105 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2106 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002107 for (unsigned I = 0; I < N; ++I) {
2108 bool IsSystem = I >= NumUserInputs;
2109 InputFileInfo FI = readInputFileInfo(F, I+1);
2110 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2111 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002112 }
2113
Guy Benyei11169dd2012-12-18 14:30:41 +00002114 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002115 }
2116
Chris Lattnere7b154b2013-01-19 21:39:22 +00002117 case llvm::BitstreamEntry::SubBlock:
2118 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002119 case INPUT_FILES_BLOCK_ID:
2120 F.InputFilesCursor = Stream;
2121 if (Stream.SkipBlock() || // Skip with the main cursor
2122 // Read the abbreviations
2123 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2124 Error("malformed block record in AST file");
2125 return Failure;
2126 }
2127 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002128
Guy Benyei11169dd2012-12-18 14:30:41 +00002129 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002130 if (Stream.SkipBlock()) {
2131 Error("malformed block record in AST file");
2132 return Failure;
2133 }
2134 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002135 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002136
2137 case llvm::BitstreamEntry::Record:
2138 // The interesting case.
2139 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002140 }
2141
2142 // Read and process a record.
2143 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002144 StringRef Blob;
2145 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002146 case METADATA: {
2147 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2148 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002149 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2150 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002151 return VersionMismatch;
2152 }
2153
2154 bool hasErrors = Record[5];
2155 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2156 Diag(diag::err_pch_with_compiler_errors);
2157 return HadErrors;
2158 }
2159
2160 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002161 // Relative paths in a relocatable PCH are relative to our sysroot.
2162 if (F.RelocatablePCH)
2163 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002164
2165 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002166 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002167 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2168 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002169 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002170 return VersionMismatch;
2171 }
2172 break;
2173 }
2174
Ben Langmuir487ea142014-10-23 18:05:36 +00002175 case SIGNATURE:
2176 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2177 F.Signature = Record[0];
2178 break;
2179
Guy Benyei11169dd2012-12-18 14:30:41 +00002180 case IMPORTS: {
2181 // Load each of the imported PCH files.
2182 unsigned Idx = 0, N = Record.size();
2183 while (Idx < N) {
2184 // Read information about the AST file.
2185 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2186 // The import location will be the local one for now; we will adjust
2187 // all import locations of module imports after the global source
2188 // location info are setup.
2189 SourceLocation ImportLoc =
2190 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002191 off_t StoredSize = (off_t)Record[Idx++];
2192 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002193 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002194 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002195
Richard Smith0f99d6a2015-08-09 08:48:41 +00002196 // If our client can't cope with us being out of date, we can't cope with
2197 // our dependency being missing.
2198 unsigned Capabilities = ClientLoadCapabilities;
2199 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2200 Capabilities &= ~ARR_Missing;
2201
Guy Benyei11169dd2012-12-18 14:30:41 +00002202 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002203 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2204 Loaded, StoredSize, StoredModTime,
2205 StoredSignature, Capabilities);
2206
2207 // If we diagnosed a problem, produce a backtrace.
2208 if (isDiagnosedResult(Result, Capabilities))
2209 Diag(diag::note_module_file_imported_by)
2210 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2211
2212 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002213 case Failure: return Failure;
2214 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002215 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002216 case OutOfDate: return OutOfDate;
2217 case VersionMismatch: return VersionMismatch;
2218 case ConfigurationMismatch: return ConfigurationMismatch;
2219 case HadErrors: return HadErrors;
2220 case Success: break;
2221 }
2222 }
2223 break;
2224 }
2225
2226 case LANGUAGE_OPTIONS: {
2227 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002228 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002229 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002230 ParseLanguageOptions(Record, Complain, *Listener,
2231 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002232 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002233 return ConfigurationMismatch;
2234 break;
2235 }
2236
2237 case TARGET_OPTIONS: {
2238 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2239 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002240 ParseTargetOptions(Record, Complain, *Listener,
2241 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002242 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002243 return ConfigurationMismatch;
2244 break;
2245 }
2246
2247 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002248 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002249 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002250 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002251 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002252 !DisableValidation)
2253 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002254 break;
2255 }
2256
2257 case FILE_SYSTEM_OPTIONS: {
2258 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2259 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002260 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002261 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002262 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002263 return ConfigurationMismatch;
2264 break;
2265 }
2266
2267 case HEADER_SEARCH_OPTIONS: {
2268 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2269 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002270 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002271 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002272 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002273 return ConfigurationMismatch;
2274 break;
2275 }
2276
2277 case PREPROCESSOR_OPTIONS: {
2278 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2279 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002280 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002281 ParsePreprocessorOptions(Record, Complain, *Listener,
2282 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002283 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002284 return ConfigurationMismatch;
2285 break;
2286 }
2287
2288 case ORIGINAL_FILE:
2289 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002290 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002291 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002292 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002293 break;
2294
2295 case ORIGINAL_FILE_ID:
2296 F.OriginalSourceFileID = FileID::get(Record[0]);
2297 break;
2298
2299 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002300 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002301 break;
2302
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002303 case MODULE_NAME:
2304 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002305 if (Listener)
2306 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002307 break;
2308
Richard Smith223d3f22014-12-06 03:21:08 +00002309 case MODULE_DIRECTORY: {
2310 assert(!F.ModuleName.empty() &&
2311 "MODULE_DIRECTORY found before MODULE_NAME");
2312 // If we've already loaded a module map file covering this module, we may
2313 // have a better path for it (relative to the current build).
2314 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2315 if (M && M->Directory) {
2316 // If we're implicitly loading a module, the base directory can't
2317 // change between the build and use.
2318 if (F.Kind != MK_ExplicitModule) {
2319 const DirectoryEntry *BuildDir =
2320 PP.getFileManager().getDirectory(Blob);
2321 if (!BuildDir || BuildDir != M->Directory) {
2322 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2323 Diag(diag::err_imported_module_relocated)
2324 << F.ModuleName << Blob << M->Directory->getName();
2325 return OutOfDate;
2326 }
2327 }
2328 F.BaseDirectory = M->Directory->getName();
2329 } else {
2330 F.BaseDirectory = Blob;
2331 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002332 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002333 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002334
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002335 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002336 if (ASTReadResult Result =
2337 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2338 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002339 break;
2340
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002341 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002342 NumInputs = Record[0];
2343 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002344 F.InputFileOffsets =
2345 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002346 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002347 break;
2348 }
2349 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002350}
2351
Ben Langmuir2c9af442014-04-10 17:57:43 +00002352ASTReader::ASTReadResult
2353ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002354 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002355
2356 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2357 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002358 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002359 }
2360
2361 // Read all of the records and blocks for the AST file.
2362 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002363 while (1) {
2364 llvm::BitstreamEntry Entry = Stream.advance();
2365
2366 switch (Entry.Kind) {
2367 case llvm::BitstreamEntry::Error:
2368 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002369 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002370 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002371 // Outside of C++, we do not store a lookup map for the translation unit.
2372 // Instead, mark it as needing a lookup map to be built if this module
2373 // contains any declarations lexically within it (which it always does!).
2374 // This usually has no cost, since we very rarely need the lookup map for
2375 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002376 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002377 if (DC->hasExternalLexicalStorage() &&
2378 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002379 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002380
Ben Langmuir2c9af442014-04-10 17:57:43 +00002381 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002382 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002383 case llvm::BitstreamEntry::SubBlock:
2384 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002385 case DECLTYPES_BLOCK_ID:
2386 // We lazily load the decls block, but we want to set up the
2387 // DeclsCursor cursor to point into it. Clone our current bitcode
2388 // cursor to it, enter the block and read the abbrevs in that block.
2389 // With the main cursor, we just skip over it.
2390 F.DeclsCursor = Stream;
2391 if (Stream.SkipBlock() || // Skip with the main cursor.
2392 // Read the abbrevs.
2393 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2394 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002395 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002396 }
2397 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002398
Guy Benyei11169dd2012-12-18 14:30:41 +00002399 case PREPROCESSOR_BLOCK_ID:
2400 F.MacroCursor = Stream;
2401 if (!PP.getExternalSource())
2402 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002403
Guy Benyei11169dd2012-12-18 14:30:41 +00002404 if (Stream.SkipBlock() ||
2405 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2406 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002407 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002408 }
2409 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2410 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002411
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 case PREPROCESSOR_DETAIL_BLOCK_ID:
2413 F.PreprocessorDetailCursor = Stream;
2414 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002415 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002416 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002417 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002418 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002419 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002421 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2422
Guy Benyei11169dd2012-12-18 14:30:41 +00002423 if (!PP.getPreprocessingRecord())
2424 PP.createPreprocessingRecord();
2425 if (!PP.getPreprocessingRecord()->getExternalSource())
2426 PP.getPreprocessingRecord()->SetExternalSource(*this);
2427 break;
2428
2429 case SOURCE_MANAGER_BLOCK_ID:
2430 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002431 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002432 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002433
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002435 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2436 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002437 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002438
Guy Benyei11169dd2012-12-18 14:30:41 +00002439 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002440 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 if (Stream.SkipBlock() ||
2442 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2443 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002444 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002445 }
2446 CommentsCursors.push_back(std::make_pair(C, &F));
2447 break;
2448 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002449
Guy Benyei11169dd2012-12-18 14:30:41 +00002450 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002451 if (Stream.SkipBlock()) {
2452 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002453 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002454 }
2455 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002456 }
2457 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002458
2459 case llvm::BitstreamEntry::Record:
2460 // The interesting case.
2461 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002462 }
2463
2464 // Read and process a record.
2465 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002466 StringRef Blob;
2467 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002468 default: // Default behavior: ignore.
2469 break;
2470
2471 case TYPE_OFFSET: {
2472 if (F.LocalNumTypes != 0) {
2473 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002474 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002476 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002477 F.LocalNumTypes = Record[0];
2478 unsigned LocalBaseTypeIndex = Record[1];
2479 F.BaseTypeIndex = getTotalNumTypes();
2480
2481 if (F.LocalNumTypes > 0) {
2482 // Introduce the global -> local mapping for types within this module.
2483 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2484
2485 // Introduce the local -> global mapping for types within this module.
2486 F.TypeRemap.insertOrReplace(
2487 std::make_pair(LocalBaseTypeIndex,
2488 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002489
2490 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 }
2492 break;
2493 }
2494
2495 case DECL_OFFSET: {
2496 if (F.LocalNumDecls != 0) {
2497 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002498 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002500 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 F.LocalNumDecls = Record[0];
2502 unsigned LocalBaseDeclID = Record[1];
2503 F.BaseDeclID = getTotalNumDecls();
2504
2505 if (F.LocalNumDecls > 0) {
2506 // Introduce the global -> local mapping for declarations within this
2507 // module.
2508 GlobalDeclMap.insert(
2509 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2510
2511 // Introduce the local -> global mapping for declarations within this
2512 // module.
2513 F.DeclRemap.insertOrReplace(
2514 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2515
2516 // Introduce the global -> local mapping for declarations within this
2517 // module.
2518 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002519
Ben Langmuir52ca6782014-10-20 16:27:32 +00002520 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2521 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 break;
2523 }
2524
2525 case TU_UPDATE_LEXICAL: {
2526 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002527 LexicalContents Contents(
2528 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2529 Blob.data()),
2530 static_cast<unsigned int>(Blob.size() / 4));
2531 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 TU->setHasExternalLexicalStorage(true);
2533 break;
2534 }
2535
2536 case UPDATE_VISIBLE: {
2537 unsigned Idx = 0;
2538 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002539 auto *Data = (const unsigned char*)Blob.data();
2540 unsigned BucketOffset = Record[Idx++];
2541 PendingVisibleUpdates[ID].push_back(
2542 PendingVisibleUpdate{&F, Data, BucketOffset});
2543 // If we've already loaded the decl, perform the updates when we finish
2544 // loading this block.
2545 if (Decl *D = GetExistingDecl(ID))
2546 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 break;
2548 }
2549
2550 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002551 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002552 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002553 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2554 (const unsigned char *)F.IdentifierTableData + Record[0],
2555 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2556 (const unsigned char *)F.IdentifierTableData,
2557 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002558
2559 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2560 }
2561 break;
2562
2563 case IDENTIFIER_OFFSET: {
2564 if (F.LocalNumIdentifiers != 0) {
2565 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002566 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002567 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002568 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002569 F.LocalNumIdentifiers = Record[0];
2570 unsigned LocalBaseIdentifierID = Record[1];
2571 F.BaseIdentifierID = getTotalNumIdentifiers();
2572
2573 if (F.LocalNumIdentifiers > 0) {
2574 // Introduce the global -> local mapping for identifiers within this
2575 // module.
2576 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2577 &F));
2578
2579 // Introduce the local -> global mapping for identifiers within this
2580 // module.
2581 F.IdentifierRemap.insertOrReplace(
2582 std::make_pair(LocalBaseIdentifierID,
2583 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002584
Ben Langmuir52ca6782014-10-20 16:27:32 +00002585 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2586 + F.LocalNumIdentifiers);
2587 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 break;
2589 }
2590
Richard Smith33e0f7e2015-07-22 02:08:40 +00002591 case INTERESTING_IDENTIFIERS:
2592 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2593 break;
2594
Ben Langmuir332aafe2014-01-31 01:06:56 +00002595 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002596 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2597 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002599 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 break;
2601
2602 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002603 if (SpecialTypes.empty()) {
2604 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2605 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2606 break;
2607 }
2608
2609 if (SpecialTypes.size() != Record.size()) {
2610 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002611 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002612 }
2613
2614 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2615 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2616 if (!SpecialTypes[I])
2617 SpecialTypes[I] = ID;
2618 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2619 // merge step?
2620 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 break;
2622
2623 case STATISTICS:
2624 TotalNumStatements += Record[0];
2625 TotalNumMacros += Record[1];
2626 TotalLexicalDeclContexts += Record[2];
2627 TotalVisibleDeclContexts += Record[3];
2628 break;
2629
2630 case UNUSED_FILESCOPED_DECLS:
2631 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2632 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2633 break;
2634
2635 case DELEGATING_CTORS:
2636 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2637 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2638 break;
2639
2640 case WEAK_UNDECLARED_IDENTIFIERS:
2641 if (Record.size() % 4 != 0) {
2642 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002643 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002644 }
2645
2646 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2647 // files. This isn't the way to do it :)
2648 WeakUndeclaredIdentifiers.clear();
2649
2650 // Translate the weak, undeclared identifiers into global IDs.
2651 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2652 WeakUndeclaredIdentifiers.push_back(
2653 getGlobalIdentifierID(F, Record[I++]));
2654 WeakUndeclaredIdentifiers.push_back(
2655 getGlobalIdentifierID(F, Record[I++]));
2656 WeakUndeclaredIdentifiers.push_back(
2657 ReadSourceLocation(F, Record, I).getRawEncoding());
2658 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2659 }
2660 break;
2661
Guy Benyei11169dd2012-12-18 14:30:41 +00002662 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002663 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002664 F.LocalNumSelectors = Record[0];
2665 unsigned LocalBaseSelectorID = Record[1];
2666 F.BaseSelectorID = getTotalNumSelectors();
2667
2668 if (F.LocalNumSelectors > 0) {
2669 // Introduce the global -> local mapping for selectors within this
2670 // module.
2671 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2672
2673 // Introduce the local -> global mapping for selectors within this
2674 // module.
2675 F.SelectorRemap.insertOrReplace(
2676 std::make_pair(LocalBaseSelectorID,
2677 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002678
2679 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 }
2681 break;
2682 }
2683
2684 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002685 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 if (Record[0])
2687 F.SelectorLookupTable
2688 = ASTSelectorLookupTable::Create(
2689 F.SelectorLookupTableData + Record[0],
2690 F.SelectorLookupTableData,
2691 ASTSelectorLookupTrait(*this, F));
2692 TotalNumMethodPoolEntries += Record[1];
2693 break;
2694
2695 case REFERENCED_SELECTOR_POOL:
2696 if (!Record.empty()) {
2697 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2698 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2699 Record[Idx++]));
2700 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2701 getRawEncoding());
2702 }
2703 }
2704 break;
2705
2706 case PP_COUNTER_VALUE:
2707 if (!Record.empty() && Listener)
2708 Listener->ReadCounter(F, Record[0]);
2709 break;
2710
2711 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002712 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 F.NumFileSortedDecls = Record[0];
2714 break;
2715
2716 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002717 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002718 F.LocalNumSLocEntries = Record[0];
2719 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002720 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002721 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002722 SLocSpaceSize);
2723 // Make our entry in the range map. BaseID is negative and growing, so
2724 // we invert it. Because we invert it, though, we need the other end of
2725 // the range.
2726 unsigned RangeStart =
2727 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2728 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2729 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2730
2731 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2732 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2733 GlobalSLocOffsetMap.insert(
2734 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2735 - SLocSpaceSize,&F));
2736
2737 // Initialize the remapping table.
2738 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002739 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002741 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2743
2744 TotalNumSLocEntries += F.LocalNumSLocEntries;
2745 break;
2746 }
2747
2748 case MODULE_OFFSET_MAP: {
2749 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002750 const unsigned char *Data = (const unsigned char*)Blob.data();
2751 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002752
2753 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2754 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2755 F.SLocRemap.insert(std::make_pair(0U, 0));
2756 F.SLocRemap.insert(std::make_pair(2U, 1));
2757 }
2758
Guy Benyei11169dd2012-12-18 14:30:41 +00002759 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002760 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2761 RemapBuilder;
2762 RemapBuilder SLocRemap(F.SLocRemap);
2763 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2764 RemapBuilder MacroRemap(F.MacroRemap);
2765 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2766 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2767 RemapBuilder SelectorRemap(F.SelectorRemap);
2768 RemapBuilder DeclRemap(F.DeclRemap);
2769 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002770
2771 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002772 using namespace llvm::support;
2773 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002774 StringRef Name = StringRef((const char*)Data, Len);
2775 Data += Len;
2776 ModuleFile *OM = ModuleMgr.lookup(Name);
2777 if (!OM) {
2778 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002779 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002780 }
2781
Justin Bogner57ba0b22014-03-28 22:03:24 +00002782 uint32_t SLocOffset =
2783 endian::readNext<uint32_t, little, unaligned>(Data);
2784 uint32_t IdentifierIDOffset =
2785 endian::readNext<uint32_t, little, unaligned>(Data);
2786 uint32_t MacroIDOffset =
2787 endian::readNext<uint32_t, little, unaligned>(Data);
2788 uint32_t PreprocessedEntityIDOffset =
2789 endian::readNext<uint32_t, little, unaligned>(Data);
2790 uint32_t SubmoduleIDOffset =
2791 endian::readNext<uint32_t, little, unaligned>(Data);
2792 uint32_t SelectorIDOffset =
2793 endian::readNext<uint32_t, little, unaligned>(Data);
2794 uint32_t DeclIDOffset =
2795 endian::readNext<uint32_t, little, unaligned>(Data);
2796 uint32_t TypeIndexOffset =
2797 endian::readNext<uint32_t, little, unaligned>(Data);
2798
Ben Langmuir785180e2014-10-20 16:27:30 +00002799 uint32_t None = std::numeric_limits<uint32_t>::max();
2800
2801 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2802 RemapBuilder &Remap) {
2803 if (Offset != None)
2804 Remap.insert(std::make_pair(Offset,
2805 static_cast<int>(BaseOffset - Offset)));
2806 };
2807 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2808 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2809 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2810 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2811 PreprocessedEntityRemap);
2812 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2813 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2814 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2815 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002816
2817 // Global -> local mappings.
2818 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2819 }
2820 break;
2821 }
2822
2823 case SOURCE_MANAGER_LINE_TABLE:
2824 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002825 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002826 break;
2827
2828 case SOURCE_LOCATION_PRELOADS: {
2829 // Need to transform from the local view (1-based IDs) to the global view,
2830 // which is based off F.SLocEntryBaseID.
2831 if (!F.PreloadSLocEntries.empty()) {
2832 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002833 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002834 }
2835
2836 F.PreloadSLocEntries.swap(Record);
2837 break;
2838 }
2839
2840 case EXT_VECTOR_DECLS:
2841 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2842 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2843 break;
2844
2845 case VTABLE_USES:
2846 if (Record.size() % 3 != 0) {
2847 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002848 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002849 }
2850
2851 // Later tables overwrite earlier ones.
2852 // FIXME: Modules will have some trouble with this. This is clearly not
2853 // the right way to do this.
2854 VTableUses.clear();
2855
2856 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2857 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2858 VTableUses.push_back(
2859 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2860 VTableUses.push_back(Record[Idx++]);
2861 }
2862 break;
2863
Guy Benyei11169dd2012-12-18 14:30:41 +00002864 case PENDING_IMPLICIT_INSTANTIATIONS:
2865 if (PendingInstantiations.size() % 2 != 0) {
2866 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002867 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002868 }
2869
2870 if (Record.size() % 2 != 0) {
2871 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002872 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002873 }
2874
2875 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2876 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2877 PendingInstantiations.push_back(
2878 ReadSourceLocation(F, Record, I).getRawEncoding());
2879 }
2880 break;
2881
2882 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002883 if (Record.size() != 2) {
2884 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002885 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002886 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002887 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2888 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2889 break;
2890
2891 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002892 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2893 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2894 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002895
2896 unsigned LocalBasePreprocessedEntityID = Record[0];
2897
2898 unsigned StartingID;
2899 if (!PP.getPreprocessingRecord())
2900 PP.createPreprocessingRecord();
2901 if (!PP.getPreprocessingRecord()->getExternalSource())
2902 PP.getPreprocessingRecord()->SetExternalSource(*this);
2903 StartingID
2904 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002905 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002906 F.BasePreprocessedEntityID = StartingID;
2907
2908 if (F.NumPreprocessedEntities > 0) {
2909 // Introduce the global -> local mapping for preprocessed entities in
2910 // this module.
2911 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2912
2913 // Introduce the local -> global mapping for preprocessed entities in
2914 // this module.
2915 F.PreprocessedEntityRemap.insertOrReplace(
2916 std::make_pair(LocalBasePreprocessedEntityID,
2917 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2918 }
2919
2920 break;
2921 }
2922
2923 case DECL_UPDATE_OFFSETS: {
2924 if (Record.size() % 2 != 0) {
2925 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002926 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002927 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002928 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2929 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2930 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2931
2932 // If we've already loaded the decl, perform the updates when we finish
2933 // loading this block.
2934 if (Decl *D = GetExistingDecl(ID))
2935 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2936 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002937 break;
2938 }
2939
2940 case DECL_REPLACEMENTS: {
2941 if (Record.size() % 3 != 0) {
2942 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002943 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 }
2945 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2946 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2947 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2948 break;
2949 }
2950
2951 case OBJC_CATEGORIES_MAP: {
2952 if (F.LocalNumObjCCategoriesInMap != 0) {
2953 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002954 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002955 }
2956
2957 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002958 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002959 break;
2960 }
2961
2962 case OBJC_CATEGORIES:
2963 F.ObjCCategories.swap(Record);
2964 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00002965
Guy Benyei11169dd2012-12-18 14:30:41 +00002966 case CXX_BASE_SPECIFIER_OFFSETS: {
2967 if (F.LocalNumCXXBaseSpecifiers != 0) {
2968 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002969 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002970 }
Richard Smithc2bb8182015-03-24 06:36:48 +00002971
Guy Benyei11169dd2012-12-18 14:30:41 +00002972 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002973 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00002974 break;
2975 }
2976
2977 case CXX_CTOR_INITIALIZERS_OFFSETS: {
2978 if (F.LocalNumCXXCtorInitializers != 0) {
2979 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2980 return Failure;
2981 }
2982
2983 F.LocalNumCXXCtorInitializers = Record[0];
2984 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002985 break;
2986 }
2987
2988 case DIAG_PRAGMA_MAPPINGS:
2989 if (F.PragmaDiagMappings.empty())
2990 F.PragmaDiagMappings.swap(Record);
2991 else
2992 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2993 Record.begin(), Record.end());
2994 break;
2995
2996 case CUDA_SPECIAL_DECL_REFS:
2997 // Later tables overwrite earlier ones.
2998 // FIXME: Modules will have trouble with this.
2999 CUDASpecialDeclRefs.clear();
3000 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3001 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3002 break;
3003
3004 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003005 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003006 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003007 if (Record[0]) {
3008 F.HeaderFileInfoTable
3009 = HeaderFileInfoLookupTable::Create(
3010 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3011 (const unsigned char *)F.HeaderFileInfoTableData,
3012 HeaderFileInfoTrait(*this, F,
3013 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003014 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003015
3016 PP.getHeaderSearchInfo().SetExternalSource(this);
3017 if (!PP.getHeaderSearchInfo().getExternalLookup())
3018 PP.getHeaderSearchInfo().SetExternalLookup(this);
3019 }
3020 break;
3021 }
3022
3023 case FP_PRAGMA_OPTIONS:
3024 // Later tables overwrite earlier ones.
3025 FPPragmaOptions.swap(Record);
3026 break;
3027
3028 case OPENCL_EXTENSIONS:
3029 // Later tables overwrite earlier ones.
3030 OpenCLExtensions.swap(Record);
3031 break;
3032
3033 case TENTATIVE_DEFINITIONS:
3034 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3035 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3036 break;
3037
3038 case KNOWN_NAMESPACES:
3039 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3040 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3041 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003042
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003043 case UNDEFINED_BUT_USED:
3044 if (UndefinedButUsed.size() % 2 != 0) {
3045 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003046 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003047 }
3048
3049 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003050 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003051 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003052 }
3053 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003054 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3055 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003056 ReadSourceLocation(F, Record, I).getRawEncoding());
3057 }
3058 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003059 case DELETE_EXPRS_TO_ANALYZE:
3060 for (unsigned I = 0, N = Record.size(); I != N;) {
3061 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3062 const uint64_t Count = Record[I++];
3063 DelayedDeleteExprs.push_back(Count);
3064 for (uint64_t C = 0; C < Count; ++C) {
3065 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3066 bool IsArrayForm = Record[I++] == 1;
3067 DelayedDeleteExprs.push_back(IsArrayForm);
3068 }
3069 }
3070 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003071
Guy Benyei11169dd2012-12-18 14:30:41 +00003072 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003073 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003074 // If we aren't loading a module (which has its own exports), make
3075 // all of the imported modules visible.
3076 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003077 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3078 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3079 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3080 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003081 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003082 }
3083 }
3084 break;
3085 }
3086
3087 case LOCAL_REDECLARATIONS: {
3088 F.RedeclarationChains.swap(Record);
3089 break;
3090 }
3091
3092 case LOCAL_REDECLARATIONS_MAP: {
3093 if (F.LocalNumRedeclarationsInMap != 0) {
3094 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003095 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003096 }
3097
3098 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003099 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003100 break;
3101 }
3102
Guy Benyei11169dd2012-12-18 14:30:41 +00003103 case MACRO_OFFSET: {
3104 if (F.LocalNumMacros != 0) {
3105 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003106 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003108 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003109 F.LocalNumMacros = Record[0];
3110 unsigned LocalBaseMacroID = Record[1];
3111 F.BaseMacroID = getTotalNumMacros();
3112
3113 if (F.LocalNumMacros > 0) {
3114 // Introduce the global -> local mapping for macros within this module.
3115 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3116
3117 // Introduce the local -> global mapping for macros within this module.
3118 F.MacroRemap.insertOrReplace(
3119 std::make_pair(LocalBaseMacroID,
3120 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003121
3122 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003123 }
3124 break;
3125 }
3126
Richard Smithe40f2ba2013-08-07 21:41:30 +00003127 case LATE_PARSED_TEMPLATE: {
3128 LateParsedTemplates.append(Record.begin(), Record.end());
3129 break;
3130 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003131
3132 case OPTIMIZE_PRAGMA_OPTIONS:
3133 if (Record.size() != 1) {
3134 Error("invalid pragma optimize record");
3135 return Failure;
3136 }
3137 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3138 break;
Nico Weber72889432014-09-06 01:25:55 +00003139
3140 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3141 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3142 UnusedLocalTypedefNameCandidates.push_back(
3143 getGlobalDeclID(F, Record[I]));
3144 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003145 }
3146 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003147}
3148
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003149ASTReader::ASTReadResult
3150ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3151 const ModuleFile *ImportedBy,
3152 unsigned ClientLoadCapabilities) {
3153 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003154 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003155
Richard Smithe842a472014-10-22 02:05:46 +00003156 if (F.Kind == MK_ExplicitModule) {
3157 // For an explicitly-loaded module, we don't care whether the original
3158 // module map file exists or matches.
3159 return Success;
3160 }
3161
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003162 // Try to resolve ModuleName in the current header search context and
3163 // verify that it is found in the same module map file as we saved. If the
3164 // top-level AST file is a main file, skip this check because there is no
3165 // usable header search context.
3166 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003167 "MODULE_NAME should come before MODULE_MAP_FILE");
3168 if (F.Kind == MK_ImplicitModule &&
3169 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3170 // An implicitly-loaded module file should have its module listed in some
3171 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003172 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003173 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3174 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3175 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003176 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003177 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3178 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3179 // This module was defined by an imported (explicit) module.
3180 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3181 << ASTFE->getName();
3182 else
3183 // This module was built with a different module map.
3184 Diag(diag::err_imported_module_not_found)
3185 << F.ModuleName << F.FileName << ImportedBy->FileName
3186 << F.ModuleMapPath;
3187 }
3188 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003189 }
3190
Richard Smithe842a472014-10-22 02:05:46 +00003191 assert(M->Name == F.ModuleName && "found module with different name");
3192
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003193 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003194 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003195 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3196 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003197 assert(ImportedBy && "top-level import should be verified");
3198 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3199 Diag(diag::err_imported_module_modmap_changed)
3200 << F.ModuleName << ImportedBy->FileName
3201 << ModMap->getName() << F.ModuleMapPath;
3202 return OutOfDate;
3203 }
3204
3205 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3206 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3207 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003208 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003209 const FileEntry *F =
3210 FileMgr.getFile(Filename, false, false);
3211 if (F == nullptr) {
3212 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3213 Error("could not find file '" + Filename +"' referenced by AST file");
3214 return OutOfDate;
3215 }
3216 AdditionalStoredMaps.insert(F);
3217 }
3218
3219 // Check any additional module map files (e.g. module.private.modulemap)
3220 // that are not in the pcm.
3221 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3222 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3223 // Remove files that match
3224 // Note: SmallPtrSet::erase is really remove
3225 if (!AdditionalStoredMaps.erase(ModMap)) {
3226 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3227 Diag(diag::err_module_different_modmap)
3228 << F.ModuleName << /*new*/0 << ModMap->getName();
3229 return OutOfDate;
3230 }
3231 }
3232 }
3233
3234 // Check any additional module map files that are in the pcm, but not
3235 // found in header search. Cases that match are already removed.
3236 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3237 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3238 Diag(diag::err_module_different_modmap)
3239 << F.ModuleName << /*not new*/1 << ModMap->getName();
3240 return OutOfDate;
3241 }
3242 }
3243
3244 if (Listener)
3245 Listener->ReadModuleMapFile(F.ModuleMapPath);
3246 return Success;
3247}
3248
3249
Douglas Gregorc1489562013-02-12 23:36:21 +00003250/// \brief Move the given method to the back of the global list of methods.
3251static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3252 // Find the entry for this selector in the method pool.
3253 Sema::GlobalMethodPool::iterator Known
3254 = S.MethodPool.find(Method->getSelector());
3255 if (Known == S.MethodPool.end())
3256 return;
3257
3258 // Retrieve the appropriate method list.
3259 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3260 : Known->second.second;
3261 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003262 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003263 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003264 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003265 Found = true;
3266 } else {
3267 // Keep searching.
3268 continue;
3269 }
3270 }
3271
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003272 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003273 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003274 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003275 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003276 }
3277}
3278
Richard Smithde711422015-04-23 21:20:19 +00003279void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003280 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003281 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003282 bool wasHidden = D->Hidden;
3283 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003284
Richard Smith49f906a2014-03-01 00:08:04 +00003285 if (wasHidden && SemaObj) {
3286 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3287 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003288 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003289 }
3290 }
3291}
3292
Richard Smith49f906a2014-03-01 00:08:04 +00003293void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003294 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003295 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003296 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003297 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003298 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003299 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003300 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003301
3302 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003303 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003304 // there is nothing more to do.
3305 continue;
3306 }
Richard Smith49f906a2014-03-01 00:08:04 +00003307
Guy Benyei11169dd2012-12-18 14:30:41 +00003308 if (!Mod->isAvailable()) {
3309 // Modules that aren't available cannot be made visible.
3310 continue;
3311 }
3312
3313 // Update the module's name visibility.
3314 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003315
Guy Benyei11169dd2012-12-18 14:30:41 +00003316 // If we've already deserialized any names from this module,
3317 // mark them as visible.
3318 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3319 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003320 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003321 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003322 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003323 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3324 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003325 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003326
Guy Benyei11169dd2012-12-18 14:30:41 +00003327 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003328 SmallVector<Module *, 16> Exports;
3329 Mod->getExportedModules(Exports);
3330 for (SmallVectorImpl<Module *>::iterator
3331 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3332 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003333 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003334 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003335 }
3336 }
3337}
3338
Douglas Gregore060e572013-01-25 01:03:03 +00003339bool ASTReader::loadGlobalIndex() {
3340 if (GlobalIndex)
3341 return false;
3342
3343 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3344 !Context.getLangOpts().Modules)
3345 return true;
3346
3347 // Try to load the global index.
3348 TriedLoadingGlobalIndex = true;
3349 StringRef ModuleCachePath
3350 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3351 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003352 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003353 if (!Result.first)
3354 return true;
3355
3356 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003357 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003358 return false;
3359}
3360
3361bool ASTReader::isGlobalIndexUnavailable() const {
3362 return Context.getLangOpts().Modules && UseGlobalIndex &&
3363 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3364}
3365
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003366static void updateModuleTimestamp(ModuleFile &MF) {
3367 // Overwrite the timestamp file contents so that file's mtime changes.
3368 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003369 std::error_code EC;
3370 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3371 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003372 return;
3373 OS << "Timestamp file\n";
3374}
3375
Guy Benyei11169dd2012-12-18 14:30:41 +00003376ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3377 ModuleKind Type,
3378 SourceLocation ImportLoc,
3379 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003380 llvm::SaveAndRestore<SourceLocation>
3381 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3382
Richard Smithd1c46742014-04-30 02:24:17 +00003383 // Defer any pending actions until we get to the end of reading the AST file.
3384 Deserializing AnASTFile(this);
3385
Guy Benyei11169dd2012-12-18 14:30:41 +00003386 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003387 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003388
3389 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003390 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003391 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003392 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003393 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003394 ClientLoadCapabilities)) {
3395 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003396 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003397 case OutOfDate:
3398 case VersionMismatch:
3399 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003400 case HadErrors: {
3401 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3402 for (const ImportedModule &IM : Loaded)
3403 LoadedSet.insert(IM.Mod);
3404
Douglas Gregor7029ce12013-03-19 00:28:20 +00003405 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003406 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003407 Context.getLangOpts().Modules
3408 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003409 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003410
3411 // If we find that any modules are unusable, the global index is going
3412 // to be out-of-date. Just remove it.
3413 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003414 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003415 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003416 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003417 case Success:
3418 break;
3419 }
3420
3421 // Here comes stuff that we only do once the entire chain is loaded.
3422
3423 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003424 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3425 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003426 M != MEnd; ++M) {
3427 ModuleFile &F = *M->Mod;
3428
3429 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003430 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3431 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003432
3433 // Once read, set the ModuleFile bit base offset and update the size in
3434 // bits of all files we've seen.
3435 F.GlobalBitOffset = TotalModulesSizeInBits;
3436 TotalModulesSizeInBits += F.SizeInBits;
3437 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3438
3439 // Preload SLocEntries.
3440 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3441 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3442 // Load it through the SourceManager and don't call ReadSLocEntry()
3443 // directly because the entry may have already been loaded in which case
3444 // calling ReadSLocEntry() directly would trigger an assertion in
3445 // SourceManager.
3446 SourceMgr.getLoadedSLocEntryByID(Index);
3447 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003448
3449 // Preload all the pending interesting identifiers by marking them out of
3450 // date.
3451 for (auto Offset : F.PreloadIdentifierOffsets) {
3452 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3453 F.IdentifierTableData + Offset);
3454
3455 ASTIdentifierLookupTrait Trait(*this, F);
3456 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3457 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3458 PP.getIdentifierTable().getOwn(Key).setOutOfDate(true);
3459 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003460 }
3461
Douglas Gregor603cd862013-03-22 18:50:14 +00003462 // Setup the import locations and notify the module manager that we've
3463 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003464 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3465 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003466 M != MEnd; ++M) {
3467 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003468
3469 ModuleMgr.moduleFileAccepted(&F);
3470
3471 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003472 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003473 if (!M->ImportedBy)
3474 F.ImportLoc = M->ImportLoc;
3475 else
3476 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3477 M->ImportLoc.getRawEncoding());
3478 }
3479
Richard Smith33e0f7e2015-07-22 02:08:40 +00003480 if (!Context.getLangOpts().CPlusPlus ||
3481 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3482 // Mark all of the identifiers in the identifier table as being out of date,
3483 // so that various accessors know to check the loaded modules when the
3484 // identifier is used.
3485 //
3486 // For C++ modules, we don't need information on many identifiers (just
3487 // those that provide macros or are poisoned), so we mark all of
3488 // the interesting ones via PreloadIdentifierOffsets.
3489 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3490 IdEnd = PP.getIdentifierTable().end();
3491 Id != IdEnd; ++Id)
3492 Id->second->setOutOfDate(true);
3493 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003494
3495 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003496 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3497 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003498 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3499 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003500
3501 switch (Unresolved.Kind) {
3502 case UnresolvedModuleRef::Conflict:
3503 if (ResolvedMod) {
3504 Module::Conflict Conflict;
3505 Conflict.Other = ResolvedMod;
3506 Conflict.Message = Unresolved.String.str();
3507 Unresolved.Mod->Conflicts.push_back(Conflict);
3508 }
3509 continue;
3510
3511 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003512 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003513 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003514 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003515
Douglas Gregorfb912652013-03-20 21:10:35 +00003516 case UnresolvedModuleRef::Export:
3517 if (ResolvedMod || Unresolved.IsWildcard)
3518 Unresolved.Mod->Exports.push_back(
3519 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3520 continue;
3521 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003522 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003523 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003524
3525 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3526 // Might be unnecessary as use declarations are only used to build the
3527 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003528
3529 InitializeContext();
3530
Richard Smith3d8e97e2013-10-18 06:54:39 +00003531 if (SemaObj)
3532 UpdateSema();
3533
Guy Benyei11169dd2012-12-18 14:30:41 +00003534 if (DeserializationListener)
3535 DeserializationListener->ReaderInitialized(this);
3536
3537 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3538 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3539 PrimaryModule.OriginalSourceFileID
3540 = FileID::get(PrimaryModule.SLocEntryBaseID
3541 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3542
3543 // If this AST file is a precompiled preamble, then set the
3544 // preamble file ID of the source manager to the file source file
3545 // from which the preamble was built.
3546 if (Type == MK_Preamble) {
3547 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3548 } else if (Type == MK_MainFile) {
3549 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3550 }
3551 }
3552
3553 // For any Objective-C class definitions we have already loaded, make sure
3554 // that we load any additional categories.
3555 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3556 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3557 ObjCClassesLoaded[I],
3558 PreviousGeneration);
3559 }
Douglas Gregore060e572013-01-25 01:03:03 +00003560
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003561 if (PP.getHeaderSearchInfo()
3562 .getHeaderSearchOpts()
3563 .ModulesValidateOncePerBuildSession) {
3564 // Now we are certain that the module and all modules it depends on are
3565 // up to date. Create or update timestamp files for modules that are
3566 // located in the module cache (not for PCH files that could be anywhere
3567 // in the filesystem).
3568 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3569 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003570 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003571 updateModuleTimestamp(*M.Mod);
3572 }
3573 }
3574 }
3575
Guy Benyei11169dd2012-12-18 14:30:41 +00003576 return Success;
3577}
3578
Ben Langmuir487ea142014-10-23 18:05:36 +00003579static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3580
Ben Langmuir70a1b812015-03-24 04:43:52 +00003581/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3582static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3583 return Stream.Read(8) == 'C' &&
3584 Stream.Read(8) == 'P' &&
3585 Stream.Read(8) == 'C' &&
3586 Stream.Read(8) == 'H';
3587}
3588
Richard Smith0f99d6a2015-08-09 08:48:41 +00003589static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3590 switch (Kind) {
3591 case MK_PCH:
3592 return 0; // PCH
3593 case MK_ImplicitModule:
3594 case MK_ExplicitModule:
3595 return 1; // module
3596 case MK_MainFile:
3597 case MK_Preamble:
3598 return 2; // main source file
3599 }
3600 llvm_unreachable("unknown module kind");
3601}
3602
Guy Benyei11169dd2012-12-18 14:30:41 +00003603ASTReader::ASTReadResult
3604ASTReader::ReadASTCore(StringRef FileName,
3605 ModuleKind Type,
3606 SourceLocation ImportLoc,
3607 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003608 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003609 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003610 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003611 unsigned ClientLoadCapabilities) {
3612 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003613 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003614 ModuleManager::AddModuleResult AddResult
3615 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003616 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003617 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003618 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003619
Douglas Gregor7029ce12013-03-19 00:28:20 +00003620 switch (AddResult) {
3621 case ModuleManager::AlreadyLoaded:
3622 return Success;
3623
3624 case ModuleManager::NewlyLoaded:
3625 // Load module file below.
3626 break;
3627
3628 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003629 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003630 // it.
3631 if (ClientLoadCapabilities & ARR_Missing)
3632 return Missing;
3633
3634 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003635 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3636 << FileName << ErrorStr.empty()
3637 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003638 return Failure;
3639
3640 case ModuleManager::OutOfDate:
3641 // We couldn't load the module file because it is out-of-date. If the
3642 // client can handle out-of-date, return it.
3643 if (ClientLoadCapabilities & ARR_OutOfDate)
3644 return OutOfDate;
3645
3646 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003647 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3648 << FileName << ErrorStr.empty()
3649 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003650 return Failure;
3651 }
3652
Douglas Gregor7029ce12013-03-19 00:28:20 +00003653 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003654
3655 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3656 // module?
3657 if (FileName != "-") {
3658 CurrentDir = llvm::sys::path::parent_path(FileName);
3659 if (CurrentDir.empty()) CurrentDir = ".";
3660 }
3661
3662 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003663 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003664 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003665 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003666 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3667
Guy Benyei11169dd2012-12-18 14:30:41 +00003668 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003669 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003670 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3671 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003672 return Failure;
3673 }
3674
3675 // This is used for compatibility with older PCH formats.
3676 bool HaveReadControlBlock = false;
3677
Chris Lattnerefa77172013-01-20 00:00:22 +00003678 while (1) {
3679 llvm::BitstreamEntry Entry = Stream.advance();
3680
3681 switch (Entry.Kind) {
3682 case llvm::BitstreamEntry::Error:
3683 case llvm::BitstreamEntry::EndBlock:
3684 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003685 Error("invalid record at top-level of AST file");
3686 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003687
3688 case llvm::BitstreamEntry::SubBlock:
3689 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003690 }
3691
Guy Benyei11169dd2012-12-18 14:30:41 +00003692 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003693 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003694 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3695 if (Stream.ReadBlockInfoBlock()) {
3696 Error("malformed BlockInfoBlock in AST file");
3697 return Failure;
3698 }
3699 break;
3700 case CONTROL_BLOCK_ID:
3701 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003702 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003703 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003704 // Check that we didn't try to load a non-module AST file as a module.
3705 //
3706 // FIXME: Should we also perform the converse check? Loading a module as
3707 // a PCH file sort of works, but it's a bit wonky.
3708 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule) &&
3709 F.ModuleName.empty()) {
3710 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3711 if (Result != OutOfDate ||
3712 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3713 Diag(diag::err_module_file_not_module) << FileName;
3714 return Result;
3715 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003716 break;
3717
3718 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003719 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003720 case OutOfDate: return OutOfDate;
3721 case VersionMismatch: return VersionMismatch;
3722 case ConfigurationMismatch: return ConfigurationMismatch;
3723 case HadErrors: return HadErrors;
3724 }
3725 break;
3726 case AST_BLOCK_ID:
3727 if (!HaveReadControlBlock) {
3728 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003729 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003730 return VersionMismatch;
3731 }
3732
3733 // Record that we've loaded this module.
3734 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3735 return Success;
3736
3737 default:
3738 if (Stream.SkipBlock()) {
3739 Error("malformed block record in AST file");
3740 return Failure;
3741 }
3742 break;
3743 }
3744 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003745}
3746
Richard Smitha7e2cc62015-05-01 01:53:09 +00003747void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003748 // If there's a listener, notify them that we "read" the translation unit.
3749 if (DeserializationListener)
3750 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3751 Context.getTranslationUnitDecl());
3752
Guy Benyei11169dd2012-12-18 14:30:41 +00003753 // FIXME: Find a better way to deal with collisions between these
3754 // built-in types. Right now, we just ignore the problem.
3755
3756 // Load the special types.
3757 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3758 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3759 if (!Context.CFConstantStringTypeDecl)
3760 Context.setCFConstantStringType(GetType(String));
3761 }
3762
3763 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3764 QualType FileType = GetType(File);
3765 if (FileType.isNull()) {
3766 Error("FILE type is NULL");
3767 return;
3768 }
3769
3770 if (!Context.FILEDecl) {
3771 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3772 Context.setFILEDecl(Typedef->getDecl());
3773 else {
3774 const TagType *Tag = FileType->getAs<TagType>();
3775 if (!Tag) {
3776 Error("Invalid FILE type in AST file");
3777 return;
3778 }
3779 Context.setFILEDecl(Tag->getDecl());
3780 }
3781 }
3782 }
3783
3784 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3785 QualType Jmp_bufType = GetType(Jmp_buf);
3786 if (Jmp_bufType.isNull()) {
3787 Error("jmp_buf type is NULL");
3788 return;
3789 }
3790
3791 if (!Context.jmp_bufDecl) {
3792 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3793 Context.setjmp_bufDecl(Typedef->getDecl());
3794 else {
3795 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3796 if (!Tag) {
3797 Error("Invalid jmp_buf type in AST file");
3798 return;
3799 }
3800 Context.setjmp_bufDecl(Tag->getDecl());
3801 }
3802 }
3803 }
3804
3805 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3806 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3807 if (Sigjmp_bufType.isNull()) {
3808 Error("sigjmp_buf type is NULL");
3809 return;
3810 }
3811
3812 if (!Context.sigjmp_bufDecl) {
3813 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3814 Context.setsigjmp_bufDecl(Typedef->getDecl());
3815 else {
3816 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3817 assert(Tag && "Invalid sigjmp_buf type in AST file");
3818 Context.setsigjmp_bufDecl(Tag->getDecl());
3819 }
3820 }
3821 }
3822
3823 if (unsigned ObjCIdRedef
3824 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3825 if (Context.ObjCIdRedefinitionType.isNull())
3826 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3827 }
3828
3829 if (unsigned ObjCClassRedef
3830 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3831 if (Context.ObjCClassRedefinitionType.isNull())
3832 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3833 }
3834
3835 if (unsigned ObjCSelRedef
3836 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3837 if (Context.ObjCSelRedefinitionType.isNull())
3838 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3839 }
3840
3841 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3842 QualType Ucontext_tType = GetType(Ucontext_t);
3843 if (Ucontext_tType.isNull()) {
3844 Error("ucontext_t type is NULL");
3845 return;
3846 }
3847
3848 if (!Context.ucontext_tDecl) {
3849 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3850 Context.setucontext_tDecl(Typedef->getDecl());
3851 else {
3852 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3853 assert(Tag && "Invalid ucontext_t type in AST file");
3854 Context.setucontext_tDecl(Tag->getDecl());
3855 }
3856 }
3857 }
3858 }
3859
3860 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3861
3862 // If there were any CUDA special declarations, deserialize them.
3863 if (!CUDASpecialDeclRefs.empty()) {
3864 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3865 Context.setcudaConfigureCallDecl(
3866 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3867 }
Richard Smith56be7542014-03-21 00:33:59 +00003868
Guy Benyei11169dd2012-12-18 14:30:41 +00003869 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003870 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003871 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003872 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003873 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003874 /*ImportLoc=*/Import.ImportLoc);
3875 PP.makeModuleVisible(Imported, Import.ImportLoc);
3876 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003877 }
3878 ImportedModules.clear();
3879}
3880
3881void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003882 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003883}
3884
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003885/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3886/// cursor into the start of the given block ID, returning false on success and
3887/// true on failure.
3888static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003889 while (1) {
3890 llvm::BitstreamEntry Entry = Cursor.advance();
3891 switch (Entry.Kind) {
3892 case llvm::BitstreamEntry::Error:
3893 case llvm::BitstreamEntry::EndBlock:
3894 return true;
3895
3896 case llvm::BitstreamEntry::Record:
3897 // Ignore top-level records.
3898 Cursor.skipRecord(Entry.ID);
3899 break;
3900
3901 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003902 if (Entry.ID == BlockID) {
3903 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003904 return true;
3905 // Found it!
3906 return false;
3907 }
3908
3909 if (Cursor.SkipBlock())
3910 return true;
3911 }
3912 }
3913}
3914
Ben Langmuir70a1b812015-03-24 04:43:52 +00003915/// \brief Reads and return the signature record from \p StreamFile's control
3916/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003917static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3918 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003919 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003920 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003921
3922 // Scan for the CONTROL_BLOCK_ID block.
3923 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3924 return 0;
3925
3926 // Scan for SIGNATURE inside the control block.
3927 ASTReader::RecordData Record;
3928 while (1) {
3929 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3930 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3931 Entry.Kind != llvm::BitstreamEntry::Record)
3932 return 0;
3933
3934 Record.clear();
3935 StringRef Blob;
3936 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3937 return Record[0];
3938 }
3939}
3940
Guy Benyei11169dd2012-12-18 14:30:41 +00003941/// \brief Retrieve the name of the original source file name
3942/// directly from the AST file, without actually loading the AST
3943/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003944std::string ASTReader::getOriginalSourceFile(
3945 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003946 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003947 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00003948 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00003949 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00003950 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3951 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00003952 return std::string();
3953 }
3954
3955 // Initialize the stream
3956 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003957 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003958 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003959
3960 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003961 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003962 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3963 return std::string();
3964 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003965
Chris Lattnere7b154b2013-01-19 21:39:22 +00003966 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003967 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003968 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3969 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003970 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003971
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003972 // Scan for ORIGINAL_FILE inside the control block.
3973 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003974 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003975 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003976 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3977 return std::string();
3978
3979 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3980 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3981 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003982 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003983
Guy Benyei11169dd2012-12-18 14:30:41 +00003984 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003985 StringRef Blob;
3986 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3987 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003988 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003989}
3990
3991namespace {
3992 class SimplePCHValidator : public ASTReaderListener {
3993 const LangOptions &ExistingLangOpts;
3994 const TargetOptions &ExistingTargetOpts;
3995 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003996 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00003997 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003998
Guy Benyei11169dd2012-12-18 14:30:41 +00003999 public:
4000 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4001 const TargetOptions &ExistingTargetOpts,
4002 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004003 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004004 FileManager &FileMgr)
4005 : ExistingLangOpts(ExistingLangOpts),
4006 ExistingTargetOpts(ExistingTargetOpts),
4007 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004008 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004009 FileMgr(FileMgr)
4010 {
4011 }
4012
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004013 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4014 bool AllowCompatibleDifferences) override {
4015 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4016 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004017 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004018 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4019 bool AllowCompatibleDifferences) override {
4020 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4021 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004022 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004023 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4024 StringRef SpecificModuleCachePath,
4025 bool Complain) override {
4026 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4027 ExistingModuleCachePath,
4028 nullptr, ExistingLangOpts);
4029 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004030 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4031 bool Complain,
4032 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004033 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004034 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004035 }
4036 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004037}
Guy Benyei11169dd2012-12-18 14:30:41 +00004038
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004039bool ASTReader::readASTFileControlBlock(
4040 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004041 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004042 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004043 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004044 // FIXME: This allows use of the VFS; we do not allow use of the
4045 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004046 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004047 if (!Buffer) {
4048 return true;
4049 }
4050
4051 // Initialize the stream
4052 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004053 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004054 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004055
4056 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004057 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004058 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004059
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004060 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004061 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004062 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004063
4064 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004065 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004066 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004067 BitstreamCursor InputFilesCursor;
4068 if (NeedsInputFiles) {
4069 InputFilesCursor = Stream;
4070 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4071 return true;
4072
4073 // Read the abbreviations
4074 while (true) {
4075 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4076 unsigned Code = InputFilesCursor.ReadCode();
4077
4078 // We expect all abbrevs to be at the start of the block.
4079 if (Code != llvm::bitc::DEFINE_ABBREV) {
4080 InputFilesCursor.JumpToBit(Offset);
4081 break;
4082 }
4083 InputFilesCursor.ReadAbbrevRecord();
4084 }
4085 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004086
4087 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004088 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004089 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004090 while (1) {
4091 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4092 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4093 return false;
4094
4095 if (Entry.Kind != llvm::BitstreamEntry::Record)
4096 return true;
4097
Guy Benyei11169dd2012-12-18 14:30:41 +00004098 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004099 StringRef Blob;
4100 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004101 switch ((ControlRecordTypes)RecCode) {
4102 case METADATA: {
4103 if (Record[0] != VERSION_MAJOR)
4104 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004105
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004106 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004107 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004108
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004109 break;
4110 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004111 case MODULE_NAME:
4112 Listener.ReadModuleName(Blob);
4113 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004114 case MODULE_DIRECTORY:
4115 ModuleDir = Blob;
4116 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004117 case MODULE_MAP_FILE: {
4118 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004119 auto Path = ReadString(Record, Idx);
4120 ResolveImportedPath(Path, ModuleDir);
4121 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004122 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004123 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004124 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004125 if (ParseLanguageOptions(Record, false, Listener,
4126 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004127 return true;
4128 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004129
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004130 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004131 if (ParseTargetOptions(Record, false, Listener,
4132 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004133 return true;
4134 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004135
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004136 case DIAGNOSTIC_OPTIONS:
4137 if (ParseDiagnosticOptions(Record, false, Listener))
4138 return true;
4139 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004140
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004141 case FILE_SYSTEM_OPTIONS:
4142 if (ParseFileSystemOptions(Record, false, Listener))
4143 return true;
4144 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004145
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004146 case HEADER_SEARCH_OPTIONS:
4147 if (ParseHeaderSearchOptions(Record, false, Listener))
4148 return true;
4149 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004150
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004151 case PREPROCESSOR_OPTIONS: {
4152 std::string IgnoredSuggestedPredefines;
4153 if (ParsePreprocessorOptions(Record, false, Listener,
4154 IgnoredSuggestedPredefines))
4155 return true;
4156 break;
4157 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004158
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004159 case INPUT_FILE_OFFSETS: {
4160 if (!NeedsInputFiles)
4161 break;
4162
4163 unsigned NumInputFiles = Record[0];
4164 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004165 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004166 for (unsigned I = 0; I != NumInputFiles; ++I) {
4167 // Go find this input file.
4168 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004169
4170 if (isSystemFile && !NeedsSystemInputFiles)
4171 break; // the rest are system input files
4172
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004173 BitstreamCursor &Cursor = InputFilesCursor;
4174 SavedStreamPosition SavedPosition(Cursor);
4175 Cursor.JumpToBit(InputFileOffs[I]);
4176
4177 unsigned Code = Cursor.ReadCode();
4178 RecordData Record;
4179 StringRef Blob;
4180 bool shouldContinue = false;
4181 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4182 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004183 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004184 std::string Filename = Blob;
4185 ResolveImportedPath(Filename, ModuleDir);
4186 shouldContinue =
4187 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004188 break;
4189 }
4190 if (!shouldContinue)
4191 break;
4192 }
4193 break;
4194 }
4195
Richard Smithd4b230b2014-10-27 23:01:16 +00004196 case IMPORTS: {
4197 if (!NeedsImports)
4198 break;
4199
4200 unsigned Idx = 0, N = Record.size();
4201 while (Idx < N) {
4202 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004203 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004204 std::string Filename = ReadString(Record, Idx);
4205 ResolveImportedPath(Filename, ModuleDir);
4206 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004207 }
4208 break;
4209 }
4210
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004211 default:
4212 // No other validation to perform.
4213 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004214 }
4215 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004216}
4217
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004218bool ASTReader::isAcceptableASTFile(
4219 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004220 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004221 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4222 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004223 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4224 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004225 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004226 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004227}
4228
Ben Langmuir2c9af442014-04-10 17:57:43 +00004229ASTReader::ASTReadResult
4230ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004231 // Enter the submodule block.
4232 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4233 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004234 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004235 }
4236
4237 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4238 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004239 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004240 RecordData Record;
4241 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004242 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4243
4244 switch (Entry.Kind) {
4245 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4246 case llvm::BitstreamEntry::Error:
4247 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004248 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004249 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004250 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004251 case llvm::BitstreamEntry::Record:
4252 // The interesting case.
4253 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004254 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004255
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004257 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004258 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004259 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4260
4261 if ((Kind == SUBMODULE_METADATA) != First) {
4262 Error("submodule metadata record should be at beginning of block");
4263 return Failure;
4264 }
4265 First = false;
4266
4267 // Submodule information is only valid if we have a current module.
4268 // FIXME: Should we error on these cases?
4269 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4270 Kind != SUBMODULE_DEFINITION)
4271 continue;
4272
4273 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004274 default: // Default behavior: ignore.
4275 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004276
Richard Smith03478d92014-10-23 22:12:14 +00004277 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004278 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004280 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004281 }
Richard Smith03478d92014-10-23 22:12:14 +00004282
Chris Lattner0e6c9402013-01-20 02:38:54 +00004283 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004284 unsigned Idx = 0;
4285 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4286 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4287 bool IsFramework = Record[Idx++];
4288 bool IsExplicit = Record[Idx++];
4289 bool IsSystem = Record[Idx++];
4290 bool IsExternC = Record[Idx++];
4291 bool InferSubmodules = Record[Idx++];
4292 bool InferExplicitSubmodules = Record[Idx++];
4293 bool InferExportWildcard = Record[Idx++];
4294 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004295
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004296 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004297 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004298 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004299
Guy Benyei11169dd2012-12-18 14:30:41 +00004300 // Retrieve this (sub)module from the module map, creating it if
4301 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004302 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004304
4305 // FIXME: set the definition loc for CurrentModule, or call
4306 // ModMap.setInferredModuleAllowedBy()
4307
Guy Benyei11169dd2012-12-18 14:30:41 +00004308 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4309 if (GlobalIndex >= SubmodulesLoaded.size() ||
4310 SubmodulesLoaded[GlobalIndex]) {
4311 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004312 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004313 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004314
Douglas Gregor7029ce12013-03-19 00:28:20 +00004315 if (!ParentModule) {
4316 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4317 if (CurFile != F.File) {
4318 if (!Diags.isDiagnosticInFlight()) {
4319 Diag(diag::err_module_file_conflict)
4320 << CurrentModule->getTopLevelModuleName()
4321 << CurFile->getName()
4322 << F.File->getName();
4323 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004324 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004325 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004326 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004327
4328 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004329 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004330
Adrian Prantl15bcf702015-06-30 17:39:43 +00004331 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004332 CurrentModule->IsFromModuleFile = true;
4333 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004334 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 CurrentModule->InferSubmodules = InferSubmodules;
4336 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4337 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004338 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 if (DeserializationListener)
4340 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4341
4342 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004343
Douglas Gregorfb912652013-03-20 21:10:35 +00004344 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004345 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004346 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004347 CurrentModule->UnresolvedConflicts.clear();
4348 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 break;
4350 }
4351
4352 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004353 std::string Filename = Blob;
4354 ResolveImportedPath(F, Filename);
4355 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004356 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004357 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4358 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004359 // This can be a spurious difference caused by changing the VFS to
4360 // point to a different copy of the file, and it is too late to
4361 // to rebuild safely.
4362 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4363 // after input file validation only real problems would remain and we
4364 // could just error. For now, assume it's okay.
4365 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004366 }
4367 }
4368 break;
4369 }
4370
Richard Smith202210b2014-10-24 20:23:01 +00004371 case SUBMODULE_HEADER:
4372 case SUBMODULE_EXCLUDED_HEADER:
4373 case SUBMODULE_PRIVATE_HEADER:
4374 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004375 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4376 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004377 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004378
Richard Smith202210b2014-10-24 20:23:01 +00004379 case SUBMODULE_TEXTUAL_HEADER:
4380 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4381 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4382 // them here.
4383 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004384
Guy Benyei11169dd2012-12-18 14:30:41 +00004385 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004386 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 break;
4388 }
4389
4390 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004391 std::string Dirname = Blob;
4392 ResolveImportedPath(F, Dirname);
4393 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004395 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4396 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004397 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4398 Error("mismatched umbrella directories in submodule");
4399 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004400 }
4401 }
4402 break;
4403 }
4404
4405 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004406 F.BaseSubmoduleID = getTotalNumSubmodules();
4407 F.LocalNumSubmodules = Record[0];
4408 unsigned LocalBaseSubmoduleID = Record[1];
4409 if (F.LocalNumSubmodules > 0) {
4410 // Introduce the global -> local mapping for submodules within this
4411 // module.
4412 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4413
4414 // Introduce the local -> global mapping for submodules within this
4415 // module.
4416 F.SubmoduleRemap.insertOrReplace(
4417 std::make_pair(LocalBaseSubmoduleID,
4418 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004419
Ben Langmuir52ca6782014-10-20 16:27:32 +00004420 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4421 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004422 break;
4423 }
4424
4425 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004426 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004427 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004428 Unresolved.File = &F;
4429 Unresolved.Mod = CurrentModule;
4430 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004431 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004432 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004433 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004434 }
4435 break;
4436 }
4437
4438 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004440 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 Unresolved.File = &F;
4442 Unresolved.Mod = CurrentModule;
4443 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004444 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004446 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004447 }
4448
4449 // Once we've loaded the set of exports, there's no reason to keep
4450 // the parsed, unresolved exports around.
4451 CurrentModule->UnresolvedExports.clear();
4452 break;
4453 }
4454 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004455 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004456 Context.getTargetInfo());
4457 break;
4458 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004459
4460 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004461 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004462 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004463 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004464
4465 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004466 CurrentModule->ConfigMacros.push_back(Blob.str());
4467 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004468
4469 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004470 UnresolvedModuleRef Unresolved;
4471 Unresolved.File = &F;
4472 Unresolved.Mod = CurrentModule;
4473 Unresolved.ID = Record[0];
4474 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4475 Unresolved.IsWildcard = false;
4476 Unresolved.String = Blob;
4477 UnresolvedModuleRefs.push_back(Unresolved);
4478 break;
4479 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004480 }
4481 }
4482}
4483
4484/// \brief Parse the record that corresponds to a LangOptions data
4485/// structure.
4486///
4487/// This routine parses the language options from the AST file and then gives
4488/// them to the AST listener if one is set.
4489///
4490/// \returns true if the listener deems the file unacceptable, false otherwise.
4491bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4492 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004493 ASTReaderListener &Listener,
4494 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 LangOptions LangOpts;
4496 unsigned Idx = 0;
4497#define LANGOPT(Name, Bits, Default, Description) \
4498 LangOpts.Name = Record[Idx++];
4499#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4500 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4501#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004502#define SANITIZER(NAME, ID) \
4503 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004504#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004505
Ben Langmuircd98cb72015-06-23 18:20:18 +00004506 for (unsigned N = Record[Idx++]; N; --N)
4507 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4508
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4510 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4511 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004512
Ben Langmuird4a667a2015-06-23 18:20:23 +00004513 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004514
4515 // Comment options.
4516 for (unsigned N = Record[Idx++]; N; --N) {
4517 LangOpts.CommentOpts.BlockCommandNames.push_back(
4518 ReadString(Record, Idx));
4519 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004520 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004521
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004522 return Listener.ReadLanguageOptions(LangOpts, Complain,
4523 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004524}
4525
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004526bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4527 ASTReaderListener &Listener,
4528 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004529 unsigned Idx = 0;
4530 TargetOptions TargetOpts;
4531 TargetOpts.Triple = ReadString(Record, Idx);
4532 TargetOpts.CPU = ReadString(Record, Idx);
4533 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004534 for (unsigned N = Record[Idx++]; N; --N) {
4535 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4536 }
4537 for (unsigned N = Record[Idx++]; N; --N) {
4538 TargetOpts.Features.push_back(ReadString(Record, Idx));
4539 }
4540
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004541 return Listener.ReadTargetOptions(TargetOpts, Complain,
4542 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004543}
4544
4545bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4546 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004547 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004548 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004549#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004550#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004551 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004552#include "clang/Basic/DiagnosticOptions.def"
4553
Richard Smith3be1cb22014-08-07 00:24:21 +00004554 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004555 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004556 for (unsigned N = Record[Idx++]; N; --N)
4557 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004558
4559 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4560}
4561
4562bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4563 ASTReaderListener &Listener) {
4564 FileSystemOptions FSOpts;
4565 unsigned Idx = 0;
4566 FSOpts.WorkingDir = ReadString(Record, Idx);
4567 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4568}
4569
4570bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4571 bool Complain,
4572 ASTReaderListener &Listener) {
4573 HeaderSearchOptions HSOpts;
4574 unsigned Idx = 0;
4575 HSOpts.Sysroot = ReadString(Record, Idx);
4576
4577 // Include entries.
4578 for (unsigned N = Record[Idx++]; N; --N) {
4579 std::string Path = ReadString(Record, Idx);
4580 frontend::IncludeDirGroup Group
4581 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004582 bool IsFramework = Record[Idx++];
4583 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004584 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4585 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004586 }
4587
4588 // System header prefixes.
4589 for (unsigned N = Record[Idx++]; N; --N) {
4590 std::string Prefix = ReadString(Record, Idx);
4591 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004592 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004593 }
4594
4595 HSOpts.ResourceDir = ReadString(Record, Idx);
4596 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004597 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004598 HSOpts.DisableModuleHash = Record[Idx++];
4599 HSOpts.UseBuiltinIncludes = Record[Idx++];
4600 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4601 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4602 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004603 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004604
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004605 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4606 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004607}
4608
4609bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4610 bool Complain,
4611 ASTReaderListener &Listener,
4612 std::string &SuggestedPredefines) {
4613 PreprocessorOptions PPOpts;
4614 unsigned Idx = 0;
4615
4616 // Macro definitions/undefs
4617 for (unsigned N = Record[Idx++]; N; --N) {
4618 std::string Macro = ReadString(Record, Idx);
4619 bool IsUndef = Record[Idx++];
4620 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4621 }
4622
4623 // Includes
4624 for (unsigned N = Record[Idx++]; N; --N) {
4625 PPOpts.Includes.push_back(ReadString(Record, Idx));
4626 }
4627
4628 // Macro Includes
4629 for (unsigned N = Record[Idx++]; N; --N) {
4630 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4631 }
4632
4633 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004634 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4636 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4637 PPOpts.ObjCXXARCStandardLibrary =
4638 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4639 SuggestedPredefines.clear();
4640 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4641 SuggestedPredefines);
4642}
4643
4644std::pair<ModuleFile *, unsigned>
4645ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4646 GlobalPreprocessedEntityMapType::iterator
4647 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4648 assert(I != GlobalPreprocessedEntityMap.end() &&
4649 "Corrupted global preprocessed entity map");
4650 ModuleFile *M = I->second;
4651 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4652 return std::make_pair(M, LocalIndex);
4653}
4654
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004655llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004656ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4657 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4658 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4659 Mod.NumPreprocessedEntities);
4660
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004661 return llvm::make_range(PreprocessingRecord::iterator(),
4662 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004663}
4664
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004665llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004666ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004667 return llvm::make_range(
4668 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4669 ModuleDeclIterator(this, &Mod,
4670 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004671}
4672
4673PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4674 PreprocessedEntityID PPID = Index+1;
4675 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4676 ModuleFile &M = *PPInfo.first;
4677 unsigned LocalIndex = PPInfo.second;
4678 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4679
Guy Benyei11169dd2012-12-18 14:30:41 +00004680 if (!PP.getPreprocessingRecord()) {
4681 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004682 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004683 }
4684
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004685 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4686 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4687
4688 llvm::BitstreamEntry Entry =
4689 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4690 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004691 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004692
Guy Benyei11169dd2012-12-18 14:30:41 +00004693 // Read the record.
4694 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4695 ReadSourceLocation(M, PPOffs.End));
4696 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004697 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004698 RecordData Record;
4699 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004700 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4701 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004702 switch (RecType) {
4703 case PPD_MACRO_EXPANSION: {
4704 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004705 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004706 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004707 if (isBuiltin)
4708 Name = getLocalIdentifier(M, Record[1]);
4709 else {
Richard Smith66a81862015-05-04 02:25:31 +00004710 PreprocessedEntityID GlobalID =
4711 getGlobalPreprocessedEntityID(M, Record[1]);
4712 Def = cast<MacroDefinitionRecord>(
4713 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004714 }
4715
4716 MacroExpansion *ME;
4717 if (isBuiltin)
4718 ME = new (PPRec) MacroExpansion(Name, Range);
4719 else
4720 ME = new (PPRec) MacroExpansion(Def, Range);
4721
4722 return ME;
4723 }
4724
4725 case PPD_MACRO_DEFINITION: {
4726 // Decode the identifier info and then check again; if the macro is
4727 // still defined and associated with the identifier,
4728 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004729 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004730
4731 if (DeserializationListener)
4732 DeserializationListener->MacroDefinitionRead(PPID, MD);
4733
4734 return MD;
4735 }
4736
4737 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004738 const char *FullFileNameStart = Blob.data() + Record[0];
4739 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004740 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004741 if (!FullFileName.empty())
4742 File = PP.getFileManager().getFile(FullFileName);
4743
4744 // FIXME: Stable encoding
4745 InclusionDirective::InclusionKind Kind
4746 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4747 InclusionDirective *ID
4748 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004749 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004750 Record[1], Record[3],
4751 File,
4752 Range);
4753 return ID;
4754 }
4755 }
4756
4757 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4758}
4759
4760/// \brief \arg SLocMapI points at a chunk of a module that contains no
4761/// preprocessed entities or the entities it contains are not the ones we are
4762/// looking for. Find the next module that contains entities and return the ID
4763/// of the first entry.
4764PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4765 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4766 ++SLocMapI;
4767 for (GlobalSLocOffsetMapType::const_iterator
4768 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4769 ModuleFile &M = *SLocMapI->second;
4770 if (M.NumPreprocessedEntities)
4771 return M.BasePreprocessedEntityID;
4772 }
4773
4774 return getTotalNumPreprocessedEntities();
4775}
4776
4777namespace {
4778
4779template <unsigned PPEntityOffset::*PPLoc>
4780struct PPEntityComp {
4781 const ASTReader &Reader;
4782 ModuleFile &M;
4783
4784 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4785
4786 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4787 SourceLocation LHS = getLoc(L);
4788 SourceLocation RHS = getLoc(R);
4789 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4790 }
4791
4792 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4793 SourceLocation LHS = getLoc(L);
4794 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4795 }
4796
4797 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4798 SourceLocation RHS = getLoc(R);
4799 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4800 }
4801
4802 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4803 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4804 }
4805};
4806
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004807}
Guy Benyei11169dd2012-12-18 14:30:41 +00004808
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004809PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4810 bool EndsAfter) const {
4811 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004812 return getTotalNumPreprocessedEntities();
4813
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004814 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4815 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004816 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4817 "Corrupted global sloc offset map");
4818
4819 if (SLocMapI->second->NumPreprocessedEntities == 0)
4820 return findNextPreprocessedEntity(SLocMapI);
4821
4822 ModuleFile &M = *SLocMapI->second;
4823 typedef const PPEntityOffset *pp_iterator;
4824 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4825 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4826
4827 size_t Count = M.NumPreprocessedEntities;
4828 size_t Half;
4829 pp_iterator First = pp_begin;
4830 pp_iterator PPI;
4831
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004832 if (EndsAfter) {
4833 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4834 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4835 } else {
4836 // Do a binary search manually instead of using std::lower_bound because
4837 // The end locations of entities may be unordered (when a macro expansion
4838 // is inside another macro argument), but for this case it is not important
4839 // whether we get the first macro expansion or its containing macro.
4840 while (Count > 0) {
4841 Half = Count / 2;
4842 PPI = First;
4843 std::advance(PPI, Half);
4844 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4845 Loc)) {
4846 First = PPI;
4847 ++First;
4848 Count = Count - Half - 1;
4849 } else
4850 Count = Half;
4851 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004852 }
4853
4854 if (PPI == pp_end)
4855 return findNextPreprocessedEntity(SLocMapI);
4856
4857 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4858}
4859
Guy Benyei11169dd2012-12-18 14:30:41 +00004860/// \brief Returns a pair of [Begin, End) indices of preallocated
4861/// preprocessed entities that \arg Range encompasses.
4862std::pair<unsigned, unsigned>
4863 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4864 if (Range.isInvalid())
4865 return std::make_pair(0,0);
4866 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4867
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004868 PreprocessedEntityID BeginID =
4869 findPreprocessedEntity(Range.getBegin(), false);
4870 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004871 return std::make_pair(BeginID, EndID);
4872}
4873
4874/// \brief Optionally returns true or false if the preallocated preprocessed
4875/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004876Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004877 FileID FID) {
4878 if (FID.isInvalid())
4879 return false;
4880
4881 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4882 ModuleFile &M = *PPInfo.first;
4883 unsigned LocalIndex = PPInfo.second;
4884 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4885
4886 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4887 if (Loc.isInvalid())
4888 return false;
4889
4890 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4891 return true;
4892 else
4893 return false;
4894}
4895
4896namespace {
4897 /// \brief Visitor used to search for information about a header file.
4898 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004899 const FileEntry *FE;
4900
David Blaikie05785d12013-02-20 22:23:23 +00004901 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004902
4903 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004904 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4905 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004906
4907 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004908 HeaderFileInfoLookupTable *Table
4909 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4910 if (!Table)
4911 return false;
4912
4913 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00004914 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 if (Pos == Table->end())
4916 return false;
4917
Richard Smithbdf2d932015-07-30 03:37:16 +00004918 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00004919 return true;
4920 }
4921
David Blaikie05785d12013-02-20 22:23:23 +00004922 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004923 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004924}
Guy Benyei11169dd2012-12-18 14:30:41 +00004925
4926HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004927 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004928 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004929 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004930 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004931
4932 return HeaderFileInfo();
4933}
4934
4935void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4936 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004937 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004938 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4939 ModuleFile &F = *(*I);
4940 unsigned Idx = 0;
4941 DiagStates.clear();
4942 assert(!Diag.DiagStates.empty());
4943 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4944 while (Idx < F.PragmaDiagMappings.size()) {
4945 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4946 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4947 if (DiagStateID != 0) {
4948 Diag.DiagStatePoints.push_back(
4949 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4950 FullSourceLoc(Loc, SourceMgr)));
4951 continue;
4952 }
4953
4954 assert(DiagStateID == 0);
4955 // A new DiagState was created here.
4956 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4957 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4958 DiagStates.push_back(NewState);
4959 Diag.DiagStatePoints.push_back(
4960 DiagnosticsEngine::DiagStatePoint(NewState,
4961 FullSourceLoc(Loc, SourceMgr)));
4962 while (1) {
4963 assert(Idx < F.PragmaDiagMappings.size() &&
4964 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4965 if (Idx >= F.PragmaDiagMappings.size()) {
4966 break; // Something is messed up but at least avoid infinite loop in
4967 // release build.
4968 }
4969 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4970 if (DiagID == (unsigned)-1) {
4971 break; // no more diag/map pairs for this location.
4972 }
Alp Tokerc726c362014-06-10 09:31:37 +00004973 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4974 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4975 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00004976 }
4977 }
4978 }
4979}
4980
4981/// \brief Get the correct cursor and offset for loading a type.
4982ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4983 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4984 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4985 ModuleFile *M = I->second;
4986 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4987}
4988
4989/// \brief Read and return the type with the given index..
4990///
4991/// The index is the type ID, shifted and minus the number of predefs. This
4992/// routine actually reads the record corresponding to the type at the given
4993/// location. It is a helper routine for GetType, which deals with reading type
4994/// IDs.
4995QualType ASTReader::readTypeRecord(unsigned Index) {
4996 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004997 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004998
4999 // Keep track of where we are in the stream, then jump back there
5000 // after reading this type.
5001 SavedStreamPosition SavedPosition(DeclsCursor);
5002
5003 ReadingKindTracker ReadingKind(Read_Type, *this);
5004
5005 // Note that we are loading a type record.
5006 Deserializing AType(this);
5007
5008 unsigned Idx = 0;
5009 DeclsCursor.JumpToBit(Loc.Offset);
5010 RecordData Record;
5011 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005012 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005013 case TYPE_EXT_QUAL: {
5014 if (Record.size() != 2) {
5015 Error("Incorrect encoding of extended qualifier type");
5016 return QualType();
5017 }
5018 QualType Base = readType(*Loc.F, Record, Idx);
5019 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5020 return Context.getQualifiedType(Base, Quals);
5021 }
5022
5023 case TYPE_COMPLEX: {
5024 if (Record.size() != 1) {
5025 Error("Incorrect encoding of complex type");
5026 return QualType();
5027 }
5028 QualType ElemType = readType(*Loc.F, Record, Idx);
5029 return Context.getComplexType(ElemType);
5030 }
5031
5032 case TYPE_POINTER: {
5033 if (Record.size() != 1) {
5034 Error("Incorrect encoding of pointer type");
5035 return QualType();
5036 }
5037 QualType PointeeType = readType(*Loc.F, Record, Idx);
5038 return Context.getPointerType(PointeeType);
5039 }
5040
Reid Kleckner8a365022013-06-24 17:51:48 +00005041 case TYPE_DECAYED: {
5042 if (Record.size() != 1) {
5043 Error("Incorrect encoding of decayed type");
5044 return QualType();
5045 }
5046 QualType OriginalType = readType(*Loc.F, Record, Idx);
5047 QualType DT = Context.getAdjustedParameterType(OriginalType);
5048 if (!isa<DecayedType>(DT))
5049 Error("Decayed type does not decay");
5050 return DT;
5051 }
5052
Reid Kleckner0503a872013-12-05 01:23:43 +00005053 case TYPE_ADJUSTED: {
5054 if (Record.size() != 2) {
5055 Error("Incorrect encoding of adjusted type");
5056 return QualType();
5057 }
5058 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5059 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5060 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5061 }
5062
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 case TYPE_BLOCK_POINTER: {
5064 if (Record.size() != 1) {
5065 Error("Incorrect encoding of block pointer type");
5066 return QualType();
5067 }
5068 QualType PointeeType = readType(*Loc.F, Record, Idx);
5069 return Context.getBlockPointerType(PointeeType);
5070 }
5071
5072 case TYPE_LVALUE_REFERENCE: {
5073 if (Record.size() != 2) {
5074 Error("Incorrect encoding of lvalue reference type");
5075 return QualType();
5076 }
5077 QualType PointeeType = readType(*Loc.F, Record, Idx);
5078 return Context.getLValueReferenceType(PointeeType, Record[1]);
5079 }
5080
5081 case TYPE_RVALUE_REFERENCE: {
5082 if (Record.size() != 1) {
5083 Error("Incorrect encoding of rvalue reference type");
5084 return QualType();
5085 }
5086 QualType PointeeType = readType(*Loc.F, Record, Idx);
5087 return Context.getRValueReferenceType(PointeeType);
5088 }
5089
5090 case TYPE_MEMBER_POINTER: {
5091 if (Record.size() != 2) {
5092 Error("Incorrect encoding of member pointer type");
5093 return QualType();
5094 }
5095 QualType PointeeType = readType(*Loc.F, Record, Idx);
5096 QualType ClassType = readType(*Loc.F, Record, Idx);
5097 if (PointeeType.isNull() || ClassType.isNull())
5098 return QualType();
5099
5100 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5101 }
5102
5103 case TYPE_CONSTANT_ARRAY: {
5104 QualType ElementType = readType(*Loc.F, Record, Idx);
5105 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5106 unsigned IndexTypeQuals = Record[2];
5107 unsigned Idx = 3;
5108 llvm::APInt Size = ReadAPInt(Record, Idx);
5109 return Context.getConstantArrayType(ElementType, Size,
5110 ASM, IndexTypeQuals);
5111 }
5112
5113 case TYPE_INCOMPLETE_ARRAY: {
5114 QualType ElementType = readType(*Loc.F, Record, Idx);
5115 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5116 unsigned IndexTypeQuals = Record[2];
5117 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5118 }
5119
5120 case TYPE_VARIABLE_ARRAY: {
5121 QualType ElementType = readType(*Loc.F, Record, Idx);
5122 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5123 unsigned IndexTypeQuals = Record[2];
5124 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5125 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5126 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5127 ASM, IndexTypeQuals,
5128 SourceRange(LBLoc, RBLoc));
5129 }
5130
5131 case TYPE_VECTOR: {
5132 if (Record.size() != 3) {
5133 Error("incorrect encoding of vector type in AST file");
5134 return QualType();
5135 }
5136
5137 QualType ElementType = readType(*Loc.F, Record, Idx);
5138 unsigned NumElements = Record[1];
5139 unsigned VecKind = Record[2];
5140 return Context.getVectorType(ElementType, NumElements,
5141 (VectorType::VectorKind)VecKind);
5142 }
5143
5144 case TYPE_EXT_VECTOR: {
5145 if (Record.size() != 3) {
5146 Error("incorrect encoding of extended vector type in AST file");
5147 return QualType();
5148 }
5149
5150 QualType ElementType = readType(*Loc.F, Record, Idx);
5151 unsigned NumElements = Record[1];
5152 return Context.getExtVectorType(ElementType, NumElements);
5153 }
5154
5155 case TYPE_FUNCTION_NO_PROTO: {
5156 if (Record.size() != 6) {
5157 Error("incorrect encoding of no-proto function type");
5158 return QualType();
5159 }
5160 QualType ResultType = readType(*Loc.F, Record, Idx);
5161 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5162 (CallingConv)Record[4], Record[5]);
5163 return Context.getFunctionNoProtoType(ResultType, Info);
5164 }
5165
5166 case TYPE_FUNCTION_PROTO: {
5167 QualType ResultType = readType(*Loc.F, Record, Idx);
5168
5169 FunctionProtoType::ExtProtoInfo EPI;
5170 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5171 /*hasregparm*/ Record[2],
5172 /*regparm*/ Record[3],
5173 static_cast<CallingConv>(Record[4]),
5174 /*produces*/ Record[5]);
5175
5176 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005177
5178 EPI.Variadic = Record[Idx++];
5179 EPI.HasTrailingReturn = Record[Idx++];
5180 EPI.TypeQuals = Record[Idx++];
5181 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005182 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005183 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005184
5185 unsigned NumParams = Record[Idx++];
5186 SmallVector<QualType, 16> ParamTypes;
5187 for (unsigned I = 0; I != NumParams; ++I)
5188 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5189
Jordan Rose5c382722013-03-08 21:51:21 +00005190 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005191 }
5192
5193 case TYPE_UNRESOLVED_USING: {
5194 unsigned Idx = 0;
5195 return Context.getTypeDeclType(
5196 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5197 }
5198
5199 case TYPE_TYPEDEF: {
5200 if (Record.size() != 2) {
5201 Error("incorrect encoding of typedef type");
5202 return QualType();
5203 }
5204 unsigned Idx = 0;
5205 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5206 QualType Canonical = readType(*Loc.F, Record, Idx);
5207 if (!Canonical.isNull())
5208 Canonical = Context.getCanonicalType(Canonical);
5209 return Context.getTypedefType(Decl, Canonical);
5210 }
5211
5212 case TYPE_TYPEOF_EXPR:
5213 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5214
5215 case TYPE_TYPEOF: {
5216 if (Record.size() != 1) {
5217 Error("incorrect encoding of typeof(type) in AST file");
5218 return QualType();
5219 }
5220 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5221 return Context.getTypeOfType(UnderlyingType);
5222 }
5223
5224 case TYPE_DECLTYPE: {
5225 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5226 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5227 }
5228
5229 case TYPE_UNARY_TRANSFORM: {
5230 QualType BaseType = readType(*Loc.F, Record, Idx);
5231 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5232 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5233 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5234 }
5235
Richard Smith74aeef52013-04-26 16:15:35 +00005236 case TYPE_AUTO: {
5237 QualType Deduced = readType(*Loc.F, Record, Idx);
5238 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005239 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005240 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005241 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005242
5243 case TYPE_RECORD: {
5244 if (Record.size() != 2) {
5245 Error("incorrect encoding of record type");
5246 return QualType();
5247 }
5248 unsigned Idx = 0;
5249 bool IsDependent = Record[Idx++];
5250 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5251 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5252 QualType T = Context.getRecordType(RD);
5253 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5254 return T;
5255 }
5256
5257 case TYPE_ENUM: {
5258 if (Record.size() != 2) {
5259 Error("incorrect encoding of enum type");
5260 return QualType();
5261 }
5262 unsigned Idx = 0;
5263 bool IsDependent = Record[Idx++];
5264 QualType T
5265 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5266 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5267 return T;
5268 }
5269
5270 case TYPE_ATTRIBUTED: {
5271 if (Record.size() != 3) {
5272 Error("incorrect encoding of attributed type");
5273 return QualType();
5274 }
5275 QualType modifiedType = readType(*Loc.F, Record, Idx);
5276 QualType equivalentType = readType(*Loc.F, Record, Idx);
5277 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5278 return Context.getAttributedType(kind, modifiedType, equivalentType);
5279 }
5280
5281 case TYPE_PAREN: {
5282 if (Record.size() != 1) {
5283 Error("incorrect encoding of paren type");
5284 return QualType();
5285 }
5286 QualType InnerType = readType(*Loc.F, Record, Idx);
5287 return Context.getParenType(InnerType);
5288 }
5289
5290 case TYPE_PACK_EXPANSION: {
5291 if (Record.size() != 2) {
5292 Error("incorrect encoding of pack expansion type");
5293 return QualType();
5294 }
5295 QualType Pattern = readType(*Loc.F, Record, Idx);
5296 if (Pattern.isNull())
5297 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005298 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005299 if (Record[1])
5300 NumExpansions = Record[1] - 1;
5301 return Context.getPackExpansionType(Pattern, NumExpansions);
5302 }
5303
5304 case TYPE_ELABORATED: {
5305 unsigned Idx = 0;
5306 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5307 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5308 QualType NamedType = readType(*Loc.F, Record, Idx);
5309 return Context.getElaboratedType(Keyword, NNS, NamedType);
5310 }
5311
5312 case TYPE_OBJC_INTERFACE: {
5313 unsigned Idx = 0;
5314 ObjCInterfaceDecl *ItfD
5315 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5316 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5317 }
5318
5319 case TYPE_OBJC_OBJECT: {
5320 unsigned Idx = 0;
5321 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005322 unsigned NumTypeArgs = Record[Idx++];
5323 SmallVector<QualType, 4> TypeArgs;
5324 for (unsigned I = 0; I != NumTypeArgs; ++I)
5325 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005326 unsigned NumProtos = Record[Idx++];
5327 SmallVector<ObjCProtocolDecl*, 4> Protos;
5328 for (unsigned I = 0; I != NumProtos; ++I)
5329 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005330 bool IsKindOf = Record[Idx++];
5331 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005332 }
5333
5334 case TYPE_OBJC_OBJECT_POINTER: {
5335 unsigned Idx = 0;
5336 QualType Pointee = readType(*Loc.F, Record, Idx);
5337 return Context.getObjCObjectPointerType(Pointee);
5338 }
5339
5340 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5341 unsigned Idx = 0;
5342 QualType Parm = readType(*Loc.F, Record, Idx);
5343 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005344 return Context.getSubstTemplateTypeParmType(
5345 cast<TemplateTypeParmType>(Parm),
5346 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005347 }
5348
5349 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5350 unsigned Idx = 0;
5351 QualType Parm = readType(*Loc.F, Record, Idx);
5352 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5353 return Context.getSubstTemplateTypeParmPackType(
5354 cast<TemplateTypeParmType>(Parm),
5355 ArgPack);
5356 }
5357
5358 case TYPE_INJECTED_CLASS_NAME: {
5359 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5360 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5361 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5362 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005363 const Type *T = nullptr;
5364 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5365 if (const Type *Existing = DI->getTypeForDecl()) {
5366 T = Existing;
5367 break;
5368 }
5369 }
5370 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005371 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005372 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5373 DI->setTypeForDecl(T);
5374 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005375 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005376 }
5377
5378 case TYPE_TEMPLATE_TYPE_PARM: {
5379 unsigned Idx = 0;
5380 unsigned Depth = Record[Idx++];
5381 unsigned Index = Record[Idx++];
5382 bool Pack = Record[Idx++];
5383 TemplateTypeParmDecl *D
5384 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5385 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5386 }
5387
5388 case TYPE_DEPENDENT_NAME: {
5389 unsigned Idx = 0;
5390 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5391 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005392 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005393 QualType Canon = readType(*Loc.F, Record, Idx);
5394 if (!Canon.isNull())
5395 Canon = Context.getCanonicalType(Canon);
5396 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5397 }
5398
5399 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5400 unsigned Idx = 0;
5401 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5402 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005403 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005404 unsigned NumArgs = Record[Idx++];
5405 SmallVector<TemplateArgument, 8> Args;
5406 Args.reserve(NumArgs);
5407 while (NumArgs--)
5408 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5409 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5410 Args.size(), Args.data());
5411 }
5412
5413 case TYPE_DEPENDENT_SIZED_ARRAY: {
5414 unsigned Idx = 0;
5415
5416 // ArrayType
5417 QualType ElementType = readType(*Loc.F, Record, Idx);
5418 ArrayType::ArraySizeModifier ASM
5419 = (ArrayType::ArraySizeModifier)Record[Idx++];
5420 unsigned IndexTypeQuals = Record[Idx++];
5421
5422 // DependentSizedArrayType
5423 Expr *NumElts = ReadExpr(*Loc.F);
5424 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5425
5426 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5427 IndexTypeQuals, Brackets);
5428 }
5429
5430 case TYPE_TEMPLATE_SPECIALIZATION: {
5431 unsigned Idx = 0;
5432 bool IsDependent = Record[Idx++];
5433 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5434 SmallVector<TemplateArgument, 8> Args;
5435 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5436 QualType Underlying = readType(*Loc.F, Record, Idx);
5437 QualType T;
5438 if (Underlying.isNull())
5439 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5440 Args.size());
5441 else
5442 T = Context.getTemplateSpecializationType(Name, Args.data(),
5443 Args.size(), Underlying);
5444 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5445 return T;
5446 }
5447
5448 case TYPE_ATOMIC: {
5449 if (Record.size() != 1) {
5450 Error("Incorrect encoding of atomic type");
5451 return QualType();
5452 }
5453 QualType ValueType = readType(*Loc.F, Record, Idx);
5454 return Context.getAtomicType(ValueType);
5455 }
5456 }
5457 llvm_unreachable("Invalid TypeCode!");
5458}
5459
Richard Smith564417a2014-03-20 21:47:22 +00005460void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5461 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005462 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005463 const RecordData &Record, unsigned &Idx) {
5464 ExceptionSpecificationType EST =
5465 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005466 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005467 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005468 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005469 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005470 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005471 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005472 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005473 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005474 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5475 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005476 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005477 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005478 }
5479}
5480
Guy Benyei11169dd2012-12-18 14:30:41 +00005481class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5482 ASTReader &Reader;
5483 ModuleFile &F;
5484 const ASTReader::RecordData &Record;
5485 unsigned &Idx;
5486
5487 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5488 unsigned &I) {
5489 return Reader.ReadSourceLocation(F, R, I);
5490 }
5491
5492 template<typename T>
5493 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5494 return Reader.ReadDeclAs<T>(F, Record, Idx);
5495 }
5496
5497public:
5498 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5499 const ASTReader::RecordData &Record, unsigned &Idx)
5500 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5501 { }
5502
5503 // We want compile-time assurance that we've enumerated all of
5504 // these, so unfortunately we have to declare them first, then
5505 // define them out-of-line.
5506#define ABSTRACT_TYPELOC(CLASS, PARENT)
5507#define TYPELOC(CLASS, PARENT) \
5508 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5509#include "clang/AST/TypeLocNodes.def"
5510
5511 void VisitFunctionTypeLoc(FunctionTypeLoc);
5512 void VisitArrayTypeLoc(ArrayTypeLoc);
5513};
5514
5515void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5516 // nothing to do
5517}
5518void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5519 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5520 if (TL.needsExtraLocalData()) {
5521 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5522 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5523 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5524 TL.setModeAttr(Record[Idx++]);
5525 }
5526}
5527void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5528 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5529}
5530void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5531 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5532}
Reid Kleckner8a365022013-06-24 17:51:48 +00005533void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5534 // nothing to do
5535}
Reid Kleckner0503a872013-12-05 01:23:43 +00005536void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5537 // nothing to do
5538}
Guy Benyei11169dd2012-12-18 14:30:41 +00005539void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5540 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5541}
5542void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5543 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5544}
5545void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5546 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5547}
5548void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5549 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5550 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5551}
5552void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5553 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5554 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5555 if (Record[Idx++])
5556 TL.setSizeExpr(Reader.ReadExpr(F));
5557 else
Craig Toppera13603a2014-05-22 05:54:18 +00005558 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005559}
5560void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5561 VisitArrayTypeLoc(TL);
5562}
5563void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5564 VisitArrayTypeLoc(TL);
5565}
5566void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5567 VisitArrayTypeLoc(TL);
5568}
5569void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5570 DependentSizedArrayTypeLoc TL) {
5571 VisitArrayTypeLoc(TL);
5572}
5573void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5574 DependentSizedExtVectorTypeLoc TL) {
5575 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5576}
5577void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5578 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5579}
5580void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5581 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5582}
5583void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5584 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5585 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5586 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5587 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005588 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5589 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005590 }
5591}
5592void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5593 VisitFunctionTypeLoc(TL);
5594}
5595void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5596 VisitFunctionTypeLoc(TL);
5597}
5598void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5599 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5600}
5601void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5602 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5603}
5604void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5605 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5606 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5607 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5608}
5609void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5610 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5611 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5612 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5613 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5614}
5615void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5616 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5617}
5618void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5619 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5620 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5621 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5622 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5623}
5624void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5625 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5626}
5627void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5628 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5629}
5630void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5631 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5632}
5633void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5634 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5635 if (TL.hasAttrOperand()) {
5636 SourceRange range;
5637 range.setBegin(ReadSourceLocation(Record, Idx));
5638 range.setEnd(ReadSourceLocation(Record, Idx));
5639 TL.setAttrOperandParensRange(range);
5640 }
5641 if (TL.hasAttrExprOperand()) {
5642 if (Record[Idx++])
5643 TL.setAttrExprOperand(Reader.ReadExpr(F));
5644 else
Craig Toppera13603a2014-05-22 05:54:18 +00005645 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005646 } else if (TL.hasAttrEnumOperand())
5647 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5648}
5649void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5650 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5651}
5652void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5653 SubstTemplateTypeParmTypeLoc TL) {
5654 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5655}
5656void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5657 SubstTemplateTypeParmPackTypeLoc TL) {
5658 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5659}
5660void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5661 TemplateSpecializationTypeLoc TL) {
5662 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5663 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5664 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5665 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5666 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5667 TL.setArgLocInfo(i,
5668 Reader.GetTemplateArgumentLocInfo(F,
5669 TL.getTypePtr()->getArg(i).getKind(),
5670 Record, Idx));
5671}
5672void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5673 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5674 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5675}
5676void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5677 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5678 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5679}
5680void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5681 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5682}
5683void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5684 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5685 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5686 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5687}
5688void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5689 DependentTemplateSpecializationTypeLoc TL) {
5690 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5691 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5692 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5693 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5694 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5695 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5696 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5697 TL.setArgLocInfo(I,
5698 Reader.GetTemplateArgumentLocInfo(F,
5699 TL.getTypePtr()->getArg(I).getKind(),
5700 Record, Idx));
5701}
5702void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5703 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5704}
5705void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5706 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5707}
5708void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5709 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005710 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5711 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5712 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5713 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5714 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5715 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005716 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5717 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5718}
5719void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5720 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5721}
5722void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5723 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5724 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5725 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5726}
5727
5728TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5729 const RecordData &Record,
5730 unsigned &Idx) {
5731 QualType InfoTy = readType(F, Record, Idx);
5732 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005733 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005734
5735 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5736 TypeLocReader TLR(*this, F, Record, Idx);
5737 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5738 TLR.Visit(TL);
5739 return TInfo;
5740}
5741
5742QualType ASTReader::GetType(TypeID ID) {
5743 unsigned FastQuals = ID & Qualifiers::FastMask;
5744 unsigned Index = ID >> Qualifiers::FastWidth;
5745
5746 if (Index < NUM_PREDEF_TYPE_IDS) {
5747 QualType T;
5748 switch ((PredefinedTypeIDs)Index) {
5749 case PREDEF_TYPE_NULL_ID: return QualType();
5750 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5751 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5752
5753 case PREDEF_TYPE_CHAR_U_ID:
5754 case PREDEF_TYPE_CHAR_S_ID:
5755 // FIXME: Check that the signedness of CharTy is correct!
5756 T = Context.CharTy;
5757 break;
5758
5759 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5760 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5761 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5762 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5763 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5764 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5765 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5766 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5767 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5768 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5769 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5770 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5771 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5772 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5773 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5774 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5775 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5776 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5777 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5778 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5779 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5780 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5781 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5782 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5783 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5784 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5785 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5786 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005787 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5788 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5789 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5790 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5791 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5792 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005793 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005794 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005795 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5796
5797 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5798 T = Context.getAutoRRefDeductType();
5799 break;
5800
5801 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5802 T = Context.ARCUnbridgedCastTy;
5803 break;
5804
Guy Benyei11169dd2012-12-18 14:30:41 +00005805 case PREDEF_TYPE_BUILTIN_FN:
5806 T = Context.BuiltinFnTy;
5807 break;
5808 }
5809
5810 assert(!T.isNull() && "Unknown predefined type");
5811 return T.withFastQualifiers(FastQuals);
5812 }
5813
5814 Index -= NUM_PREDEF_TYPE_IDS;
5815 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5816 if (TypesLoaded[Index].isNull()) {
5817 TypesLoaded[Index] = readTypeRecord(Index);
5818 if (TypesLoaded[Index].isNull())
5819 return QualType();
5820
5821 TypesLoaded[Index]->setFromAST();
5822 if (DeserializationListener)
5823 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5824 TypesLoaded[Index]);
5825 }
5826
5827 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5828}
5829
5830QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5831 return GetType(getGlobalTypeID(F, LocalID));
5832}
5833
5834serialization::TypeID
5835ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5836 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5837 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5838
5839 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5840 return LocalID;
5841
5842 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5843 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5844 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5845
5846 unsigned GlobalIndex = LocalIndex + I->second;
5847 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5848}
5849
5850TemplateArgumentLocInfo
5851ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5852 TemplateArgument::ArgKind Kind,
5853 const RecordData &Record,
5854 unsigned &Index) {
5855 switch (Kind) {
5856 case TemplateArgument::Expression:
5857 return ReadExpr(F);
5858 case TemplateArgument::Type:
5859 return GetTypeSourceInfo(F, Record, Index);
5860 case TemplateArgument::Template: {
5861 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5862 Index);
5863 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5864 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5865 SourceLocation());
5866 }
5867 case TemplateArgument::TemplateExpansion: {
5868 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5869 Index);
5870 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5871 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5872 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5873 EllipsisLoc);
5874 }
5875 case TemplateArgument::Null:
5876 case TemplateArgument::Integral:
5877 case TemplateArgument::Declaration:
5878 case TemplateArgument::NullPtr:
5879 case TemplateArgument::Pack:
5880 // FIXME: Is this right?
5881 return TemplateArgumentLocInfo();
5882 }
5883 llvm_unreachable("unexpected template argument loc");
5884}
5885
5886TemplateArgumentLoc
5887ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5888 const RecordData &Record, unsigned &Index) {
5889 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5890
5891 if (Arg.getKind() == TemplateArgument::Expression) {
5892 if (Record[Index++]) // bool InfoHasSameExpr.
5893 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5894 }
5895 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5896 Record, Index));
5897}
5898
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005899const ASTTemplateArgumentListInfo*
5900ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5901 const RecordData &Record,
5902 unsigned &Index) {
5903 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5904 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5905 unsigned NumArgsAsWritten = Record[Index++];
5906 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5907 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5908 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5909 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5910}
5911
Guy Benyei11169dd2012-12-18 14:30:41 +00005912Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5913 return GetDecl(ID);
5914}
5915
Richard Smith50895422015-01-31 03:04:55 +00005916template<typename TemplateSpecializationDecl>
5917static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5918 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5919 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5920}
5921
Richard Smith053f6c62014-05-16 23:01:30 +00005922void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005923 if (NumCurrentElementsDeserializing) {
5924 // We arrange to not care about the complete redeclaration chain while we're
5925 // deserializing. Just remember that the AST has marked this one as complete
5926 // but that it's not actually complete yet, so we know we still need to
5927 // complete it later.
5928 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5929 return;
5930 }
5931
Richard Smith053f6c62014-05-16 23:01:30 +00005932 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5933
Richard Smith053f6c62014-05-16 23:01:30 +00005934 // If this is a named declaration, complete it by looking it up
5935 // within its context.
5936 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005937 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005938 // all mergeable entities within it.
5939 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5940 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5941 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00005942 if (!getContext().getLangOpts().CPlusPlus &&
5943 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00005944 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00005945 // the identifier instead. (For C++ modules, we don't store decls
5946 // in the serialized identifier table, so we do the lookup in the TU.)
5947 auto *II = Name.getAsIdentifierInfo();
5948 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00005949 if (II->isOutOfDate())
5950 updateOutOfDateIdentifier(*II);
5951 } else
5952 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005953 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00005954 // Find all declarations of this kind from the relevant context.
5955 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
5956 auto *DC = cast<DeclContext>(DCDecl);
5957 SmallVector<Decl*, 8> Decls;
5958 FindExternalLexicalDecls(
5959 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
5960 }
Richard Smith053f6c62014-05-16 23:01:30 +00005961 }
5962 }
Richard Smith50895422015-01-31 03:04:55 +00005963
5964 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5965 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5966 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5967 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5968 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5969 if (auto *Template = FD->getPrimaryTemplate())
5970 Template->LoadLazySpecializations();
5971 }
Richard Smith053f6c62014-05-16 23:01:30 +00005972}
5973
Richard Smithc2bb8182015-03-24 06:36:48 +00005974uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5975 const RecordData &Record,
5976 unsigned &Idx) {
5977 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5978 Error("malformed AST file: missing C++ ctor initializers");
5979 return 0;
5980 }
5981
5982 unsigned LocalID = Record[Idx++];
5983 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
5984}
5985
5986CXXCtorInitializer **
5987ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
5988 RecordLocation Loc = getLocalBitOffset(Offset);
5989 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
5990 SavedStreamPosition SavedPosition(Cursor);
5991 Cursor.JumpToBit(Loc.Offset);
5992 ReadingKindTracker ReadingKind(Read_Decl, *this);
5993
5994 RecordData Record;
5995 unsigned Code = Cursor.ReadCode();
5996 unsigned RecCode = Cursor.readRecord(Code, Record);
5997 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
5998 Error("malformed AST file: missing C++ ctor initializers");
5999 return nullptr;
6000 }
6001
6002 unsigned Idx = 0;
6003 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6004}
6005
Richard Smithcd45dbc2014-04-19 03:48:30 +00006006uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6007 const RecordData &Record,
6008 unsigned &Idx) {
6009 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6010 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006011 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006012 }
6013
Guy Benyei11169dd2012-12-18 14:30:41 +00006014 unsigned LocalID = Record[Idx++];
6015 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6016}
6017
6018CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6019 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006020 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006021 SavedStreamPosition SavedPosition(Cursor);
6022 Cursor.JumpToBit(Loc.Offset);
6023 ReadingKindTracker ReadingKind(Read_Decl, *this);
6024 RecordData Record;
6025 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006026 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006027 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006028 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006029 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006030 }
6031
6032 unsigned Idx = 0;
6033 unsigned NumBases = Record[Idx++];
6034 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6035 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6036 for (unsigned I = 0; I != NumBases; ++I)
6037 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6038 return Bases;
6039}
6040
6041serialization::DeclID
6042ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6043 if (LocalID < NUM_PREDEF_DECL_IDS)
6044 return LocalID;
6045
6046 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6047 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6048 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6049
6050 return LocalID + I->second;
6051}
6052
6053bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6054 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006055 // Predefined decls aren't from any module.
6056 if (ID < NUM_PREDEF_DECL_IDS)
6057 return false;
6058
Richard Smithbcda1a92015-07-12 23:51:20 +00006059 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6060 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006061}
6062
Douglas Gregor9f782892013-01-21 15:25:38 +00006063ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006064 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006065 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006066 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6067 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6068 return I->second;
6069}
6070
6071SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6072 if (ID < NUM_PREDEF_DECL_IDS)
6073 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006074
Guy Benyei11169dd2012-12-18 14:30:41 +00006075 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6076
6077 if (Index > DeclsLoaded.size()) {
6078 Error("declaration ID out-of-range for AST file");
6079 return SourceLocation();
6080 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006081
Guy Benyei11169dd2012-12-18 14:30:41 +00006082 if (Decl *D = DeclsLoaded[Index])
6083 return D->getLocation();
6084
6085 unsigned RawLocation = 0;
6086 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6087 return ReadSourceLocation(*Rec.F, RawLocation);
6088}
6089
Richard Smithfe620d22015-03-05 23:24:12 +00006090static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6091 switch (ID) {
6092 case PREDEF_DECL_NULL_ID:
6093 return nullptr;
6094
6095 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6096 return Context.getTranslationUnitDecl();
6097
6098 case PREDEF_DECL_OBJC_ID_ID:
6099 return Context.getObjCIdDecl();
6100
6101 case PREDEF_DECL_OBJC_SEL_ID:
6102 return Context.getObjCSelDecl();
6103
6104 case PREDEF_DECL_OBJC_CLASS_ID:
6105 return Context.getObjCClassDecl();
6106
6107 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6108 return Context.getObjCProtocolDecl();
6109
6110 case PREDEF_DECL_INT_128_ID:
6111 return Context.getInt128Decl();
6112
6113 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6114 return Context.getUInt128Decl();
6115
6116 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6117 return Context.getObjCInstanceTypeDecl();
6118
6119 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6120 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006121
Richard Smith9b88a4c2015-07-27 05:40:23 +00006122 case PREDEF_DECL_VA_LIST_TAG:
6123 return Context.getVaListTagDecl();
6124
Richard Smithf19e1272015-03-07 00:04:49 +00006125 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6126 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006127 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006128 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006129}
6130
Richard Smithcd45dbc2014-04-19 03:48:30 +00006131Decl *ASTReader::GetExistingDecl(DeclID ID) {
6132 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006133 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6134 if (D) {
6135 // Track that we have merged the declaration with ID \p ID into the
6136 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006137 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006138 if (Merged.empty())
6139 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006140 }
Richard Smithfe620d22015-03-05 23:24:12 +00006141 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006142 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006143
Guy Benyei11169dd2012-12-18 14:30:41 +00006144 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6145
6146 if (Index >= DeclsLoaded.size()) {
6147 assert(0 && "declaration ID out-of-range for AST file");
6148 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006149 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006150 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006151
6152 return DeclsLoaded[Index];
6153}
6154
6155Decl *ASTReader::GetDecl(DeclID ID) {
6156 if (ID < NUM_PREDEF_DECL_IDS)
6157 return GetExistingDecl(ID);
6158
6159 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6160
6161 if (Index >= DeclsLoaded.size()) {
6162 assert(0 && "declaration ID out-of-range for AST file");
6163 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006164 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006165 }
6166
Guy Benyei11169dd2012-12-18 14:30:41 +00006167 if (!DeclsLoaded[Index]) {
6168 ReadDeclRecord(ID);
6169 if (DeserializationListener)
6170 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6171 }
6172
6173 return DeclsLoaded[Index];
6174}
6175
6176DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6177 DeclID GlobalID) {
6178 if (GlobalID < NUM_PREDEF_DECL_IDS)
6179 return GlobalID;
6180
6181 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6182 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6183 ModuleFile *Owner = I->second;
6184
6185 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6186 = M.GlobalToLocalDeclIDs.find(Owner);
6187 if (Pos == M.GlobalToLocalDeclIDs.end())
6188 return 0;
6189
6190 return GlobalID - Owner->BaseDeclID + Pos->second;
6191}
6192
6193serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6194 const RecordData &Record,
6195 unsigned &Idx) {
6196 if (Idx >= Record.size()) {
6197 Error("Corrupted AST file");
6198 return 0;
6199 }
6200
6201 return getGlobalDeclID(F, Record[Idx++]);
6202}
6203
6204/// \brief Resolve the offset of a statement into a statement.
6205///
6206/// This operation will read a new statement from the external
6207/// source each time it is called, and is meant to be used via a
6208/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6209Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6210 // Switch case IDs are per Decl.
6211 ClearSwitchCaseIDs();
6212
6213 // Offset here is a global offset across the entire chain.
6214 RecordLocation Loc = getLocalBitOffset(Offset);
6215 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6216 return ReadStmtFromStream(*Loc.F);
6217}
6218
Richard Smith3cb15722015-08-05 22:41:45 +00006219void ASTReader::FindExternalLexicalDecls(
6220 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6221 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006222 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6223
Richard Smith9ccdd932015-08-06 22:14:12 +00006224 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006225 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6226 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6227 auto K = (Decl::Kind)+LexicalDecls[I];
6228 if (!IsKindWeWant(K))
6229 continue;
6230
6231 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6232
6233 // Don't add predefined declarations to the lexical context more
6234 // than once.
6235 if (ID < NUM_PREDEF_DECL_IDS) {
6236 if (PredefsVisited[ID])
6237 continue;
6238
6239 PredefsVisited[ID] = true;
6240 }
6241
6242 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006243 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006244 if (!DC->isDeclInLexicalTraversal(D))
6245 Decls.push_back(D);
6246 }
6247 }
6248 };
6249
6250 if (isa<TranslationUnitDecl>(DC)) {
6251 for (auto Lexical : TULexicalDecls)
6252 Visit(Lexical.first, Lexical.second);
6253 } else {
6254 auto I = LexicalDecls.find(DC);
6255 if (I != LexicalDecls.end())
6256 Visit(getOwningModuleFile(cast<Decl>(DC)), I->second);
6257 }
6258
Guy Benyei11169dd2012-12-18 14:30:41 +00006259 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006260}
6261
6262namespace {
6263
6264class DeclIDComp {
6265 ASTReader &Reader;
6266 ModuleFile &Mod;
6267
6268public:
6269 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6270
6271 bool operator()(LocalDeclID L, LocalDeclID R) const {
6272 SourceLocation LHS = getLocation(L);
6273 SourceLocation RHS = getLocation(R);
6274 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6275 }
6276
6277 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6278 SourceLocation RHS = getLocation(R);
6279 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6280 }
6281
6282 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6283 SourceLocation LHS = getLocation(L);
6284 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6285 }
6286
6287 SourceLocation getLocation(LocalDeclID ID) const {
6288 return Reader.getSourceManager().getFileLoc(
6289 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6290 }
6291};
6292
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006293}
Guy Benyei11169dd2012-12-18 14:30:41 +00006294
6295void ASTReader::FindFileRegionDecls(FileID File,
6296 unsigned Offset, unsigned Length,
6297 SmallVectorImpl<Decl *> &Decls) {
6298 SourceManager &SM = getSourceManager();
6299
6300 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6301 if (I == FileDeclIDs.end())
6302 return;
6303
6304 FileDeclsInfo &DInfo = I->second;
6305 if (DInfo.Decls.empty())
6306 return;
6307
6308 SourceLocation
6309 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6310 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6311
6312 DeclIDComp DIDComp(*this, *DInfo.Mod);
6313 ArrayRef<serialization::LocalDeclID>::iterator
6314 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6315 BeginLoc, DIDComp);
6316 if (BeginIt != DInfo.Decls.begin())
6317 --BeginIt;
6318
6319 // If we are pointing at a top-level decl inside an objc container, we need
6320 // to backtrack until we find it otherwise we will fail to report that the
6321 // region overlaps with an objc container.
6322 while (BeginIt != DInfo.Decls.begin() &&
6323 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6324 ->isTopLevelDeclInObjCContainer())
6325 --BeginIt;
6326
6327 ArrayRef<serialization::LocalDeclID>::iterator
6328 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6329 EndLoc, DIDComp);
6330 if (EndIt != DInfo.Decls.end())
6331 ++EndIt;
6332
6333 for (ArrayRef<serialization::LocalDeclID>::iterator
6334 DIt = BeginIt; DIt != EndIt; ++DIt)
6335 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6336}
6337
Richard Smith3b637412015-07-14 18:42:41 +00006338/// \brief Retrieve the "definitive" module file for the definition of the
6339/// given declaration context, if there is one.
6340///
6341/// The "definitive" module file is the only place where we need to look to
6342/// find information about the declarations within the given declaration
6343/// context. For example, C++ and Objective-C classes, C structs/unions, and
6344/// Objective-C protocols, categories, and extensions are all defined in a
6345/// single place in the source code, so they have definitive module files
6346/// associated with them. C++ namespaces, on the other hand, can have
6347/// definitions in multiple different module files.
6348///
6349/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6350/// NDEBUG checking.
6351static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6352 ASTReader &Reader) {
6353 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6354 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6355
6356 return nullptr;
6357}
6358
Guy Benyei11169dd2012-12-18 14:30:41 +00006359namespace {
6360 /// \brief ModuleFile visitor used to perform name lookup into a
6361 /// declaration context.
6362 class DeclContextNameLookupVisitor {
6363 ASTReader &Reader;
Richard Smithf13c68d2015-08-06 21:05:21 +00006364 const DeclContext *Context;
Guy Benyei11169dd2012-12-18 14:30:41 +00006365 DeclarationName Name;
Richard Smith3b637412015-07-14 18:42:41 +00006366 ASTDeclContextNameLookupTrait::DeclNameKey NameKey;
6367 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00006368 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006369 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006370
6371 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006372 DeclContextNameLookupVisitor(ASTReader &Reader,
Richard Smithf13c68d2015-08-06 21:05:21 +00006373 const DeclContext *Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00006374 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006375 SmallVectorImpl<NamedDecl *> &Decls,
6376 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
Richard Smithf13c68d2015-08-06 21:05:21 +00006377 : Reader(Reader), Context(Context), Name(Name),
Richard Smith3b637412015-07-14 18:42:41 +00006378 NameKey(ASTDeclContextNameLookupTrait::GetInternalKey(Name)),
6379 NameHash(ASTDeclContextNameLookupTrait::ComputeHash(NameKey)),
6380 Decls(Decls), DeclSet(DeclSet) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006381
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006382 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006383 // Check whether we have any visible declaration information for
6384 // this context in this module.
Richard Smithf13c68d2015-08-06 21:05:21 +00006385 auto Info = M.DeclContextInfos.find(Context);
6386 if (Info == M.DeclContextInfos.end() || !Info->second.NameLookupTableData)
Guy Benyei11169dd2012-12-18 14:30:41 +00006387 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006388
Guy Benyei11169dd2012-12-18 14:30:41 +00006389 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006390 ASTDeclContextNameLookupTable *LookupTable =
Richard Smithf13c68d2015-08-06 21:05:21 +00006391 Info->second.NameLookupTableData;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006392 ASTDeclContextNameLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00006393 LookupTable->find_hashed(NameKey, NameHash);
Guy Benyei11169dd2012-12-18 14:30:41 +00006394 if (Pos == LookupTable->end())
6395 return false;
6396
6397 bool FoundAnything = false;
6398 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6399 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006400 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006401 if (!ND)
6402 continue;
6403
Richard Smithbdf2d932015-07-30 03:37:16 +00006404 if (ND->getDeclName() != Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006405 // A name might be null because the decl's redeclarable part is
6406 // currently read before reading its name. The lookup is triggered by
6407 // building that decl (likely indirectly), and so it is later in the
6408 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006409 // FIXME: This should not happen; deserializing declarations should
6410 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006411 continue;
6412 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006413
Guy Benyei11169dd2012-12-18 14:30:41 +00006414 // Record this declaration.
6415 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006416 if (DeclSet.insert(ND).second)
6417 Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006418 }
6419
6420 return FoundAnything;
6421 }
6422 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006423}
Guy Benyei11169dd2012-12-18 14:30:41 +00006424
Richard Smith9ce12e32013-02-07 03:30:24 +00006425bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006426ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6427 DeclarationName Name) {
6428 assert(DC->hasExternalVisibleStorage() &&
6429 "DeclContext has no visible decls in storage");
6430 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006431 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006432
Richard Smith8c913ec2014-08-14 02:21:01 +00006433 Deserializing LookupResults(this);
6434
Guy Benyei11169dd2012-12-18 14:30:41 +00006435 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006436 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006437
Richard Smithf13c68d2015-08-06 21:05:21 +00006438 DeclContextNameLookupVisitor Visitor(*this, DC, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006439
Richard Smithf13c68d2015-08-06 21:05:21 +00006440 // If we can definitively determine which module file to look into,
6441 // only look there. Otherwise, look in all module files.
6442 if (ModuleFile *Definitive = getDefinitiveModuleFileFor(DC, *this))
6443 Visitor(*Definitive);
6444 else
6445 ModuleMgr.visit(Visitor);
Richard Smithcd45dbc2014-04-19 03:48:30 +00006446
Guy Benyei11169dd2012-12-18 14:30:41 +00006447 ++NumVisibleDeclContextsRead;
6448 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006449 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006450}
6451
6452namespace {
6453 /// \brief ModuleFile visitor used to retrieve all visible names in a
6454 /// declaration context.
6455 class DeclContextAllNamesVisitor {
6456 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006457 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006458 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006459 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006460 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006461
6462 public:
6463 DeclContextAllNamesVisitor(ASTReader &Reader,
6464 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006465 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006466 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006467
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006468 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006469 // Check whether we have any visible declaration information for
6470 // this context in this module.
6471 ModuleFile::DeclContextInfosMap::iterator Info;
6472 bool FoundInfo = false;
Richard Smithbdf2d932015-07-30 03:37:16 +00006473 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
6474 Info = M.DeclContextInfos.find(Contexts[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006475 if (Info != M.DeclContextInfos.end() &&
6476 Info->second.NameLookupTableData) {
6477 FoundInfo = true;
6478 break;
6479 }
6480 }
6481
6482 if (!FoundInfo)
6483 return false;
6484
Richard Smith52e3fba2014-03-11 07:17:35 +00006485 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006486 Info->second.NameLookupTableData;
6487 bool FoundAnything = false;
6488 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006489 I = LookupTable->data_begin(), E = LookupTable->data_end();
6490 I != E;
6491 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006492 ASTDeclContextNameLookupTrait::data_type Data = *I;
6493 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006494 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006495 if (!ND)
6496 continue;
6497
6498 // Record this declaration.
6499 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006500 if (DeclSet.insert(ND).second)
6501 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006502 }
6503 }
6504
Richard Smithbdf2d932015-07-30 03:37:16 +00006505 return FoundAnything && !VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006506 }
6507 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006508}
Guy Benyei11169dd2012-12-18 14:30:41 +00006509
6510void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6511 if (!DC->hasExternalVisibleStorage())
6512 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006513 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006514
6515 // Compute the declaration contexts we need to look into. Multiple such
6516 // declaration contexts occur when two declaration contexts from disjoint
6517 // modules get merged, e.g., when two namespaces with the same name are
6518 // independently defined in separate modules.
6519 SmallVector<const DeclContext *, 2> Contexts;
6520 Contexts.push_back(DC);
6521
6522 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006523 KeyDeclsMap::iterator Key =
6524 KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6525 if (Key != KeyDecls.end()) {
6526 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6527 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006528 }
6529 }
6530
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006531 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6532 /*VisitAll=*/DC->isFileContext());
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006533 ModuleMgr.visit(Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006534 ++NumVisibleDeclContextsRead;
6535
Craig Topper79be4cd2013-07-05 04:33:53 +00006536 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006537 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6538 }
6539 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6540}
6541
6542/// \brief Under non-PCH compilation the consumer receives the objc methods
6543/// before receiving the implementation, and codegen depends on this.
6544/// We simulate this by deserializing and passing to consumer the methods of the
6545/// implementation before passing the deserialized implementation decl.
6546static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6547 ASTConsumer *Consumer) {
6548 assert(ImplD && Consumer);
6549
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006550 for (auto *I : ImplD->methods())
6551 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006552
6553 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6554}
6555
6556void ASTReader::PassInterestingDeclsToConsumer() {
6557 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006558
6559 if (PassingDeclsToConsumer)
6560 return;
6561
6562 // Guard variable to avoid recursively redoing the process of passing
6563 // decls to consumer.
6564 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6565 true);
6566
Richard Smith9e2341d2015-03-23 03:25:59 +00006567 // Ensure that we've loaded all potentially-interesting declarations
6568 // that need to be eagerly loaded.
6569 for (auto ID : EagerlyDeserializedDecls)
6570 GetDecl(ID);
6571 EagerlyDeserializedDecls.clear();
6572
Guy Benyei11169dd2012-12-18 14:30:41 +00006573 while (!InterestingDecls.empty()) {
6574 Decl *D = InterestingDecls.front();
6575 InterestingDecls.pop_front();
6576
6577 PassInterestingDeclToConsumer(D);
6578 }
6579}
6580
6581void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6582 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6583 PassObjCImplDeclToConsumer(ImplD, Consumer);
6584 else
6585 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6586}
6587
6588void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6589 this->Consumer = Consumer;
6590
Richard Smith9e2341d2015-03-23 03:25:59 +00006591 if (Consumer)
6592 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006593
6594 if (DeserializationListener)
6595 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006596}
6597
6598void ASTReader::PrintStats() {
6599 std::fprintf(stderr, "*** AST File Statistics:\n");
6600
6601 unsigned NumTypesLoaded
6602 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6603 QualType());
6604 unsigned NumDeclsLoaded
6605 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006606 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006607 unsigned NumIdentifiersLoaded
6608 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6609 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006610 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006611 unsigned NumMacrosLoaded
6612 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6613 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006614 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006615 unsigned NumSelectorsLoaded
6616 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6617 SelectorsLoaded.end(),
6618 Selector());
6619
6620 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6621 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6622 NumSLocEntriesRead, TotalNumSLocEntries,
6623 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6624 if (!TypesLoaded.empty())
6625 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6626 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6627 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6628 if (!DeclsLoaded.empty())
6629 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6630 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6631 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6632 if (!IdentifiersLoaded.empty())
6633 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6634 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6635 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6636 if (!MacrosLoaded.empty())
6637 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6638 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6639 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6640 if (!SelectorsLoaded.empty())
6641 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6642 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6643 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6644 if (TotalNumStatements)
6645 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6646 NumStatementsRead, TotalNumStatements,
6647 ((float)NumStatementsRead/TotalNumStatements * 100));
6648 if (TotalNumMacros)
6649 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6650 NumMacrosRead, TotalNumMacros,
6651 ((float)NumMacrosRead/TotalNumMacros * 100));
6652 if (TotalLexicalDeclContexts)
6653 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6654 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6655 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6656 * 100));
6657 if (TotalVisibleDeclContexts)
6658 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6659 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6660 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6661 * 100));
6662 if (TotalNumMethodPoolEntries) {
6663 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6664 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6665 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6666 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006667 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006668 if (NumMethodPoolLookups) {
6669 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6670 NumMethodPoolHits, NumMethodPoolLookups,
6671 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6672 }
6673 if (NumMethodPoolTableLookups) {
6674 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6675 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6676 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6677 * 100.0));
6678 }
6679
Douglas Gregor00a50f72013-01-25 00:38:33 +00006680 if (NumIdentifierLookupHits) {
6681 std::fprintf(stderr,
6682 " %u / %u identifier table lookups succeeded (%f%%)\n",
6683 NumIdentifierLookupHits, NumIdentifierLookups,
6684 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6685 }
6686
Douglas Gregore060e572013-01-25 01:03:03 +00006687 if (GlobalIndex) {
6688 std::fprintf(stderr, "\n");
6689 GlobalIndex->printStats();
6690 }
6691
Guy Benyei11169dd2012-12-18 14:30:41 +00006692 std::fprintf(stderr, "\n");
6693 dump();
6694 std::fprintf(stderr, "\n");
6695}
6696
6697template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6698static void
6699dumpModuleIDMap(StringRef Name,
6700 const ContinuousRangeMap<Key, ModuleFile *,
6701 InitialCapacity> &Map) {
6702 if (Map.begin() == Map.end())
6703 return;
6704
6705 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6706 llvm::errs() << Name << ":\n";
6707 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6708 I != IEnd; ++I) {
6709 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6710 << "\n";
6711 }
6712}
6713
6714void ASTReader::dump() {
6715 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6716 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6717 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6718 dumpModuleIDMap("Global type map", GlobalTypeMap);
6719 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6720 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6721 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6722 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6723 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6724 dumpModuleIDMap("Global preprocessed entity map",
6725 GlobalPreprocessedEntityMap);
6726
6727 llvm::errs() << "\n*** PCH/Modules Loaded:";
6728 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6729 MEnd = ModuleMgr.end();
6730 M != MEnd; ++M)
6731 (*M)->dump();
6732}
6733
6734/// Return the amount of memory used by memory buffers, breaking down
6735/// by heap-backed versus mmap'ed memory.
6736void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6737 for (ModuleConstIterator I = ModuleMgr.begin(),
6738 E = ModuleMgr.end(); I != E; ++I) {
6739 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6740 size_t bytes = buf->getBufferSize();
6741 switch (buf->getBufferKind()) {
6742 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6743 sizes.malloc_bytes += bytes;
6744 break;
6745 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6746 sizes.mmap_bytes += bytes;
6747 break;
6748 }
6749 }
6750 }
6751}
6752
6753void ASTReader::InitializeSema(Sema &S) {
6754 SemaObj = &S;
6755 S.addExternalSource(this);
6756
6757 // Makes sure any declarations that were deserialized "too early"
6758 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006759 for (uint64_t ID : PreloadedDeclIDs) {
6760 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6761 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006762 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006763 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006764
Richard Smith3d8e97e2013-10-18 06:54:39 +00006765 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006766 if (!FPPragmaOptions.empty()) {
6767 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6768 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6769 }
6770
Richard Smith3d8e97e2013-10-18 06:54:39 +00006771 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006772 if (!OpenCLExtensions.empty()) {
6773 unsigned I = 0;
6774#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6775#include "clang/Basic/OpenCLExtensions.def"
6776
6777 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6778 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006779
6780 UpdateSema();
6781}
6782
6783void ASTReader::UpdateSema() {
6784 assert(SemaObj && "no Sema to update");
6785
6786 // Load the offsets of the declarations that Sema references.
6787 // They will be lazily deserialized when needed.
6788 if (!SemaDeclRefs.empty()) {
6789 assert(SemaDeclRefs.size() % 2 == 0);
6790 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6791 if (!SemaObj->StdNamespace)
6792 SemaObj->StdNamespace = SemaDeclRefs[I];
6793 if (!SemaObj->StdBadAlloc)
6794 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6795 }
6796 SemaDeclRefs.clear();
6797 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006798
6799 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6800 // encountered the pragma in the source.
6801 if(OptimizeOffPragmaLocation.isValid())
6802 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006803}
6804
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006805IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006806 // Note that we are loading an identifier.
6807 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006808
Douglas Gregor7211ac12013-01-25 23:32:03 +00006809 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006810 NumIdentifierLookups,
6811 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006812
6813 // We don't need to do identifier table lookups in C++ modules (we preload
6814 // all interesting declarations, and don't need to use the scope for name
6815 // lookups). Perform the lookup in PCH files, though, since we don't build
6816 // a complete initial identifier table if we're carrying on from a PCH.
6817 if (Context.getLangOpts().CPlusPlus) {
6818 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006819 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006820 break;
6821 } else {
6822 // If there is a global index, look there first to determine which modules
6823 // provably do not have any results for this identifier.
6824 GlobalModuleIndex::HitSet Hits;
6825 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6826 if (!loadGlobalIndex()) {
6827 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6828 HitsPtr = &Hits;
6829 }
6830 }
6831
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006832 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006833 }
6834
Guy Benyei11169dd2012-12-18 14:30:41 +00006835 IdentifierInfo *II = Visitor.getIdentifierInfo();
6836 markIdentifierUpToDate(II);
6837 return II;
6838}
6839
6840namespace clang {
6841 /// \brief An identifier-lookup iterator that enumerates all of the
6842 /// identifiers stored within a set of AST files.
6843 class ASTIdentifierIterator : public IdentifierIterator {
6844 /// \brief The AST reader whose identifiers are being enumerated.
6845 const ASTReader &Reader;
6846
6847 /// \brief The current index into the chain of AST files stored in
6848 /// the AST reader.
6849 unsigned Index;
6850
6851 /// \brief The current position within the identifier lookup table
6852 /// of the current AST file.
6853 ASTIdentifierLookupTable::key_iterator Current;
6854
6855 /// \brief The end position within the identifier lookup table of
6856 /// the current AST file.
6857 ASTIdentifierLookupTable::key_iterator End;
6858
6859 public:
6860 explicit ASTIdentifierIterator(const ASTReader &Reader);
6861
Craig Topper3e89dfe2014-03-13 02:13:41 +00006862 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006863 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006864}
Guy Benyei11169dd2012-12-18 14:30:41 +00006865
6866ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6867 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6868 ASTIdentifierLookupTable *IdTable
6869 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6870 Current = IdTable->key_begin();
6871 End = IdTable->key_end();
6872}
6873
6874StringRef ASTIdentifierIterator::Next() {
6875 while (Current == End) {
6876 // If we have exhausted all of our AST files, we're done.
6877 if (Index == 0)
6878 return StringRef();
6879
6880 --Index;
6881 ASTIdentifierLookupTable *IdTable
6882 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6883 IdentifierLookupTable;
6884 Current = IdTable->key_begin();
6885 End = IdTable->key_end();
6886 }
6887
6888 // We have any identifiers remaining in the current AST file; return
6889 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006890 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006891 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006892 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006893}
6894
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006895IdentifierIterator *ASTReader::getIdentifiers() {
6896 if (!loadGlobalIndex())
6897 return GlobalIndex->createIdentifierIterator();
6898
Guy Benyei11169dd2012-12-18 14:30:41 +00006899 return new ASTIdentifierIterator(*this);
6900}
6901
6902namespace clang { namespace serialization {
6903 class ReadMethodPoolVisitor {
6904 ASTReader &Reader;
6905 Selector Sel;
6906 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006907 unsigned InstanceBits;
6908 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006909 bool InstanceHasMoreThanOneDecl;
6910 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006911 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6912 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006913
6914 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006915 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006916 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006917 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006918 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6919 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006920
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006921 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006922 if (!M.SelectorLookupTable)
6923 return false;
6924
6925 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00006926 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00006927 return true;
6928
Richard Smithbdf2d932015-07-30 03:37:16 +00006929 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006930 ASTSelectorLookupTable *PoolTable
6931 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00006932 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00006933 if (Pos == PoolTable->end())
6934 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006935
Richard Smithbdf2d932015-07-30 03:37:16 +00006936 ++Reader.NumMethodPoolTableHits;
6937 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006938 // FIXME: Not quite happy with the statistics here. We probably should
6939 // disable this tracking when called via LoadSelector.
6940 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00006941 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006942 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00006943 if (Reader.DeserializationListener)
6944 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006945
Richard Smithbdf2d932015-07-30 03:37:16 +00006946 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6947 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6948 InstanceBits = Data.InstanceBits;
6949 FactoryBits = Data.FactoryBits;
6950 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6951 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006952 return true;
6953 }
6954
6955 /// \brief Retrieve the instance methods found by this visitor.
6956 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6957 return InstanceMethods;
6958 }
6959
6960 /// \brief Retrieve the instance methods found by this visitor.
6961 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6962 return FactoryMethods;
6963 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006964
6965 unsigned getInstanceBits() const { return InstanceBits; }
6966 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006967 bool instanceHasMoreThanOneDecl() const {
6968 return InstanceHasMoreThanOneDecl;
6969 }
6970 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006971 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006972} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00006973
6974/// \brief Add the given set of methods to the method list.
6975static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6976 ObjCMethodList &List) {
6977 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6978 S.addMethodToGlobalList(&List, Methods[I]);
6979 }
6980}
6981
6982void ASTReader::ReadMethodPool(Selector Sel) {
6983 // Get the selector generation and update it to the current generation.
6984 unsigned &Generation = SelectorGeneration[Sel];
6985 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00006986 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00006987
6988 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006989 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006990 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006991 ModuleMgr.visit(Visitor);
6992
Guy Benyei11169dd2012-12-18 14:30:41 +00006993 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006994 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006995 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006996
6997 ++NumMethodPoolHits;
6998
Guy Benyei11169dd2012-12-18 14:30:41 +00006999 if (!getSema())
7000 return;
7001
7002 Sema &S = *getSema();
7003 Sema::GlobalMethodPool::iterator Pos
7004 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007005
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007006 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007007 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007008 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007009 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007010
7011 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7012 // when building a module we keep every method individually and may need to
7013 // update hasMoreThanOneDecl as we add the methods.
7014 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7015 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007016}
7017
7018void ASTReader::ReadKnownNamespaces(
7019 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7020 Namespaces.clear();
7021
7022 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7023 if (NamespaceDecl *Namespace
7024 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7025 Namespaces.push_back(Namespace);
7026 }
7027}
7028
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007029void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007030 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007031 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7032 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007033 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007034 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007035 Undefined.insert(std::make_pair(D, Loc));
7036 }
7037}
Nick Lewycky8334af82013-01-26 00:35:08 +00007038
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007039void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7040 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7041 Exprs) {
7042 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7043 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7044 uint64_t Count = DelayedDeleteExprs[Idx++];
7045 for (uint64_t C = 0; C < Count; ++C) {
7046 SourceLocation DeleteLoc =
7047 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7048 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7049 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7050 }
7051 }
7052}
7053
Guy Benyei11169dd2012-12-18 14:30:41 +00007054void ASTReader::ReadTentativeDefinitions(
7055 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7056 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7057 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7058 if (Var)
7059 TentativeDefs.push_back(Var);
7060 }
7061 TentativeDefinitions.clear();
7062}
7063
7064void ASTReader::ReadUnusedFileScopedDecls(
7065 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7066 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7067 DeclaratorDecl *D
7068 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7069 if (D)
7070 Decls.push_back(D);
7071 }
7072 UnusedFileScopedDecls.clear();
7073}
7074
7075void ASTReader::ReadDelegatingConstructors(
7076 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7077 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7078 CXXConstructorDecl *D
7079 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7080 if (D)
7081 Decls.push_back(D);
7082 }
7083 DelegatingCtorDecls.clear();
7084}
7085
7086void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7087 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7088 TypedefNameDecl *D
7089 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7090 if (D)
7091 Decls.push_back(D);
7092 }
7093 ExtVectorDecls.clear();
7094}
7095
Nico Weber72889432014-09-06 01:25:55 +00007096void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7097 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7098 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7099 ++I) {
7100 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7101 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7102 if (D)
7103 Decls.insert(D);
7104 }
7105 UnusedLocalTypedefNameCandidates.clear();
7106}
7107
Guy Benyei11169dd2012-12-18 14:30:41 +00007108void ASTReader::ReadReferencedSelectors(
7109 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7110 if (ReferencedSelectorsData.empty())
7111 return;
7112
7113 // If there are @selector references added them to its pool. This is for
7114 // implementation of -Wselector.
7115 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7116 unsigned I = 0;
7117 while (I < DataSize) {
7118 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7119 SourceLocation SelLoc
7120 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7121 Sels.push_back(std::make_pair(Sel, SelLoc));
7122 }
7123 ReferencedSelectorsData.clear();
7124}
7125
7126void ASTReader::ReadWeakUndeclaredIdentifiers(
7127 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7128 if (WeakUndeclaredIdentifiers.empty())
7129 return;
7130
7131 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7132 IdentifierInfo *WeakId
7133 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7134 IdentifierInfo *AliasId
7135 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7136 SourceLocation Loc
7137 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7138 bool Used = WeakUndeclaredIdentifiers[I++];
7139 WeakInfo WI(AliasId, Loc);
7140 WI.setUsed(Used);
7141 WeakIDs.push_back(std::make_pair(WeakId, WI));
7142 }
7143 WeakUndeclaredIdentifiers.clear();
7144}
7145
7146void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7147 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7148 ExternalVTableUse VT;
7149 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7150 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7151 VT.DefinitionRequired = VTableUses[Idx++];
7152 VTables.push_back(VT);
7153 }
7154
7155 VTableUses.clear();
7156}
7157
7158void ASTReader::ReadPendingInstantiations(
7159 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7160 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7161 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7162 SourceLocation Loc
7163 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7164
7165 Pending.push_back(std::make_pair(D, Loc));
7166 }
7167 PendingInstantiations.clear();
7168}
7169
Richard Smithe40f2ba2013-08-07 21:41:30 +00007170void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007171 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007172 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7173 /* In loop */) {
7174 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7175
7176 LateParsedTemplate *LT = new LateParsedTemplate;
7177 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7178
7179 ModuleFile *F = getOwningModuleFile(LT->D);
7180 assert(F && "No module");
7181
7182 unsigned TokN = LateParsedTemplates[Idx++];
7183 LT->Toks.reserve(TokN);
7184 for (unsigned T = 0; T < TokN; ++T)
7185 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7186
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007187 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007188 }
7189
7190 LateParsedTemplates.clear();
7191}
7192
Guy Benyei11169dd2012-12-18 14:30:41 +00007193void ASTReader::LoadSelector(Selector Sel) {
7194 // It would be complicated to avoid reading the methods anyway. So don't.
7195 ReadMethodPool(Sel);
7196}
7197
7198void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7199 assert(ID && "Non-zero identifier ID required");
7200 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7201 IdentifiersLoaded[ID - 1] = II;
7202 if (DeserializationListener)
7203 DeserializationListener->IdentifierRead(ID, II);
7204}
7205
7206/// \brief Set the globally-visible declarations associated with the given
7207/// identifier.
7208///
7209/// If the AST reader is currently in a state where the given declaration IDs
7210/// cannot safely be resolved, they are queued until it is safe to resolve
7211/// them.
7212///
7213/// \param II an IdentifierInfo that refers to one or more globally-visible
7214/// declarations.
7215///
7216/// \param DeclIDs the set of declaration IDs with the name @p II that are
7217/// visible at global scope.
7218///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007219/// \param Decls if non-null, this vector will be populated with the set of
7220/// deserialized declarations. These declarations will not be pushed into
7221/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007222void
7223ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7224 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007225 SmallVectorImpl<Decl *> *Decls) {
7226 if (NumCurrentElementsDeserializing && !Decls) {
7227 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007228 return;
7229 }
7230
7231 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007232 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007233 // Queue this declaration so that it will be added to the
7234 // translation unit scope and identifier's declaration chain
7235 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007236 PreloadedDeclIDs.push_back(DeclIDs[I]);
7237 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007238 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007239
7240 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7241
7242 // If we're simply supposed to record the declarations, do so now.
7243 if (Decls) {
7244 Decls->push_back(D);
7245 continue;
7246 }
7247
7248 // Introduce this declaration into the translation-unit scope
7249 // and add it to the declaration chain for this identifier, so
7250 // that (unqualified) name lookup will find it.
7251 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007252 }
7253}
7254
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007255IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007256 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007257 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007258
7259 if (IdentifiersLoaded.empty()) {
7260 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007261 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007262 }
7263
7264 ID -= 1;
7265 if (!IdentifiersLoaded[ID]) {
7266 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7267 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7268 ModuleFile *M = I->second;
7269 unsigned Index = ID - M->BaseIdentifierID;
7270 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7271
7272 // All of the strings in the AST file are preceded by a 16-bit length.
7273 // Extract that 16-bit length to avoid having to execute strlen().
7274 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7275 // unsigned integers. This is important to avoid integer overflow when
7276 // we cast them to 'unsigned'.
7277 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7278 unsigned StrLen = (((unsigned) StrLenPtr[0])
7279 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007280 IdentifiersLoaded[ID]
7281 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007282 if (DeserializationListener)
7283 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7284 }
7285
7286 return IdentifiersLoaded[ID];
7287}
7288
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007289IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7290 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007291}
7292
7293IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7294 if (LocalID < NUM_PREDEF_IDENT_IDS)
7295 return LocalID;
7296
7297 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7298 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7299 assert(I != M.IdentifierRemap.end()
7300 && "Invalid index into identifier index remap");
7301
7302 return LocalID + I->second;
7303}
7304
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007305MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007306 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007307 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007308
7309 if (MacrosLoaded.empty()) {
7310 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007311 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007312 }
7313
7314 ID -= NUM_PREDEF_MACRO_IDS;
7315 if (!MacrosLoaded[ID]) {
7316 GlobalMacroMapType::iterator I
7317 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7318 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7319 ModuleFile *M = I->second;
7320 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007321 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7322
7323 if (DeserializationListener)
7324 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7325 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007326 }
7327
7328 return MacrosLoaded[ID];
7329}
7330
7331MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7332 if (LocalID < NUM_PREDEF_MACRO_IDS)
7333 return LocalID;
7334
7335 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7336 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7337 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7338
7339 return LocalID + I->second;
7340}
7341
7342serialization::SubmoduleID
7343ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7344 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7345 return LocalID;
7346
7347 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7348 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7349 assert(I != M.SubmoduleRemap.end()
7350 && "Invalid index into submodule index remap");
7351
7352 return LocalID + I->second;
7353}
7354
7355Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7356 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7357 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007358 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007359 }
7360
7361 if (GlobalID > SubmodulesLoaded.size()) {
7362 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007363 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007364 }
7365
7366 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7367}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007368
7369Module *ASTReader::getModule(unsigned ID) {
7370 return getSubmodule(ID);
7371}
7372
Adrian Prantl15bcf702015-06-30 17:39:43 +00007373ExternalASTSource::ASTSourceDescriptor
7374ASTReader::getSourceDescriptor(const Module &M) {
7375 StringRef Dir, Filename;
7376 if (M.Directory)
7377 Dir = M.Directory->getName();
7378 if (auto *File = M.getASTFile())
7379 Filename = File->getName();
7380 return ASTReader::ASTSourceDescriptor{
7381 M.getFullModuleName(), Dir, Filename,
7382 M.Signature
7383 };
7384}
7385
7386llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7387ASTReader::getSourceDescriptor(unsigned ID) {
7388 if (const Module *M = getSubmodule(ID))
7389 return getSourceDescriptor(*M);
7390
7391 // If there is only a single PCH, return it instead.
7392 // Chained PCH are not suported.
7393 if (ModuleMgr.size() == 1) {
7394 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7395 return ASTReader::ASTSourceDescriptor{
7396 MF.OriginalSourceFileName, MF.OriginalDir,
7397 MF.FileName,
7398 MF.Signature
7399 };
7400 }
7401 return None;
7402}
7403
Guy Benyei11169dd2012-12-18 14:30:41 +00007404Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7405 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7406}
7407
7408Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7409 if (ID == 0)
7410 return Selector();
7411
7412 if (ID > SelectorsLoaded.size()) {
7413 Error("selector ID out of range in AST file");
7414 return Selector();
7415 }
7416
Craig Toppera13603a2014-05-22 05:54:18 +00007417 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007418 // Load this selector from the selector table.
7419 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7420 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7421 ModuleFile &M = *I->second;
7422 ASTSelectorLookupTrait Trait(*this, M);
7423 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7424 SelectorsLoaded[ID - 1] =
7425 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7426 if (DeserializationListener)
7427 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7428 }
7429
7430 return SelectorsLoaded[ID - 1];
7431}
7432
7433Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7434 return DecodeSelector(ID);
7435}
7436
7437uint32_t ASTReader::GetNumExternalSelectors() {
7438 // ID 0 (the null selector) is considered an external selector.
7439 return getTotalNumSelectors() + 1;
7440}
7441
7442serialization::SelectorID
7443ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7444 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7445 return LocalID;
7446
7447 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7448 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7449 assert(I != M.SelectorRemap.end()
7450 && "Invalid index into selector index remap");
7451
7452 return LocalID + I->second;
7453}
7454
7455DeclarationName
7456ASTReader::ReadDeclarationName(ModuleFile &F,
7457 const RecordData &Record, unsigned &Idx) {
7458 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7459 switch (Kind) {
7460 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007461 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007462
7463 case DeclarationName::ObjCZeroArgSelector:
7464 case DeclarationName::ObjCOneArgSelector:
7465 case DeclarationName::ObjCMultiArgSelector:
7466 return DeclarationName(ReadSelector(F, Record, Idx));
7467
7468 case DeclarationName::CXXConstructorName:
7469 return Context.DeclarationNames.getCXXConstructorName(
7470 Context.getCanonicalType(readType(F, Record, Idx)));
7471
7472 case DeclarationName::CXXDestructorName:
7473 return Context.DeclarationNames.getCXXDestructorName(
7474 Context.getCanonicalType(readType(F, Record, Idx)));
7475
7476 case DeclarationName::CXXConversionFunctionName:
7477 return Context.DeclarationNames.getCXXConversionFunctionName(
7478 Context.getCanonicalType(readType(F, Record, Idx)));
7479
7480 case DeclarationName::CXXOperatorName:
7481 return Context.DeclarationNames.getCXXOperatorName(
7482 (OverloadedOperatorKind)Record[Idx++]);
7483
7484 case DeclarationName::CXXLiteralOperatorName:
7485 return Context.DeclarationNames.getCXXLiteralOperatorName(
7486 GetIdentifierInfo(F, Record, Idx));
7487
7488 case DeclarationName::CXXUsingDirective:
7489 return DeclarationName::getUsingDirectiveName();
7490 }
7491
7492 llvm_unreachable("Invalid NameKind!");
7493}
7494
7495void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7496 DeclarationNameLoc &DNLoc,
7497 DeclarationName Name,
7498 const RecordData &Record, unsigned &Idx) {
7499 switch (Name.getNameKind()) {
7500 case DeclarationName::CXXConstructorName:
7501 case DeclarationName::CXXDestructorName:
7502 case DeclarationName::CXXConversionFunctionName:
7503 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7504 break;
7505
7506 case DeclarationName::CXXOperatorName:
7507 DNLoc.CXXOperatorName.BeginOpNameLoc
7508 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7509 DNLoc.CXXOperatorName.EndOpNameLoc
7510 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7511 break;
7512
7513 case DeclarationName::CXXLiteralOperatorName:
7514 DNLoc.CXXLiteralOperatorName.OpNameLoc
7515 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7516 break;
7517
7518 case DeclarationName::Identifier:
7519 case DeclarationName::ObjCZeroArgSelector:
7520 case DeclarationName::ObjCOneArgSelector:
7521 case DeclarationName::ObjCMultiArgSelector:
7522 case DeclarationName::CXXUsingDirective:
7523 break;
7524 }
7525}
7526
7527void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7528 DeclarationNameInfo &NameInfo,
7529 const RecordData &Record, unsigned &Idx) {
7530 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7531 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7532 DeclarationNameLoc DNLoc;
7533 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7534 NameInfo.setInfo(DNLoc);
7535}
7536
7537void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7538 const RecordData &Record, unsigned &Idx) {
7539 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7540 unsigned NumTPLists = Record[Idx++];
7541 Info.NumTemplParamLists = NumTPLists;
7542 if (NumTPLists) {
7543 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7544 for (unsigned i=0; i != NumTPLists; ++i)
7545 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7546 }
7547}
7548
7549TemplateName
7550ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7551 unsigned &Idx) {
7552 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7553 switch (Kind) {
7554 case TemplateName::Template:
7555 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7556
7557 case TemplateName::OverloadedTemplate: {
7558 unsigned size = Record[Idx++];
7559 UnresolvedSet<8> Decls;
7560 while (size--)
7561 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7562
7563 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7564 }
7565
7566 case TemplateName::QualifiedTemplate: {
7567 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7568 bool hasTemplKeyword = Record[Idx++];
7569 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7570 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7571 }
7572
7573 case TemplateName::DependentTemplate: {
7574 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7575 if (Record[Idx++]) // isIdentifier
7576 return Context.getDependentTemplateName(NNS,
7577 GetIdentifierInfo(F, Record,
7578 Idx));
7579 return Context.getDependentTemplateName(NNS,
7580 (OverloadedOperatorKind)Record[Idx++]);
7581 }
7582
7583 case TemplateName::SubstTemplateTemplateParm: {
7584 TemplateTemplateParmDecl *param
7585 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7586 if (!param) return TemplateName();
7587 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7588 return Context.getSubstTemplateTemplateParm(param, replacement);
7589 }
7590
7591 case TemplateName::SubstTemplateTemplateParmPack: {
7592 TemplateTemplateParmDecl *Param
7593 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7594 if (!Param)
7595 return TemplateName();
7596
7597 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7598 if (ArgPack.getKind() != TemplateArgument::Pack)
7599 return TemplateName();
7600
7601 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7602 }
7603 }
7604
7605 llvm_unreachable("Unhandled template name kind!");
7606}
7607
Richard Smith2bb3c342015-08-09 01:05:31 +00007608TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7609 const RecordData &Record,
7610 unsigned &Idx,
7611 bool Canonicalize) {
7612 if (Canonicalize) {
7613 // The caller wants a canonical template argument. Sometimes the AST only
7614 // wants template arguments in canonical form (particularly as the template
7615 // argument lists of template specializations) so ensure we preserve that
7616 // canonical form across serialization.
7617 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7618 return Context.getCanonicalTemplateArgument(Arg);
7619 }
7620
Guy Benyei11169dd2012-12-18 14:30:41 +00007621 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7622 switch (Kind) {
7623 case TemplateArgument::Null:
7624 return TemplateArgument();
7625 case TemplateArgument::Type:
7626 return TemplateArgument(readType(F, Record, Idx));
7627 case TemplateArgument::Declaration: {
7628 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007629 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007630 }
7631 case TemplateArgument::NullPtr:
7632 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7633 case TemplateArgument::Integral: {
7634 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7635 QualType T = readType(F, Record, Idx);
7636 return TemplateArgument(Context, Value, T);
7637 }
7638 case TemplateArgument::Template:
7639 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7640 case TemplateArgument::TemplateExpansion: {
7641 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007642 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007643 if (unsigned NumExpansions = Record[Idx++])
7644 NumTemplateExpansions = NumExpansions - 1;
7645 return TemplateArgument(Name, NumTemplateExpansions);
7646 }
7647 case TemplateArgument::Expression:
7648 return TemplateArgument(ReadExpr(F));
7649 case TemplateArgument::Pack: {
7650 unsigned NumArgs = Record[Idx++];
7651 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7652 for (unsigned I = 0; I != NumArgs; ++I)
7653 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007654 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007655 }
7656 }
7657
7658 llvm_unreachable("Unhandled template argument kind!");
7659}
7660
7661TemplateParameterList *
7662ASTReader::ReadTemplateParameterList(ModuleFile &F,
7663 const RecordData &Record, unsigned &Idx) {
7664 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7665 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7666 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7667
7668 unsigned NumParams = Record[Idx++];
7669 SmallVector<NamedDecl *, 16> Params;
7670 Params.reserve(NumParams);
7671 while (NumParams--)
7672 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7673
7674 TemplateParameterList* TemplateParams =
7675 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7676 Params.data(), Params.size(), RAngleLoc);
7677 return TemplateParams;
7678}
7679
7680void
7681ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007682ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007683 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007684 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007685 unsigned NumTemplateArgs = Record[Idx++];
7686 TemplArgs.reserve(NumTemplateArgs);
7687 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007688 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007689}
7690
7691/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007692void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007693 const RecordData &Record, unsigned &Idx) {
7694 unsigned NumDecls = Record[Idx++];
7695 Set.reserve(Context, NumDecls);
7696 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007697 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007698 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007699 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007700 }
7701}
7702
7703CXXBaseSpecifier
7704ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7705 const RecordData &Record, unsigned &Idx) {
7706 bool isVirtual = static_cast<bool>(Record[Idx++]);
7707 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7708 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7709 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7710 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7711 SourceRange Range = ReadSourceRange(F, Record, Idx);
7712 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7713 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7714 EllipsisLoc);
7715 Result.setInheritConstructors(inheritConstructors);
7716 return Result;
7717}
7718
Richard Smithc2bb8182015-03-24 06:36:48 +00007719CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007720ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7721 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007722 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007723 assert(NumInitializers && "wrote ctor initializers but have no inits");
7724 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7725 for (unsigned i = 0; i != NumInitializers; ++i) {
7726 TypeSourceInfo *TInfo = nullptr;
7727 bool IsBaseVirtual = false;
7728 FieldDecl *Member = nullptr;
7729 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007730
Richard Smithc2bb8182015-03-24 06:36:48 +00007731 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7732 switch (Type) {
7733 case CTOR_INITIALIZER_BASE:
7734 TInfo = GetTypeSourceInfo(F, Record, Idx);
7735 IsBaseVirtual = Record[Idx++];
7736 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007737
Richard Smithc2bb8182015-03-24 06:36:48 +00007738 case CTOR_INITIALIZER_DELEGATING:
7739 TInfo = GetTypeSourceInfo(F, Record, Idx);
7740 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007741
Richard Smithc2bb8182015-03-24 06:36:48 +00007742 case CTOR_INITIALIZER_MEMBER:
7743 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7744 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007745
Richard Smithc2bb8182015-03-24 06:36:48 +00007746 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7747 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7748 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007749 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007750
7751 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7752 Expr *Init = ReadExpr(F);
7753 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7754 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7755 bool IsWritten = Record[Idx++];
7756 unsigned SourceOrderOrNumArrayIndices;
7757 SmallVector<VarDecl *, 8> Indices;
7758 if (IsWritten) {
7759 SourceOrderOrNumArrayIndices = Record[Idx++];
7760 } else {
7761 SourceOrderOrNumArrayIndices = Record[Idx++];
7762 Indices.reserve(SourceOrderOrNumArrayIndices);
7763 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7764 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7765 }
7766
7767 CXXCtorInitializer *BOMInit;
7768 if (Type == CTOR_INITIALIZER_BASE) {
7769 BOMInit = new (Context)
7770 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7771 RParenLoc, MemberOrEllipsisLoc);
7772 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7773 BOMInit = new (Context)
7774 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7775 } else if (IsWritten) {
7776 if (Member)
7777 BOMInit = new (Context) CXXCtorInitializer(
7778 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7779 else
7780 BOMInit = new (Context)
7781 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7782 LParenLoc, Init, RParenLoc);
7783 } else {
7784 if (IndirectMember) {
7785 assert(Indices.empty() && "Indirect field improperly initialized");
7786 BOMInit = new (Context)
7787 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7788 LParenLoc, Init, RParenLoc);
7789 } else {
7790 BOMInit = CXXCtorInitializer::Create(
7791 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7792 Indices.data(), Indices.size());
7793 }
7794 }
7795
7796 if (IsWritten)
7797 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7798 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007799 }
7800
Richard Smithc2bb8182015-03-24 06:36:48 +00007801 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007802}
7803
7804NestedNameSpecifier *
7805ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7806 const RecordData &Record, unsigned &Idx) {
7807 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007808 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007809 for (unsigned I = 0; I != N; ++I) {
7810 NestedNameSpecifier::SpecifierKind Kind
7811 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7812 switch (Kind) {
7813 case NestedNameSpecifier::Identifier: {
7814 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7815 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7816 break;
7817 }
7818
7819 case NestedNameSpecifier::Namespace: {
7820 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7821 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7822 break;
7823 }
7824
7825 case NestedNameSpecifier::NamespaceAlias: {
7826 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7827 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7828 break;
7829 }
7830
7831 case NestedNameSpecifier::TypeSpec:
7832 case NestedNameSpecifier::TypeSpecWithTemplate: {
7833 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7834 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007835 return nullptr;
7836
Guy Benyei11169dd2012-12-18 14:30:41 +00007837 bool Template = Record[Idx++];
7838 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7839 break;
7840 }
7841
7842 case NestedNameSpecifier::Global: {
7843 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7844 // No associated value, and there can't be a prefix.
7845 break;
7846 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007847
7848 case NestedNameSpecifier::Super: {
7849 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7850 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7851 break;
7852 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007853 }
7854 Prev = NNS;
7855 }
7856 return NNS;
7857}
7858
7859NestedNameSpecifierLoc
7860ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7861 unsigned &Idx) {
7862 unsigned N = Record[Idx++];
7863 NestedNameSpecifierLocBuilder Builder;
7864 for (unsigned I = 0; I != N; ++I) {
7865 NestedNameSpecifier::SpecifierKind Kind
7866 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7867 switch (Kind) {
7868 case NestedNameSpecifier::Identifier: {
7869 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7870 SourceRange Range = ReadSourceRange(F, Record, Idx);
7871 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7872 break;
7873 }
7874
7875 case NestedNameSpecifier::Namespace: {
7876 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7877 SourceRange Range = ReadSourceRange(F, Record, Idx);
7878 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7879 break;
7880 }
7881
7882 case NestedNameSpecifier::NamespaceAlias: {
7883 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7884 SourceRange Range = ReadSourceRange(F, Record, Idx);
7885 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7886 break;
7887 }
7888
7889 case NestedNameSpecifier::TypeSpec:
7890 case NestedNameSpecifier::TypeSpecWithTemplate: {
7891 bool Template = Record[Idx++];
7892 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7893 if (!T)
7894 return NestedNameSpecifierLoc();
7895 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7896
7897 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7898 Builder.Extend(Context,
7899 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7900 T->getTypeLoc(), ColonColonLoc);
7901 break;
7902 }
7903
7904 case NestedNameSpecifier::Global: {
7905 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7906 Builder.MakeGlobal(Context, ColonColonLoc);
7907 break;
7908 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007909
7910 case NestedNameSpecifier::Super: {
7911 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7912 SourceRange Range = ReadSourceRange(F, Record, Idx);
7913 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7914 break;
7915 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007916 }
7917 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007918
Guy Benyei11169dd2012-12-18 14:30:41 +00007919 return Builder.getWithLocInContext(Context);
7920}
7921
7922SourceRange
7923ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7924 unsigned &Idx) {
7925 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7926 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7927 return SourceRange(beg, end);
7928}
7929
7930/// \brief Read an integral value
7931llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7932 unsigned BitWidth = Record[Idx++];
7933 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7934 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7935 Idx += NumWords;
7936 return Result;
7937}
7938
7939/// \brief Read a signed integral value
7940llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7941 bool isUnsigned = Record[Idx++];
7942 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7943}
7944
7945/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007946llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7947 const llvm::fltSemantics &Sem,
7948 unsigned &Idx) {
7949 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007950}
7951
7952// \brief Read a string
7953std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7954 unsigned Len = Record[Idx++];
7955 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7956 Idx += Len;
7957 return Result;
7958}
7959
Richard Smith7ed1bc92014-12-05 22:42:13 +00007960std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7961 unsigned &Idx) {
7962 std::string Filename = ReadString(Record, Idx);
7963 ResolveImportedPath(F, Filename);
7964 return Filename;
7965}
7966
Guy Benyei11169dd2012-12-18 14:30:41 +00007967VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7968 unsigned &Idx) {
7969 unsigned Major = Record[Idx++];
7970 unsigned Minor = Record[Idx++];
7971 unsigned Subminor = Record[Idx++];
7972 if (Minor == 0)
7973 return VersionTuple(Major);
7974 if (Subminor == 0)
7975 return VersionTuple(Major, Minor - 1);
7976 return VersionTuple(Major, Minor - 1, Subminor - 1);
7977}
7978
7979CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7980 const RecordData &Record,
7981 unsigned &Idx) {
7982 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7983 return CXXTemporary::Create(Context, Decl);
7984}
7985
7986DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007987 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007988}
7989
7990DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7991 return Diags.Report(Loc, DiagID);
7992}
7993
7994/// \brief Retrieve the identifier table associated with the
7995/// preprocessor.
7996IdentifierTable &ASTReader::getIdentifierTable() {
7997 return PP.getIdentifierTable();
7998}
7999
8000/// \brief Record that the given ID maps to the given switch-case
8001/// statement.
8002void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008003 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008004 "Already have a SwitchCase with this ID");
8005 (*CurrSwitchCaseStmts)[ID] = SC;
8006}
8007
8008/// \brief Retrieve the switch-case statement with the given ID.
8009SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008010 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008011 return (*CurrSwitchCaseStmts)[ID];
8012}
8013
8014void ASTReader::ClearSwitchCaseIDs() {
8015 CurrSwitchCaseStmts->clear();
8016}
8017
8018void ASTReader::ReadComments() {
8019 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008020 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008021 serialization::ModuleFile *> >::iterator
8022 I = CommentsCursors.begin(),
8023 E = CommentsCursors.end();
8024 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008025 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008026 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008027 serialization::ModuleFile &F = *I->second;
8028 SavedStreamPosition SavedPosition(Cursor);
8029
8030 RecordData Record;
8031 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008032 llvm::BitstreamEntry Entry =
8033 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008034
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008035 switch (Entry.Kind) {
8036 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8037 case llvm::BitstreamEntry::Error:
8038 Error("malformed block record in AST file");
8039 return;
8040 case llvm::BitstreamEntry::EndBlock:
8041 goto NextCursor;
8042 case llvm::BitstreamEntry::Record:
8043 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008044 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008045 }
8046
8047 // Read a record.
8048 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008049 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008050 case COMMENTS_RAW_COMMENT: {
8051 unsigned Idx = 0;
8052 SourceRange SR = ReadSourceRange(F, Record, Idx);
8053 RawComment::CommentKind Kind =
8054 (RawComment::CommentKind) Record[Idx++];
8055 bool IsTrailingComment = Record[Idx++];
8056 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008057 Comments.push_back(new (Context) RawComment(
8058 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8059 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008060 break;
8061 }
8062 }
8063 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008064 NextCursor:
8065 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008066 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008067}
8068
Richard Smithcd45dbc2014-04-19 03:48:30 +00008069std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8070 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008071 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008072 return M->getFullModuleName();
8073
8074 // Otherwise, use the name of the top-level module the decl is within.
8075 if (ModuleFile *M = getOwningModuleFile(D))
8076 return M->ModuleName;
8077
8078 // Not from a module.
8079 return "";
8080}
8081
Guy Benyei11169dd2012-12-18 14:30:41 +00008082void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008083 while (!PendingIdentifierInfos.empty() ||
8084 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008085 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008086 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008087 // If any identifiers with corresponding top-level declarations have
8088 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008089 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8090 TopLevelDeclsMap;
8091 TopLevelDeclsMap TopLevelDecls;
8092
Guy Benyei11169dd2012-12-18 14:30:41 +00008093 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008094 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008095 SmallVector<uint32_t, 4> DeclIDs =
8096 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008097 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008098
8099 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008100 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008101
Richard Smith851072e2014-05-19 20:59:20 +00008102 // For each decl chain that we wanted to complete while deserializing, mark
8103 // it as "still needs to be completed".
8104 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8105 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8106 }
8107 PendingIncompleteDeclChains.clear();
8108
Guy Benyei11169dd2012-12-18 14:30:41 +00008109 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008110 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008111 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008112 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008113 }
8114 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008115 PendingDeclChains.clear();
8116
Richard Smith9b88a4c2015-07-27 05:40:23 +00008117 assert(RedeclsDeserialized.empty() && "some redecls not wired up");
8118
Douglas Gregor6168bd22013-02-18 15:53:43 +00008119 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008120 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8121 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008122 IdentifierInfo *II = TLD->first;
8123 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008124 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008125 }
8126 }
8127
Guy Benyei11169dd2012-12-18 14:30:41 +00008128 // Load any pending macro definitions.
8129 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008130 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8131 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8132 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8133 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008134 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008135 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008136 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008137 if (Info.M->Kind != MK_ImplicitModule &&
8138 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008139 resolvePendingMacro(II, Info);
8140 }
8141 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008142 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008143 ++IDIdx) {
8144 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008145 if (Info.M->Kind == MK_ImplicitModule ||
8146 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008147 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008148 }
8149 }
8150 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008151
8152 // Wire up the DeclContexts for Decls that we delayed setting until
8153 // recursive loading is completed.
8154 while (!PendingDeclContextInfos.empty()) {
8155 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8156 PendingDeclContextInfos.pop_front();
8157 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8158 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8159 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8160 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008161
Richard Smithd1c46742014-04-30 02:24:17 +00008162 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008163 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008164 auto Update = PendingUpdateRecords.pop_back_val();
8165 ReadingKindTracker ReadingKind(Read_Decl, *this);
8166 loadDeclUpdateRecords(Update.first, Update.second);
8167 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008168 }
Richard Smith8a639892015-01-24 01:07:20 +00008169
8170 // At this point, all update records for loaded decls are in place, so any
8171 // fake class definitions should have become real.
8172 assert(PendingFakeDefinitionData.empty() &&
8173 "faked up a class definition but never saw the real one");
8174
Guy Benyei11169dd2012-12-18 14:30:41 +00008175 // If we deserialized any C++ or Objective-C class definitions, any
8176 // Objective-C protocol definitions, or any redeclarable templates, make sure
8177 // that all redeclarations point to the definitions. Note that this can only
8178 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008179 for (Decl *D : PendingDefinitions) {
8180 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008181 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008182 // Make sure that the TagType points at the definition.
8183 const_cast<TagType*>(TagT)->decl = TD;
8184 }
Richard Smith8ce51082015-03-11 01:44:51 +00008185
Craig Topperc6914d02014-08-25 04:15:02 +00008186 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008187 for (auto *R = getMostRecentExistingDecl(RD); R;
8188 R = R->getPreviousDecl()) {
8189 assert((R == D) ==
8190 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008191 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008192 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008193 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008194 }
8195
8196 continue;
8197 }
Richard Smith8ce51082015-03-11 01:44:51 +00008198
Craig Topperc6914d02014-08-25 04:15:02 +00008199 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008200 // Make sure that the ObjCInterfaceType points at the definition.
8201 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8202 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008203
8204 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8205 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8206
Guy Benyei11169dd2012-12-18 14:30:41 +00008207 continue;
8208 }
Richard Smith8ce51082015-03-11 01:44:51 +00008209
Craig Topperc6914d02014-08-25 04:15:02 +00008210 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008211 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8212 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8213
Guy Benyei11169dd2012-12-18 14:30:41 +00008214 continue;
8215 }
Richard Smith8ce51082015-03-11 01:44:51 +00008216
Craig Topperc6914d02014-08-25 04:15:02 +00008217 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008218 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8219 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008220 }
8221 PendingDefinitions.clear();
8222
8223 // Load the bodies of any functions or methods we've encountered. We do
8224 // this now (delayed) so that we can be sure that the declaration chains
8225 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008226 // FIXME: There seems to be no point in delaying this, it does not depend
8227 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008228 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8229 PBEnd = PendingBodies.end();
8230 PB != PBEnd; ++PB) {
8231 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8232 // FIXME: Check for =delete/=default?
8233 // FIXME: Complain about ODR violations here?
8234 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8235 FD->setLazyBody(PB->second);
8236 continue;
8237 }
8238
8239 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8240 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8241 MD->setLazyBody(PB->second);
8242 }
8243 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008244
8245 // Do some cleanup.
8246 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8247 getContext().deduplicateMergedDefinitonsFor(ND);
8248 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008249}
8250
8251void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008252 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8253 return;
8254
Richard Smitha0ce9c42014-07-29 23:23:27 +00008255 // Trigger the import of the full definition of each class that had any
8256 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008257 // These updates may in turn find and diagnose some ODR failures, so take
8258 // ownership of the set first.
8259 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8260 PendingOdrMergeFailures.clear();
8261 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008262 Merge.first->buildLookup();
8263 Merge.first->decls_begin();
8264 Merge.first->bases_begin();
8265 Merge.first->vbases_begin();
8266 for (auto *RD : Merge.second) {
8267 RD->decls_begin();
8268 RD->bases_begin();
8269 RD->vbases_begin();
8270 }
8271 }
8272
8273 // For each declaration from a merged context, check that the canonical
8274 // definition of that context also contains a declaration of the same
8275 // entity.
8276 //
8277 // Caution: this loop does things that might invalidate iterators into
8278 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8279 while (!PendingOdrMergeChecks.empty()) {
8280 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8281
8282 // FIXME: Skip over implicit declarations for now. This matters for things
8283 // like implicitly-declared special member functions. This isn't entirely
8284 // correct; we can end up with multiple unmerged declarations of the same
8285 // implicit entity.
8286 if (D->isImplicit())
8287 continue;
8288
8289 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008290
8291 bool Found = false;
8292 const Decl *DCanon = D->getCanonicalDecl();
8293
Richard Smith01bdb7a2014-08-28 05:44:07 +00008294 for (auto RI : D->redecls()) {
8295 if (RI->getLexicalDeclContext() == CanonDef) {
8296 Found = true;
8297 break;
8298 }
8299 }
8300 if (Found)
8301 continue;
8302
Richard Smith0f4e2c42015-08-06 04:23:48 +00008303 // Quick check failed, time to do the slow thing. Note, we can't just
8304 // look up the name of D in CanonDef here, because the member that is
8305 // in CanonDef might not be found by name lookup (it might have been
8306 // replaced by a more recent declaration in the lookup table), and we
8307 // can't necessarily find it in the redeclaration chain because it might
8308 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008309 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008310 for (auto *CanonMember : CanonDef->decls()) {
8311 if (CanonMember->getCanonicalDecl() == DCanon) {
8312 // This can happen if the declaration is merely mergeable and not
8313 // actually redeclarable (we looked for redeclarations earlier).
8314 //
8315 // FIXME: We should be able to detect this more efficiently, without
8316 // pulling in all of the members of CanonDef.
8317 Found = true;
8318 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008319 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008320 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8321 if (ND->getDeclName() == D->getDeclName())
8322 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008323 }
8324
8325 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008326 // The AST doesn't like TagDecls becoming invalid after they've been
8327 // completed. We only really need to mark FieldDecls as invalid here.
8328 if (!isa<TagDecl>(D))
8329 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008330
8331 // Ensure we don't accidentally recursively enter deserialization while
8332 // we're producing our diagnostic.
8333 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008334
8335 std::string CanonDefModule =
8336 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8337 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8338 << D << getOwningModuleNameForDiagnostic(D)
8339 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8340
8341 if (Candidates.empty())
8342 Diag(cast<Decl>(CanonDef)->getLocation(),
8343 diag::note_module_odr_violation_no_possible_decls) << D;
8344 else {
8345 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8346 Diag(Candidates[I]->getLocation(),
8347 diag::note_module_odr_violation_possible_decl)
8348 << Candidates[I];
8349 }
8350
8351 DiagnosedOdrMergeFailures.insert(CanonDef);
8352 }
8353 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008354
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008355 if (OdrMergeFailures.empty())
8356 return;
8357
8358 // Ensure we don't accidentally recursively enter deserialization while
8359 // we're producing our diagnostics.
8360 Deserializing RecursionGuard(this);
8361
Richard Smithcd45dbc2014-04-19 03:48:30 +00008362 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008363 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008364 // If we've already pointed out a specific problem with this class, don't
8365 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008366 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008367 continue;
8368
8369 bool Diagnosed = false;
8370 for (auto *RD : Merge.second) {
8371 // Multiple different declarations got merged together; tell the user
8372 // where they came from.
8373 if (Merge.first != RD) {
8374 // FIXME: Walk the definition, figure out what's different,
8375 // and diagnose that.
8376 if (!Diagnosed) {
8377 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8378 Diag(Merge.first->getLocation(),
8379 diag::err_module_odr_violation_different_definitions)
8380 << Merge.first << Module.empty() << Module;
8381 Diagnosed = true;
8382 }
8383
8384 Diag(RD->getLocation(),
8385 diag::note_module_odr_violation_different_definitions)
8386 << getOwningModuleNameForDiagnostic(RD);
8387 }
8388 }
8389
8390 if (!Diagnosed) {
8391 // All definitions are updates to the same declaration. This happens if a
8392 // module instantiates the declaration of a class template specialization
8393 // and two or more other modules instantiate its definition.
8394 //
8395 // FIXME: Indicate which modules had instantiations of this definition.
8396 // FIXME: How can this even happen?
8397 Diag(Merge.first->getLocation(),
8398 diag::err_module_odr_violation_different_instantiations)
8399 << Merge.first;
8400 }
8401 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008402}
8403
Richard Smithce18a182015-07-14 00:26:00 +00008404void ASTReader::StartedDeserializing() {
8405 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8406 ReadTimer->startTimer();
8407}
8408
Guy Benyei11169dd2012-12-18 14:30:41 +00008409void ASTReader::FinishedDeserializing() {
8410 assert(NumCurrentElementsDeserializing &&
8411 "FinishedDeserializing not paired with StartedDeserializing");
8412 if (NumCurrentElementsDeserializing == 1) {
8413 // We decrease NumCurrentElementsDeserializing only after pending actions
8414 // are finished, to avoid recursively re-calling finishPendingActions().
8415 finishPendingActions();
8416 }
8417 --NumCurrentElementsDeserializing;
8418
Richard Smitha0ce9c42014-07-29 23:23:27 +00008419 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008420 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008421 while (!PendingExceptionSpecUpdates.empty()) {
8422 auto Updates = std::move(PendingExceptionSpecUpdates);
8423 PendingExceptionSpecUpdates.clear();
8424 for (auto Update : Updates) {
8425 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8426 SemaObj->UpdateExceptionSpec(Update.second,
8427 FPT->getExtProtoInfo().ExceptionSpec);
8428 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008429 }
8430
Richard Smithce18a182015-07-14 00:26:00 +00008431 if (ReadTimer)
8432 ReadTimer->stopTimer();
8433
Richard Smith0f4e2c42015-08-06 04:23:48 +00008434 diagnoseOdrViolations();
8435
Richard Smith04d05b52014-03-23 00:27:18 +00008436 // We are not in recursive loading, so it's safe to pass the "interesting"
8437 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008438 if (Consumer)
8439 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008440 }
8441}
8442
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008443void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008444 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8445 // Remove any fake results before adding any real ones.
8446 auto It = PendingFakeLookupResults.find(II);
8447 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008448 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008449 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008450 // FIXME: this works around module+PCH performance issue.
8451 // Rather than erase the result from the map, which is O(n), just clear
8452 // the vector of NamedDecls.
8453 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008454 }
8455 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008456
8457 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8458 SemaObj->TUScope->AddDecl(D);
8459 } else if (SemaObj->TUScope) {
8460 // Adding the decl to IdResolver may have failed because it was already in
8461 // (even though it was not added in scope). If it is already in, make sure
8462 // it gets in the scope as well.
8463 if (std::find(SemaObj->IdResolver.begin(Name),
8464 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8465 SemaObj->TUScope->AddDecl(D);
8466 }
8467}
8468
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008469ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008470 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008471 StringRef isysroot, bool DisableValidation,
8472 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008473 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Richard Smithce18a182015-07-14 00:26:00 +00008474 bool UseGlobalIndex,
8475 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008476 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008477 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008478 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008479 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008480 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008481 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008482 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008483 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8484 AllowConfigurationMismatch(AllowConfigurationMismatch),
8485 ValidateSystemInputs(ValidateSystemInputs),
8486 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008487 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8488 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8489 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8490 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008491 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8492 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8493 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8494 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8495 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8496 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008497 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008498 SourceMgr.setExternalSLocEntrySource(this);
8499}
8500
8501ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008502 if (OwnsDeserializationListener)
8503 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008504}