blob: abc91e771ecbbc7f8adb78c6072e315435a137e2 [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
958bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000959 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000960 const std::pair<uint64_t, uint64_t> &Offsets,
961 DeclContextInfo &Info) {
962 SavedStreamPosition SavedPosition(Cursor);
963 // First the lexical decls.
964 if (Offsets.first != 0) {
965 Cursor.JumpToBit(Offsets.first);
966
967 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000968 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000969 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000970 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000971 if (RecCode != DECL_CONTEXT_LEXICAL) {
972 Error("Expected lexical block");
973 return true;
974 }
975
Richard Smith787c0e42015-07-23 00:53:59 +0000976 Info.LexicalDecls = llvm::makeArrayRef(
977 reinterpret_cast<const KindDeclIDPair *>(Blob.data()),
978 Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +0000979 }
980
981 // Now the lookup table.
982 if (Offsets.second != 0) {
983 Cursor.JumpToBit(Offsets.second);
984
985 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000986 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000987 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000988 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000989 if (RecCode != DECL_CONTEXT_VISIBLE) {
990 Error("Expected visible lookup table block");
991 return true;
992 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000993 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
994 (const unsigned char *)Blob.data() + Record[0],
995 (const unsigned char *)Blob.data() + sizeof(uint32_t),
996 (const unsigned char *)Blob.data(),
997 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000998 }
999
1000 return false;
1001}
1002
1003void ASTReader::Error(StringRef Msg) {
1004 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001005 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1006 Diag(diag::note_module_cache_path)
1007 << PP.getHeaderSearchInfo().getModuleCachePath();
1008 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001009}
1010
1011void ASTReader::Error(unsigned DiagID,
1012 StringRef Arg1, StringRef Arg2) {
1013 if (Diags.isDiagnosticInFlight())
1014 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1015 else
1016 Diag(DiagID) << Arg1 << Arg2;
1017}
1018
1019//===----------------------------------------------------------------------===//
1020// Source Manager Deserialization
1021//===----------------------------------------------------------------------===//
1022
1023/// \brief Read the line table in the source manager block.
1024/// \returns true if there was an error.
1025bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001026 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 unsigned Idx = 0;
1028 LineTableInfo &LineTable = SourceMgr.getLineTable();
1029
1030 // Parse the file names
1031 std::map<int, int> FileIDs;
1032 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1033 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001034 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001035 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1036 }
1037
1038 // Parse the line entries
1039 std::vector<LineEntry> Entries;
1040 while (Idx < Record.size()) {
1041 int FID = Record[Idx++];
1042 assert(FID >= 0 && "Serialized line entries for non-local file.");
1043 // Remap FileID from 1-based old view.
1044 FID += F.SLocEntryBaseID - 1;
1045
1046 // Extract the line entries
1047 unsigned NumEntries = Record[Idx++];
1048 assert(NumEntries && "Numentries is 00000");
1049 Entries.clear();
1050 Entries.reserve(NumEntries);
1051 for (unsigned I = 0; I != NumEntries; ++I) {
1052 unsigned FileOffset = Record[Idx++];
1053 unsigned LineNo = Record[Idx++];
1054 int FilenameID = FileIDs[Record[Idx++]];
1055 SrcMgr::CharacteristicKind FileKind
1056 = (SrcMgr::CharacteristicKind)Record[Idx++];
1057 unsigned IncludeOffset = Record[Idx++];
1058 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1059 FileKind, IncludeOffset));
1060 }
1061 LineTable.AddEntry(FileID::get(FID), Entries);
1062 }
1063
1064 return false;
1065}
1066
1067/// \brief Read a source manager block
1068bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1069 using namespace SrcMgr;
1070
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001071 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001072
1073 // Set the source-location entry cursor to the current position in
1074 // the stream. This cursor will be used to read the contents of the
1075 // source manager block initially, and then lazily read
1076 // source-location entries as needed.
1077 SLocEntryCursor = F.Stream;
1078
1079 // The stream itself is going to skip over the source manager block.
1080 if (F.Stream.SkipBlock()) {
1081 Error("malformed block record in AST file");
1082 return true;
1083 }
1084
1085 // Enter the source manager block.
1086 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1087 Error("malformed source manager block record in AST file");
1088 return true;
1089 }
1090
1091 RecordData Record;
1092 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001093 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1094
1095 switch (E.Kind) {
1096 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1097 case llvm::BitstreamEntry::Error:
1098 Error("malformed block record in AST file");
1099 return true;
1100 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001101 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001102 case llvm::BitstreamEntry::Record:
1103 // The interesting case.
1104 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001105 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001106
Guy Benyei11169dd2012-12-18 14:30:41 +00001107 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001108 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001109 StringRef Blob;
1110 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001111 default: // Default behavior: ignore.
1112 break;
1113
1114 case SM_SLOC_FILE_ENTRY:
1115 case SM_SLOC_BUFFER_ENTRY:
1116 case SM_SLOC_EXPANSION_ENTRY:
1117 // Once we hit one of the source location entries, we're done.
1118 return false;
1119 }
1120 }
1121}
1122
1123/// \brief If a header file is not found at the path that we expect it to be
1124/// and the PCH file was moved from its original location, try to resolve the
1125/// file by assuming that header+PCH were moved together and the header is in
1126/// the same place relative to the PCH.
1127static std::string
1128resolveFileRelativeToOriginalDir(const std::string &Filename,
1129 const std::string &OriginalDir,
1130 const std::string &CurrDir) {
1131 assert(OriginalDir != CurrDir &&
1132 "No point trying to resolve the file if the PCH dir didn't change");
1133 using namespace llvm::sys;
1134 SmallString<128> filePath(Filename);
1135 fs::make_absolute(filePath);
1136 assert(path::is_absolute(OriginalDir));
1137 SmallString<128> currPCHPath(CurrDir);
1138
1139 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1140 fileDirE = path::end(path::parent_path(filePath));
1141 path::const_iterator origDirI = path::begin(OriginalDir),
1142 origDirE = path::end(OriginalDir);
1143 // Skip the common path components from filePath and OriginalDir.
1144 while (fileDirI != fileDirE && origDirI != origDirE &&
1145 *fileDirI == *origDirI) {
1146 ++fileDirI;
1147 ++origDirI;
1148 }
1149 for (; origDirI != origDirE; ++origDirI)
1150 path::append(currPCHPath, "..");
1151 path::append(currPCHPath, fileDirI, fileDirE);
1152 path::append(currPCHPath, path::filename(Filename));
1153 return currPCHPath.str();
1154}
1155
1156bool ASTReader::ReadSLocEntry(int ID) {
1157 if (ID == 0)
1158 return false;
1159
1160 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1161 Error("source location entry ID out-of-range for AST file");
1162 return true;
1163 }
1164
1165 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1166 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001167 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001168 unsigned BaseOffset = F->SLocEntryBaseOffset;
1169
1170 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001171 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1172 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001173 Error("incorrectly-formatted source location entry in AST file");
1174 return true;
1175 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001176
Guy Benyei11169dd2012-12-18 14:30:41 +00001177 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001178 StringRef Blob;
1179 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001180 default:
1181 Error("incorrectly-formatted source location entry in AST file");
1182 return true;
1183
1184 case SM_SLOC_FILE_ENTRY: {
1185 // We will detect whether a file changed and return 'Failure' for it, but
1186 // we will also try to fail gracefully by setting up the SLocEntry.
1187 unsigned InputID = Record[4];
1188 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001189 const FileEntry *File = IF.getFile();
1190 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001191
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001192 // Note that we only check if a File was returned. If it was out-of-date
1193 // we have complained but we will continue creating a FileID to recover
1194 // gracefully.
1195 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001196 return true;
1197
1198 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1199 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1200 // This is the module's main file.
1201 IncludeLoc = getImportLocation(F);
1202 }
1203 SrcMgr::CharacteristicKind
1204 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1205 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1206 ID, BaseOffset + Record[0]);
1207 SrcMgr::FileInfo &FileInfo =
1208 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1209 FileInfo.NumCreatedFIDs = Record[5];
1210 if (Record[3])
1211 FileInfo.setHasLineDirectives();
1212
1213 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1214 unsigned NumFileDecls = Record[7];
1215 if (NumFileDecls) {
1216 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1217 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1218 NumFileDecls));
1219 }
1220
1221 const SrcMgr::ContentCache *ContentCache
1222 = SourceMgr.getOrCreateContentCache(File,
1223 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1224 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1225 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1226 unsigned Code = SLocEntryCursor.ReadCode();
1227 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001228 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001229
1230 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1231 Error("AST record has invalid code");
1232 return true;
1233 }
1234
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001235 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001236 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001237 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001238 }
1239
1240 break;
1241 }
1242
1243 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001244 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001245 unsigned Offset = Record[0];
1246 SrcMgr::CharacteristicKind
1247 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1248 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001249 if (IncludeLoc.isInvalid() &&
1250 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001251 IncludeLoc = getImportLocation(F);
1252 }
1253 unsigned Code = SLocEntryCursor.ReadCode();
1254 Record.clear();
1255 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001256 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001257
1258 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1259 Error("AST record has invalid code");
1260 return true;
1261 }
1262
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001263 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1264 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001265 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001266 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001267 break;
1268 }
1269
1270 case SM_SLOC_EXPANSION_ENTRY: {
1271 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1272 SourceMgr.createExpansionLoc(SpellingLoc,
1273 ReadSourceLocation(*F, Record[2]),
1274 ReadSourceLocation(*F, Record[3]),
1275 Record[4],
1276 ID,
1277 BaseOffset + Record[0]);
1278 break;
1279 }
1280 }
1281
1282 return false;
1283}
1284
1285std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1286 if (ID == 0)
1287 return std::make_pair(SourceLocation(), "");
1288
1289 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1290 Error("source location entry ID out-of-range for AST file");
1291 return std::make_pair(SourceLocation(), "");
1292 }
1293
1294 // Find which module file this entry lands in.
1295 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001296 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001297 return std::make_pair(SourceLocation(), "");
1298
1299 // FIXME: Can we map this down to a particular submodule? That would be
1300 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001301 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001302}
1303
1304/// \brief Find the location where the module F is imported.
1305SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1306 if (F->ImportLoc.isValid())
1307 return F->ImportLoc;
1308
1309 // Otherwise we have a PCH. It's considered to be "imported" at the first
1310 // location of its includer.
1311 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001312 // Main file is the importer.
1313 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1314 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001315 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001316 return F->ImportedBy[0]->FirstLoc;
1317}
1318
1319/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1320/// specified cursor. Read the abbreviations that are at the top of the block
1321/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001322bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001323 if (Cursor.EnterSubBlock(BlockID)) {
1324 Error("malformed block record in AST file");
1325 return Failure;
1326 }
1327
1328 while (true) {
1329 uint64_t Offset = Cursor.GetCurrentBitNo();
1330 unsigned Code = Cursor.ReadCode();
1331
1332 // We expect all abbrevs to be at the start of the block.
1333 if (Code != llvm::bitc::DEFINE_ABBREV) {
1334 Cursor.JumpToBit(Offset);
1335 return false;
1336 }
1337 Cursor.ReadAbbrevRecord();
1338 }
1339}
1340
Richard Smithe40f2ba2013-08-07 21:41:30 +00001341Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001342 unsigned &Idx) {
1343 Token Tok;
1344 Tok.startToken();
1345 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1346 Tok.setLength(Record[Idx++]);
1347 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1348 Tok.setIdentifierInfo(II);
1349 Tok.setKind((tok::TokenKind)Record[Idx++]);
1350 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1351 return Tok;
1352}
1353
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001354MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001355 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001356
1357 // Keep track of where we are in the stream, then jump back there
1358 // after reading this macro.
1359 SavedStreamPosition SavedPosition(Stream);
1360
1361 Stream.JumpToBit(Offset);
1362 RecordData Record;
1363 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001364 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001365
Guy Benyei11169dd2012-12-18 14:30:41 +00001366 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001367 // Advance to the next record, but if we get to the end of the block, don't
1368 // pop it (removing all the abbreviations from the cursor) since we want to
1369 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001370 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001371 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1372
1373 switch (Entry.Kind) {
1374 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1375 case llvm::BitstreamEntry::Error:
1376 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001377 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001378 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001379 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001380 case llvm::BitstreamEntry::Record:
1381 // The interesting case.
1382 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001383 }
1384
1385 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001386 Record.clear();
1387 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001388 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001389 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001390 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001391 case PP_MACRO_DIRECTIVE_HISTORY:
1392 return Macro;
1393
Guy Benyei11169dd2012-12-18 14:30:41 +00001394 case PP_MACRO_OBJECT_LIKE:
1395 case PP_MACRO_FUNCTION_LIKE: {
1396 // If we already have a macro, that means that we've hit the end
1397 // of the definition of the macro we were looking for. We're
1398 // done.
1399 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001400 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001401
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001402 unsigned NextIndex = 1; // Skip identifier ID.
1403 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001404 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001405 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001406 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001407 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001408 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001409
Guy Benyei11169dd2012-12-18 14:30:41 +00001410 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1411 // Decode function-like macro info.
1412 bool isC99VarArgs = Record[NextIndex++];
1413 bool isGNUVarArgs = Record[NextIndex++];
1414 bool hasCommaPasting = Record[NextIndex++];
1415 MacroArgs.clear();
1416 unsigned NumArgs = Record[NextIndex++];
1417 for (unsigned i = 0; i != NumArgs; ++i)
1418 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1419
1420 // Install function-like macro info.
1421 MI->setIsFunctionLike();
1422 if (isC99VarArgs) MI->setIsC99Varargs();
1423 if (isGNUVarArgs) MI->setIsGNUVarargs();
1424 if (hasCommaPasting) MI->setHasCommaPasting();
1425 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1426 PP.getPreprocessorAllocator());
1427 }
1428
Guy Benyei11169dd2012-12-18 14:30:41 +00001429 // Remember that we saw this macro last so that we add the tokens that
1430 // form its body to it.
1431 Macro = MI;
1432
1433 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1434 Record[NextIndex]) {
1435 // We have a macro definition. Register the association
1436 PreprocessedEntityID
1437 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1438 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001439 PreprocessingRecord::PPEntityID PPID =
1440 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1441 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1442 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001443 if (PPDef)
1444 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001445 }
1446
1447 ++NumMacrosRead;
1448 break;
1449 }
1450
1451 case PP_TOKEN: {
1452 // If we see a TOKEN before a PP_MACRO_*, then the file is
1453 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001454 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001455
John McCallf413f5e2013-05-03 00:10:13 +00001456 unsigned Idx = 0;
1457 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001458 Macro->AddTokenToBody(Tok);
1459 break;
1460 }
1461 }
1462 }
1463}
1464
1465PreprocessedEntityID
1466ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1467 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1468 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1469 assert(I != M.PreprocessedEntityRemap.end()
1470 && "Invalid index into preprocessed entity index remap");
1471
1472 return LocalID + I->second;
1473}
1474
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001475unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1476 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001477}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001478
Guy Benyei11169dd2012-12-18 14:30:41 +00001479HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001480HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1481 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001482 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001483 return ikey;
1484}
Guy Benyei11169dd2012-12-18 14:30:41 +00001485
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001486bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1487 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001488 return false;
1489
Richard Smith7ed1bc92014-12-05 22:42:13 +00001490 if (llvm::sys::path::is_absolute(a.Filename) &&
1491 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001492 return true;
1493
Guy Benyei11169dd2012-12-18 14:30:41 +00001494 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001495 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001496 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1497 if (!Key.Imported)
1498 return FileMgr.getFile(Key.Filename);
1499
1500 std::string Resolved = Key.Filename;
1501 Reader.ResolveImportedPath(M, Resolved);
1502 return FileMgr.getFile(Resolved);
1503 };
1504
1505 const FileEntry *FEA = GetFile(a);
1506 const FileEntry *FEB = GetFile(b);
1507 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001508}
1509
1510std::pair<unsigned, unsigned>
1511HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001512 using namespace llvm::support;
1513 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001514 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001515 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001516}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001517
1518HeaderFileInfoTrait::internal_key_type
1519HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001520 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001521 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001522 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1523 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001524 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001525 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001526 return ikey;
1527}
1528
Guy Benyei11169dd2012-12-18 14:30:41 +00001529HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001530HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001531 unsigned DataLen) {
1532 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001533 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001534 HeaderFileInfo HFI;
1535 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001536 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1537 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001538 HFI.isImport = (Flags >> 5) & 0x01;
1539 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1540 HFI.DirInfo = (Flags >> 2) & 0x03;
1541 HFI.Resolved = (Flags >> 1) & 0x01;
1542 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001543 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1544 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1545 M, endian::readNext<uint32_t, little, unaligned>(d));
1546 if (unsigned FrameworkOffset =
1547 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001548 // The framework offset is 1 greater than the actual offset,
1549 // since 0 is used as an indicator for "no framework name".
1550 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1551 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1552 }
1553
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001554 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001555 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001556 if (LocalSMID) {
1557 // This header is part of a module. Associate it with the module to enable
1558 // implicit module import.
1559 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1560 Module *Mod = Reader.getSubmodule(GlobalSMID);
1561 HFI.isModuleHeader = true;
1562 FileManager &FileMgr = Reader.getFileManager();
1563 ModuleMap &ModMap =
1564 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001565 // FIXME: This information should be propagated through the
1566 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001567 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001568 std::string Filename = key.Filename;
1569 if (key.Imported)
1570 Reader.ResolveImportedPath(M, Filename);
1571 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001572 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001573 }
1574 }
1575
Guy Benyei11169dd2012-12-18 14:30:41 +00001576 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1577 (void)End;
1578
1579 // This HeaderFileInfo was externally loaded.
1580 HFI.External = true;
1581 return HFI;
1582}
1583
Richard Smithd7329392015-04-21 21:46:32 +00001584void ASTReader::addPendingMacro(IdentifierInfo *II,
1585 ModuleFile *M,
1586 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001587 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1588 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001589}
1590
1591void ASTReader::ReadDefinedMacros() {
1592 // Note that we are loading defined macros.
1593 Deserializing Macros(this);
1594
Pete Cooper57d3f142015-07-30 17:22:52 +00001595 for (auto &I : llvm::reverse(ModuleMgr)) {
1596 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001597
1598 // If there was no preprocessor block, skip this file.
1599 if (!MacroCursor.getBitStreamReader())
1600 continue;
1601
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001602 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001603 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001604
1605 RecordData Record;
1606 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001607 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1608
1609 switch (E.Kind) {
1610 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1611 case llvm::BitstreamEntry::Error:
1612 Error("malformed block record in AST file");
1613 return;
1614 case llvm::BitstreamEntry::EndBlock:
1615 goto NextCursor;
1616
1617 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001618 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001619 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001620 default: // Default behavior: ignore.
1621 break;
1622
1623 case PP_MACRO_OBJECT_LIKE:
1624 case PP_MACRO_FUNCTION_LIKE:
Pete Cooper57d3f142015-07-30 17:22:52 +00001625 getLocalIdentifier(*I, Record[0]);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001626 break;
1627
1628 case PP_TOKEN:
1629 // Ignore tokens.
1630 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001631 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001632 break;
1633 }
1634 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001635 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001636 }
1637}
1638
1639namespace {
1640 /// \brief Visitor class used to look up identifirs in an AST file.
1641 class IdentifierLookupVisitor {
1642 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001643 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001644 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001645 unsigned &NumIdentifierLookups;
1646 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001647 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001648
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001650 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1651 unsigned &NumIdentifierLookups,
1652 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001653 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1654 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001655 NumIdentifierLookups(NumIdentifierLookups),
1656 NumIdentifierLookupHits(NumIdentifierLookupHits),
1657 Found()
1658 {
1659 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001660
1661 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001662 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001663 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001664 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001665
Guy Benyei11169dd2012-12-18 14:30:41 +00001666 ASTIdentifierLookupTable *IdTable
1667 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1668 if (!IdTable)
1669 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001670
1671 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001672 Found);
1673 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001674 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001675 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001676 if (Pos == IdTable->end())
1677 return false;
1678
1679 // Dereferencing the iterator has the effect of building the
1680 // IdentifierInfo node and populating it with the various
1681 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001682 ++NumIdentifierLookupHits;
1683 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001684 return true;
1685 }
1686
1687 // \brief Retrieve the identifier info found within the module
1688 // files.
1689 IdentifierInfo *getIdentifierInfo() const { return Found; }
1690 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001691}
Guy Benyei11169dd2012-12-18 14:30:41 +00001692
1693void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1694 // Note that we are loading an identifier.
1695 Deserializing AnIdentifier(this);
1696
1697 unsigned PriorGeneration = 0;
1698 if (getContext().getLangOpts().Modules)
1699 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001700
1701 // If there is a global index, look there first to determine which modules
1702 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001703 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001704 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001705 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001706 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1707 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001708 }
1709 }
1710
Douglas Gregor7211ac12013-01-25 23:32:03 +00001711 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001712 NumIdentifierLookups,
1713 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001714 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001715 markIdentifierUpToDate(&II);
1716}
1717
1718void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1719 if (!II)
1720 return;
1721
1722 II->setOutOfDate(false);
1723
1724 // Update the generation for this identifier.
1725 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001726 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001727}
1728
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001729void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1730 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001731 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001732
1733 BitstreamCursor &Cursor = M.MacroCursor;
1734 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001735 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001736
Richard Smith713369b2015-04-23 20:40:50 +00001737 struct ModuleMacroRecord {
1738 SubmoduleID SubModID;
1739 MacroInfo *MI;
1740 SmallVector<SubmoduleID, 8> Overrides;
1741 };
1742 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001743
Richard Smithd7329392015-04-21 21:46:32 +00001744 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1745 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1746 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001747 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001748 while (true) {
1749 llvm::BitstreamEntry Entry =
1750 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1751 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1752 Error("malformed block record in AST file");
1753 return;
1754 }
1755
1756 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001757 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001758 case PP_MACRO_DIRECTIVE_HISTORY:
1759 break;
1760
1761 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001762 ModuleMacros.push_back(ModuleMacroRecord());
1763 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001764 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1765 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001766 for (int I = 2, N = Record.size(); I != N; ++I)
1767 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001768 continue;
1769 }
1770
1771 default:
1772 Error("malformed block record in AST file");
1773 return;
1774 }
1775
1776 // We found the macro directive history; that's the last record
1777 // for this macro.
1778 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001779 }
1780
Richard Smithd7329392015-04-21 21:46:32 +00001781 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001782 {
1783 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001784 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001785 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001786 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001787 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001788 Module *Mod = getSubmodule(ModID);
1789 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001790 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001791 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001792 }
1793
1794 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001795 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001796 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001797 }
1798 }
1799
1800 // Don't read the directive history for a module; we don't have anywhere
1801 // to put it.
1802 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1803 return;
1804
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001805 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001806 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001807 unsigned Idx = 0, N = Record.size();
1808 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001809 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001810 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001811 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1812 switch (K) {
1813 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001814 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001815 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001816 break;
1817 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001818 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001819 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001820 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001821 }
1822 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001823 bool isPublic = Record[Idx++];
1824 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1825 break;
1826 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001827
1828 if (!Latest)
1829 Latest = MD;
1830 if (Earliest)
1831 Earliest->setPrevious(MD);
1832 Earliest = MD;
1833 }
1834
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001835 if (Latest)
1836 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001837}
1838
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001839ASTReader::InputFileInfo
1840ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001841 // Go find this input file.
1842 BitstreamCursor &Cursor = F.InputFilesCursor;
1843 SavedStreamPosition SavedPosition(Cursor);
1844 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1845
1846 unsigned Code = Cursor.ReadCode();
1847 RecordData Record;
1848 StringRef Blob;
1849
1850 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1851 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1852 "invalid record type for input file");
1853 (void)Result;
1854
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001855 std::string Filename;
1856 off_t StoredSize;
1857 time_t StoredTime;
1858 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001859
Ben Langmuir198c1682014-03-07 07:27:49 +00001860 assert(Record[0] == ID && "Bogus stored ID or offset");
1861 StoredSize = static_cast<off_t>(Record[1]);
1862 StoredTime = static_cast<time_t>(Record[2]);
1863 Overridden = static_cast<bool>(Record[3]);
1864 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001865 ResolveImportedPath(F, Filename);
1866
Hans Wennborg73945142014-03-14 17:45:06 +00001867 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1868 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001869}
1870
1871std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001872 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00001873}
1874
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001875InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001876 // If this ID is bogus, just return an empty input file.
1877 if (ID == 0 || ID > F.InputFilesLoaded.size())
1878 return InputFile();
1879
1880 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001881 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001882 return F.InputFilesLoaded[ID-1];
1883
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001884 if (F.InputFilesLoaded[ID-1].isNotFound())
1885 return InputFile();
1886
Guy Benyei11169dd2012-12-18 14:30:41 +00001887 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001888 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001889 SavedStreamPosition SavedPosition(Cursor);
1890 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1891
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001892 InputFileInfo FI = readInputFileInfo(F, ID);
1893 off_t StoredSize = FI.StoredSize;
1894 time_t StoredTime = FI.StoredTime;
1895 bool Overridden = FI.Overridden;
1896 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001897
Ben Langmuir198c1682014-03-07 07:27:49 +00001898 const FileEntry *File
1899 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1900 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1901
1902 // If we didn't find the file, resolve it relative to the
1903 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001904 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001905 F.OriginalDir != CurrentDir) {
1906 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1907 F.OriginalDir,
1908 CurrentDir);
1909 if (!Resolved.empty())
1910 File = FileMgr.getFile(Resolved);
1911 }
1912
1913 // For an overridden file, create a virtual file with the stored
1914 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001915 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001916 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1917 }
1918
Craig Toppera13603a2014-05-22 05:54:18 +00001919 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001920 if (Complain) {
1921 std::string ErrorStr = "could not find file '";
1922 ErrorStr += Filename;
1923 ErrorStr += "' referenced by AST file";
1924 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001925 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001926 // Record that we didn't find the file.
1927 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1928 return InputFile();
1929 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001930
Ben Langmuir198c1682014-03-07 07:27:49 +00001931 // Check if there was a request to override the contents of the file
1932 // that was part of the precompiled header. Overridding such a file
1933 // can lead to problems when lexing using the source locations from the
1934 // PCH.
1935 SourceManager &SM = getSourceManager();
1936 if (!Overridden && SM.isFileOverridden(File)) {
1937 if (Complain)
1938 Error(diag::err_fe_pch_file_overridden, Filename);
1939 // After emitting the diagnostic, recover by disabling the override so
1940 // that the original file will be used.
1941 SM.disableFileContentsOverride(File);
1942 // The FileEntry is a virtual file entry with the size of the contents
1943 // that would override the original contents. Set it to the original's
1944 // size/time.
1945 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1946 StoredSize, StoredTime);
1947 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001948
Ben Langmuir198c1682014-03-07 07:27:49 +00001949 bool IsOutOfDate = false;
1950
1951 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001952 if (!Overridden && //
1953 (StoredSize != File->getSize() ||
1954#if defined(LLVM_ON_WIN32)
1955 false
1956#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001957 // In our regression testing, the Windows file system seems to
1958 // have inconsistent modification times that sometimes
1959 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001960 //
1961 // This also happens in networked file systems, so disable this
1962 // check if validation is disabled or if we have an explicitly
1963 // built PCM file.
1964 //
1965 // FIXME: Should we also do this for PCH files? They could also
1966 // reasonably get shared across a network during a distributed build.
1967 (StoredTime != File->getModificationTime() && !DisableValidation &&
1968 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001969#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001970 )) {
1971 if (Complain) {
1972 // Build a list of the PCH imports that got us here (in reverse).
1973 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1974 while (ImportStack.back()->ImportedBy.size() > 0)
1975 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001976
Ben Langmuir198c1682014-03-07 07:27:49 +00001977 // The top-level PCH is stale.
1978 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1979 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00001980
Ben Langmuir198c1682014-03-07 07:27:49 +00001981 // Print the import stack.
1982 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1983 Diag(diag::note_pch_required_by)
1984 << Filename << ImportStack[0]->FileName;
1985 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00001986 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00001987 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00001988 }
1989
Ben Langmuir198c1682014-03-07 07:27:49 +00001990 if (!Diags.isDiagnosticInFlight())
1991 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00001992 }
1993
Ben Langmuir198c1682014-03-07 07:27:49 +00001994 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001995 }
1996
Ben Langmuir198c1682014-03-07 07:27:49 +00001997 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
1998
1999 // Note that we've loaded this input file.
2000 F.InputFilesLoaded[ID-1] = IF;
2001 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002002}
2003
Richard Smith7ed1bc92014-12-05 22:42:13 +00002004/// \brief If we are loading a relocatable PCH or module file, and the filename
2005/// is not an absolute path, add the system or module root to the beginning of
2006/// the file name.
2007void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2008 // Resolve relative to the base directory, if we have one.
2009 if (!M.BaseDirectory.empty())
2010 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002011}
2012
Richard Smith7ed1bc92014-12-05 22:42:13 +00002013void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002014 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2015 return;
2016
Richard Smith7ed1bc92014-12-05 22:42:13 +00002017 SmallString<128> Buffer;
2018 llvm::sys::path::append(Buffer, Prefix, Filename);
2019 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002020}
2021
2022ASTReader::ASTReadResult
2023ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002024 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002025 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002026 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002027 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002028
2029 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2030 Error("malformed block record in AST file");
2031 return Failure;
2032 }
2033
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002034 // Should we allow the configuration of the module file to differ from the
2035 // configuration of the current translation unit in a compatible way?
2036 //
2037 // FIXME: Allow this for files explicitly specified with -include-pch too.
2038 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2039
Guy Benyei11169dd2012-12-18 14:30:41 +00002040 // Read all of the records and blocks in the control block.
2041 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002042 unsigned NumInputs = 0;
2043 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002044 while (1) {
2045 llvm::BitstreamEntry Entry = Stream.advance();
2046
2047 switch (Entry.Kind) {
2048 case llvm::BitstreamEntry::Error:
2049 Error("malformed block record in AST file");
2050 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002051 case llvm::BitstreamEntry::EndBlock: {
2052 // Validate input files.
2053 const HeaderSearchOptions &HSOpts =
2054 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002055
Richard Smitha1825302014-10-23 22:18:29 +00002056 // All user input files reside at the index range [0, NumUserInputs), and
2057 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002058 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002059 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002060
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002061 // If we are reading a module, we will create a verification timestamp,
2062 // so we verify all input files. Otherwise, verify only user input
2063 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002064
2065 unsigned N = NumUserInputs;
2066 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002067 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002068 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002069 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002070 N = NumInputs;
2071
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002072 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002073 InputFile IF = getInputFile(F, I+1, Complain);
2074 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002075 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002076 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002077 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002078
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002079 if (Listener)
2080 Listener->visitModuleFile(F.FileName);
2081
Ben Langmuircb69b572014-03-07 06:40:32 +00002082 if (Listener && Listener->needsInputFileVisitation()) {
2083 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2084 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002085 for (unsigned I = 0; I < N; ++I) {
2086 bool IsSystem = I >= NumUserInputs;
2087 InputFileInfo FI = readInputFileInfo(F, I+1);
2088 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2089 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002090 }
2091
Guy Benyei11169dd2012-12-18 14:30:41 +00002092 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002093 }
2094
Chris Lattnere7b154b2013-01-19 21:39:22 +00002095 case llvm::BitstreamEntry::SubBlock:
2096 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002097 case INPUT_FILES_BLOCK_ID:
2098 F.InputFilesCursor = Stream;
2099 if (Stream.SkipBlock() || // Skip with the main cursor
2100 // Read the abbreviations
2101 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2102 Error("malformed block record in AST file");
2103 return Failure;
2104 }
2105 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002106
Guy Benyei11169dd2012-12-18 14:30:41 +00002107 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002108 if (Stream.SkipBlock()) {
2109 Error("malformed block record in AST file");
2110 return Failure;
2111 }
2112 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002113 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002114
2115 case llvm::BitstreamEntry::Record:
2116 // The interesting case.
2117 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002118 }
2119
2120 // Read and process a record.
2121 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002122 StringRef Blob;
2123 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002124 case METADATA: {
2125 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2126 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002127 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2128 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002129 return VersionMismatch;
2130 }
2131
2132 bool hasErrors = Record[5];
2133 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2134 Diag(diag::err_pch_with_compiler_errors);
2135 return HadErrors;
2136 }
2137
2138 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002139 // Relative paths in a relocatable PCH are relative to our sysroot.
2140 if (F.RelocatablePCH)
2141 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002142
2143 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002144 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002145 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2146 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002147 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002148 return VersionMismatch;
2149 }
2150 break;
2151 }
2152
Ben Langmuir487ea142014-10-23 18:05:36 +00002153 case SIGNATURE:
2154 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2155 F.Signature = Record[0];
2156 break;
2157
Guy Benyei11169dd2012-12-18 14:30:41 +00002158 case IMPORTS: {
2159 // Load each of the imported PCH files.
2160 unsigned Idx = 0, N = Record.size();
2161 while (Idx < N) {
2162 // Read information about the AST file.
2163 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2164 // The import location will be the local one for now; we will adjust
2165 // all import locations of module imports after the global source
2166 // location info are setup.
2167 SourceLocation ImportLoc =
2168 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002169 off_t StoredSize = (off_t)Record[Idx++];
2170 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002171 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002172 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002173
2174 // Load the AST file.
2175 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002176 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002177 ClientLoadCapabilities)) {
2178 case Failure: return Failure;
2179 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002180 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002181 case OutOfDate: return OutOfDate;
2182 case VersionMismatch: return VersionMismatch;
2183 case ConfigurationMismatch: return ConfigurationMismatch;
2184 case HadErrors: return HadErrors;
2185 case Success: break;
2186 }
2187 }
2188 break;
2189 }
2190
Richard Smith7f330cd2015-03-18 01:42:29 +00002191 case KNOWN_MODULE_FILES:
2192 break;
2193
Guy Benyei11169dd2012-12-18 14:30:41 +00002194 case LANGUAGE_OPTIONS: {
2195 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002196 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002197 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002198 ParseLanguageOptions(Record, Complain, *Listener,
2199 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002200 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002201 return ConfigurationMismatch;
2202 break;
2203 }
2204
2205 case TARGET_OPTIONS: {
2206 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2207 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002208 ParseTargetOptions(Record, Complain, *Listener,
2209 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002210 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002211 return ConfigurationMismatch;
2212 break;
2213 }
2214
2215 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002216 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002217 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002218 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002219 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002220 !DisableValidation)
2221 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002222 break;
2223 }
2224
2225 case FILE_SYSTEM_OPTIONS: {
2226 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2227 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002228 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002229 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002230 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002231 return ConfigurationMismatch;
2232 break;
2233 }
2234
2235 case HEADER_SEARCH_OPTIONS: {
2236 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2237 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002238 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002239 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002240 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002241 return ConfigurationMismatch;
2242 break;
2243 }
2244
2245 case PREPROCESSOR_OPTIONS: {
2246 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2247 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002248 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002249 ParsePreprocessorOptions(Record, Complain, *Listener,
2250 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002251 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002252 return ConfigurationMismatch;
2253 break;
2254 }
2255
2256 case ORIGINAL_FILE:
2257 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002258 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002259 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002260 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002261 break;
2262
2263 case ORIGINAL_FILE_ID:
2264 F.OriginalSourceFileID = FileID::get(Record[0]);
2265 break;
2266
2267 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002268 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002269 break;
2270
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002271 case MODULE_NAME:
2272 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002273 if (Listener)
2274 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002275 break;
2276
Richard Smith223d3f22014-12-06 03:21:08 +00002277 case MODULE_DIRECTORY: {
2278 assert(!F.ModuleName.empty() &&
2279 "MODULE_DIRECTORY found before MODULE_NAME");
2280 // If we've already loaded a module map file covering this module, we may
2281 // have a better path for it (relative to the current build).
2282 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2283 if (M && M->Directory) {
2284 // If we're implicitly loading a module, the base directory can't
2285 // change between the build and use.
2286 if (F.Kind != MK_ExplicitModule) {
2287 const DirectoryEntry *BuildDir =
2288 PP.getFileManager().getDirectory(Blob);
2289 if (!BuildDir || BuildDir != M->Directory) {
2290 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2291 Diag(diag::err_imported_module_relocated)
2292 << F.ModuleName << Blob << M->Directory->getName();
2293 return OutOfDate;
2294 }
2295 }
2296 F.BaseDirectory = M->Directory->getName();
2297 } else {
2298 F.BaseDirectory = Blob;
2299 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002300 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002301 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002302
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002303 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002304 if (ASTReadResult Result =
2305 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2306 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002307 break;
2308
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002309 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002310 NumInputs = Record[0];
2311 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002312 F.InputFileOffsets =
2313 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002314 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002315 break;
2316 }
2317 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002318}
2319
Ben Langmuir2c9af442014-04-10 17:57:43 +00002320ASTReader::ASTReadResult
2321ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002322 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002323
2324 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2325 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002326 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002327 }
2328
2329 // Read all of the records and blocks for the AST file.
2330 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002331 while (1) {
2332 llvm::BitstreamEntry Entry = Stream.advance();
2333
2334 switch (Entry.Kind) {
2335 case llvm::BitstreamEntry::Error:
2336 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002337 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002338 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002339 // Outside of C++, we do not store a lookup map for the translation unit.
2340 // Instead, mark it as needing a lookup map to be built if this module
2341 // contains any declarations lexically within it (which it always does!).
2342 // This usually has no cost, since we very rarely need the lookup map for
2343 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002344 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002345 if (DC->hasExternalLexicalStorage() &&
2346 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002347 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002348
Ben Langmuir2c9af442014-04-10 17:57:43 +00002349 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002350 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002351 case llvm::BitstreamEntry::SubBlock:
2352 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 case DECLTYPES_BLOCK_ID:
2354 // We lazily load the decls block, but we want to set up the
2355 // DeclsCursor cursor to point into it. Clone our current bitcode
2356 // cursor to it, enter the block and read the abbrevs in that block.
2357 // With the main cursor, we just skip over it.
2358 F.DeclsCursor = Stream;
2359 if (Stream.SkipBlock() || // Skip with the main cursor.
2360 // Read the abbrevs.
2361 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2362 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002363 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002364 }
2365 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002366
Guy Benyei11169dd2012-12-18 14:30:41 +00002367 case PREPROCESSOR_BLOCK_ID:
2368 F.MacroCursor = Stream;
2369 if (!PP.getExternalSource())
2370 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002371
Guy Benyei11169dd2012-12-18 14:30:41 +00002372 if (Stream.SkipBlock() ||
2373 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2374 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002375 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002376 }
2377 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2378 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002379
Guy Benyei11169dd2012-12-18 14:30:41 +00002380 case PREPROCESSOR_DETAIL_BLOCK_ID:
2381 F.PreprocessorDetailCursor = Stream;
2382 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002383 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002385 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002386 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002387 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002388 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002389 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2390
Guy Benyei11169dd2012-12-18 14:30:41 +00002391 if (!PP.getPreprocessingRecord())
2392 PP.createPreprocessingRecord();
2393 if (!PP.getPreprocessingRecord()->getExternalSource())
2394 PP.getPreprocessingRecord()->SetExternalSource(*this);
2395 break;
2396
2397 case SOURCE_MANAGER_BLOCK_ID:
2398 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002399 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002400 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002401
Guy Benyei11169dd2012-12-18 14:30:41 +00002402 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002403 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2404 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002406
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002408 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002409 if (Stream.SkipBlock() ||
2410 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2411 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002412 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002413 }
2414 CommentsCursors.push_back(std::make_pair(C, &F));
2415 break;
2416 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002417
Guy Benyei11169dd2012-12-18 14:30:41 +00002418 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002419 if (Stream.SkipBlock()) {
2420 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002421 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002422 }
2423 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 }
2425 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002426
2427 case llvm::BitstreamEntry::Record:
2428 // The interesting case.
2429 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002430 }
2431
2432 // Read and process a record.
2433 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002434 StringRef Blob;
2435 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002436 default: // Default behavior: ignore.
2437 break;
2438
2439 case TYPE_OFFSET: {
2440 if (F.LocalNumTypes != 0) {
2441 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002442 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002443 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002444 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002445 F.LocalNumTypes = Record[0];
2446 unsigned LocalBaseTypeIndex = Record[1];
2447 F.BaseTypeIndex = getTotalNumTypes();
2448
2449 if (F.LocalNumTypes > 0) {
2450 // Introduce the global -> local mapping for types within this module.
2451 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2452
2453 // Introduce the local -> global mapping for types within this module.
2454 F.TypeRemap.insertOrReplace(
2455 std::make_pair(LocalBaseTypeIndex,
2456 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002457
2458 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002459 }
2460 break;
2461 }
2462
2463 case DECL_OFFSET: {
2464 if (F.LocalNumDecls != 0) {
2465 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002466 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002467 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002468 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 F.LocalNumDecls = Record[0];
2470 unsigned LocalBaseDeclID = Record[1];
2471 F.BaseDeclID = getTotalNumDecls();
2472
2473 if (F.LocalNumDecls > 0) {
2474 // Introduce the global -> local mapping for declarations within this
2475 // module.
2476 GlobalDeclMap.insert(
2477 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2478
2479 // Introduce the local -> global mapping for declarations within this
2480 // module.
2481 F.DeclRemap.insertOrReplace(
2482 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2483
2484 // Introduce the global -> local mapping for declarations within this
2485 // module.
2486 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002487
Ben Langmuir52ca6782014-10-20 16:27:32 +00002488 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2489 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 break;
2491 }
2492
2493 case TU_UPDATE_LEXICAL: {
2494 DeclContext *TU = Context.getTranslationUnitDecl();
2495 DeclContextInfo &Info = F.DeclContextInfos[TU];
Richard Smith787c0e42015-07-23 00:53:59 +00002496 Info.LexicalDecls = llvm::makeArrayRef(
2497 reinterpret_cast<const KindDeclIDPair *>(Blob.data()),
2498 static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 TU->setHasExternalLexicalStorage(true);
2500 break;
2501 }
2502
2503 case UPDATE_VISIBLE: {
2504 unsigned Idx = 0;
2505 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2506 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002507 ASTDeclContextNameLookupTable::Create(
2508 (const unsigned char *)Blob.data() + Record[Idx++],
2509 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2510 (const unsigned char *)Blob.data(),
2511 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002512 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002513 auto *DC = cast<DeclContext>(D);
2514 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002515 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2516 delete LookupTable;
2517 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 } else
2519 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2520 break;
2521 }
2522
2523 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002524 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002526 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2527 (const unsigned char *)F.IdentifierTableData + Record[0],
2528 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2529 (const unsigned char *)F.IdentifierTableData,
2530 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002531
2532 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2533 }
2534 break;
2535
2536 case IDENTIFIER_OFFSET: {
2537 if (F.LocalNumIdentifiers != 0) {
2538 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002539 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002540 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002541 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 F.LocalNumIdentifiers = Record[0];
2543 unsigned LocalBaseIdentifierID = Record[1];
2544 F.BaseIdentifierID = getTotalNumIdentifiers();
2545
2546 if (F.LocalNumIdentifiers > 0) {
2547 // Introduce the global -> local mapping for identifiers within this
2548 // module.
2549 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2550 &F));
2551
2552 // Introduce the local -> global mapping for identifiers within this
2553 // module.
2554 F.IdentifierRemap.insertOrReplace(
2555 std::make_pair(LocalBaseIdentifierID,
2556 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002557
Ben Langmuir52ca6782014-10-20 16:27:32 +00002558 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2559 + F.LocalNumIdentifiers);
2560 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 break;
2562 }
2563
Richard Smith33e0f7e2015-07-22 02:08:40 +00002564 case INTERESTING_IDENTIFIERS:
2565 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2566 break;
2567
Ben Langmuir332aafe2014-01-31 01:06:56 +00002568 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002569 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2570 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002572 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 break;
2574
2575 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002576 if (SpecialTypes.empty()) {
2577 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2578 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2579 break;
2580 }
2581
2582 if (SpecialTypes.size() != Record.size()) {
2583 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002584 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002585 }
2586
2587 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2588 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2589 if (!SpecialTypes[I])
2590 SpecialTypes[I] = ID;
2591 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2592 // merge step?
2593 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 break;
2595
2596 case STATISTICS:
2597 TotalNumStatements += Record[0];
2598 TotalNumMacros += Record[1];
2599 TotalLexicalDeclContexts += Record[2];
2600 TotalVisibleDeclContexts += Record[3];
2601 break;
2602
2603 case UNUSED_FILESCOPED_DECLS:
2604 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2605 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2606 break;
2607
2608 case DELEGATING_CTORS:
2609 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2610 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2611 break;
2612
2613 case WEAK_UNDECLARED_IDENTIFIERS:
2614 if (Record.size() % 4 != 0) {
2615 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002616 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002617 }
2618
2619 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2620 // files. This isn't the way to do it :)
2621 WeakUndeclaredIdentifiers.clear();
2622
2623 // Translate the weak, undeclared identifiers into global IDs.
2624 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2625 WeakUndeclaredIdentifiers.push_back(
2626 getGlobalIdentifierID(F, Record[I++]));
2627 WeakUndeclaredIdentifiers.push_back(
2628 getGlobalIdentifierID(F, Record[I++]));
2629 WeakUndeclaredIdentifiers.push_back(
2630 ReadSourceLocation(F, Record, I).getRawEncoding());
2631 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2632 }
2633 break;
2634
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002636 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 F.LocalNumSelectors = Record[0];
2638 unsigned LocalBaseSelectorID = Record[1];
2639 F.BaseSelectorID = getTotalNumSelectors();
2640
2641 if (F.LocalNumSelectors > 0) {
2642 // Introduce the global -> local mapping for selectors within this
2643 // module.
2644 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2645
2646 // Introduce the local -> global mapping for selectors within this
2647 // module.
2648 F.SelectorRemap.insertOrReplace(
2649 std::make_pair(LocalBaseSelectorID,
2650 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002651
2652 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 }
2654 break;
2655 }
2656
2657 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002658 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002659 if (Record[0])
2660 F.SelectorLookupTable
2661 = ASTSelectorLookupTable::Create(
2662 F.SelectorLookupTableData + Record[0],
2663 F.SelectorLookupTableData,
2664 ASTSelectorLookupTrait(*this, F));
2665 TotalNumMethodPoolEntries += Record[1];
2666 break;
2667
2668 case REFERENCED_SELECTOR_POOL:
2669 if (!Record.empty()) {
2670 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2671 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2672 Record[Idx++]));
2673 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2674 getRawEncoding());
2675 }
2676 }
2677 break;
2678
2679 case PP_COUNTER_VALUE:
2680 if (!Record.empty() && Listener)
2681 Listener->ReadCounter(F, Record[0]);
2682 break;
2683
2684 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002685 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 F.NumFileSortedDecls = Record[0];
2687 break;
2688
2689 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002690 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 F.LocalNumSLocEntries = Record[0];
2692 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002693 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002694 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002695 SLocSpaceSize);
2696 // Make our entry in the range map. BaseID is negative and growing, so
2697 // we invert it. Because we invert it, though, we need the other end of
2698 // the range.
2699 unsigned RangeStart =
2700 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2701 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2702 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2703
2704 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2705 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2706 GlobalSLocOffsetMap.insert(
2707 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2708 - SLocSpaceSize,&F));
2709
2710 // Initialize the remapping table.
2711 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002712 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002714 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2716
2717 TotalNumSLocEntries += F.LocalNumSLocEntries;
2718 break;
2719 }
2720
2721 case MODULE_OFFSET_MAP: {
2722 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002723 const unsigned char *Data = (const unsigned char*)Blob.data();
2724 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002725
2726 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2727 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2728 F.SLocRemap.insert(std::make_pair(0U, 0));
2729 F.SLocRemap.insert(std::make_pair(2U, 1));
2730 }
2731
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002733 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2734 RemapBuilder;
2735 RemapBuilder SLocRemap(F.SLocRemap);
2736 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2737 RemapBuilder MacroRemap(F.MacroRemap);
2738 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2739 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2740 RemapBuilder SelectorRemap(F.SelectorRemap);
2741 RemapBuilder DeclRemap(F.DeclRemap);
2742 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002743
2744 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002745 using namespace llvm::support;
2746 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 StringRef Name = StringRef((const char*)Data, Len);
2748 Data += Len;
2749 ModuleFile *OM = ModuleMgr.lookup(Name);
2750 if (!OM) {
2751 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002752 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002753 }
2754
Justin Bogner57ba0b22014-03-28 22:03:24 +00002755 uint32_t SLocOffset =
2756 endian::readNext<uint32_t, little, unaligned>(Data);
2757 uint32_t IdentifierIDOffset =
2758 endian::readNext<uint32_t, little, unaligned>(Data);
2759 uint32_t MacroIDOffset =
2760 endian::readNext<uint32_t, little, unaligned>(Data);
2761 uint32_t PreprocessedEntityIDOffset =
2762 endian::readNext<uint32_t, little, unaligned>(Data);
2763 uint32_t SubmoduleIDOffset =
2764 endian::readNext<uint32_t, little, unaligned>(Data);
2765 uint32_t SelectorIDOffset =
2766 endian::readNext<uint32_t, little, unaligned>(Data);
2767 uint32_t DeclIDOffset =
2768 endian::readNext<uint32_t, little, unaligned>(Data);
2769 uint32_t TypeIndexOffset =
2770 endian::readNext<uint32_t, little, unaligned>(Data);
2771
Ben Langmuir785180e2014-10-20 16:27:30 +00002772 uint32_t None = std::numeric_limits<uint32_t>::max();
2773
2774 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2775 RemapBuilder &Remap) {
2776 if (Offset != None)
2777 Remap.insert(std::make_pair(Offset,
2778 static_cast<int>(BaseOffset - Offset)));
2779 };
2780 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2781 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2782 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2783 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2784 PreprocessedEntityRemap);
2785 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2786 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2787 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2788 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002789
2790 // Global -> local mappings.
2791 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2792 }
2793 break;
2794 }
2795
2796 case SOURCE_MANAGER_LINE_TABLE:
2797 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002798 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002799 break;
2800
2801 case SOURCE_LOCATION_PRELOADS: {
2802 // Need to transform from the local view (1-based IDs) to the global view,
2803 // which is based off F.SLocEntryBaseID.
2804 if (!F.PreloadSLocEntries.empty()) {
2805 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002806 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002807 }
2808
2809 F.PreloadSLocEntries.swap(Record);
2810 break;
2811 }
2812
2813 case EXT_VECTOR_DECLS:
2814 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2815 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2816 break;
2817
2818 case VTABLE_USES:
2819 if (Record.size() % 3 != 0) {
2820 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002821 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002822 }
2823
2824 // Later tables overwrite earlier ones.
2825 // FIXME: Modules will have some trouble with this. This is clearly not
2826 // the right way to do this.
2827 VTableUses.clear();
2828
2829 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2830 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2831 VTableUses.push_back(
2832 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2833 VTableUses.push_back(Record[Idx++]);
2834 }
2835 break;
2836
Guy Benyei11169dd2012-12-18 14:30:41 +00002837 case PENDING_IMPLICIT_INSTANTIATIONS:
2838 if (PendingInstantiations.size() % 2 != 0) {
2839 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002840 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002841 }
2842
2843 if (Record.size() % 2 != 0) {
2844 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002845 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002846 }
2847
2848 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2849 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2850 PendingInstantiations.push_back(
2851 ReadSourceLocation(F, Record, I).getRawEncoding());
2852 }
2853 break;
2854
2855 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002856 if (Record.size() != 2) {
2857 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002858 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002859 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2861 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2862 break;
2863
2864 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002865 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2866 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2867 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002868
2869 unsigned LocalBasePreprocessedEntityID = Record[0];
2870
2871 unsigned StartingID;
2872 if (!PP.getPreprocessingRecord())
2873 PP.createPreprocessingRecord();
2874 if (!PP.getPreprocessingRecord()->getExternalSource())
2875 PP.getPreprocessingRecord()->SetExternalSource(*this);
2876 StartingID
2877 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002878 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002879 F.BasePreprocessedEntityID = StartingID;
2880
2881 if (F.NumPreprocessedEntities > 0) {
2882 // Introduce the global -> local mapping for preprocessed entities in
2883 // this module.
2884 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2885
2886 // Introduce the local -> global mapping for preprocessed entities in
2887 // this module.
2888 F.PreprocessedEntityRemap.insertOrReplace(
2889 std::make_pair(LocalBasePreprocessedEntityID,
2890 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2891 }
2892
2893 break;
2894 }
2895
2896 case DECL_UPDATE_OFFSETS: {
2897 if (Record.size() % 2 != 0) {
2898 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002899 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002900 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002901 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2902 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2903 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2904
2905 // If we've already loaded the decl, perform the updates when we finish
2906 // loading this block.
2907 if (Decl *D = GetExistingDecl(ID))
2908 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2909 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002910 break;
2911 }
2912
2913 case DECL_REPLACEMENTS: {
2914 if (Record.size() % 3 != 0) {
2915 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002916 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002917 }
2918 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2919 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2920 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2921 break;
2922 }
2923
2924 case OBJC_CATEGORIES_MAP: {
2925 if (F.LocalNumObjCCategoriesInMap != 0) {
2926 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002927 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002928 }
2929
2930 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002931 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002932 break;
2933 }
2934
2935 case OBJC_CATEGORIES:
2936 F.ObjCCategories.swap(Record);
2937 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00002938
Guy Benyei11169dd2012-12-18 14:30:41 +00002939 case CXX_BASE_SPECIFIER_OFFSETS: {
2940 if (F.LocalNumCXXBaseSpecifiers != 0) {
2941 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002942 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002943 }
Richard Smithc2bb8182015-03-24 06:36:48 +00002944
Guy Benyei11169dd2012-12-18 14:30:41 +00002945 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002946 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00002947 break;
2948 }
2949
2950 case CXX_CTOR_INITIALIZERS_OFFSETS: {
2951 if (F.LocalNumCXXCtorInitializers != 0) {
2952 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2953 return Failure;
2954 }
2955
2956 F.LocalNumCXXCtorInitializers = Record[0];
2957 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002958 break;
2959 }
2960
2961 case DIAG_PRAGMA_MAPPINGS:
2962 if (F.PragmaDiagMappings.empty())
2963 F.PragmaDiagMappings.swap(Record);
2964 else
2965 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2966 Record.begin(), Record.end());
2967 break;
2968
2969 case CUDA_SPECIAL_DECL_REFS:
2970 // Later tables overwrite earlier ones.
2971 // FIXME: Modules will have trouble with this.
2972 CUDASpecialDeclRefs.clear();
2973 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2974 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2975 break;
2976
2977 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002978 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002979 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002980 if (Record[0]) {
2981 F.HeaderFileInfoTable
2982 = HeaderFileInfoLookupTable::Create(
2983 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2984 (const unsigned char *)F.HeaderFileInfoTableData,
2985 HeaderFileInfoTrait(*this, F,
2986 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002987 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002988
2989 PP.getHeaderSearchInfo().SetExternalSource(this);
2990 if (!PP.getHeaderSearchInfo().getExternalLookup())
2991 PP.getHeaderSearchInfo().SetExternalLookup(this);
2992 }
2993 break;
2994 }
2995
2996 case FP_PRAGMA_OPTIONS:
2997 // Later tables overwrite earlier ones.
2998 FPPragmaOptions.swap(Record);
2999 break;
3000
3001 case OPENCL_EXTENSIONS:
3002 // Later tables overwrite earlier ones.
3003 OpenCLExtensions.swap(Record);
3004 break;
3005
3006 case TENTATIVE_DEFINITIONS:
3007 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3008 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3009 break;
3010
3011 case KNOWN_NAMESPACES:
3012 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3013 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3014 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003015
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003016 case UNDEFINED_BUT_USED:
3017 if (UndefinedButUsed.size() % 2 != 0) {
3018 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003019 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003020 }
3021
3022 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003023 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003024 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003025 }
3026 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003027 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3028 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003029 ReadSourceLocation(F, Record, I).getRawEncoding());
3030 }
3031 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003032 case DELETE_EXPRS_TO_ANALYZE:
3033 for (unsigned I = 0, N = Record.size(); I != N;) {
3034 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3035 const uint64_t Count = Record[I++];
3036 DelayedDeleteExprs.push_back(Count);
3037 for (uint64_t C = 0; C < Count; ++C) {
3038 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3039 bool IsArrayForm = Record[I++] == 1;
3040 DelayedDeleteExprs.push_back(IsArrayForm);
3041 }
3042 }
3043 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003044
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003046 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003047 // If we aren't loading a module (which has its own exports), make
3048 // all of the imported modules visible.
3049 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003050 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3051 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3052 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3053 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003054 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003055 }
3056 }
3057 break;
3058 }
3059
3060 case LOCAL_REDECLARATIONS: {
3061 F.RedeclarationChains.swap(Record);
3062 break;
3063 }
3064
3065 case LOCAL_REDECLARATIONS_MAP: {
3066 if (F.LocalNumRedeclarationsInMap != 0) {
3067 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003068 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003069 }
3070
3071 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003072 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003073 break;
3074 }
3075
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 case MACRO_OFFSET: {
3077 if (F.LocalNumMacros != 0) {
3078 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003079 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003080 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003081 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003082 F.LocalNumMacros = Record[0];
3083 unsigned LocalBaseMacroID = Record[1];
3084 F.BaseMacroID = getTotalNumMacros();
3085
3086 if (F.LocalNumMacros > 0) {
3087 // Introduce the global -> local mapping for macros within this module.
3088 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3089
3090 // Introduce the local -> global mapping for macros within this module.
3091 F.MacroRemap.insertOrReplace(
3092 std::make_pair(LocalBaseMacroID,
3093 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003094
3095 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003096 }
3097 break;
3098 }
3099
Richard Smithe40f2ba2013-08-07 21:41:30 +00003100 case LATE_PARSED_TEMPLATE: {
3101 LateParsedTemplates.append(Record.begin(), Record.end());
3102 break;
3103 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003104
3105 case OPTIMIZE_PRAGMA_OPTIONS:
3106 if (Record.size() != 1) {
3107 Error("invalid pragma optimize record");
3108 return Failure;
3109 }
3110 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3111 break;
Nico Weber72889432014-09-06 01:25:55 +00003112
3113 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3114 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3115 UnusedLocalTypedefNameCandidates.push_back(
3116 getGlobalDeclID(F, Record[I]));
3117 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003118 }
3119 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003120}
3121
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003122ASTReader::ASTReadResult
3123ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3124 const ModuleFile *ImportedBy,
3125 unsigned ClientLoadCapabilities) {
3126 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003127 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003128
Richard Smithe842a472014-10-22 02:05:46 +00003129 if (F.Kind == MK_ExplicitModule) {
3130 // For an explicitly-loaded module, we don't care whether the original
3131 // module map file exists or matches.
3132 return Success;
3133 }
3134
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003135 // Try to resolve ModuleName in the current header search context and
3136 // verify that it is found in the same module map file as we saved. If the
3137 // top-level AST file is a main file, skip this check because there is no
3138 // usable header search context.
3139 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003140 "MODULE_NAME should come before MODULE_MAP_FILE");
3141 if (F.Kind == MK_ImplicitModule &&
3142 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3143 // An implicitly-loaded module file should have its module listed in some
3144 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003145 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003146 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3147 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3148 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003149 assert(ImportedBy && "top-level import should be verified");
3150 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003151 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3152 << ImportedBy->FileName
3153 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003154 return Missing;
3155 }
3156
Richard Smithe842a472014-10-22 02:05:46 +00003157 assert(M->Name == F.ModuleName && "found module with different name");
3158
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003159 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003160 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003161 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3162 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003163 assert(ImportedBy && "top-level import should be verified");
3164 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3165 Diag(diag::err_imported_module_modmap_changed)
3166 << F.ModuleName << ImportedBy->FileName
3167 << ModMap->getName() << F.ModuleMapPath;
3168 return OutOfDate;
3169 }
3170
3171 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3172 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3173 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003174 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003175 const FileEntry *F =
3176 FileMgr.getFile(Filename, false, false);
3177 if (F == nullptr) {
3178 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3179 Error("could not find file '" + Filename +"' referenced by AST file");
3180 return OutOfDate;
3181 }
3182 AdditionalStoredMaps.insert(F);
3183 }
3184
3185 // Check any additional module map files (e.g. module.private.modulemap)
3186 // that are not in the pcm.
3187 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3188 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3189 // Remove files that match
3190 // Note: SmallPtrSet::erase is really remove
3191 if (!AdditionalStoredMaps.erase(ModMap)) {
3192 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3193 Diag(diag::err_module_different_modmap)
3194 << F.ModuleName << /*new*/0 << ModMap->getName();
3195 return OutOfDate;
3196 }
3197 }
3198 }
3199
3200 // Check any additional module map files that are in the pcm, but not
3201 // found in header search. Cases that match are already removed.
3202 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3203 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3204 Diag(diag::err_module_different_modmap)
3205 << F.ModuleName << /*not new*/1 << ModMap->getName();
3206 return OutOfDate;
3207 }
3208 }
3209
3210 if (Listener)
3211 Listener->ReadModuleMapFile(F.ModuleMapPath);
3212 return Success;
3213}
3214
3215
Douglas Gregorc1489562013-02-12 23:36:21 +00003216/// \brief Move the given method to the back of the global list of methods.
3217static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3218 // Find the entry for this selector in the method pool.
3219 Sema::GlobalMethodPool::iterator Known
3220 = S.MethodPool.find(Method->getSelector());
3221 if (Known == S.MethodPool.end())
3222 return;
3223
3224 // Retrieve the appropriate method list.
3225 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3226 : Known->second.second;
3227 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003228 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003229 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003230 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003231 Found = true;
3232 } else {
3233 // Keep searching.
3234 continue;
3235 }
3236 }
3237
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003238 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003239 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003240 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003241 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003242 }
3243}
3244
Richard Smithde711422015-04-23 21:20:19 +00003245void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003246 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003247 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003248 bool wasHidden = D->Hidden;
3249 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003250
Richard Smith49f906a2014-03-01 00:08:04 +00003251 if (wasHidden && SemaObj) {
3252 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3253 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003254 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003255 }
3256 }
3257}
3258
Richard Smith49f906a2014-03-01 00:08:04 +00003259void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003260 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003261 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003262 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003263 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003264 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003265 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003266 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003267
3268 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003269 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003270 // there is nothing more to do.
3271 continue;
3272 }
Richard Smith49f906a2014-03-01 00:08:04 +00003273
Guy Benyei11169dd2012-12-18 14:30:41 +00003274 if (!Mod->isAvailable()) {
3275 // Modules that aren't available cannot be made visible.
3276 continue;
3277 }
3278
3279 // Update the module's name visibility.
3280 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003281
Guy Benyei11169dd2012-12-18 14:30:41 +00003282 // If we've already deserialized any names from this module,
3283 // mark them as visible.
3284 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3285 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003286 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003287 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003288 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003289 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3290 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003291 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003292
Guy Benyei11169dd2012-12-18 14:30:41 +00003293 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003294 SmallVector<Module *, 16> Exports;
3295 Mod->getExportedModules(Exports);
3296 for (SmallVectorImpl<Module *>::iterator
3297 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3298 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003299 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003300 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003301 }
3302 }
3303}
3304
Douglas Gregore060e572013-01-25 01:03:03 +00003305bool ASTReader::loadGlobalIndex() {
3306 if (GlobalIndex)
3307 return false;
3308
3309 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3310 !Context.getLangOpts().Modules)
3311 return true;
3312
3313 // Try to load the global index.
3314 TriedLoadingGlobalIndex = true;
3315 StringRef ModuleCachePath
3316 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3317 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003318 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003319 if (!Result.first)
3320 return true;
3321
3322 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003323 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003324 return false;
3325}
3326
3327bool ASTReader::isGlobalIndexUnavailable() const {
3328 return Context.getLangOpts().Modules && UseGlobalIndex &&
3329 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3330}
3331
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003332static void updateModuleTimestamp(ModuleFile &MF) {
3333 // Overwrite the timestamp file contents so that file's mtime changes.
3334 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003335 std::error_code EC;
3336 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3337 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003338 return;
3339 OS << "Timestamp file\n";
3340}
3341
Guy Benyei11169dd2012-12-18 14:30:41 +00003342ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3343 ModuleKind Type,
3344 SourceLocation ImportLoc,
3345 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003346 llvm::SaveAndRestore<SourceLocation>
3347 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3348
Richard Smithd1c46742014-04-30 02:24:17 +00003349 // Defer any pending actions until we get to the end of reading the AST file.
3350 Deserializing AnASTFile(this);
3351
Guy Benyei11169dd2012-12-18 14:30:41 +00003352 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003353 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003354
3355 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003356 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003357 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003358 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003359 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003360 ClientLoadCapabilities)) {
3361 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003362 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003363 case OutOfDate:
3364 case VersionMismatch:
3365 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003366 case HadErrors: {
3367 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3368 for (const ImportedModule &IM : Loaded)
3369 LoadedSet.insert(IM.Mod);
3370
Douglas Gregor7029ce12013-03-19 00:28:20 +00003371 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003372 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003373 Context.getLangOpts().Modules
3374 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003375 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003376
3377 // If we find that any modules are unusable, the global index is going
3378 // to be out-of-date. Just remove it.
3379 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003380 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003381 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003382 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003383 case Success:
3384 break;
3385 }
3386
3387 // Here comes stuff that we only do once the entire chain is loaded.
3388
3389 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003390 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3391 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003392 M != MEnd; ++M) {
3393 ModuleFile &F = *M->Mod;
3394
3395 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003396 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3397 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003398
3399 // Once read, set the ModuleFile bit base offset and update the size in
3400 // bits of all files we've seen.
3401 F.GlobalBitOffset = TotalModulesSizeInBits;
3402 TotalModulesSizeInBits += F.SizeInBits;
3403 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3404
3405 // Preload SLocEntries.
3406 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3407 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3408 // Load it through the SourceManager and don't call ReadSLocEntry()
3409 // directly because the entry may have already been loaded in which case
3410 // calling ReadSLocEntry() directly would trigger an assertion in
3411 // SourceManager.
3412 SourceMgr.getLoadedSLocEntryByID(Index);
3413 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003414
3415 // Preload all the pending interesting identifiers by marking them out of
3416 // date.
3417 for (auto Offset : F.PreloadIdentifierOffsets) {
3418 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3419 F.IdentifierTableData + Offset);
3420
3421 ASTIdentifierLookupTrait Trait(*this, F);
3422 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3423 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3424 PP.getIdentifierTable().getOwn(Key).setOutOfDate(true);
3425 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003426 }
3427
Douglas Gregor603cd862013-03-22 18:50:14 +00003428 // Setup the import locations and notify the module manager that we've
3429 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003430 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3431 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003432 M != MEnd; ++M) {
3433 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003434
3435 ModuleMgr.moduleFileAccepted(&F);
3436
3437 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003438 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003439 if (!M->ImportedBy)
3440 F.ImportLoc = M->ImportLoc;
3441 else
3442 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3443 M->ImportLoc.getRawEncoding());
3444 }
3445
Richard Smith33e0f7e2015-07-22 02:08:40 +00003446 if (!Context.getLangOpts().CPlusPlus ||
3447 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3448 // Mark all of the identifiers in the identifier table as being out of date,
3449 // so that various accessors know to check the loaded modules when the
3450 // identifier is used.
3451 //
3452 // For C++ modules, we don't need information on many identifiers (just
3453 // those that provide macros or are poisoned), so we mark all of
3454 // the interesting ones via PreloadIdentifierOffsets.
3455 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3456 IdEnd = PP.getIdentifierTable().end();
3457 Id != IdEnd; ++Id)
3458 Id->second->setOutOfDate(true);
3459 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003460
3461 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003462 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3463 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003464 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3465 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003466
3467 switch (Unresolved.Kind) {
3468 case UnresolvedModuleRef::Conflict:
3469 if (ResolvedMod) {
3470 Module::Conflict Conflict;
3471 Conflict.Other = ResolvedMod;
3472 Conflict.Message = Unresolved.String.str();
3473 Unresolved.Mod->Conflicts.push_back(Conflict);
3474 }
3475 continue;
3476
3477 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003478 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003479 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003480 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003481
Douglas Gregorfb912652013-03-20 21:10:35 +00003482 case UnresolvedModuleRef::Export:
3483 if (ResolvedMod || Unresolved.IsWildcard)
3484 Unresolved.Mod->Exports.push_back(
3485 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3486 continue;
3487 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003488 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003489 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003490
3491 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3492 // Might be unnecessary as use declarations are only used to build the
3493 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003494
3495 InitializeContext();
3496
Richard Smith3d8e97e2013-10-18 06:54:39 +00003497 if (SemaObj)
3498 UpdateSema();
3499
Guy Benyei11169dd2012-12-18 14:30:41 +00003500 if (DeserializationListener)
3501 DeserializationListener->ReaderInitialized(this);
3502
3503 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3504 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3505 PrimaryModule.OriginalSourceFileID
3506 = FileID::get(PrimaryModule.SLocEntryBaseID
3507 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3508
3509 // If this AST file is a precompiled preamble, then set the
3510 // preamble file ID of the source manager to the file source file
3511 // from which the preamble was built.
3512 if (Type == MK_Preamble) {
3513 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3514 } else if (Type == MK_MainFile) {
3515 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3516 }
3517 }
3518
3519 // For any Objective-C class definitions we have already loaded, make sure
3520 // that we load any additional categories.
3521 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3522 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3523 ObjCClassesLoaded[I],
3524 PreviousGeneration);
3525 }
Douglas Gregore060e572013-01-25 01:03:03 +00003526
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003527 if (PP.getHeaderSearchInfo()
3528 .getHeaderSearchOpts()
3529 .ModulesValidateOncePerBuildSession) {
3530 // Now we are certain that the module and all modules it depends on are
3531 // up to date. Create or update timestamp files for modules that are
3532 // located in the module cache (not for PCH files that could be anywhere
3533 // in the filesystem).
3534 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3535 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003536 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003537 updateModuleTimestamp(*M.Mod);
3538 }
3539 }
3540 }
3541
Guy Benyei11169dd2012-12-18 14:30:41 +00003542 return Success;
3543}
3544
Ben Langmuir487ea142014-10-23 18:05:36 +00003545static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3546
Ben Langmuir70a1b812015-03-24 04:43:52 +00003547/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3548static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3549 return Stream.Read(8) == 'C' &&
3550 Stream.Read(8) == 'P' &&
3551 Stream.Read(8) == 'C' &&
3552 Stream.Read(8) == 'H';
3553}
3554
Guy Benyei11169dd2012-12-18 14:30:41 +00003555ASTReader::ASTReadResult
3556ASTReader::ReadASTCore(StringRef FileName,
3557 ModuleKind Type,
3558 SourceLocation ImportLoc,
3559 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003560 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003561 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003562 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003563 unsigned ClientLoadCapabilities) {
3564 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003565 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003566 ModuleManager::AddModuleResult AddResult
3567 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003568 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003569 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003570 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003571
Douglas Gregor7029ce12013-03-19 00:28:20 +00003572 switch (AddResult) {
3573 case ModuleManager::AlreadyLoaded:
3574 return Success;
3575
3576 case ModuleManager::NewlyLoaded:
3577 // Load module file below.
3578 break;
3579
3580 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003581 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003582 // it.
3583 if (ClientLoadCapabilities & ARR_Missing)
3584 return Missing;
3585
3586 // Otherwise, return an error.
3587 {
3588 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3589 + ErrorStr;
3590 Error(Msg);
3591 }
3592 return Failure;
3593
3594 case ModuleManager::OutOfDate:
3595 // We couldn't load the module file because it is out-of-date. If the
3596 // client can handle out-of-date, return it.
3597 if (ClientLoadCapabilities & ARR_OutOfDate)
3598 return OutOfDate;
3599
3600 // Otherwise, return an error.
3601 {
3602 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3603 + ErrorStr;
3604 Error(Msg);
3605 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003606 return Failure;
3607 }
3608
Douglas Gregor7029ce12013-03-19 00:28:20 +00003609 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003610
3611 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3612 // module?
3613 if (FileName != "-") {
3614 CurrentDir = llvm::sys::path::parent_path(FileName);
3615 if (CurrentDir.empty()) CurrentDir = ".";
3616 }
3617
3618 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003619 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003620 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003621 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003622 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3623
Guy Benyei11169dd2012-12-18 14:30:41 +00003624 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003625 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003626 Diag(diag::err_not_a_pch_file) << FileName;
3627 return Failure;
3628 }
3629
3630 // This is used for compatibility with older PCH formats.
3631 bool HaveReadControlBlock = false;
3632
Chris Lattnerefa77172013-01-20 00:00:22 +00003633 while (1) {
3634 llvm::BitstreamEntry Entry = Stream.advance();
3635
3636 switch (Entry.Kind) {
3637 case llvm::BitstreamEntry::Error:
3638 case llvm::BitstreamEntry::EndBlock:
3639 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003640 Error("invalid record at top-level of AST file");
3641 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003642
3643 case llvm::BitstreamEntry::SubBlock:
3644 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003645 }
3646
Guy Benyei11169dd2012-12-18 14:30:41 +00003647 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003648 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003649 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3650 if (Stream.ReadBlockInfoBlock()) {
3651 Error("malformed BlockInfoBlock in AST file");
3652 return Failure;
3653 }
3654 break;
3655 case CONTROL_BLOCK_ID:
3656 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003657 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003658 case Success:
3659 break;
3660
3661 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003662 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003663 case OutOfDate: return OutOfDate;
3664 case VersionMismatch: return VersionMismatch;
3665 case ConfigurationMismatch: return ConfigurationMismatch;
3666 case HadErrors: return HadErrors;
3667 }
3668 break;
3669 case AST_BLOCK_ID:
3670 if (!HaveReadControlBlock) {
3671 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003672 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003673 return VersionMismatch;
3674 }
3675
3676 // Record that we've loaded this module.
3677 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3678 return Success;
3679
3680 default:
3681 if (Stream.SkipBlock()) {
3682 Error("malformed block record in AST file");
3683 return Failure;
3684 }
3685 break;
3686 }
3687 }
3688
3689 return Success;
3690}
3691
Richard Smitha7e2cc62015-05-01 01:53:09 +00003692void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003693 // If there's a listener, notify them that we "read" the translation unit.
3694 if (DeserializationListener)
3695 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3696 Context.getTranslationUnitDecl());
3697
Guy Benyei11169dd2012-12-18 14:30:41 +00003698 // FIXME: Find a better way to deal with collisions between these
3699 // built-in types. Right now, we just ignore the problem.
3700
3701 // Load the special types.
3702 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3703 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3704 if (!Context.CFConstantStringTypeDecl)
3705 Context.setCFConstantStringType(GetType(String));
3706 }
3707
3708 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3709 QualType FileType = GetType(File);
3710 if (FileType.isNull()) {
3711 Error("FILE type is NULL");
3712 return;
3713 }
3714
3715 if (!Context.FILEDecl) {
3716 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3717 Context.setFILEDecl(Typedef->getDecl());
3718 else {
3719 const TagType *Tag = FileType->getAs<TagType>();
3720 if (!Tag) {
3721 Error("Invalid FILE type in AST file");
3722 return;
3723 }
3724 Context.setFILEDecl(Tag->getDecl());
3725 }
3726 }
3727 }
3728
3729 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3730 QualType Jmp_bufType = GetType(Jmp_buf);
3731 if (Jmp_bufType.isNull()) {
3732 Error("jmp_buf type is NULL");
3733 return;
3734 }
3735
3736 if (!Context.jmp_bufDecl) {
3737 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3738 Context.setjmp_bufDecl(Typedef->getDecl());
3739 else {
3740 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3741 if (!Tag) {
3742 Error("Invalid jmp_buf type in AST file");
3743 return;
3744 }
3745 Context.setjmp_bufDecl(Tag->getDecl());
3746 }
3747 }
3748 }
3749
3750 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3751 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3752 if (Sigjmp_bufType.isNull()) {
3753 Error("sigjmp_buf type is NULL");
3754 return;
3755 }
3756
3757 if (!Context.sigjmp_bufDecl) {
3758 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3759 Context.setsigjmp_bufDecl(Typedef->getDecl());
3760 else {
3761 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3762 assert(Tag && "Invalid sigjmp_buf type in AST file");
3763 Context.setsigjmp_bufDecl(Tag->getDecl());
3764 }
3765 }
3766 }
3767
3768 if (unsigned ObjCIdRedef
3769 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3770 if (Context.ObjCIdRedefinitionType.isNull())
3771 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3772 }
3773
3774 if (unsigned ObjCClassRedef
3775 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3776 if (Context.ObjCClassRedefinitionType.isNull())
3777 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3778 }
3779
3780 if (unsigned ObjCSelRedef
3781 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3782 if (Context.ObjCSelRedefinitionType.isNull())
3783 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3784 }
3785
3786 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3787 QualType Ucontext_tType = GetType(Ucontext_t);
3788 if (Ucontext_tType.isNull()) {
3789 Error("ucontext_t type is NULL");
3790 return;
3791 }
3792
3793 if (!Context.ucontext_tDecl) {
3794 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3795 Context.setucontext_tDecl(Typedef->getDecl());
3796 else {
3797 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3798 assert(Tag && "Invalid ucontext_t type in AST file");
3799 Context.setucontext_tDecl(Tag->getDecl());
3800 }
3801 }
3802 }
3803 }
3804
3805 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3806
3807 // If there were any CUDA special declarations, deserialize them.
3808 if (!CUDASpecialDeclRefs.empty()) {
3809 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3810 Context.setcudaConfigureCallDecl(
3811 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3812 }
Richard Smith56be7542014-03-21 00:33:59 +00003813
Guy Benyei11169dd2012-12-18 14:30:41 +00003814 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003815 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003816 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003817 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003818 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003819 /*ImportLoc=*/Import.ImportLoc);
3820 PP.makeModuleVisible(Imported, Import.ImportLoc);
3821 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003822 }
3823 ImportedModules.clear();
3824}
3825
3826void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003827 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003828}
3829
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003830/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3831/// cursor into the start of the given block ID, returning false on success and
3832/// true on failure.
3833static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003834 while (1) {
3835 llvm::BitstreamEntry Entry = Cursor.advance();
3836 switch (Entry.Kind) {
3837 case llvm::BitstreamEntry::Error:
3838 case llvm::BitstreamEntry::EndBlock:
3839 return true;
3840
3841 case llvm::BitstreamEntry::Record:
3842 // Ignore top-level records.
3843 Cursor.skipRecord(Entry.ID);
3844 break;
3845
3846 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003847 if (Entry.ID == BlockID) {
3848 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003849 return true;
3850 // Found it!
3851 return false;
3852 }
3853
3854 if (Cursor.SkipBlock())
3855 return true;
3856 }
3857 }
3858}
3859
Ben Langmuir70a1b812015-03-24 04:43:52 +00003860/// \brief Reads and return the signature record from \p StreamFile's control
3861/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003862static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3863 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003864 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003865 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003866
3867 // Scan for the CONTROL_BLOCK_ID block.
3868 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3869 return 0;
3870
3871 // Scan for SIGNATURE inside the control block.
3872 ASTReader::RecordData Record;
3873 while (1) {
3874 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3875 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3876 Entry.Kind != llvm::BitstreamEntry::Record)
3877 return 0;
3878
3879 Record.clear();
3880 StringRef Blob;
3881 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3882 return Record[0];
3883 }
3884}
3885
Guy Benyei11169dd2012-12-18 14:30:41 +00003886/// \brief Retrieve the name of the original source file name
3887/// directly from the AST file, without actually loading the AST
3888/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003889std::string ASTReader::getOriginalSourceFile(
3890 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003891 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003892 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00003893 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00003894 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00003895 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3896 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00003897 return std::string();
3898 }
3899
3900 // Initialize the stream
3901 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003902 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003903 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003904
3905 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003906 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003907 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3908 return std::string();
3909 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003910
Chris Lattnere7b154b2013-01-19 21:39:22 +00003911 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003912 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003913 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3914 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003915 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003916
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003917 // Scan for ORIGINAL_FILE inside the control block.
3918 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003919 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003920 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003921 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3922 return std::string();
3923
3924 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3925 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3926 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003927 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003928
Guy Benyei11169dd2012-12-18 14:30:41 +00003929 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003930 StringRef Blob;
3931 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3932 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003933 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003934}
3935
3936namespace {
3937 class SimplePCHValidator : public ASTReaderListener {
3938 const LangOptions &ExistingLangOpts;
3939 const TargetOptions &ExistingTargetOpts;
3940 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003941 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00003942 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003943
Guy Benyei11169dd2012-12-18 14:30:41 +00003944 public:
3945 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3946 const TargetOptions &ExistingTargetOpts,
3947 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003948 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00003949 FileManager &FileMgr)
3950 : ExistingLangOpts(ExistingLangOpts),
3951 ExistingTargetOpts(ExistingTargetOpts),
3952 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003953 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00003954 FileMgr(FileMgr)
3955 {
3956 }
3957
Richard Smith1e2cf0d2014-10-31 02:28:58 +00003958 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
3959 bool AllowCompatibleDifferences) override {
3960 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
3961 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003962 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00003963 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
3964 bool AllowCompatibleDifferences) override {
3965 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
3966 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003967 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003968 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
3969 StringRef SpecificModuleCachePath,
3970 bool Complain) override {
3971 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
3972 ExistingModuleCachePath,
3973 nullptr, ExistingLangOpts);
3974 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003975 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3976 bool Complain,
3977 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00003978 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003979 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003980 }
3981 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003982}
Guy Benyei11169dd2012-12-18 14:30:41 +00003983
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003984bool ASTReader::readASTFileControlBlock(
3985 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003986 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003987 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003988 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00003989 // FIXME: This allows use of the VFS; we do not allow use of the
3990 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00003991 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00003992 if (!Buffer) {
3993 return true;
3994 }
3995
3996 // Initialize the stream
3997 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003998 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003999 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004000
4001 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004002 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004003 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004004
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004005 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004006 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004007 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004008
4009 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004010 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004011 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004012 BitstreamCursor InputFilesCursor;
4013 if (NeedsInputFiles) {
4014 InputFilesCursor = Stream;
4015 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4016 return true;
4017
4018 // Read the abbreviations
4019 while (true) {
4020 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4021 unsigned Code = InputFilesCursor.ReadCode();
4022
4023 // We expect all abbrevs to be at the start of the block.
4024 if (Code != llvm::bitc::DEFINE_ABBREV) {
4025 InputFilesCursor.JumpToBit(Offset);
4026 break;
4027 }
4028 InputFilesCursor.ReadAbbrevRecord();
4029 }
4030 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004031
4032 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004033 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004034 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004035 while (1) {
4036 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4037 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4038 return false;
4039
4040 if (Entry.Kind != llvm::BitstreamEntry::Record)
4041 return true;
4042
Guy Benyei11169dd2012-12-18 14:30:41 +00004043 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004044 StringRef Blob;
4045 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004046 switch ((ControlRecordTypes)RecCode) {
4047 case METADATA: {
4048 if (Record[0] != VERSION_MAJOR)
4049 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004050
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004051 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004052 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004053
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004054 break;
4055 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004056 case MODULE_NAME:
4057 Listener.ReadModuleName(Blob);
4058 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004059 case MODULE_DIRECTORY:
4060 ModuleDir = Blob;
4061 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004062 case MODULE_MAP_FILE: {
4063 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004064 auto Path = ReadString(Record, Idx);
4065 ResolveImportedPath(Path, ModuleDir);
4066 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004067 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004068 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004069 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004070 if (ParseLanguageOptions(Record, false, Listener,
4071 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004072 return true;
4073 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004074
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004075 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004076 if (ParseTargetOptions(Record, false, Listener,
4077 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004078 return true;
4079 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004080
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004081 case DIAGNOSTIC_OPTIONS:
4082 if (ParseDiagnosticOptions(Record, false, Listener))
4083 return true;
4084 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004085
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004086 case FILE_SYSTEM_OPTIONS:
4087 if (ParseFileSystemOptions(Record, false, Listener))
4088 return true;
4089 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004090
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004091 case HEADER_SEARCH_OPTIONS:
4092 if (ParseHeaderSearchOptions(Record, false, Listener))
4093 return true;
4094 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004095
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004096 case PREPROCESSOR_OPTIONS: {
4097 std::string IgnoredSuggestedPredefines;
4098 if (ParsePreprocessorOptions(Record, false, Listener,
4099 IgnoredSuggestedPredefines))
4100 return true;
4101 break;
4102 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004103
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004104 case INPUT_FILE_OFFSETS: {
4105 if (!NeedsInputFiles)
4106 break;
4107
4108 unsigned NumInputFiles = Record[0];
4109 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004110 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004111 for (unsigned I = 0; I != NumInputFiles; ++I) {
4112 // Go find this input file.
4113 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004114
4115 if (isSystemFile && !NeedsSystemInputFiles)
4116 break; // the rest are system input files
4117
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004118 BitstreamCursor &Cursor = InputFilesCursor;
4119 SavedStreamPosition SavedPosition(Cursor);
4120 Cursor.JumpToBit(InputFileOffs[I]);
4121
4122 unsigned Code = Cursor.ReadCode();
4123 RecordData Record;
4124 StringRef Blob;
4125 bool shouldContinue = false;
4126 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4127 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004128 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004129 std::string Filename = Blob;
4130 ResolveImportedPath(Filename, ModuleDir);
4131 shouldContinue =
4132 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004133 break;
4134 }
4135 if (!shouldContinue)
4136 break;
4137 }
4138 break;
4139 }
4140
Richard Smithd4b230b2014-10-27 23:01:16 +00004141 case IMPORTS: {
4142 if (!NeedsImports)
4143 break;
4144
4145 unsigned Idx = 0, N = Record.size();
4146 while (Idx < N) {
4147 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004148 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004149 std::string Filename = ReadString(Record, Idx);
4150 ResolveImportedPath(Filename, ModuleDir);
4151 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004152 }
4153 break;
4154 }
4155
Richard Smith7f330cd2015-03-18 01:42:29 +00004156 case KNOWN_MODULE_FILES: {
4157 // Known-but-not-technically-used module files are treated as imports.
4158 if (!NeedsImports)
4159 break;
4160
4161 unsigned Idx = 0, N = Record.size();
4162 while (Idx < N) {
4163 std::string Filename = ReadString(Record, Idx);
4164 ResolveImportedPath(Filename, ModuleDir);
4165 Listener.visitImport(Filename);
4166 }
4167 break;
4168 }
4169
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004170 default:
4171 // No other validation to perform.
4172 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004173 }
4174 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004175}
4176
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004177bool ASTReader::isAcceptableASTFile(
4178 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004179 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004180 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4181 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004182 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4183 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004184 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004185 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004186}
4187
Ben Langmuir2c9af442014-04-10 17:57:43 +00004188ASTReader::ASTReadResult
4189ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004190 // Enter the submodule block.
4191 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4192 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004193 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004194 }
4195
4196 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4197 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004198 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004199 RecordData Record;
4200 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004201 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4202
4203 switch (Entry.Kind) {
4204 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4205 case llvm::BitstreamEntry::Error:
4206 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004207 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004208 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004209 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004210 case llvm::BitstreamEntry::Record:
4211 // The interesting case.
4212 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004214
Guy Benyei11169dd2012-12-18 14:30:41 +00004215 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004216 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004217 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004218 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4219
4220 if ((Kind == SUBMODULE_METADATA) != First) {
4221 Error("submodule metadata record should be at beginning of block");
4222 return Failure;
4223 }
4224 First = false;
4225
4226 // Submodule information is only valid if we have a current module.
4227 // FIXME: Should we error on these cases?
4228 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4229 Kind != SUBMODULE_DEFINITION)
4230 continue;
4231
4232 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004233 default: // Default behavior: ignore.
4234 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004235
Richard Smith03478d92014-10-23 22:12:14 +00004236 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004237 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004238 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004239 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004240 }
Richard Smith03478d92014-10-23 22:12:14 +00004241
Chris Lattner0e6c9402013-01-20 02:38:54 +00004242 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004243 unsigned Idx = 0;
4244 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4245 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4246 bool IsFramework = Record[Idx++];
4247 bool IsExplicit = Record[Idx++];
4248 bool IsSystem = Record[Idx++];
4249 bool IsExternC = Record[Idx++];
4250 bool InferSubmodules = Record[Idx++];
4251 bool InferExplicitSubmodules = Record[Idx++];
4252 bool InferExportWildcard = Record[Idx++];
4253 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004254
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004255 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004256 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004257 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004258
Guy Benyei11169dd2012-12-18 14:30:41 +00004259 // Retrieve this (sub)module from the module map, creating it if
4260 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004261 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004262 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004263
4264 // FIXME: set the definition loc for CurrentModule, or call
4265 // ModMap.setInferredModuleAllowedBy()
4266
Guy Benyei11169dd2012-12-18 14:30:41 +00004267 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4268 if (GlobalIndex >= SubmodulesLoaded.size() ||
4269 SubmodulesLoaded[GlobalIndex]) {
4270 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004271 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004272 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004273
Douglas Gregor7029ce12013-03-19 00:28:20 +00004274 if (!ParentModule) {
4275 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4276 if (CurFile != F.File) {
4277 if (!Diags.isDiagnosticInFlight()) {
4278 Diag(diag::err_module_file_conflict)
4279 << CurrentModule->getTopLevelModuleName()
4280 << CurFile->getName()
4281 << F.File->getName();
4282 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004283 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004284 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004285 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004286
4287 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004288 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004289
Adrian Prantl15bcf702015-06-30 17:39:43 +00004290 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004291 CurrentModule->IsFromModuleFile = true;
4292 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004293 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004294 CurrentModule->InferSubmodules = InferSubmodules;
4295 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4296 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004297 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004298 if (DeserializationListener)
4299 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4300
4301 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004302
Douglas Gregorfb912652013-03-20 21:10:35 +00004303 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004304 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004305 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004306 CurrentModule->UnresolvedConflicts.clear();
4307 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004308 break;
4309 }
4310
4311 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004312 std::string Filename = Blob;
4313 ResolveImportedPath(F, Filename);
4314 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004315 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004316 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4317 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004318 // This can be a spurious difference caused by changing the VFS to
4319 // point to a different copy of the file, and it is too late to
4320 // to rebuild safely.
4321 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4322 // after input file validation only real problems would remain and we
4323 // could just error. For now, assume it's okay.
4324 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004325 }
4326 }
4327 break;
4328 }
4329
Richard Smith202210b2014-10-24 20:23:01 +00004330 case SUBMODULE_HEADER:
4331 case SUBMODULE_EXCLUDED_HEADER:
4332 case SUBMODULE_PRIVATE_HEADER:
4333 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004334 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4335 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004336 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004337
Richard Smith202210b2014-10-24 20:23:01 +00004338 case SUBMODULE_TEXTUAL_HEADER:
4339 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4340 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4341 // them here.
4342 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004343
Guy Benyei11169dd2012-12-18 14:30:41 +00004344 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004345 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004346 break;
4347 }
4348
4349 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004350 std::string Dirname = Blob;
4351 ResolveImportedPath(F, Dirname);
4352 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004354 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4355 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004356 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4357 Error("mismatched umbrella directories in submodule");
4358 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004359 }
4360 }
4361 break;
4362 }
4363
4364 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004365 F.BaseSubmoduleID = getTotalNumSubmodules();
4366 F.LocalNumSubmodules = Record[0];
4367 unsigned LocalBaseSubmoduleID = Record[1];
4368 if (F.LocalNumSubmodules > 0) {
4369 // Introduce the global -> local mapping for submodules within this
4370 // module.
4371 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4372
4373 // Introduce the local -> global mapping for submodules within this
4374 // module.
4375 F.SubmoduleRemap.insertOrReplace(
4376 std::make_pair(LocalBaseSubmoduleID,
4377 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004378
Ben Langmuir52ca6782014-10-20 16:27:32 +00004379 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4380 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004381 break;
4382 }
4383
4384 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004385 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004386 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 Unresolved.File = &F;
4388 Unresolved.Mod = CurrentModule;
4389 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004390 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004391 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004392 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004393 }
4394 break;
4395 }
4396
4397 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004398 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004399 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004400 Unresolved.File = &F;
4401 Unresolved.Mod = CurrentModule;
4402 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004403 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004405 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004406 }
4407
4408 // Once we've loaded the set of exports, there's no reason to keep
4409 // the parsed, unresolved exports around.
4410 CurrentModule->UnresolvedExports.clear();
4411 break;
4412 }
4413 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004414 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 Context.getTargetInfo());
4416 break;
4417 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004418
4419 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004420 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004421 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004422 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004423
4424 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004425 CurrentModule->ConfigMacros.push_back(Blob.str());
4426 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004427
4428 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004429 UnresolvedModuleRef Unresolved;
4430 Unresolved.File = &F;
4431 Unresolved.Mod = CurrentModule;
4432 Unresolved.ID = Record[0];
4433 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4434 Unresolved.IsWildcard = false;
4435 Unresolved.String = Blob;
4436 UnresolvedModuleRefs.push_back(Unresolved);
4437 break;
4438 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 }
4440 }
4441}
4442
4443/// \brief Parse the record that corresponds to a LangOptions data
4444/// structure.
4445///
4446/// This routine parses the language options from the AST file and then gives
4447/// them to the AST listener if one is set.
4448///
4449/// \returns true if the listener deems the file unacceptable, false otherwise.
4450bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4451 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004452 ASTReaderListener &Listener,
4453 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004454 LangOptions LangOpts;
4455 unsigned Idx = 0;
4456#define LANGOPT(Name, Bits, Default, Description) \
4457 LangOpts.Name = Record[Idx++];
4458#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4459 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4460#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004461#define SANITIZER(NAME, ID) \
4462 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004463#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004464
Ben Langmuircd98cb72015-06-23 18:20:18 +00004465 for (unsigned N = Record[Idx++]; N; --N)
4466 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4467
Guy Benyei11169dd2012-12-18 14:30:41 +00004468 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4469 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4470 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004471
Ben Langmuird4a667a2015-06-23 18:20:23 +00004472 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004473
4474 // Comment options.
4475 for (unsigned N = Record[Idx++]; N; --N) {
4476 LangOpts.CommentOpts.BlockCommandNames.push_back(
4477 ReadString(Record, Idx));
4478 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004479 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004480
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004481 return Listener.ReadLanguageOptions(LangOpts, Complain,
4482 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004483}
4484
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004485bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4486 ASTReaderListener &Listener,
4487 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004488 unsigned Idx = 0;
4489 TargetOptions TargetOpts;
4490 TargetOpts.Triple = ReadString(Record, Idx);
4491 TargetOpts.CPU = ReadString(Record, Idx);
4492 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004493 for (unsigned N = Record[Idx++]; N; --N) {
4494 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4495 }
4496 for (unsigned N = Record[Idx++]; N; --N) {
4497 TargetOpts.Features.push_back(ReadString(Record, Idx));
4498 }
4499
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004500 return Listener.ReadTargetOptions(TargetOpts, Complain,
4501 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004502}
4503
4504bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4505 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004506 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004507 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004508#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004509#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004510 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004511#include "clang/Basic/DiagnosticOptions.def"
4512
Richard Smith3be1cb22014-08-07 00:24:21 +00004513 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004514 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004515 for (unsigned N = Record[Idx++]; N; --N)
4516 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004517
4518 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4519}
4520
4521bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4522 ASTReaderListener &Listener) {
4523 FileSystemOptions FSOpts;
4524 unsigned Idx = 0;
4525 FSOpts.WorkingDir = ReadString(Record, Idx);
4526 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4527}
4528
4529bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4530 bool Complain,
4531 ASTReaderListener &Listener) {
4532 HeaderSearchOptions HSOpts;
4533 unsigned Idx = 0;
4534 HSOpts.Sysroot = ReadString(Record, Idx);
4535
4536 // Include entries.
4537 for (unsigned N = Record[Idx++]; N; --N) {
4538 std::string Path = ReadString(Record, Idx);
4539 frontend::IncludeDirGroup Group
4540 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004541 bool IsFramework = Record[Idx++];
4542 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004543 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4544 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 }
4546
4547 // System header prefixes.
4548 for (unsigned N = Record[Idx++]; N; --N) {
4549 std::string Prefix = ReadString(Record, Idx);
4550 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004551 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004552 }
4553
4554 HSOpts.ResourceDir = ReadString(Record, Idx);
4555 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004556 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 HSOpts.DisableModuleHash = Record[Idx++];
4558 HSOpts.UseBuiltinIncludes = Record[Idx++];
4559 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4560 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4561 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004562 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004563
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004564 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4565 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004566}
4567
4568bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4569 bool Complain,
4570 ASTReaderListener &Listener,
4571 std::string &SuggestedPredefines) {
4572 PreprocessorOptions PPOpts;
4573 unsigned Idx = 0;
4574
4575 // Macro definitions/undefs
4576 for (unsigned N = Record[Idx++]; N; --N) {
4577 std::string Macro = ReadString(Record, Idx);
4578 bool IsUndef = Record[Idx++];
4579 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4580 }
4581
4582 // Includes
4583 for (unsigned N = Record[Idx++]; N; --N) {
4584 PPOpts.Includes.push_back(ReadString(Record, Idx));
4585 }
4586
4587 // Macro Includes
4588 for (unsigned N = Record[Idx++]; N; --N) {
4589 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4590 }
4591
4592 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004593 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004594 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4595 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4596 PPOpts.ObjCXXARCStandardLibrary =
4597 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4598 SuggestedPredefines.clear();
4599 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4600 SuggestedPredefines);
4601}
4602
4603std::pair<ModuleFile *, unsigned>
4604ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4605 GlobalPreprocessedEntityMapType::iterator
4606 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4607 assert(I != GlobalPreprocessedEntityMap.end() &&
4608 "Corrupted global preprocessed entity map");
4609 ModuleFile *M = I->second;
4610 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4611 return std::make_pair(M, LocalIndex);
4612}
4613
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004614llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004615ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4616 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4617 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4618 Mod.NumPreprocessedEntities);
4619
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004620 return llvm::make_range(PreprocessingRecord::iterator(),
4621 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004622}
4623
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004624llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004625ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004626 return llvm::make_range(
4627 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4628 ModuleDeclIterator(this, &Mod,
4629 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004630}
4631
4632PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4633 PreprocessedEntityID PPID = Index+1;
4634 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4635 ModuleFile &M = *PPInfo.first;
4636 unsigned LocalIndex = PPInfo.second;
4637 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4638
Guy Benyei11169dd2012-12-18 14:30:41 +00004639 if (!PP.getPreprocessingRecord()) {
4640 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004641 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004642 }
4643
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004644 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4645 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4646
4647 llvm::BitstreamEntry Entry =
4648 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4649 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004650 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004651
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 // Read the record.
4653 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4654 ReadSourceLocation(M, PPOffs.End));
4655 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004656 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 RecordData Record;
4658 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004659 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4660 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 switch (RecType) {
4662 case PPD_MACRO_EXPANSION: {
4663 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004664 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004665 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004666 if (isBuiltin)
4667 Name = getLocalIdentifier(M, Record[1]);
4668 else {
Richard Smith66a81862015-05-04 02:25:31 +00004669 PreprocessedEntityID GlobalID =
4670 getGlobalPreprocessedEntityID(M, Record[1]);
4671 Def = cast<MacroDefinitionRecord>(
4672 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004673 }
4674
4675 MacroExpansion *ME;
4676 if (isBuiltin)
4677 ME = new (PPRec) MacroExpansion(Name, Range);
4678 else
4679 ME = new (PPRec) MacroExpansion(Def, Range);
4680
4681 return ME;
4682 }
4683
4684 case PPD_MACRO_DEFINITION: {
4685 // Decode the identifier info and then check again; if the macro is
4686 // still defined and associated with the identifier,
4687 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004688 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004689
4690 if (DeserializationListener)
4691 DeserializationListener->MacroDefinitionRead(PPID, MD);
4692
4693 return MD;
4694 }
4695
4696 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004697 const char *FullFileNameStart = Blob.data() + Record[0];
4698 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004699 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004700 if (!FullFileName.empty())
4701 File = PP.getFileManager().getFile(FullFileName);
4702
4703 // FIXME: Stable encoding
4704 InclusionDirective::InclusionKind Kind
4705 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4706 InclusionDirective *ID
4707 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004708 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004709 Record[1], Record[3],
4710 File,
4711 Range);
4712 return ID;
4713 }
4714 }
4715
4716 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4717}
4718
4719/// \brief \arg SLocMapI points at a chunk of a module that contains no
4720/// preprocessed entities or the entities it contains are not the ones we are
4721/// looking for. Find the next module that contains entities and return the ID
4722/// of the first entry.
4723PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4724 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4725 ++SLocMapI;
4726 for (GlobalSLocOffsetMapType::const_iterator
4727 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4728 ModuleFile &M = *SLocMapI->second;
4729 if (M.NumPreprocessedEntities)
4730 return M.BasePreprocessedEntityID;
4731 }
4732
4733 return getTotalNumPreprocessedEntities();
4734}
4735
4736namespace {
4737
4738template <unsigned PPEntityOffset::*PPLoc>
4739struct PPEntityComp {
4740 const ASTReader &Reader;
4741 ModuleFile &M;
4742
4743 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4744
4745 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4746 SourceLocation LHS = getLoc(L);
4747 SourceLocation RHS = getLoc(R);
4748 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4749 }
4750
4751 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4752 SourceLocation LHS = getLoc(L);
4753 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4754 }
4755
4756 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4757 SourceLocation RHS = getLoc(R);
4758 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4759 }
4760
4761 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4762 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4763 }
4764};
4765
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004766}
Guy Benyei11169dd2012-12-18 14:30:41 +00004767
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004768PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4769 bool EndsAfter) const {
4770 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 return getTotalNumPreprocessedEntities();
4772
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004773 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4774 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004775 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4776 "Corrupted global sloc offset map");
4777
4778 if (SLocMapI->second->NumPreprocessedEntities == 0)
4779 return findNextPreprocessedEntity(SLocMapI);
4780
4781 ModuleFile &M = *SLocMapI->second;
4782 typedef const PPEntityOffset *pp_iterator;
4783 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4784 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4785
4786 size_t Count = M.NumPreprocessedEntities;
4787 size_t Half;
4788 pp_iterator First = pp_begin;
4789 pp_iterator PPI;
4790
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004791 if (EndsAfter) {
4792 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4793 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4794 } else {
4795 // Do a binary search manually instead of using std::lower_bound because
4796 // The end locations of entities may be unordered (when a macro expansion
4797 // is inside another macro argument), but for this case it is not important
4798 // whether we get the first macro expansion or its containing macro.
4799 while (Count > 0) {
4800 Half = Count / 2;
4801 PPI = First;
4802 std::advance(PPI, Half);
4803 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4804 Loc)) {
4805 First = PPI;
4806 ++First;
4807 Count = Count - Half - 1;
4808 } else
4809 Count = Half;
4810 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004811 }
4812
4813 if (PPI == pp_end)
4814 return findNextPreprocessedEntity(SLocMapI);
4815
4816 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4817}
4818
Guy Benyei11169dd2012-12-18 14:30:41 +00004819/// \brief Returns a pair of [Begin, End) indices of preallocated
4820/// preprocessed entities that \arg Range encompasses.
4821std::pair<unsigned, unsigned>
4822 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4823 if (Range.isInvalid())
4824 return std::make_pair(0,0);
4825 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4826
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004827 PreprocessedEntityID BeginID =
4828 findPreprocessedEntity(Range.getBegin(), false);
4829 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004830 return std::make_pair(BeginID, EndID);
4831}
4832
4833/// \brief Optionally returns true or false if the preallocated preprocessed
4834/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004835Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004836 FileID FID) {
4837 if (FID.isInvalid())
4838 return false;
4839
4840 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4841 ModuleFile &M = *PPInfo.first;
4842 unsigned LocalIndex = PPInfo.second;
4843 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4844
4845 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4846 if (Loc.isInvalid())
4847 return false;
4848
4849 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4850 return true;
4851 else
4852 return false;
4853}
4854
4855namespace {
4856 /// \brief Visitor used to search for information about a header file.
4857 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004858 const FileEntry *FE;
4859
David Blaikie05785d12013-02-20 22:23:23 +00004860 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004861
4862 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004863 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4864 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004865
4866 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004867 HeaderFileInfoLookupTable *Table
4868 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4869 if (!Table)
4870 return false;
4871
4872 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00004873 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004874 if (Pos == Table->end())
4875 return false;
4876
Richard Smithbdf2d932015-07-30 03:37:16 +00004877 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00004878 return true;
4879 }
4880
David Blaikie05785d12013-02-20 22:23:23 +00004881 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004882 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004883}
Guy Benyei11169dd2012-12-18 14:30:41 +00004884
4885HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004886 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004887 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004888 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004889 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004890
4891 return HeaderFileInfo();
4892}
4893
4894void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4895 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004896 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004897 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4898 ModuleFile &F = *(*I);
4899 unsigned Idx = 0;
4900 DiagStates.clear();
4901 assert(!Diag.DiagStates.empty());
4902 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4903 while (Idx < F.PragmaDiagMappings.size()) {
4904 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4905 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4906 if (DiagStateID != 0) {
4907 Diag.DiagStatePoints.push_back(
4908 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4909 FullSourceLoc(Loc, SourceMgr)));
4910 continue;
4911 }
4912
4913 assert(DiagStateID == 0);
4914 // A new DiagState was created here.
4915 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4916 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4917 DiagStates.push_back(NewState);
4918 Diag.DiagStatePoints.push_back(
4919 DiagnosticsEngine::DiagStatePoint(NewState,
4920 FullSourceLoc(Loc, SourceMgr)));
4921 while (1) {
4922 assert(Idx < F.PragmaDiagMappings.size() &&
4923 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4924 if (Idx >= F.PragmaDiagMappings.size()) {
4925 break; // Something is messed up but at least avoid infinite loop in
4926 // release build.
4927 }
4928 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4929 if (DiagID == (unsigned)-1) {
4930 break; // no more diag/map pairs for this location.
4931 }
Alp Tokerc726c362014-06-10 09:31:37 +00004932 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4933 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4934 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00004935 }
4936 }
4937 }
4938}
4939
4940/// \brief Get the correct cursor and offset for loading a type.
4941ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4942 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4943 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4944 ModuleFile *M = I->second;
4945 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4946}
4947
4948/// \brief Read and return the type with the given index..
4949///
4950/// The index is the type ID, shifted and minus the number of predefs. This
4951/// routine actually reads the record corresponding to the type at the given
4952/// location. It is a helper routine for GetType, which deals with reading type
4953/// IDs.
4954QualType ASTReader::readTypeRecord(unsigned Index) {
4955 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004956 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004957
4958 // Keep track of where we are in the stream, then jump back there
4959 // after reading this type.
4960 SavedStreamPosition SavedPosition(DeclsCursor);
4961
4962 ReadingKindTracker ReadingKind(Read_Type, *this);
4963
4964 // Note that we are loading a type record.
4965 Deserializing AType(this);
4966
4967 unsigned Idx = 0;
4968 DeclsCursor.JumpToBit(Loc.Offset);
4969 RecordData Record;
4970 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004971 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004972 case TYPE_EXT_QUAL: {
4973 if (Record.size() != 2) {
4974 Error("Incorrect encoding of extended qualifier type");
4975 return QualType();
4976 }
4977 QualType Base = readType(*Loc.F, Record, Idx);
4978 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4979 return Context.getQualifiedType(Base, Quals);
4980 }
4981
4982 case TYPE_COMPLEX: {
4983 if (Record.size() != 1) {
4984 Error("Incorrect encoding of complex type");
4985 return QualType();
4986 }
4987 QualType ElemType = readType(*Loc.F, Record, Idx);
4988 return Context.getComplexType(ElemType);
4989 }
4990
4991 case TYPE_POINTER: {
4992 if (Record.size() != 1) {
4993 Error("Incorrect encoding of pointer type");
4994 return QualType();
4995 }
4996 QualType PointeeType = readType(*Loc.F, Record, Idx);
4997 return Context.getPointerType(PointeeType);
4998 }
4999
Reid Kleckner8a365022013-06-24 17:51:48 +00005000 case TYPE_DECAYED: {
5001 if (Record.size() != 1) {
5002 Error("Incorrect encoding of decayed type");
5003 return QualType();
5004 }
5005 QualType OriginalType = readType(*Loc.F, Record, Idx);
5006 QualType DT = Context.getAdjustedParameterType(OriginalType);
5007 if (!isa<DecayedType>(DT))
5008 Error("Decayed type does not decay");
5009 return DT;
5010 }
5011
Reid Kleckner0503a872013-12-05 01:23:43 +00005012 case TYPE_ADJUSTED: {
5013 if (Record.size() != 2) {
5014 Error("Incorrect encoding of adjusted type");
5015 return QualType();
5016 }
5017 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5018 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5019 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5020 }
5021
Guy Benyei11169dd2012-12-18 14:30:41 +00005022 case TYPE_BLOCK_POINTER: {
5023 if (Record.size() != 1) {
5024 Error("Incorrect encoding of block pointer type");
5025 return QualType();
5026 }
5027 QualType PointeeType = readType(*Loc.F, Record, Idx);
5028 return Context.getBlockPointerType(PointeeType);
5029 }
5030
5031 case TYPE_LVALUE_REFERENCE: {
5032 if (Record.size() != 2) {
5033 Error("Incorrect encoding of lvalue reference type");
5034 return QualType();
5035 }
5036 QualType PointeeType = readType(*Loc.F, Record, Idx);
5037 return Context.getLValueReferenceType(PointeeType, Record[1]);
5038 }
5039
5040 case TYPE_RVALUE_REFERENCE: {
5041 if (Record.size() != 1) {
5042 Error("Incorrect encoding of rvalue reference type");
5043 return QualType();
5044 }
5045 QualType PointeeType = readType(*Loc.F, Record, Idx);
5046 return Context.getRValueReferenceType(PointeeType);
5047 }
5048
5049 case TYPE_MEMBER_POINTER: {
5050 if (Record.size() != 2) {
5051 Error("Incorrect encoding of member pointer type");
5052 return QualType();
5053 }
5054 QualType PointeeType = readType(*Loc.F, Record, Idx);
5055 QualType ClassType = readType(*Loc.F, Record, Idx);
5056 if (PointeeType.isNull() || ClassType.isNull())
5057 return QualType();
5058
5059 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5060 }
5061
5062 case TYPE_CONSTANT_ARRAY: {
5063 QualType ElementType = readType(*Loc.F, Record, Idx);
5064 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5065 unsigned IndexTypeQuals = Record[2];
5066 unsigned Idx = 3;
5067 llvm::APInt Size = ReadAPInt(Record, Idx);
5068 return Context.getConstantArrayType(ElementType, Size,
5069 ASM, IndexTypeQuals);
5070 }
5071
5072 case TYPE_INCOMPLETE_ARRAY: {
5073 QualType ElementType = readType(*Loc.F, Record, Idx);
5074 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5075 unsigned IndexTypeQuals = Record[2];
5076 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5077 }
5078
5079 case TYPE_VARIABLE_ARRAY: {
5080 QualType ElementType = readType(*Loc.F, Record, Idx);
5081 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5082 unsigned IndexTypeQuals = Record[2];
5083 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5084 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5085 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5086 ASM, IndexTypeQuals,
5087 SourceRange(LBLoc, RBLoc));
5088 }
5089
5090 case TYPE_VECTOR: {
5091 if (Record.size() != 3) {
5092 Error("incorrect encoding of vector type in AST file");
5093 return QualType();
5094 }
5095
5096 QualType ElementType = readType(*Loc.F, Record, Idx);
5097 unsigned NumElements = Record[1];
5098 unsigned VecKind = Record[2];
5099 return Context.getVectorType(ElementType, NumElements,
5100 (VectorType::VectorKind)VecKind);
5101 }
5102
5103 case TYPE_EXT_VECTOR: {
5104 if (Record.size() != 3) {
5105 Error("incorrect encoding of extended vector type in AST file");
5106 return QualType();
5107 }
5108
5109 QualType ElementType = readType(*Loc.F, Record, Idx);
5110 unsigned NumElements = Record[1];
5111 return Context.getExtVectorType(ElementType, NumElements);
5112 }
5113
5114 case TYPE_FUNCTION_NO_PROTO: {
5115 if (Record.size() != 6) {
5116 Error("incorrect encoding of no-proto function type");
5117 return QualType();
5118 }
5119 QualType ResultType = readType(*Loc.F, Record, Idx);
5120 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5121 (CallingConv)Record[4], Record[5]);
5122 return Context.getFunctionNoProtoType(ResultType, Info);
5123 }
5124
5125 case TYPE_FUNCTION_PROTO: {
5126 QualType ResultType = readType(*Loc.F, Record, Idx);
5127
5128 FunctionProtoType::ExtProtoInfo EPI;
5129 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5130 /*hasregparm*/ Record[2],
5131 /*regparm*/ Record[3],
5132 static_cast<CallingConv>(Record[4]),
5133 /*produces*/ Record[5]);
5134
5135 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005136
5137 EPI.Variadic = Record[Idx++];
5138 EPI.HasTrailingReturn = Record[Idx++];
5139 EPI.TypeQuals = Record[Idx++];
5140 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005141 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005142 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005143
5144 unsigned NumParams = Record[Idx++];
5145 SmallVector<QualType, 16> ParamTypes;
5146 for (unsigned I = 0; I != NumParams; ++I)
5147 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5148
Jordan Rose5c382722013-03-08 21:51:21 +00005149 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 }
5151
5152 case TYPE_UNRESOLVED_USING: {
5153 unsigned Idx = 0;
5154 return Context.getTypeDeclType(
5155 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5156 }
5157
5158 case TYPE_TYPEDEF: {
5159 if (Record.size() != 2) {
5160 Error("incorrect encoding of typedef type");
5161 return QualType();
5162 }
5163 unsigned Idx = 0;
5164 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5165 QualType Canonical = readType(*Loc.F, Record, Idx);
5166 if (!Canonical.isNull())
5167 Canonical = Context.getCanonicalType(Canonical);
5168 return Context.getTypedefType(Decl, Canonical);
5169 }
5170
5171 case TYPE_TYPEOF_EXPR:
5172 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5173
5174 case TYPE_TYPEOF: {
5175 if (Record.size() != 1) {
5176 Error("incorrect encoding of typeof(type) in AST file");
5177 return QualType();
5178 }
5179 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5180 return Context.getTypeOfType(UnderlyingType);
5181 }
5182
5183 case TYPE_DECLTYPE: {
5184 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5185 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5186 }
5187
5188 case TYPE_UNARY_TRANSFORM: {
5189 QualType BaseType = readType(*Loc.F, Record, Idx);
5190 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5191 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5192 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5193 }
5194
Richard Smith74aeef52013-04-26 16:15:35 +00005195 case TYPE_AUTO: {
5196 QualType Deduced = readType(*Loc.F, Record, Idx);
5197 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005198 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005199 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005200 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005201
5202 case TYPE_RECORD: {
5203 if (Record.size() != 2) {
5204 Error("incorrect encoding of record type");
5205 return QualType();
5206 }
5207 unsigned Idx = 0;
5208 bool IsDependent = Record[Idx++];
5209 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5210 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5211 QualType T = Context.getRecordType(RD);
5212 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5213 return T;
5214 }
5215
5216 case TYPE_ENUM: {
5217 if (Record.size() != 2) {
5218 Error("incorrect encoding of enum type");
5219 return QualType();
5220 }
5221 unsigned Idx = 0;
5222 bool IsDependent = Record[Idx++];
5223 QualType T
5224 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5225 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5226 return T;
5227 }
5228
5229 case TYPE_ATTRIBUTED: {
5230 if (Record.size() != 3) {
5231 Error("incorrect encoding of attributed type");
5232 return QualType();
5233 }
5234 QualType modifiedType = readType(*Loc.F, Record, Idx);
5235 QualType equivalentType = readType(*Loc.F, Record, Idx);
5236 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5237 return Context.getAttributedType(kind, modifiedType, equivalentType);
5238 }
5239
5240 case TYPE_PAREN: {
5241 if (Record.size() != 1) {
5242 Error("incorrect encoding of paren type");
5243 return QualType();
5244 }
5245 QualType InnerType = readType(*Loc.F, Record, Idx);
5246 return Context.getParenType(InnerType);
5247 }
5248
5249 case TYPE_PACK_EXPANSION: {
5250 if (Record.size() != 2) {
5251 Error("incorrect encoding of pack expansion type");
5252 return QualType();
5253 }
5254 QualType Pattern = readType(*Loc.F, Record, Idx);
5255 if (Pattern.isNull())
5256 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005257 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005258 if (Record[1])
5259 NumExpansions = Record[1] - 1;
5260 return Context.getPackExpansionType(Pattern, NumExpansions);
5261 }
5262
5263 case TYPE_ELABORATED: {
5264 unsigned Idx = 0;
5265 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5266 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5267 QualType NamedType = readType(*Loc.F, Record, Idx);
5268 return Context.getElaboratedType(Keyword, NNS, NamedType);
5269 }
5270
5271 case TYPE_OBJC_INTERFACE: {
5272 unsigned Idx = 0;
5273 ObjCInterfaceDecl *ItfD
5274 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5275 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5276 }
5277
5278 case TYPE_OBJC_OBJECT: {
5279 unsigned Idx = 0;
5280 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005281 unsigned NumTypeArgs = Record[Idx++];
5282 SmallVector<QualType, 4> TypeArgs;
5283 for (unsigned I = 0; I != NumTypeArgs; ++I)
5284 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005285 unsigned NumProtos = Record[Idx++];
5286 SmallVector<ObjCProtocolDecl*, 4> Protos;
5287 for (unsigned I = 0; I != NumProtos; ++I)
5288 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005289 bool IsKindOf = Record[Idx++];
5290 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005291 }
5292
5293 case TYPE_OBJC_OBJECT_POINTER: {
5294 unsigned Idx = 0;
5295 QualType Pointee = readType(*Loc.F, Record, Idx);
5296 return Context.getObjCObjectPointerType(Pointee);
5297 }
5298
5299 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5300 unsigned Idx = 0;
5301 QualType Parm = readType(*Loc.F, Record, Idx);
5302 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005303 return Context.getSubstTemplateTypeParmType(
5304 cast<TemplateTypeParmType>(Parm),
5305 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005306 }
5307
5308 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5309 unsigned Idx = 0;
5310 QualType Parm = readType(*Loc.F, Record, Idx);
5311 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5312 return Context.getSubstTemplateTypeParmPackType(
5313 cast<TemplateTypeParmType>(Parm),
5314 ArgPack);
5315 }
5316
5317 case TYPE_INJECTED_CLASS_NAME: {
5318 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5319 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5320 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5321 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005322 const Type *T = nullptr;
5323 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5324 if (const Type *Existing = DI->getTypeForDecl()) {
5325 T = Existing;
5326 break;
5327 }
5328 }
5329 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005330 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005331 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5332 DI->setTypeForDecl(T);
5333 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005334 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005335 }
5336
5337 case TYPE_TEMPLATE_TYPE_PARM: {
5338 unsigned Idx = 0;
5339 unsigned Depth = Record[Idx++];
5340 unsigned Index = Record[Idx++];
5341 bool Pack = Record[Idx++];
5342 TemplateTypeParmDecl *D
5343 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5344 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5345 }
5346
5347 case TYPE_DEPENDENT_NAME: {
5348 unsigned Idx = 0;
5349 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5350 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005351 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005352 QualType Canon = readType(*Loc.F, Record, Idx);
5353 if (!Canon.isNull())
5354 Canon = Context.getCanonicalType(Canon);
5355 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5356 }
5357
5358 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5359 unsigned Idx = 0;
5360 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5361 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005362 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005363 unsigned NumArgs = Record[Idx++];
5364 SmallVector<TemplateArgument, 8> Args;
5365 Args.reserve(NumArgs);
5366 while (NumArgs--)
5367 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5368 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5369 Args.size(), Args.data());
5370 }
5371
5372 case TYPE_DEPENDENT_SIZED_ARRAY: {
5373 unsigned Idx = 0;
5374
5375 // ArrayType
5376 QualType ElementType = readType(*Loc.F, Record, Idx);
5377 ArrayType::ArraySizeModifier ASM
5378 = (ArrayType::ArraySizeModifier)Record[Idx++];
5379 unsigned IndexTypeQuals = Record[Idx++];
5380
5381 // DependentSizedArrayType
5382 Expr *NumElts = ReadExpr(*Loc.F);
5383 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5384
5385 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5386 IndexTypeQuals, Brackets);
5387 }
5388
5389 case TYPE_TEMPLATE_SPECIALIZATION: {
5390 unsigned Idx = 0;
5391 bool IsDependent = Record[Idx++];
5392 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5393 SmallVector<TemplateArgument, 8> Args;
5394 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5395 QualType Underlying = readType(*Loc.F, Record, Idx);
5396 QualType T;
5397 if (Underlying.isNull())
5398 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5399 Args.size());
5400 else
5401 T = Context.getTemplateSpecializationType(Name, Args.data(),
5402 Args.size(), Underlying);
5403 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5404 return T;
5405 }
5406
5407 case TYPE_ATOMIC: {
5408 if (Record.size() != 1) {
5409 Error("Incorrect encoding of atomic type");
5410 return QualType();
5411 }
5412 QualType ValueType = readType(*Loc.F, Record, Idx);
5413 return Context.getAtomicType(ValueType);
5414 }
5415 }
5416 llvm_unreachable("Invalid TypeCode!");
5417}
5418
Richard Smith564417a2014-03-20 21:47:22 +00005419void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5420 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005421 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005422 const RecordData &Record, unsigned &Idx) {
5423 ExceptionSpecificationType EST =
5424 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005425 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005426 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005427 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005428 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005429 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005430 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005431 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005432 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005433 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5434 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005435 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005436 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005437 }
5438}
5439
Guy Benyei11169dd2012-12-18 14:30:41 +00005440class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5441 ASTReader &Reader;
5442 ModuleFile &F;
5443 const ASTReader::RecordData &Record;
5444 unsigned &Idx;
5445
5446 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5447 unsigned &I) {
5448 return Reader.ReadSourceLocation(F, R, I);
5449 }
5450
5451 template<typename T>
5452 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5453 return Reader.ReadDeclAs<T>(F, Record, Idx);
5454 }
5455
5456public:
5457 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5458 const ASTReader::RecordData &Record, unsigned &Idx)
5459 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5460 { }
5461
5462 // We want compile-time assurance that we've enumerated all of
5463 // these, so unfortunately we have to declare them first, then
5464 // define them out-of-line.
5465#define ABSTRACT_TYPELOC(CLASS, PARENT)
5466#define TYPELOC(CLASS, PARENT) \
5467 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5468#include "clang/AST/TypeLocNodes.def"
5469
5470 void VisitFunctionTypeLoc(FunctionTypeLoc);
5471 void VisitArrayTypeLoc(ArrayTypeLoc);
5472};
5473
5474void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5475 // nothing to do
5476}
5477void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5478 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5479 if (TL.needsExtraLocalData()) {
5480 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5481 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5482 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5483 TL.setModeAttr(Record[Idx++]);
5484 }
5485}
5486void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5487 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5488}
5489void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5490 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5491}
Reid Kleckner8a365022013-06-24 17:51:48 +00005492void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5493 // nothing to do
5494}
Reid Kleckner0503a872013-12-05 01:23:43 +00005495void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5496 // nothing to do
5497}
Guy Benyei11169dd2012-12-18 14:30:41 +00005498void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5499 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5500}
5501void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5502 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5503}
5504void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5505 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5506}
5507void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5508 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5509 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5510}
5511void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5512 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5513 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5514 if (Record[Idx++])
5515 TL.setSizeExpr(Reader.ReadExpr(F));
5516 else
Craig Toppera13603a2014-05-22 05:54:18 +00005517 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005518}
5519void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5520 VisitArrayTypeLoc(TL);
5521}
5522void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5523 VisitArrayTypeLoc(TL);
5524}
5525void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5526 VisitArrayTypeLoc(TL);
5527}
5528void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5529 DependentSizedArrayTypeLoc TL) {
5530 VisitArrayTypeLoc(TL);
5531}
5532void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5533 DependentSizedExtVectorTypeLoc TL) {
5534 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5535}
5536void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5537 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5538}
5539void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5540 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5541}
5542void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5543 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5544 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5545 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5546 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005547 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5548 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005549 }
5550}
5551void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5552 VisitFunctionTypeLoc(TL);
5553}
5554void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5555 VisitFunctionTypeLoc(TL);
5556}
5557void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5558 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5559}
5560void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5561 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5562}
5563void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5564 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5565 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5566 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5567}
5568void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5569 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5570 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5571 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5572 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5573}
5574void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5575 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5576}
5577void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5578 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5579 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5580 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5581 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5582}
5583void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5584 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5585}
5586void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5587 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5588}
5589void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5590 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5591}
5592void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5593 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5594 if (TL.hasAttrOperand()) {
5595 SourceRange range;
5596 range.setBegin(ReadSourceLocation(Record, Idx));
5597 range.setEnd(ReadSourceLocation(Record, Idx));
5598 TL.setAttrOperandParensRange(range);
5599 }
5600 if (TL.hasAttrExprOperand()) {
5601 if (Record[Idx++])
5602 TL.setAttrExprOperand(Reader.ReadExpr(F));
5603 else
Craig Toppera13603a2014-05-22 05:54:18 +00005604 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005605 } else if (TL.hasAttrEnumOperand())
5606 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5607}
5608void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5609 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5610}
5611void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5612 SubstTemplateTypeParmTypeLoc TL) {
5613 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5614}
5615void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5616 SubstTemplateTypeParmPackTypeLoc TL) {
5617 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5618}
5619void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5620 TemplateSpecializationTypeLoc TL) {
5621 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5622 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5623 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5624 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5625 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5626 TL.setArgLocInfo(i,
5627 Reader.GetTemplateArgumentLocInfo(F,
5628 TL.getTypePtr()->getArg(i).getKind(),
5629 Record, Idx));
5630}
5631void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5632 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5633 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5634}
5635void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5636 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5637 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5638}
5639void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5640 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5641}
5642void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5643 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5644 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5645 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5646}
5647void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5648 DependentTemplateSpecializationTypeLoc TL) {
5649 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5650 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5651 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5652 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5653 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5654 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5655 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5656 TL.setArgLocInfo(I,
5657 Reader.GetTemplateArgumentLocInfo(F,
5658 TL.getTypePtr()->getArg(I).getKind(),
5659 Record, Idx));
5660}
5661void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5662 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5663}
5664void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5665 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5666}
5667void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5668 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005669 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5670 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5671 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5672 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5673 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5674 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005675 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5676 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5677}
5678void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5679 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5680}
5681void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5682 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5683 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5684 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5685}
5686
5687TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5688 const RecordData &Record,
5689 unsigned &Idx) {
5690 QualType InfoTy = readType(F, Record, Idx);
5691 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005692 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005693
5694 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5695 TypeLocReader TLR(*this, F, Record, Idx);
5696 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5697 TLR.Visit(TL);
5698 return TInfo;
5699}
5700
5701QualType ASTReader::GetType(TypeID ID) {
5702 unsigned FastQuals = ID & Qualifiers::FastMask;
5703 unsigned Index = ID >> Qualifiers::FastWidth;
5704
5705 if (Index < NUM_PREDEF_TYPE_IDS) {
5706 QualType T;
5707 switch ((PredefinedTypeIDs)Index) {
5708 case PREDEF_TYPE_NULL_ID: return QualType();
5709 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5710 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5711
5712 case PREDEF_TYPE_CHAR_U_ID:
5713 case PREDEF_TYPE_CHAR_S_ID:
5714 // FIXME: Check that the signedness of CharTy is correct!
5715 T = Context.CharTy;
5716 break;
5717
5718 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5719 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5720 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5721 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5722 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5723 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5724 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5725 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5726 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5727 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5728 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5729 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5730 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5731 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5732 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5733 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5734 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5735 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5736 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5737 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5738 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5739 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5740 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5741 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5742 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5743 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5744 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5745 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005746 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5747 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5748 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5749 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5750 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5751 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005752 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005753 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005754 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5755
5756 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5757 T = Context.getAutoRRefDeductType();
5758 break;
5759
5760 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5761 T = Context.ARCUnbridgedCastTy;
5762 break;
5763
Guy Benyei11169dd2012-12-18 14:30:41 +00005764 case PREDEF_TYPE_BUILTIN_FN:
5765 T = Context.BuiltinFnTy;
5766 break;
5767 }
5768
5769 assert(!T.isNull() && "Unknown predefined type");
5770 return T.withFastQualifiers(FastQuals);
5771 }
5772
5773 Index -= NUM_PREDEF_TYPE_IDS;
5774 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5775 if (TypesLoaded[Index].isNull()) {
5776 TypesLoaded[Index] = readTypeRecord(Index);
5777 if (TypesLoaded[Index].isNull())
5778 return QualType();
5779
5780 TypesLoaded[Index]->setFromAST();
5781 if (DeserializationListener)
5782 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5783 TypesLoaded[Index]);
5784 }
5785
5786 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5787}
5788
5789QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5790 return GetType(getGlobalTypeID(F, LocalID));
5791}
5792
5793serialization::TypeID
5794ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5795 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5796 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5797
5798 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5799 return LocalID;
5800
5801 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5802 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5803 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5804
5805 unsigned GlobalIndex = LocalIndex + I->second;
5806 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5807}
5808
5809TemplateArgumentLocInfo
5810ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5811 TemplateArgument::ArgKind Kind,
5812 const RecordData &Record,
5813 unsigned &Index) {
5814 switch (Kind) {
5815 case TemplateArgument::Expression:
5816 return ReadExpr(F);
5817 case TemplateArgument::Type:
5818 return GetTypeSourceInfo(F, Record, Index);
5819 case TemplateArgument::Template: {
5820 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5821 Index);
5822 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5823 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5824 SourceLocation());
5825 }
5826 case TemplateArgument::TemplateExpansion: {
5827 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5828 Index);
5829 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5830 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5831 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5832 EllipsisLoc);
5833 }
5834 case TemplateArgument::Null:
5835 case TemplateArgument::Integral:
5836 case TemplateArgument::Declaration:
5837 case TemplateArgument::NullPtr:
5838 case TemplateArgument::Pack:
5839 // FIXME: Is this right?
5840 return TemplateArgumentLocInfo();
5841 }
5842 llvm_unreachable("unexpected template argument loc");
5843}
5844
5845TemplateArgumentLoc
5846ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5847 const RecordData &Record, unsigned &Index) {
5848 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5849
5850 if (Arg.getKind() == TemplateArgument::Expression) {
5851 if (Record[Index++]) // bool InfoHasSameExpr.
5852 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5853 }
5854 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5855 Record, Index));
5856}
5857
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005858const ASTTemplateArgumentListInfo*
5859ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5860 const RecordData &Record,
5861 unsigned &Index) {
5862 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5863 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5864 unsigned NumArgsAsWritten = Record[Index++];
5865 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5866 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5867 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5868 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5869}
5870
Guy Benyei11169dd2012-12-18 14:30:41 +00005871Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5872 return GetDecl(ID);
5873}
5874
Richard Smith50895422015-01-31 03:04:55 +00005875template<typename TemplateSpecializationDecl>
5876static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5877 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5878 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5879}
5880
Richard Smith053f6c62014-05-16 23:01:30 +00005881void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005882 if (NumCurrentElementsDeserializing) {
5883 // We arrange to not care about the complete redeclaration chain while we're
5884 // deserializing. Just remember that the AST has marked this one as complete
5885 // but that it's not actually complete yet, so we know we still need to
5886 // complete it later.
5887 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5888 return;
5889 }
5890
Richard Smith053f6c62014-05-16 23:01:30 +00005891 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5892
Richard Smith053f6c62014-05-16 23:01:30 +00005893 // If this is a named declaration, complete it by looking it up
5894 // within its context.
5895 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005896 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005897 // all mergeable entities within it.
5898 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5899 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5900 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00005901 if (!getContext().getLangOpts().CPlusPlus &&
5902 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00005903 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00005904 // the identifier instead. (For C++ modules, we don't store decls
5905 // in the serialized identifier table, so we do the lookup in the TU.)
5906 auto *II = Name.getAsIdentifierInfo();
5907 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00005908 if (II->isOutOfDate())
5909 updateOutOfDateIdentifier(*II);
5910 } else
5911 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005912 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00005913 // Find all declarations of this kind from the relevant context.
5914 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
5915 auto *DC = cast<DeclContext>(DCDecl);
5916 SmallVector<Decl*, 8> Decls;
5917 FindExternalLexicalDecls(
5918 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
5919 }
Richard Smith053f6c62014-05-16 23:01:30 +00005920 }
5921 }
Richard Smith50895422015-01-31 03:04:55 +00005922
5923 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5924 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5925 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5926 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5927 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5928 if (auto *Template = FD->getPrimaryTemplate())
5929 Template->LoadLazySpecializations();
5930 }
Richard Smith053f6c62014-05-16 23:01:30 +00005931}
5932
Richard Smithc2bb8182015-03-24 06:36:48 +00005933uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5934 const RecordData &Record,
5935 unsigned &Idx) {
5936 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5937 Error("malformed AST file: missing C++ ctor initializers");
5938 return 0;
5939 }
5940
5941 unsigned LocalID = Record[Idx++];
5942 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
5943}
5944
5945CXXCtorInitializer **
5946ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
5947 RecordLocation Loc = getLocalBitOffset(Offset);
5948 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
5949 SavedStreamPosition SavedPosition(Cursor);
5950 Cursor.JumpToBit(Loc.Offset);
5951 ReadingKindTracker ReadingKind(Read_Decl, *this);
5952
5953 RecordData Record;
5954 unsigned Code = Cursor.ReadCode();
5955 unsigned RecCode = Cursor.readRecord(Code, Record);
5956 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
5957 Error("malformed AST file: missing C++ ctor initializers");
5958 return nullptr;
5959 }
5960
5961 unsigned Idx = 0;
5962 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
5963}
5964
Richard Smithcd45dbc2014-04-19 03:48:30 +00005965uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5966 const RecordData &Record,
5967 unsigned &Idx) {
5968 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5969 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005970 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005971 }
5972
Guy Benyei11169dd2012-12-18 14:30:41 +00005973 unsigned LocalID = Record[Idx++];
5974 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5975}
5976
5977CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5978 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005979 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005980 SavedStreamPosition SavedPosition(Cursor);
5981 Cursor.JumpToBit(Loc.Offset);
5982 ReadingKindTracker ReadingKind(Read_Decl, *this);
5983 RecordData Record;
5984 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005985 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005986 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005987 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00005988 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005989 }
5990
5991 unsigned Idx = 0;
5992 unsigned NumBases = Record[Idx++];
5993 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5994 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5995 for (unsigned I = 0; I != NumBases; ++I)
5996 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5997 return Bases;
5998}
5999
6000serialization::DeclID
6001ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6002 if (LocalID < NUM_PREDEF_DECL_IDS)
6003 return LocalID;
6004
6005 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6006 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6007 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6008
6009 return LocalID + I->second;
6010}
6011
6012bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6013 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006014 // Predefined decls aren't from any module.
6015 if (ID < NUM_PREDEF_DECL_IDS)
6016 return false;
6017
Richard Smithbcda1a92015-07-12 23:51:20 +00006018 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6019 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006020}
6021
Douglas Gregor9f782892013-01-21 15:25:38 +00006022ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006023 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006024 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006025 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6026 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6027 return I->second;
6028}
6029
6030SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6031 if (ID < NUM_PREDEF_DECL_IDS)
6032 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006033
Guy Benyei11169dd2012-12-18 14:30:41 +00006034 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6035
6036 if (Index > DeclsLoaded.size()) {
6037 Error("declaration ID out-of-range for AST file");
6038 return SourceLocation();
6039 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006040
Guy Benyei11169dd2012-12-18 14:30:41 +00006041 if (Decl *D = DeclsLoaded[Index])
6042 return D->getLocation();
6043
6044 unsigned RawLocation = 0;
6045 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6046 return ReadSourceLocation(*Rec.F, RawLocation);
6047}
6048
Richard Smithfe620d22015-03-05 23:24:12 +00006049static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6050 switch (ID) {
6051 case PREDEF_DECL_NULL_ID:
6052 return nullptr;
6053
6054 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6055 return Context.getTranslationUnitDecl();
6056
6057 case PREDEF_DECL_OBJC_ID_ID:
6058 return Context.getObjCIdDecl();
6059
6060 case PREDEF_DECL_OBJC_SEL_ID:
6061 return Context.getObjCSelDecl();
6062
6063 case PREDEF_DECL_OBJC_CLASS_ID:
6064 return Context.getObjCClassDecl();
6065
6066 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6067 return Context.getObjCProtocolDecl();
6068
6069 case PREDEF_DECL_INT_128_ID:
6070 return Context.getInt128Decl();
6071
6072 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6073 return Context.getUInt128Decl();
6074
6075 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6076 return Context.getObjCInstanceTypeDecl();
6077
6078 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6079 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006080
Richard Smith9b88a4c2015-07-27 05:40:23 +00006081 case PREDEF_DECL_VA_LIST_TAG:
6082 return Context.getVaListTagDecl();
6083
Richard Smithf19e1272015-03-07 00:04:49 +00006084 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6085 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006086 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006087 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006088}
6089
Richard Smithcd45dbc2014-04-19 03:48:30 +00006090Decl *ASTReader::GetExistingDecl(DeclID ID) {
6091 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006092 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6093 if (D) {
6094 // Track that we have merged the declaration with ID \p ID into the
6095 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006096 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006097 if (Merged.empty())
6098 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006099 }
Richard Smithfe620d22015-03-05 23:24:12 +00006100 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006101 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006102
Guy Benyei11169dd2012-12-18 14:30:41 +00006103 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6104
6105 if (Index >= DeclsLoaded.size()) {
6106 assert(0 && "declaration ID out-of-range for AST file");
6107 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006108 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006109 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006110
6111 return DeclsLoaded[Index];
6112}
6113
6114Decl *ASTReader::GetDecl(DeclID ID) {
6115 if (ID < NUM_PREDEF_DECL_IDS)
6116 return GetExistingDecl(ID);
6117
6118 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6119
6120 if (Index >= DeclsLoaded.size()) {
6121 assert(0 && "declaration ID out-of-range for AST file");
6122 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006123 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006124 }
6125
Guy Benyei11169dd2012-12-18 14:30:41 +00006126 if (!DeclsLoaded[Index]) {
6127 ReadDeclRecord(ID);
6128 if (DeserializationListener)
6129 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6130 }
6131
6132 return DeclsLoaded[Index];
6133}
6134
6135DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6136 DeclID GlobalID) {
6137 if (GlobalID < NUM_PREDEF_DECL_IDS)
6138 return GlobalID;
6139
6140 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6141 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6142 ModuleFile *Owner = I->second;
6143
6144 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6145 = M.GlobalToLocalDeclIDs.find(Owner);
6146 if (Pos == M.GlobalToLocalDeclIDs.end())
6147 return 0;
6148
6149 return GlobalID - Owner->BaseDeclID + Pos->second;
6150}
6151
6152serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6153 const RecordData &Record,
6154 unsigned &Idx) {
6155 if (Idx >= Record.size()) {
6156 Error("Corrupted AST file");
6157 return 0;
6158 }
6159
6160 return getGlobalDeclID(F, Record[Idx++]);
6161}
6162
6163/// \brief Resolve the offset of a statement into a statement.
6164///
6165/// This operation will read a new statement from the external
6166/// source each time it is called, and is meant to be used via a
6167/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6168Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6169 // Switch case IDs are per Decl.
6170 ClearSwitchCaseIDs();
6171
6172 // Offset here is a global offset across the entire chain.
6173 RecordLocation Loc = getLocalBitOffset(Offset);
6174 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6175 return ReadStmtFromStream(*Loc.F);
6176}
6177
6178namespace {
6179 class FindExternalLexicalDeclsVisitor {
6180 ASTReader &Reader;
6181 const DeclContext *DC;
Richard Smith3cb15722015-08-05 22:41:45 +00006182 llvm::function_ref<bool(Decl::Kind)> IsKindWeWant;
Guy Benyei11169dd2012-12-18 14:30:41 +00006183
6184 SmallVectorImpl<Decl*> &Decls;
6185 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6186
6187 public:
Richard Smith3cb15722015-08-05 22:41:45 +00006188 FindExternalLexicalDeclsVisitor(
6189 ASTReader &Reader, const DeclContext *DC,
6190 llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6191 SmallVectorImpl<Decl *> &Decls)
6192 : Reader(Reader), DC(DC), IsKindWeWant(IsKindWeWant), Decls(Decls) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006193 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6194 PredefsVisited[I] = false;
6195 }
6196
Manuel Klimek9eff8b12015-05-20 10:29:23 +00006197 static bool visitPostorder(ModuleFile &M, void *UserData) {
Richard Smith3cb15722015-08-05 22:41:45 +00006198 return (*static_cast<FindExternalLexicalDeclsVisitor*>(UserData))(M);
6199 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006200
Richard Smith3cb15722015-08-05 22:41:45 +00006201 bool operator()(ModuleFile &M) {
6202 ModuleFile::DeclContextInfosMap::iterator Info =
6203 M.DeclContextInfos.find(DC);
Richard Smith787c0e42015-07-23 00:53:59 +00006204 if (Info == M.DeclContextInfos.end() || Info->second.LexicalDecls.empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006205 return false;
6206
6207 // Load all of the declaration IDs
Richard Smith787c0e42015-07-23 00:53:59 +00006208 for (const KindDeclIDPair &P : Info->second.LexicalDecls) {
Richard Smith3cb15722015-08-05 22:41:45 +00006209 if (!IsKindWeWant((Decl::Kind)P.first))
Guy Benyei11169dd2012-12-18 14:30:41 +00006210 continue;
6211
6212 // Don't add predefined declarations to the lexical context more
6213 // than once.
Richard Smith787c0e42015-07-23 00:53:59 +00006214 if (P.second < NUM_PREDEF_DECL_IDS) {
Richard Smith3cb15722015-08-05 22:41:45 +00006215 if (PredefsVisited[P.second])
Guy Benyei11169dd2012-12-18 14:30:41 +00006216 continue;
6217
Richard Smith3cb15722015-08-05 22:41:45 +00006218 PredefsVisited[P.second] = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006219 }
6220
Richard Smith3cb15722015-08-05 22:41:45 +00006221 if (Decl *D = Reader.GetLocalDecl(M, P.second)) {
6222 if (!DC->isDeclInLexicalTraversal(D))
6223 Decls.push_back(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00006224 }
6225 }
6226
6227 return false;
6228 }
6229 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006230}
Guy Benyei11169dd2012-12-18 14:30:41 +00006231
Richard Smith3cb15722015-08-05 22:41:45 +00006232void ASTReader::FindExternalLexicalDecls(
6233 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6234 SmallVectorImpl<Decl *> &Decls) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006235 // There might be lexical decls in multiple modules, for the TU at
Richard Smith3cb15722015-08-05 22:41:45 +00006236 // least. FIXME: Only look in multiple module files in the very rare
6237 // cases where this can actually happen.
6238 FindExternalLexicalDeclsVisitor Visitor(*this, DC, IsKindWeWant, Decls);
Manuel Klimek9eff8b12015-05-20 10:29:23 +00006239 ModuleMgr.visitDepthFirst(
6240 nullptr, &FindExternalLexicalDeclsVisitor::visitPostorder, &Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006241 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006242}
6243
6244namespace {
6245
6246class DeclIDComp {
6247 ASTReader &Reader;
6248 ModuleFile &Mod;
6249
6250public:
6251 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6252
6253 bool operator()(LocalDeclID L, LocalDeclID R) const {
6254 SourceLocation LHS = getLocation(L);
6255 SourceLocation RHS = getLocation(R);
6256 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6257 }
6258
6259 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6260 SourceLocation RHS = getLocation(R);
6261 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6262 }
6263
6264 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6265 SourceLocation LHS = getLocation(L);
6266 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6267 }
6268
6269 SourceLocation getLocation(LocalDeclID ID) const {
6270 return Reader.getSourceManager().getFileLoc(
6271 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6272 }
6273};
6274
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006275}
Guy Benyei11169dd2012-12-18 14:30:41 +00006276
6277void ASTReader::FindFileRegionDecls(FileID File,
6278 unsigned Offset, unsigned Length,
6279 SmallVectorImpl<Decl *> &Decls) {
6280 SourceManager &SM = getSourceManager();
6281
6282 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6283 if (I == FileDeclIDs.end())
6284 return;
6285
6286 FileDeclsInfo &DInfo = I->second;
6287 if (DInfo.Decls.empty())
6288 return;
6289
6290 SourceLocation
6291 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6292 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6293
6294 DeclIDComp DIDComp(*this, *DInfo.Mod);
6295 ArrayRef<serialization::LocalDeclID>::iterator
6296 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6297 BeginLoc, DIDComp);
6298 if (BeginIt != DInfo.Decls.begin())
6299 --BeginIt;
6300
6301 // If we are pointing at a top-level decl inside an objc container, we need
6302 // to backtrack until we find it otherwise we will fail to report that the
6303 // region overlaps with an objc container.
6304 while (BeginIt != DInfo.Decls.begin() &&
6305 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6306 ->isTopLevelDeclInObjCContainer())
6307 --BeginIt;
6308
6309 ArrayRef<serialization::LocalDeclID>::iterator
6310 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6311 EndLoc, DIDComp);
6312 if (EndIt != DInfo.Decls.end())
6313 ++EndIt;
6314
6315 for (ArrayRef<serialization::LocalDeclID>::iterator
6316 DIt = BeginIt; DIt != EndIt; ++DIt)
6317 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6318}
6319
Richard Smith3b637412015-07-14 18:42:41 +00006320/// \brief Retrieve the "definitive" module file for the definition of the
6321/// given declaration context, if there is one.
6322///
6323/// The "definitive" module file is the only place where we need to look to
6324/// find information about the declarations within the given declaration
6325/// context. For example, C++ and Objective-C classes, C structs/unions, and
6326/// Objective-C protocols, categories, and extensions are all defined in a
6327/// single place in the source code, so they have definitive module files
6328/// associated with them. C++ namespaces, on the other hand, can have
6329/// definitions in multiple different module files.
6330///
6331/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6332/// NDEBUG checking.
6333static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6334 ASTReader &Reader) {
6335 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6336 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6337
6338 return nullptr;
6339}
6340
Guy Benyei11169dd2012-12-18 14:30:41 +00006341namespace {
6342 /// \brief ModuleFile visitor used to perform name lookup into a
6343 /// declaration context.
6344 class DeclContextNameLookupVisitor {
6345 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006346 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006347 DeclarationName Name;
Richard Smith3b637412015-07-14 18:42:41 +00006348 ASTDeclContextNameLookupTrait::DeclNameKey NameKey;
6349 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00006350 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006351 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006352
6353 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006354 DeclContextNameLookupVisitor(ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006355 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006356 SmallVectorImpl<NamedDecl *> &Decls,
6357 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
Richard Smith3b637412015-07-14 18:42:41 +00006358 : Reader(Reader), Name(Name),
6359 NameKey(ASTDeclContextNameLookupTrait::GetInternalKey(Name)),
6360 NameHash(ASTDeclContextNameLookupTrait::ComputeHash(NameKey)),
6361 Decls(Decls), DeclSet(DeclSet) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006362
Richard Smith3b637412015-07-14 18:42:41 +00006363 void visitContexts(ArrayRef<const DeclContext*> Contexts) {
6364 if (Contexts.empty())
6365 return;
6366 this->Contexts = Contexts;
6367
6368 // If we can definitively determine which module file to look into,
6369 // only look there. Otherwise, look in all module files.
6370 ModuleFile *Definitive;
6371 if (Contexts.size() == 1 &&
6372 (Definitive = getDefinitiveModuleFileFor(Contexts[0], Reader))) {
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006373 (*this)(*Definitive);
Richard Smith3b637412015-07-14 18:42:41 +00006374 } else {
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006375 Reader.getModuleManager().visit(*this);
Richard Smith3b637412015-07-14 18:42:41 +00006376 }
6377 }
6378
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006379 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006380 // Check whether we have any visible declaration information for
6381 // this context in this module.
6382 ModuleFile::DeclContextInfosMap::iterator Info;
6383 bool FoundInfo = false;
Richard Smithbdf2d932015-07-30 03:37:16 +00006384 for (auto *DC : Contexts) {
Richard Smith8c913ec2014-08-14 02:21:01 +00006385 Info = M.DeclContextInfos.find(DC);
6386 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006387 Info->second.NameLookupTableData) {
6388 FoundInfo = true;
6389 break;
6390 }
6391 }
6392
6393 if (!FoundInfo)
6394 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006395
Guy Benyei11169dd2012-12-18 14:30:41 +00006396 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006397 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006398 Info->second.NameLookupTableData;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006399 ASTDeclContextNameLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00006400 LookupTable->find_hashed(NameKey, NameHash);
Guy Benyei11169dd2012-12-18 14:30:41 +00006401 if (Pos == LookupTable->end())
6402 return false;
6403
6404 bool FoundAnything = false;
6405 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6406 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006407 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006408 if (!ND)
6409 continue;
6410
Richard Smithbdf2d932015-07-30 03:37:16 +00006411 if (ND->getDeclName() != Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006412 // A name might be null because the decl's redeclarable part is
6413 // currently read before reading its name. The lookup is triggered by
6414 // building that decl (likely indirectly), and so it is later in the
6415 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006416 // FIXME: This should not happen; deserializing declarations should
6417 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006418 continue;
6419 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006420
Guy Benyei11169dd2012-12-18 14:30:41 +00006421 // Record this declaration.
6422 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006423 if (DeclSet.insert(ND).second)
6424 Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006425 }
6426
6427 return FoundAnything;
6428 }
6429 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006430}
Guy Benyei11169dd2012-12-18 14:30:41 +00006431
Richard Smith9ce12e32013-02-07 03:30:24 +00006432bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006433ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6434 DeclarationName Name) {
6435 assert(DC->hasExternalVisibleStorage() &&
6436 "DeclContext has no visible decls in storage");
6437 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006438 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006439
Richard Smith8c913ec2014-08-14 02:21:01 +00006440 Deserializing LookupResults(this);
6441
Guy Benyei11169dd2012-12-18 14:30:41 +00006442 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006443 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006444
Guy Benyei11169dd2012-12-18 14:30:41 +00006445 // Compute the declaration contexts we need to look into. Multiple such
6446 // declaration contexts occur when two declaration contexts from disjoint
6447 // modules get merged, e.g., when two namespaces with the same name are
6448 // independently defined in separate modules.
6449 SmallVector<const DeclContext *, 2> Contexts;
6450 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006451
Guy Benyei11169dd2012-12-18 14:30:41 +00006452 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006453 auto Key = KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6454 if (Key != KeyDecls.end()) {
6455 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6456 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006457 }
6458 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006459
Richard Smith3b637412015-07-14 18:42:41 +00006460 DeclContextNameLookupVisitor Visitor(*this, Name, Decls, DeclSet);
6461 Visitor.visitContexts(Contexts);
Richard Smith8c913ec2014-08-14 02:21:01 +00006462
6463 // If this might be an implicit special member function, then also search
6464 // all merged definitions of the surrounding class. We need to search them
6465 // individually, because finding an entity in one of them doesn't imply that
6466 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006467 if (isa<CXXRecordDecl>(DC)) {
Richard Smith02793752015-03-27 21:16:39 +00006468 auto Merged = MergedLookups.find(DC);
6469 if (Merged != MergedLookups.end()) {
6470 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6471 const DeclContext *Context = Merged->second[I];
Richard Smith3b637412015-07-14 18:42:41 +00006472 Visitor.visitContexts(Context);
Richard Smith02793752015-03-27 21:16:39 +00006473 // We might have just added some more merged lookups. If so, our
6474 // iterator is now invalid, so grab a fresh one before continuing.
6475 Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006476 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006477 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006478 }
6479
Guy Benyei11169dd2012-12-18 14:30:41 +00006480 ++NumVisibleDeclContextsRead;
6481 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006482 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006483}
6484
6485namespace {
6486 /// \brief ModuleFile visitor used to retrieve all visible names in a
6487 /// declaration context.
6488 class DeclContextAllNamesVisitor {
6489 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006490 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006491 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006492 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006493 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006494
6495 public:
6496 DeclContextAllNamesVisitor(ASTReader &Reader,
6497 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006498 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006499 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006500
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006501 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006502 // Check whether we have any visible declaration information for
6503 // this context in this module.
6504 ModuleFile::DeclContextInfosMap::iterator Info;
6505 bool FoundInfo = false;
Richard Smithbdf2d932015-07-30 03:37:16 +00006506 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
6507 Info = M.DeclContextInfos.find(Contexts[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006508 if (Info != M.DeclContextInfos.end() &&
6509 Info->second.NameLookupTableData) {
6510 FoundInfo = true;
6511 break;
6512 }
6513 }
6514
6515 if (!FoundInfo)
6516 return false;
6517
Richard Smith52e3fba2014-03-11 07:17:35 +00006518 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006519 Info->second.NameLookupTableData;
6520 bool FoundAnything = false;
6521 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006522 I = LookupTable->data_begin(), E = LookupTable->data_end();
6523 I != E;
6524 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006525 ASTDeclContextNameLookupTrait::data_type Data = *I;
6526 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006527 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006528 if (!ND)
6529 continue;
6530
6531 // Record this declaration.
6532 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006533 if (DeclSet.insert(ND).second)
6534 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006535 }
6536 }
6537
Richard Smithbdf2d932015-07-30 03:37:16 +00006538 return FoundAnything && !VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006539 }
6540 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006541}
Guy Benyei11169dd2012-12-18 14:30:41 +00006542
6543void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6544 if (!DC->hasExternalVisibleStorage())
6545 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006546 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006547
6548 // Compute the declaration contexts we need to look into. Multiple such
6549 // declaration contexts occur when two declaration contexts from disjoint
6550 // modules get merged, e.g., when two namespaces with the same name are
6551 // independently defined in separate modules.
6552 SmallVector<const DeclContext *, 2> Contexts;
6553 Contexts.push_back(DC);
6554
6555 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006556 KeyDeclsMap::iterator Key =
6557 KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6558 if (Key != KeyDecls.end()) {
6559 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6560 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006561 }
6562 }
6563
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006564 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6565 /*VisitAll=*/DC->isFileContext());
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006566 ModuleMgr.visit(Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006567 ++NumVisibleDeclContextsRead;
6568
Craig Topper79be4cd2013-07-05 04:33:53 +00006569 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006570 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6571 }
6572 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6573}
6574
6575/// \brief Under non-PCH compilation the consumer receives the objc methods
6576/// before receiving the implementation, and codegen depends on this.
6577/// We simulate this by deserializing and passing to consumer the methods of the
6578/// implementation before passing the deserialized implementation decl.
6579static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6580 ASTConsumer *Consumer) {
6581 assert(ImplD && Consumer);
6582
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006583 for (auto *I : ImplD->methods())
6584 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006585
6586 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6587}
6588
6589void ASTReader::PassInterestingDeclsToConsumer() {
6590 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006591
6592 if (PassingDeclsToConsumer)
6593 return;
6594
6595 // Guard variable to avoid recursively redoing the process of passing
6596 // decls to consumer.
6597 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6598 true);
6599
Richard Smith9e2341d2015-03-23 03:25:59 +00006600 // Ensure that we've loaded all potentially-interesting declarations
6601 // that need to be eagerly loaded.
6602 for (auto ID : EagerlyDeserializedDecls)
6603 GetDecl(ID);
6604 EagerlyDeserializedDecls.clear();
6605
Guy Benyei11169dd2012-12-18 14:30:41 +00006606 while (!InterestingDecls.empty()) {
6607 Decl *D = InterestingDecls.front();
6608 InterestingDecls.pop_front();
6609
6610 PassInterestingDeclToConsumer(D);
6611 }
6612}
6613
6614void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6615 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6616 PassObjCImplDeclToConsumer(ImplD, Consumer);
6617 else
6618 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6619}
6620
6621void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6622 this->Consumer = Consumer;
6623
Richard Smith9e2341d2015-03-23 03:25:59 +00006624 if (Consumer)
6625 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006626
6627 if (DeserializationListener)
6628 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006629}
6630
6631void ASTReader::PrintStats() {
6632 std::fprintf(stderr, "*** AST File Statistics:\n");
6633
6634 unsigned NumTypesLoaded
6635 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6636 QualType());
6637 unsigned NumDeclsLoaded
6638 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006639 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006640 unsigned NumIdentifiersLoaded
6641 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6642 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006643 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006644 unsigned NumMacrosLoaded
6645 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6646 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006647 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006648 unsigned NumSelectorsLoaded
6649 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6650 SelectorsLoaded.end(),
6651 Selector());
6652
6653 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6654 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6655 NumSLocEntriesRead, TotalNumSLocEntries,
6656 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6657 if (!TypesLoaded.empty())
6658 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6659 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6660 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6661 if (!DeclsLoaded.empty())
6662 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6663 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6664 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6665 if (!IdentifiersLoaded.empty())
6666 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6667 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6668 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6669 if (!MacrosLoaded.empty())
6670 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6671 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6672 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6673 if (!SelectorsLoaded.empty())
6674 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6675 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6676 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6677 if (TotalNumStatements)
6678 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6679 NumStatementsRead, TotalNumStatements,
6680 ((float)NumStatementsRead/TotalNumStatements * 100));
6681 if (TotalNumMacros)
6682 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6683 NumMacrosRead, TotalNumMacros,
6684 ((float)NumMacrosRead/TotalNumMacros * 100));
6685 if (TotalLexicalDeclContexts)
6686 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6687 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6688 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6689 * 100));
6690 if (TotalVisibleDeclContexts)
6691 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6692 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6693 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6694 * 100));
6695 if (TotalNumMethodPoolEntries) {
6696 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6697 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6698 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6699 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006700 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006701 if (NumMethodPoolLookups) {
6702 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6703 NumMethodPoolHits, NumMethodPoolLookups,
6704 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6705 }
6706 if (NumMethodPoolTableLookups) {
6707 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6708 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6709 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6710 * 100.0));
6711 }
6712
Douglas Gregor00a50f72013-01-25 00:38:33 +00006713 if (NumIdentifierLookupHits) {
6714 std::fprintf(stderr,
6715 " %u / %u identifier table lookups succeeded (%f%%)\n",
6716 NumIdentifierLookupHits, NumIdentifierLookups,
6717 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6718 }
6719
Douglas Gregore060e572013-01-25 01:03:03 +00006720 if (GlobalIndex) {
6721 std::fprintf(stderr, "\n");
6722 GlobalIndex->printStats();
6723 }
6724
Guy Benyei11169dd2012-12-18 14:30:41 +00006725 std::fprintf(stderr, "\n");
6726 dump();
6727 std::fprintf(stderr, "\n");
6728}
6729
6730template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6731static void
6732dumpModuleIDMap(StringRef Name,
6733 const ContinuousRangeMap<Key, ModuleFile *,
6734 InitialCapacity> &Map) {
6735 if (Map.begin() == Map.end())
6736 return;
6737
6738 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6739 llvm::errs() << Name << ":\n";
6740 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6741 I != IEnd; ++I) {
6742 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6743 << "\n";
6744 }
6745}
6746
6747void ASTReader::dump() {
6748 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6749 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6750 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6751 dumpModuleIDMap("Global type map", GlobalTypeMap);
6752 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6753 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6754 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6755 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6756 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6757 dumpModuleIDMap("Global preprocessed entity map",
6758 GlobalPreprocessedEntityMap);
6759
6760 llvm::errs() << "\n*** PCH/Modules Loaded:";
6761 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6762 MEnd = ModuleMgr.end();
6763 M != MEnd; ++M)
6764 (*M)->dump();
6765}
6766
6767/// Return the amount of memory used by memory buffers, breaking down
6768/// by heap-backed versus mmap'ed memory.
6769void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6770 for (ModuleConstIterator I = ModuleMgr.begin(),
6771 E = ModuleMgr.end(); I != E; ++I) {
6772 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6773 size_t bytes = buf->getBufferSize();
6774 switch (buf->getBufferKind()) {
6775 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6776 sizes.malloc_bytes += bytes;
6777 break;
6778 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6779 sizes.mmap_bytes += bytes;
6780 break;
6781 }
6782 }
6783 }
6784}
6785
6786void ASTReader::InitializeSema(Sema &S) {
6787 SemaObj = &S;
6788 S.addExternalSource(this);
6789
6790 // Makes sure any declarations that were deserialized "too early"
6791 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006792 for (uint64_t ID : PreloadedDeclIDs) {
6793 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6794 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006795 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006796 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006797
Richard Smith3d8e97e2013-10-18 06:54:39 +00006798 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006799 if (!FPPragmaOptions.empty()) {
6800 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6801 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6802 }
6803
Richard Smith3d8e97e2013-10-18 06:54:39 +00006804 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006805 if (!OpenCLExtensions.empty()) {
6806 unsigned I = 0;
6807#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6808#include "clang/Basic/OpenCLExtensions.def"
6809
6810 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6811 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006812
6813 UpdateSema();
6814}
6815
6816void ASTReader::UpdateSema() {
6817 assert(SemaObj && "no Sema to update");
6818
6819 // Load the offsets of the declarations that Sema references.
6820 // They will be lazily deserialized when needed.
6821 if (!SemaDeclRefs.empty()) {
6822 assert(SemaDeclRefs.size() % 2 == 0);
6823 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6824 if (!SemaObj->StdNamespace)
6825 SemaObj->StdNamespace = SemaDeclRefs[I];
6826 if (!SemaObj->StdBadAlloc)
6827 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6828 }
6829 SemaDeclRefs.clear();
6830 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006831
6832 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6833 // encountered the pragma in the source.
6834 if(OptimizeOffPragmaLocation.isValid())
6835 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006836}
6837
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006838IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006839 // Note that we are loading an identifier.
6840 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006841
Douglas Gregor7211ac12013-01-25 23:32:03 +00006842 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006843 NumIdentifierLookups,
6844 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006845
6846 // We don't need to do identifier table lookups in C++ modules (we preload
6847 // all interesting declarations, and don't need to use the scope for name
6848 // lookups). Perform the lookup in PCH files, though, since we don't build
6849 // a complete initial identifier table if we're carrying on from a PCH.
6850 if (Context.getLangOpts().CPlusPlus) {
6851 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006852 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006853 break;
6854 } else {
6855 // If there is a global index, look there first to determine which modules
6856 // provably do not have any results for this identifier.
6857 GlobalModuleIndex::HitSet Hits;
6858 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6859 if (!loadGlobalIndex()) {
6860 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6861 HitsPtr = &Hits;
6862 }
6863 }
6864
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006865 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006866 }
6867
Guy Benyei11169dd2012-12-18 14:30:41 +00006868 IdentifierInfo *II = Visitor.getIdentifierInfo();
6869 markIdentifierUpToDate(II);
6870 return II;
6871}
6872
6873namespace clang {
6874 /// \brief An identifier-lookup iterator that enumerates all of the
6875 /// identifiers stored within a set of AST files.
6876 class ASTIdentifierIterator : public IdentifierIterator {
6877 /// \brief The AST reader whose identifiers are being enumerated.
6878 const ASTReader &Reader;
6879
6880 /// \brief The current index into the chain of AST files stored in
6881 /// the AST reader.
6882 unsigned Index;
6883
6884 /// \brief The current position within the identifier lookup table
6885 /// of the current AST file.
6886 ASTIdentifierLookupTable::key_iterator Current;
6887
6888 /// \brief The end position within the identifier lookup table of
6889 /// the current AST file.
6890 ASTIdentifierLookupTable::key_iterator End;
6891
6892 public:
6893 explicit ASTIdentifierIterator(const ASTReader &Reader);
6894
Craig Topper3e89dfe2014-03-13 02:13:41 +00006895 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006896 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006897}
Guy Benyei11169dd2012-12-18 14:30:41 +00006898
6899ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6900 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6901 ASTIdentifierLookupTable *IdTable
6902 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6903 Current = IdTable->key_begin();
6904 End = IdTable->key_end();
6905}
6906
6907StringRef ASTIdentifierIterator::Next() {
6908 while (Current == End) {
6909 // If we have exhausted all of our AST files, we're done.
6910 if (Index == 0)
6911 return StringRef();
6912
6913 --Index;
6914 ASTIdentifierLookupTable *IdTable
6915 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6916 IdentifierLookupTable;
6917 Current = IdTable->key_begin();
6918 End = IdTable->key_end();
6919 }
6920
6921 // We have any identifiers remaining in the current AST file; return
6922 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006923 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006924 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006925 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006926}
6927
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006928IdentifierIterator *ASTReader::getIdentifiers() {
6929 if (!loadGlobalIndex())
6930 return GlobalIndex->createIdentifierIterator();
6931
Guy Benyei11169dd2012-12-18 14:30:41 +00006932 return new ASTIdentifierIterator(*this);
6933}
6934
6935namespace clang { namespace serialization {
6936 class ReadMethodPoolVisitor {
6937 ASTReader &Reader;
6938 Selector Sel;
6939 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006940 unsigned InstanceBits;
6941 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006942 bool InstanceHasMoreThanOneDecl;
6943 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006944 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6945 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006946
6947 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006948 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006949 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006950 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006951 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6952 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006953
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006954 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006955 if (!M.SelectorLookupTable)
6956 return false;
6957
6958 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00006959 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00006960 return true;
6961
Richard Smithbdf2d932015-07-30 03:37:16 +00006962 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006963 ASTSelectorLookupTable *PoolTable
6964 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00006965 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00006966 if (Pos == PoolTable->end())
6967 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006968
Richard Smithbdf2d932015-07-30 03:37:16 +00006969 ++Reader.NumMethodPoolTableHits;
6970 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006971 // FIXME: Not quite happy with the statistics here. We probably should
6972 // disable this tracking when called via LoadSelector.
6973 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00006974 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006975 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00006976 if (Reader.DeserializationListener)
6977 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006978
Richard Smithbdf2d932015-07-30 03:37:16 +00006979 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6980 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6981 InstanceBits = Data.InstanceBits;
6982 FactoryBits = Data.FactoryBits;
6983 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6984 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006985 return true;
6986 }
6987
6988 /// \brief Retrieve the instance methods found by this visitor.
6989 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6990 return InstanceMethods;
6991 }
6992
6993 /// \brief Retrieve the instance methods found by this visitor.
6994 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6995 return FactoryMethods;
6996 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006997
6998 unsigned getInstanceBits() const { return InstanceBits; }
6999 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007000 bool instanceHasMoreThanOneDecl() const {
7001 return InstanceHasMoreThanOneDecl;
7002 }
7003 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007004 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007005} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00007006
7007/// \brief Add the given set of methods to the method list.
7008static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7009 ObjCMethodList &List) {
7010 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7011 S.addMethodToGlobalList(&List, Methods[I]);
7012 }
7013}
7014
7015void ASTReader::ReadMethodPool(Selector Sel) {
7016 // Get the selector generation and update it to the current generation.
7017 unsigned &Generation = SelectorGeneration[Sel];
7018 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007019 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007020
7021 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007022 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007023 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007024 ModuleMgr.visit(Visitor);
7025
Guy Benyei11169dd2012-12-18 14:30:41 +00007026 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007027 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007028 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007029
7030 ++NumMethodPoolHits;
7031
Guy Benyei11169dd2012-12-18 14:30:41 +00007032 if (!getSema())
7033 return;
7034
7035 Sema &S = *getSema();
7036 Sema::GlobalMethodPool::iterator Pos
7037 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007038
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007039 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007040 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007041 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007042 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007043
7044 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7045 // when building a module we keep every method individually and may need to
7046 // update hasMoreThanOneDecl as we add the methods.
7047 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7048 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007049}
7050
7051void ASTReader::ReadKnownNamespaces(
7052 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7053 Namespaces.clear();
7054
7055 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7056 if (NamespaceDecl *Namespace
7057 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7058 Namespaces.push_back(Namespace);
7059 }
7060}
7061
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007062void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007063 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007064 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7065 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007066 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007067 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007068 Undefined.insert(std::make_pair(D, Loc));
7069 }
7070}
Nick Lewycky8334af82013-01-26 00:35:08 +00007071
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007072void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7073 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7074 Exprs) {
7075 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7076 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7077 uint64_t Count = DelayedDeleteExprs[Idx++];
7078 for (uint64_t C = 0; C < Count; ++C) {
7079 SourceLocation DeleteLoc =
7080 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7081 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7082 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7083 }
7084 }
7085}
7086
Guy Benyei11169dd2012-12-18 14:30:41 +00007087void ASTReader::ReadTentativeDefinitions(
7088 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7089 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7090 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7091 if (Var)
7092 TentativeDefs.push_back(Var);
7093 }
7094 TentativeDefinitions.clear();
7095}
7096
7097void ASTReader::ReadUnusedFileScopedDecls(
7098 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7099 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7100 DeclaratorDecl *D
7101 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7102 if (D)
7103 Decls.push_back(D);
7104 }
7105 UnusedFileScopedDecls.clear();
7106}
7107
7108void ASTReader::ReadDelegatingConstructors(
7109 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7110 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7111 CXXConstructorDecl *D
7112 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7113 if (D)
7114 Decls.push_back(D);
7115 }
7116 DelegatingCtorDecls.clear();
7117}
7118
7119void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7120 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7121 TypedefNameDecl *D
7122 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7123 if (D)
7124 Decls.push_back(D);
7125 }
7126 ExtVectorDecls.clear();
7127}
7128
Nico Weber72889432014-09-06 01:25:55 +00007129void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7130 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7131 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7132 ++I) {
7133 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7134 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7135 if (D)
7136 Decls.insert(D);
7137 }
7138 UnusedLocalTypedefNameCandidates.clear();
7139}
7140
Guy Benyei11169dd2012-12-18 14:30:41 +00007141void ASTReader::ReadReferencedSelectors(
7142 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7143 if (ReferencedSelectorsData.empty())
7144 return;
7145
7146 // If there are @selector references added them to its pool. This is for
7147 // implementation of -Wselector.
7148 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7149 unsigned I = 0;
7150 while (I < DataSize) {
7151 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7152 SourceLocation SelLoc
7153 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7154 Sels.push_back(std::make_pair(Sel, SelLoc));
7155 }
7156 ReferencedSelectorsData.clear();
7157}
7158
7159void ASTReader::ReadWeakUndeclaredIdentifiers(
7160 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7161 if (WeakUndeclaredIdentifiers.empty())
7162 return;
7163
7164 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7165 IdentifierInfo *WeakId
7166 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7167 IdentifierInfo *AliasId
7168 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7169 SourceLocation Loc
7170 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7171 bool Used = WeakUndeclaredIdentifiers[I++];
7172 WeakInfo WI(AliasId, Loc);
7173 WI.setUsed(Used);
7174 WeakIDs.push_back(std::make_pair(WeakId, WI));
7175 }
7176 WeakUndeclaredIdentifiers.clear();
7177}
7178
7179void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7180 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7181 ExternalVTableUse VT;
7182 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7183 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7184 VT.DefinitionRequired = VTableUses[Idx++];
7185 VTables.push_back(VT);
7186 }
7187
7188 VTableUses.clear();
7189}
7190
7191void ASTReader::ReadPendingInstantiations(
7192 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7193 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7194 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7195 SourceLocation Loc
7196 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7197
7198 Pending.push_back(std::make_pair(D, Loc));
7199 }
7200 PendingInstantiations.clear();
7201}
7202
Richard Smithe40f2ba2013-08-07 21:41:30 +00007203void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007204 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007205 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7206 /* In loop */) {
7207 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7208
7209 LateParsedTemplate *LT = new LateParsedTemplate;
7210 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7211
7212 ModuleFile *F = getOwningModuleFile(LT->D);
7213 assert(F && "No module");
7214
7215 unsigned TokN = LateParsedTemplates[Idx++];
7216 LT->Toks.reserve(TokN);
7217 for (unsigned T = 0; T < TokN; ++T)
7218 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7219
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007220 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007221 }
7222
7223 LateParsedTemplates.clear();
7224}
7225
Guy Benyei11169dd2012-12-18 14:30:41 +00007226void ASTReader::LoadSelector(Selector Sel) {
7227 // It would be complicated to avoid reading the methods anyway. So don't.
7228 ReadMethodPool(Sel);
7229}
7230
7231void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7232 assert(ID && "Non-zero identifier ID required");
7233 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7234 IdentifiersLoaded[ID - 1] = II;
7235 if (DeserializationListener)
7236 DeserializationListener->IdentifierRead(ID, II);
7237}
7238
7239/// \brief Set the globally-visible declarations associated with the given
7240/// identifier.
7241///
7242/// If the AST reader is currently in a state where the given declaration IDs
7243/// cannot safely be resolved, they are queued until it is safe to resolve
7244/// them.
7245///
7246/// \param II an IdentifierInfo that refers to one or more globally-visible
7247/// declarations.
7248///
7249/// \param DeclIDs the set of declaration IDs with the name @p II that are
7250/// visible at global scope.
7251///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007252/// \param Decls if non-null, this vector will be populated with the set of
7253/// deserialized declarations. These declarations will not be pushed into
7254/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007255void
7256ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7257 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007258 SmallVectorImpl<Decl *> *Decls) {
7259 if (NumCurrentElementsDeserializing && !Decls) {
7260 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007261 return;
7262 }
7263
7264 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007265 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007266 // Queue this declaration so that it will be added to the
7267 // translation unit scope and identifier's declaration chain
7268 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007269 PreloadedDeclIDs.push_back(DeclIDs[I]);
7270 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007271 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007272
7273 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7274
7275 // If we're simply supposed to record the declarations, do so now.
7276 if (Decls) {
7277 Decls->push_back(D);
7278 continue;
7279 }
7280
7281 // Introduce this declaration into the translation-unit scope
7282 // and add it to the declaration chain for this identifier, so
7283 // that (unqualified) name lookup will find it.
7284 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007285 }
7286}
7287
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007288IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007289 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007290 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007291
7292 if (IdentifiersLoaded.empty()) {
7293 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007294 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007295 }
7296
7297 ID -= 1;
7298 if (!IdentifiersLoaded[ID]) {
7299 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7300 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7301 ModuleFile *M = I->second;
7302 unsigned Index = ID - M->BaseIdentifierID;
7303 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7304
7305 // All of the strings in the AST file are preceded by a 16-bit length.
7306 // Extract that 16-bit length to avoid having to execute strlen().
7307 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7308 // unsigned integers. This is important to avoid integer overflow when
7309 // we cast them to 'unsigned'.
7310 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7311 unsigned StrLen = (((unsigned) StrLenPtr[0])
7312 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007313 IdentifiersLoaded[ID]
7314 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007315 if (DeserializationListener)
7316 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7317 }
7318
7319 return IdentifiersLoaded[ID];
7320}
7321
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007322IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7323 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007324}
7325
7326IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7327 if (LocalID < NUM_PREDEF_IDENT_IDS)
7328 return LocalID;
7329
7330 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7331 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7332 assert(I != M.IdentifierRemap.end()
7333 && "Invalid index into identifier index remap");
7334
7335 return LocalID + I->second;
7336}
7337
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007338MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007339 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007340 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007341
7342 if (MacrosLoaded.empty()) {
7343 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007344 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007345 }
7346
7347 ID -= NUM_PREDEF_MACRO_IDS;
7348 if (!MacrosLoaded[ID]) {
7349 GlobalMacroMapType::iterator I
7350 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7351 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7352 ModuleFile *M = I->second;
7353 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007354 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7355
7356 if (DeserializationListener)
7357 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7358 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007359 }
7360
7361 return MacrosLoaded[ID];
7362}
7363
7364MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7365 if (LocalID < NUM_PREDEF_MACRO_IDS)
7366 return LocalID;
7367
7368 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7369 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7370 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7371
7372 return LocalID + I->second;
7373}
7374
7375serialization::SubmoduleID
7376ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7377 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7378 return LocalID;
7379
7380 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7381 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7382 assert(I != M.SubmoduleRemap.end()
7383 && "Invalid index into submodule index remap");
7384
7385 return LocalID + I->second;
7386}
7387
7388Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7389 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7390 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007391 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007392 }
7393
7394 if (GlobalID > SubmodulesLoaded.size()) {
7395 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007396 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007397 }
7398
7399 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7400}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007401
7402Module *ASTReader::getModule(unsigned ID) {
7403 return getSubmodule(ID);
7404}
7405
Adrian Prantl15bcf702015-06-30 17:39:43 +00007406ExternalASTSource::ASTSourceDescriptor
7407ASTReader::getSourceDescriptor(const Module &M) {
7408 StringRef Dir, Filename;
7409 if (M.Directory)
7410 Dir = M.Directory->getName();
7411 if (auto *File = M.getASTFile())
7412 Filename = File->getName();
7413 return ASTReader::ASTSourceDescriptor{
7414 M.getFullModuleName(), Dir, Filename,
7415 M.Signature
7416 };
7417}
7418
7419llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7420ASTReader::getSourceDescriptor(unsigned ID) {
7421 if (const Module *M = getSubmodule(ID))
7422 return getSourceDescriptor(*M);
7423
7424 // If there is only a single PCH, return it instead.
7425 // Chained PCH are not suported.
7426 if (ModuleMgr.size() == 1) {
7427 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7428 return ASTReader::ASTSourceDescriptor{
7429 MF.OriginalSourceFileName, MF.OriginalDir,
7430 MF.FileName,
7431 MF.Signature
7432 };
7433 }
7434 return None;
7435}
7436
Guy Benyei11169dd2012-12-18 14:30:41 +00007437Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7438 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7439}
7440
7441Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7442 if (ID == 0)
7443 return Selector();
7444
7445 if (ID > SelectorsLoaded.size()) {
7446 Error("selector ID out of range in AST file");
7447 return Selector();
7448 }
7449
Craig Toppera13603a2014-05-22 05:54:18 +00007450 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007451 // Load this selector from the selector table.
7452 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7453 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7454 ModuleFile &M = *I->second;
7455 ASTSelectorLookupTrait Trait(*this, M);
7456 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7457 SelectorsLoaded[ID - 1] =
7458 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7459 if (DeserializationListener)
7460 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7461 }
7462
7463 return SelectorsLoaded[ID - 1];
7464}
7465
7466Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7467 return DecodeSelector(ID);
7468}
7469
7470uint32_t ASTReader::GetNumExternalSelectors() {
7471 // ID 0 (the null selector) is considered an external selector.
7472 return getTotalNumSelectors() + 1;
7473}
7474
7475serialization::SelectorID
7476ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7477 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7478 return LocalID;
7479
7480 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7481 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7482 assert(I != M.SelectorRemap.end()
7483 && "Invalid index into selector index remap");
7484
7485 return LocalID + I->second;
7486}
7487
7488DeclarationName
7489ASTReader::ReadDeclarationName(ModuleFile &F,
7490 const RecordData &Record, unsigned &Idx) {
7491 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7492 switch (Kind) {
7493 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007494 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007495
7496 case DeclarationName::ObjCZeroArgSelector:
7497 case DeclarationName::ObjCOneArgSelector:
7498 case DeclarationName::ObjCMultiArgSelector:
7499 return DeclarationName(ReadSelector(F, Record, Idx));
7500
7501 case DeclarationName::CXXConstructorName:
7502 return Context.DeclarationNames.getCXXConstructorName(
7503 Context.getCanonicalType(readType(F, Record, Idx)));
7504
7505 case DeclarationName::CXXDestructorName:
7506 return Context.DeclarationNames.getCXXDestructorName(
7507 Context.getCanonicalType(readType(F, Record, Idx)));
7508
7509 case DeclarationName::CXXConversionFunctionName:
7510 return Context.DeclarationNames.getCXXConversionFunctionName(
7511 Context.getCanonicalType(readType(F, Record, Idx)));
7512
7513 case DeclarationName::CXXOperatorName:
7514 return Context.DeclarationNames.getCXXOperatorName(
7515 (OverloadedOperatorKind)Record[Idx++]);
7516
7517 case DeclarationName::CXXLiteralOperatorName:
7518 return Context.DeclarationNames.getCXXLiteralOperatorName(
7519 GetIdentifierInfo(F, Record, Idx));
7520
7521 case DeclarationName::CXXUsingDirective:
7522 return DeclarationName::getUsingDirectiveName();
7523 }
7524
7525 llvm_unreachable("Invalid NameKind!");
7526}
7527
7528void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7529 DeclarationNameLoc &DNLoc,
7530 DeclarationName Name,
7531 const RecordData &Record, unsigned &Idx) {
7532 switch (Name.getNameKind()) {
7533 case DeclarationName::CXXConstructorName:
7534 case DeclarationName::CXXDestructorName:
7535 case DeclarationName::CXXConversionFunctionName:
7536 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7537 break;
7538
7539 case DeclarationName::CXXOperatorName:
7540 DNLoc.CXXOperatorName.BeginOpNameLoc
7541 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7542 DNLoc.CXXOperatorName.EndOpNameLoc
7543 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7544 break;
7545
7546 case DeclarationName::CXXLiteralOperatorName:
7547 DNLoc.CXXLiteralOperatorName.OpNameLoc
7548 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7549 break;
7550
7551 case DeclarationName::Identifier:
7552 case DeclarationName::ObjCZeroArgSelector:
7553 case DeclarationName::ObjCOneArgSelector:
7554 case DeclarationName::ObjCMultiArgSelector:
7555 case DeclarationName::CXXUsingDirective:
7556 break;
7557 }
7558}
7559
7560void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7561 DeclarationNameInfo &NameInfo,
7562 const RecordData &Record, unsigned &Idx) {
7563 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7564 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7565 DeclarationNameLoc DNLoc;
7566 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7567 NameInfo.setInfo(DNLoc);
7568}
7569
7570void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7571 const RecordData &Record, unsigned &Idx) {
7572 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7573 unsigned NumTPLists = Record[Idx++];
7574 Info.NumTemplParamLists = NumTPLists;
7575 if (NumTPLists) {
7576 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7577 for (unsigned i=0; i != NumTPLists; ++i)
7578 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7579 }
7580}
7581
7582TemplateName
7583ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7584 unsigned &Idx) {
7585 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7586 switch (Kind) {
7587 case TemplateName::Template:
7588 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7589
7590 case TemplateName::OverloadedTemplate: {
7591 unsigned size = Record[Idx++];
7592 UnresolvedSet<8> Decls;
7593 while (size--)
7594 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7595
7596 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7597 }
7598
7599 case TemplateName::QualifiedTemplate: {
7600 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7601 bool hasTemplKeyword = Record[Idx++];
7602 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7603 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7604 }
7605
7606 case TemplateName::DependentTemplate: {
7607 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7608 if (Record[Idx++]) // isIdentifier
7609 return Context.getDependentTemplateName(NNS,
7610 GetIdentifierInfo(F, Record,
7611 Idx));
7612 return Context.getDependentTemplateName(NNS,
7613 (OverloadedOperatorKind)Record[Idx++]);
7614 }
7615
7616 case TemplateName::SubstTemplateTemplateParm: {
7617 TemplateTemplateParmDecl *param
7618 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7619 if (!param) return TemplateName();
7620 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7621 return Context.getSubstTemplateTemplateParm(param, replacement);
7622 }
7623
7624 case TemplateName::SubstTemplateTemplateParmPack: {
7625 TemplateTemplateParmDecl *Param
7626 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7627 if (!Param)
7628 return TemplateName();
7629
7630 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7631 if (ArgPack.getKind() != TemplateArgument::Pack)
7632 return TemplateName();
7633
7634 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7635 }
7636 }
7637
7638 llvm_unreachable("Unhandled template name kind!");
7639}
7640
7641TemplateArgument
7642ASTReader::ReadTemplateArgument(ModuleFile &F,
7643 const RecordData &Record, unsigned &Idx) {
7644 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7645 switch (Kind) {
7646 case TemplateArgument::Null:
7647 return TemplateArgument();
7648 case TemplateArgument::Type:
7649 return TemplateArgument(readType(F, Record, Idx));
7650 case TemplateArgument::Declaration: {
7651 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007652 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007653 }
7654 case TemplateArgument::NullPtr:
7655 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7656 case TemplateArgument::Integral: {
7657 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7658 QualType T = readType(F, Record, Idx);
7659 return TemplateArgument(Context, Value, T);
7660 }
7661 case TemplateArgument::Template:
7662 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7663 case TemplateArgument::TemplateExpansion: {
7664 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007665 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007666 if (unsigned NumExpansions = Record[Idx++])
7667 NumTemplateExpansions = NumExpansions - 1;
7668 return TemplateArgument(Name, NumTemplateExpansions);
7669 }
7670 case TemplateArgument::Expression:
7671 return TemplateArgument(ReadExpr(F));
7672 case TemplateArgument::Pack: {
7673 unsigned NumArgs = Record[Idx++];
7674 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7675 for (unsigned I = 0; I != NumArgs; ++I)
7676 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007677 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007678 }
7679 }
7680
7681 llvm_unreachable("Unhandled template argument kind!");
7682}
7683
7684TemplateParameterList *
7685ASTReader::ReadTemplateParameterList(ModuleFile &F,
7686 const RecordData &Record, unsigned &Idx) {
7687 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7688 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7689 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7690
7691 unsigned NumParams = Record[Idx++];
7692 SmallVector<NamedDecl *, 16> Params;
7693 Params.reserve(NumParams);
7694 while (NumParams--)
7695 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7696
7697 TemplateParameterList* TemplateParams =
7698 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7699 Params.data(), Params.size(), RAngleLoc);
7700 return TemplateParams;
7701}
7702
7703void
7704ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007705ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007706 ModuleFile &F, const RecordData &Record,
7707 unsigned &Idx) {
7708 unsigned NumTemplateArgs = Record[Idx++];
7709 TemplArgs.reserve(NumTemplateArgs);
7710 while (NumTemplateArgs--)
7711 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7712}
7713
7714/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007715void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007716 const RecordData &Record, unsigned &Idx) {
7717 unsigned NumDecls = Record[Idx++];
7718 Set.reserve(Context, NumDecls);
7719 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007720 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007721 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007722 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007723 }
7724}
7725
7726CXXBaseSpecifier
7727ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7728 const RecordData &Record, unsigned &Idx) {
7729 bool isVirtual = static_cast<bool>(Record[Idx++]);
7730 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7731 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7732 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7733 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7734 SourceRange Range = ReadSourceRange(F, Record, Idx);
7735 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7736 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7737 EllipsisLoc);
7738 Result.setInheritConstructors(inheritConstructors);
7739 return Result;
7740}
7741
Richard Smithc2bb8182015-03-24 06:36:48 +00007742CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007743ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7744 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007745 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007746 assert(NumInitializers && "wrote ctor initializers but have no inits");
7747 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7748 for (unsigned i = 0; i != NumInitializers; ++i) {
7749 TypeSourceInfo *TInfo = nullptr;
7750 bool IsBaseVirtual = false;
7751 FieldDecl *Member = nullptr;
7752 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007753
Richard Smithc2bb8182015-03-24 06:36:48 +00007754 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7755 switch (Type) {
7756 case CTOR_INITIALIZER_BASE:
7757 TInfo = GetTypeSourceInfo(F, Record, Idx);
7758 IsBaseVirtual = Record[Idx++];
7759 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007760
Richard Smithc2bb8182015-03-24 06:36:48 +00007761 case CTOR_INITIALIZER_DELEGATING:
7762 TInfo = GetTypeSourceInfo(F, Record, Idx);
7763 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007764
Richard Smithc2bb8182015-03-24 06:36:48 +00007765 case CTOR_INITIALIZER_MEMBER:
7766 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7767 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007768
Richard Smithc2bb8182015-03-24 06:36:48 +00007769 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7770 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7771 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007772 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007773
7774 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7775 Expr *Init = ReadExpr(F);
7776 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7777 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7778 bool IsWritten = Record[Idx++];
7779 unsigned SourceOrderOrNumArrayIndices;
7780 SmallVector<VarDecl *, 8> Indices;
7781 if (IsWritten) {
7782 SourceOrderOrNumArrayIndices = Record[Idx++];
7783 } else {
7784 SourceOrderOrNumArrayIndices = Record[Idx++];
7785 Indices.reserve(SourceOrderOrNumArrayIndices);
7786 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7787 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7788 }
7789
7790 CXXCtorInitializer *BOMInit;
7791 if (Type == CTOR_INITIALIZER_BASE) {
7792 BOMInit = new (Context)
7793 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7794 RParenLoc, MemberOrEllipsisLoc);
7795 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7796 BOMInit = new (Context)
7797 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7798 } else if (IsWritten) {
7799 if (Member)
7800 BOMInit = new (Context) CXXCtorInitializer(
7801 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7802 else
7803 BOMInit = new (Context)
7804 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7805 LParenLoc, Init, RParenLoc);
7806 } else {
7807 if (IndirectMember) {
7808 assert(Indices.empty() && "Indirect field improperly initialized");
7809 BOMInit = new (Context)
7810 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7811 LParenLoc, Init, RParenLoc);
7812 } else {
7813 BOMInit = CXXCtorInitializer::Create(
7814 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7815 Indices.data(), Indices.size());
7816 }
7817 }
7818
7819 if (IsWritten)
7820 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7821 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007822 }
7823
Richard Smithc2bb8182015-03-24 06:36:48 +00007824 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007825}
7826
7827NestedNameSpecifier *
7828ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7829 const RecordData &Record, unsigned &Idx) {
7830 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007831 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007832 for (unsigned I = 0; I != N; ++I) {
7833 NestedNameSpecifier::SpecifierKind Kind
7834 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7835 switch (Kind) {
7836 case NestedNameSpecifier::Identifier: {
7837 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7838 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7839 break;
7840 }
7841
7842 case NestedNameSpecifier::Namespace: {
7843 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7844 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7845 break;
7846 }
7847
7848 case NestedNameSpecifier::NamespaceAlias: {
7849 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7850 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7851 break;
7852 }
7853
7854 case NestedNameSpecifier::TypeSpec:
7855 case NestedNameSpecifier::TypeSpecWithTemplate: {
7856 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7857 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007858 return nullptr;
7859
Guy Benyei11169dd2012-12-18 14:30:41 +00007860 bool Template = Record[Idx++];
7861 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7862 break;
7863 }
7864
7865 case NestedNameSpecifier::Global: {
7866 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7867 // No associated value, and there can't be a prefix.
7868 break;
7869 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007870
7871 case NestedNameSpecifier::Super: {
7872 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7873 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7874 break;
7875 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007876 }
7877 Prev = NNS;
7878 }
7879 return NNS;
7880}
7881
7882NestedNameSpecifierLoc
7883ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7884 unsigned &Idx) {
7885 unsigned N = Record[Idx++];
7886 NestedNameSpecifierLocBuilder Builder;
7887 for (unsigned I = 0; I != N; ++I) {
7888 NestedNameSpecifier::SpecifierKind Kind
7889 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7890 switch (Kind) {
7891 case NestedNameSpecifier::Identifier: {
7892 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7893 SourceRange Range = ReadSourceRange(F, Record, Idx);
7894 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7895 break;
7896 }
7897
7898 case NestedNameSpecifier::Namespace: {
7899 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7900 SourceRange Range = ReadSourceRange(F, Record, Idx);
7901 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7902 break;
7903 }
7904
7905 case NestedNameSpecifier::NamespaceAlias: {
7906 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7907 SourceRange Range = ReadSourceRange(F, Record, Idx);
7908 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7909 break;
7910 }
7911
7912 case NestedNameSpecifier::TypeSpec:
7913 case NestedNameSpecifier::TypeSpecWithTemplate: {
7914 bool Template = Record[Idx++];
7915 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7916 if (!T)
7917 return NestedNameSpecifierLoc();
7918 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7919
7920 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7921 Builder.Extend(Context,
7922 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7923 T->getTypeLoc(), ColonColonLoc);
7924 break;
7925 }
7926
7927 case NestedNameSpecifier::Global: {
7928 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7929 Builder.MakeGlobal(Context, ColonColonLoc);
7930 break;
7931 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007932
7933 case NestedNameSpecifier::Super: {
7934 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7935 SourceRange Range = ReadSourceRange(F, Record, Idx);
7936 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7937 break;
7938 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007939 }
7940 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007941
Guy Benyei11169dd2012-12-18 14:30:41 +00007942 return Builder.getWithLocInContext(Context);
7943}
7944
7945SourceRange
7946ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7947 unsigned &Idx) {
7948 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7949 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7950 return SourceRange(beg, end);
7951}
7952
7953/// \brief Read an integral value
7954llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7955 unsigned BitWidth = Record[Idx++];
7956 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7957 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7958 Idx += NumWords;
7959 return Result;
7960}
7961
7962/// \brief Read a signed integral value
7963llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7964 bool isUnsigned = Record[Idx++];
7965 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7966}
7967
7968/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007969llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7970 const llvm::fltSemantics &Sem,
7971 unsigned &Idx) {
7972 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007973}
7974
7975// \brief Read a string
7976std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7977 unsigned Len = Record[Idx++];
7978 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7979 Idx += Len;
7980 return Result;
7981}
7982
Richard Smith7ed1bc92014-12-05 22:42:13 +00007983std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7984 unsigned &Idx) {
7985 std::string Filename = ReadString(Record, Idx);
7986 ResolveImportedPath(F, Filename);
7987 return Filename;
7988}
7989
Guy Benyei11169dd2012-12-18 14:30:41 +00007990VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7991 unsigned &Idx) {
7992 unsigned Major = Record[Idx++];
7993 unsigned Minor = Record[Idx++];
7994 unsigned Subminor = Record[Idx++];
7995 if (Minor == 0)
7996 return VersionTuple(Major);
7997 if (Subminor == 0)
7998 return VersionTuple(Major, Minor - 1);
7999 return VersionTuple(Major, Minor - 1, Subminor - 1);
8000}
8001
8002CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8003 const RecordData &Record,
8004 unsigned &Idx) {
8005 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8006 return CXXTemporary::Create(Context, Decl);
8007}
8008
8009DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008010 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008011}
8012
8013DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8014 return Diags.Report(Loc, DiagID);
8015}
8016
8017/// \brief Retrieve the identifier table associated with the
8018/// preprocessor.
8019IdentifierTable &ASTReader::getIdentifierTable() {
8020 return PP.getIdentifierTable();
8021}
8022
8023/// \brief Record that the given ID maps to the given switch-case
8024/// statement.
8025void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008026 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008027 "Already have a SwitchCase with this ID");
8028 (*CurrSwitchCaseStmts)[ID] = SC;
8029}
8030
8031/// \brief Retrieve the switch-case statement with the given ID.
8032SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008033 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008034 return (*CurrSwitchCaseStmts)[ID];
8035}
8036
8037void ASTReader::ClearSwitchCaseIDs() {
8038 CurrSwitchCaseStmts->clear();
8039}
8040
8041void ASTReader::ReadComments() {
8042 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008043 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008044 serialization::ModuleFile *> >::iterator
8045 I = CommentsCursors.begin(),
8046 E = CommentsCursors.end();
8047 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008048 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008049 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008050 serialization::ModuleFile &F = *I->second;
8051 SavedStreamPosition SavedPosition(Cursor);
8052
8053 RecordData Record;
8054 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008055 llvm::BitstreamEntry Entry =
8056 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008057
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008058 switch (Entry.Kind) {
8059 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8060 case llvm::BitstreamEntry::Error:
8061 Error("malformed block record in AST file");
8062 return;
8063 case llvm::BitstreamEntry::EndBlock:
8064 goto NextCursor;
8065 case llvm::BitstreamEntry::Record:
8066 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008067 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008068 }
8069
8070 // Read a record.
8071 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008072 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008073 case COMMENTS_RAW_COMMENT: {
8074 unsigned Idx = 0;
8075 SourceRange SR = ReadSourceRange(F, Record, Idx);
8076 RawComment::CommentKind Kind =
8077 (RawComment::CommentKind) Record[Idx++];
8078 bool IsTrailingComment = Record[Idx++];
8079 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008080 Comments.push_back(new (Context) RawComment(
8081 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8082 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008083 break;
8084 }
8085 }
8086 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008087 NextCursor:
8088 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008089 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008090}
8091
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008092void ASTReader::getInputFiles(ModuleFile &F,
8093 SmallVectorImpl<serialization::InputFile> &Files) {
8094 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8095 unsigned ID = I+1;
8096 Files.push_back(getInputFile(F, ID));
8097 }
8098}
8099
Richard Smithcd45dbc2014-04-19 03:48:30 +00008100std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8101 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008102 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008103 return M->getFullModuleName();
8104
8105 // Otherwise, use the name of the top-level module the decl is within.
8106 if (ModuleFile *M = getOwningModuleFile(D))
8107 return M->ModuleName;
8108
8109 // Not from a module.
8110 return "";
8111}
8112
Guy Benyei11169dd2012-12-18 14:30:41 +00008113void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008114 while (!PendingIdentifierInfos.empty() ||
8115 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008116 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008117 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008118 // If any identifiers with corresponding top-level declarations have
8119 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008120 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8121 TopLevelDeclsMap;
8122 TopLevelDeclsMap TopLevelDecls;
8123
Guy Benyei11169dd2012-12-18 14:30:41 +00008124 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008125 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008126 SmallVector<uint32_t, 4> DeclIDs =
8127 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008128 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008129
8130 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008131 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008132
Richard Smith851072e2014-05-19 20:59:20 +00008133 // For each decl chain that we wanted to complete while deserializing, mark
8134 // it as "still needs to be completed".
8135 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8136 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8137 }
8138 PendingIncompleteDeclChains.clear();
8139
Guy Benyei11169dd2012-12-18 14:30:41 +00008140 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008141 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008142 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008143 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008144 }
8145 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008146 PendingDeclChains.clear();
8147
Richard Smith9b88a4c2015-07-27 05:40:23 +00008148 assert(RedeclsDeserialized.empty() && "some redecls not wired up");
8149
Douglas Gregor6168bd22013-02-18 15:53:43 +00008150 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008151 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8152 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008153 IdentifierInfo *II = TLD->first;
8154 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008155 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008156 }
8157 }
8158
Guy Benyei11169dd2012-12-18 14:30:41 +00008159 // Load any pending macro definitions.
8160 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008161 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8162 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8163 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8164 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008165 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008166 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008167 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008168 if (Info.M->Kind != MK_ImplicitModule &&
8169 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008170 resolvePendingMacro(II, Info);
8171 }
8172 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008173 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008174 ++IDIdx) {
8175 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008176 if (Info.M->Kind == MK_ImplicitModule ||
8177 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008178 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008179 }
8180 }
8181 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008182
8183 // Wire up the DeclContexts for Decls that we delayed setting until
8184 // recursive loading is completed.
8185 while (!PendingDeclContextInfos.empty()) {
8186 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8187 PendingDeclContextInfos.pop_front();
8188 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8189 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8190 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8191 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008192
Richard Smithd1c46742014-04-30 02:24:17 +00008193 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008194 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008195 auto Update = PendingUpdateRecords.pop_back_val();
8196 ReadingKindTracker ReadingKind(Read_Decl, *this);
8197 loadDeclUpdateRecords(Update.first, Update.second);
8198 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008199 }
Richard Smith8a639892015-01-24 01:07:20 +00008200
8201 // At this point, all update records for loaded decls are in place, so any
8202 // fake class definitions should have become real.
8203 assert(PendingFakeDefinitionData.empty() &&
8204 "faked up a class definition but never saw the real one");
8205
Guy Benyei11169dd2012-12-18 14:30:41 +00008206 // If we deserialized any C++ or Objective-C class definitions, any
8207 // Objective-C protocol definitions, or any redeclarable templates, make sure
8208 // that all redeclarations point to the definitions. Note that this can only
8209 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008210 for (Decl *D : PendingDefinitions) {
8211 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008212 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008213 // Make sure that the TagType points at the definition.
8214 const_cast<TagType*>(TagT)->decl = TD;
8215 }
Richard Smith8ce51082015-03-11 01:44:51 +00008216
Craig Topperc6914d02014-08-25 04:15:02 +00008217 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008218 for (auto *R = getMostRecentExistingDecl(RD); R;
8219 R = R->getPreviousDecl()) {
8220 assert((R == D) ==
8221 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008222 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008223 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008224 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008225 }
8226
8227 continue;
8228 }
Richard Smith8ce51082015-03-11 01:44:51 +00008229
Craig Topperc6914d02014-08-25 04:15:02 +00008230 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008231 // Make sure that the ObjCInterfaceType points at the definition.
8232 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8233 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008234
8235 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8236 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8237
Guy Benyei11169dd2012-12-18 14:30:41 +00008238 continue;
8239 }
Richard Smith8ce51082015-03-11 01:44:51 +00008240
Craig Topperc6914d02014-08-25 04:15:02 +00008241 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008242 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8243 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8244
Guy Benyei11169dd2012-12-18 14:30:41 +00008245 continue;
8246 }
Richard Smith8ce51082015-03-11 01:44:51 +00008247
Craig Topperc6914d02014-08-25 04:15:02 +00008248 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008249 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8250 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008251 }
8252 PendingDefinitions.clear();
8253
8254 // Load the bodies of any functions or methods we've encountered. We do
8255 // this now (delayed) so that we can be sure that the declaration chains
8256 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008257 // FIXME: There seems to be no point in delaying this, it does not depend
8258 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008259 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8260 PBEnd = PendingBodies.end();
8261 PB != PBEnd; ++PB) {
8262 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8263 // FIXME: Check for =delete/=default?
8264 // FIXME: Complain about ODR violations here?
8265 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8266 FD->setLazyBody(PB->second);
8267 continue;
8268 }
8269
8270 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8271 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8272 MD->setLazyBody(PB->second);
8273 }
8274 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008275
8276 // Do some cleanup.
8277 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8278 getContext().deduplicateMergedDefinitonsFor(ND);
8279 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008280}
8281
8282void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008283 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8284 return;
8285
Richard Smitha0ce9c42014-07-29 23:23:27 +00008286 // Trigger the import of the full definition of each class that had any
8287 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008288 // These updates may in turn find and diagnose some ODR failures, so take
8289 // ownership of the set first.
8290 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8291 PendingOdrMergeFailures.clear();
8292 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008293 Merge.first->buildLookup();
8294 Merge.first->decls_begin();
8295 Merge.first->bases_begin();
8296 Merge.first->vbases_begin();
8297 for (auto *RD : Merge.second) {
8298 RD->decls_begin();
8299 RD->bases_begin();
8300 RD->vbases_begin();
8301 }
8302 }
8303
8304 // For each declaration from a merged context, check that the canonical
8305 // definition of that context also contains a declaration of the same
8306 // entity.
8307 //
8308 // Caution: this loop does things that might invalidate iterators into
8309 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8310 while (!PendingOdrMergeChecks.empty()) {
8311 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8312
8313 // FIXME: Skip over implicit declarations for now. This matters for things
8314 // like implicitly-declared special member functions. This isn't entirely
8315 // correct; we can end up with multiple unmerged declarations of the same
8316 // implicit entity.
8317 if (D->isImplicit())
8318 continue;
8319
8320 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008321
8322 bool Found = false;
8323 const Decl *DCanon = D->getCanonicalDecl();
8324
Richard Smith01bdb7a2014-08-28 05:44:07 +00008325 for (auto RI : D->redecls()) {
8326 if (RI->getLexicalDeclContext() == CanonDef) {
8327 Found = true;
8328 break;
8329 }
8330 }
8331 if (Found)
8332 continue;
8333
Richard Smitha0ce9c42014-07-29 23:23:27 +00008334 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008335 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008336 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8337 !Found && I != E; ++I) {
8338 for (auto RI : (*I)->redecls()) {
8339 if (RI->getLexicalDeclContext() == CanonDef) {
8340 // This declaration is present in the canonical definition. If it's
8341 // in the same redecl chain, it's the one we're looking for.
8342 if (RI->getCanonicalDecl() == DCanon)
8343 Found = true;
8344 else
8345 Candidates.push_back(cast<NamedDecl>(RI));
8346 break;
8347 }
8348 }
8349 }
8350
8351 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008352 // The AST doesn't like TagDecls becoming invalid after they've been
8353 // completed. We only really need to mark FieldDecls as invalid here.
8354 if (!isa<TagDecl>(D))
8355 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008356
8357 // Ensure we don't accidentally recursively enter deserialization while
8358 // we're producing our diagnostic.
8359 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008360
8361 std::string CanonDefModule =
8362 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8363 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8364 << D << getOwningModuleNameForDiagnostic(D)
8365 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8366
8367 if (Candidates.empty())
8368 Diag(cast<Decl>(CanonDef)->getLocation(),
8369 diag::note_module_odr_violation_no_possible_decls) << D;
8370 else {
8371 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8372 Diag(Candidates[I]->getLocation(),
8373 diag::note_module_odr_violation_possible_decl)
8374 << Candidates[I];
8375 }
8376
8377 DiagnosedOdrMergeFailures.insert(CanonDef);
8378 }
8379 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008380
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008381 if (OdrMergeFailures.empty())
8382 return;
8383
8384 // Ensure we don't accidentally recursively enter deserialization while
8385 // we're producing our diagnostics.
8386 Deserializing RecursionGuard(this);
8387
Richard Smithcd45dbc2014-04-19 03:48:30 +00008388 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008389 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008390 // If we've already pointed out a specific problem with this class, don't
8391 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008392 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008393 continue;
8394
8395 bool Diagnosed = false;
8396 for (auto *RD : Merge.second) {
8397 // Multiple different declarations got merged together; tell the user
8398 // where they came from.
8399 if (Merge.first != RD) {
8400 // FIXME: Walk the definition, figure out what's different,
8401 // and diagnose that.
8402 if (!Diagnosed) {
8403 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8404 Diag(Merge.first->getLocation(),
8405 diag::err_module_odr_violation_different_definitions)
8406 << Merge.first << Module.empty() << Module;
8407 Diagnosed = true;
8408 }
8409
8410 Diag(RD->getLocation(),
8411 diag::note_module_odr_violation_different_definitions)
8412 << getOwningModuleNameForDiagnostic(RD);
8413 }
8414 }
8415
8416 if (!Diagnosed) {
8417 // All definitions are updates to the same declaration. This happens if a
8418 // module instantiates the declaration of a class template specialization
8419 // and two or more other modules instantiate its definition.
8420 //
8421 // FIXME: Indicate which modules had instantiations of this definition.
8422 // FIXME: How can this even happen?
8423 Diag(Merge.first->getLocation(),
8424 diag::err_module_odr_violation_different_instantiations)
8425 << Merge.first;
8426 }
8427 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008428}
8429
Richard Smithce18a182015-07-14 00:26:00 +00008430void ASTReader::StartedDeserializing() {
8431 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8432 ReadTimer->startTimer();
8433}
8434
Guy Benyei11169dd2012-12-18 14:30:41 +00008435void ASTReader::FinishedDeserializing() {
8436 assert(NumCurrentElementsDeserializing &&
8437 "FinishedDeserializing not paired with StartedDeserializing");
8438 if (NumCurrentElementsDeserializing == 1) {
8439 // We decrease NumCurrentElementsDeserializing only after pending actions
8440 // are finished, to avoid recursively re-calling finishPendingActions().
8441 finishPendingActions();
8442 }
8443 --NumCurrentElementsDeserializing;
8444
Richard Smitha0ce9c42014-07-29 23:23:27 +00008445 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008446 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008447 while (!PendingExceptionSpecUpdates.empty()) {
8448 auto Updates = std::move(PendingExceptionSpecUpdates);
8449 PendingExceptionSpecUpdates.clear();
8450 for (auto Update : Updates) {
8451 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8452 SemaObj->UpdateExceptionSpec(Update.second,
8453 FPT->getExtProtoInfo().ExceptionSpec);
8454 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008455 }
8456
Richard Smitha0ce9c42014-07-29 23:23:27 +00008457 diagnoseOdrViolations();
8458
Richard Smithce18a182015-07-14 00:26:00 +00008459 if (ReadTimer)
8460 ReadTimer->stopTimer();
8461
Richard Smith04d05b52014-03-23 00:27:18 +00008462 // We are not in recursive loading, so it's safe to pass the "interesting"
8463 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008464 if (Consumer)
8465 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008466 }
8467}
8468
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008469void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008470 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8471 // Remove any fake results before adding any real ones.
8472 auto It = PendingFakeLookupResults.find(II);
8473 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008474 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008475 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008476 // FIXME: this works around module+PCH performance issue.
8477 // Rather than erase the result from the map, which is O(n), just clear
8478 // the vector of NamedDecls.
8479 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008480 }
8481 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008482
8483 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8484 SemaObj->TUScope->AddDecl(D);
8485 } else if (SemaObj->TUScope) {
8486 // Adding the decl to IdResolver may have failed because it was already in
8487 // (even though it was not added in scope). If it is already in, make sure
8488 // it gets in the scope as well.
8489 if (std::find(SemaObj->IdResolver.begin(Name),
8490 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8491 SemaObj->TUScope->AddDecl(D);
8492 }
8493}
8494
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008495ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008496 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008497 StringRef isysroot, bool DisableValidation,
8498 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008499 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Richard Smithce18a182015-07-14 00:26:00 +00008500 bool UseGlobalIndex,
8501 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008502 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008503 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008504 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008505 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008506 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008507 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008508 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008509 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8510 AllowConfigurationMismatch(AllowConfigurationMismatch),
8511 ValidateSystemInputs(ValidateSystemInputs),
8512 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008513 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8514 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8515 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8516 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008517 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8518 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8519 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8520 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8521 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8522 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008523 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008524 SourceMgr.setExternalSLocEntrySource(this);
8525}
8526
8527ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008528 if (OwnsDeserializationListener)
8529 delete DeserializationListener;
8530
Guy Benyei11169dd2012-12-18 14:30:41 +00008531 for (DeclContextVisibleUpdatesPending::iterator
8532 I = PendingVisibleUpdates.begin(),
8533 E = PendingVisibleUpdates.end();
8534 I != E; ++I) {
8535 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8536 F = I->second.end();
8537 J != F; ++J)
8538 delete J->first;
8539 }
8540}