blob: 0a76488c900ca7d4b9321a16655e2e00c1793f76 [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
1595 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1596 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001597 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001598
1599 // If there was no preprocessor block, skip this file.
1600 if (!MacroCursor.getBitStreamReader())
1601 continue;
1602
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001603 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001604 Cursor.JumpToBit((*I)->MacroStartOffset);
1605
1606 RecordData Record;
1607 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001608 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1609
1610 switch (E.Kind) {
1611 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1612 case llvm::BitstreamEntry::Error:
1613 Error("malformed block record in AST file");
1614 return;
1615 case llvm::BitstreamEntry::EndBlock:
1616 goto NextCursor;
1617
1618 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001619 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001620 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001621 default: // Default behavior: ignore.
1622 break;
1623
1624 case PP_MACRO_OBJECT_LIKE:
1625 case PP_MACRO_FUNCTION_LIKE:
1626 getLocalIdentifier(**I, Record[0]);
1627 break;
1628
1629 case PP_TOKEN:
1630 // Ignore tokens.
1631 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001632 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001633 break;
1634 }
1635 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001636 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001637 }
1638}
1639
1640namespace {
1641 /// \brief Visitor class used to look up identifirs in an AST file.
1642 class IdentifierLookupVisitor {
1643 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001644 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001645 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001646 unsigned &NumIdentifierLookups;
1647 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001648 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001649
Guy Benyei11169dd2012-12-18 14:30:41 +00001650 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001651 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1652 unsigned &NumIdentifierLookups,
1653 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001654 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1655 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001656 NumIdentifierLookups(NumIdentifierLookups),
1657 NumIdentifierLookupHits(NumIdentifierLookupHits),
1658 Found()
1659 {
1660 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001661
1662 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001663 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001664 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001665 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001666
Guy Benyei11169dd2012-12-18 14:30:41 +00001667 ASTIdentifierLookupTable *IdTable
1668 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1669 if (!IdTable)
1670 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001671
1672 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001673 Found);
1674 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001675 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001676 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001677 if (Pos == IdTable->end())
1678 return false;
1679
1680 // Dereferencing the iterator has the effect of building the
1681 // IdentifierInfo node and populating it with the various
1682 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001683 ++NumIdentifierLookupHits;
1684 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001685 return true;
1686 }
1687
1688 // \brief Retrieve the identifier info found within the module
1689 // files.
1690 IdentifierInfo *getIdentifierInfo() const { return Found; }
1691 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001692}
Guy Benyei11169dd2012-12-18 14:30:41 +00001693
1694void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1695 // Note that we are loading an identifier.
1696 Deserializing AnIdentifier(this);
1697
1698 unsigned PriorGeneration = 0;
1699 if (getContext().getLangOpts().Modules)
1700 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001701
1702 // If there is a global index, look there first to determine which modules
1703 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001704 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001705 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001706 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001707 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1708 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001709 }
1710 }
1711
Douglas Gregor7211ac12013-01-25 23:32:03 +00001712 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001713 NumIdentifierLookups,
1714 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001715 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001716 markIdentifierUpToDate(&II);
1717}
1718
1719void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1720 if (!II)
1721 return;
1722
1723 II->setOutOfDate(false);
1724
1725 // Update the generation for this identifier.
1726 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001727 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001728}
1729
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001730void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1731 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001732 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001733
1734 BitstreamCursor &Cursor = M.MacroCursor;
1735 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001736 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001737
Richard Smith713369b2015-04-23 20:40:50 +00001738 struct ModuleMacroRecord {
1739 SubmoduleID SubModID;
1740 MacroInfo *MI;
1741 SmallVector<SubmoduleID, 8> Overrides;
1742 };
1743 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001744
Richard Smithd7329392015-04-21 21:46:32 +00001745 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1746 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1747 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001748 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001749 while (true) {
1750 llvm::BitstreamEntry Entry =
1751 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1752 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1753 Error("malformed block record in AST file");
1754 return;
1755 }
1756
1757 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001758 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001759 case PP_MACRO_DIRECTIVE_HISTORY:
1760 break;
1761
1762 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001763 ModuleMacros.push_back(ModuleMacroRecord());
1764 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001765 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1766 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001767 for (int I = 2, N = Record.size(); I != N; ++I)
1768 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001769 continue;
1770 }
1771
1772 default:
1773 Error("malformed block record in AST file");
1774 return;
1775 }
1776
1777 // We found the macro directive history; that's the last record
1778 // for this macro.
1779 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001780 }
1781
Richard Smithd7329392015-04-21 21:46:32 +00001782 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001783 {
1784 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001785 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001786 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001787 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001788 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001789 Module *Mod = getSubmodule(ModID);
1790 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001791 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001792 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001793 }
1794
1795 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001796 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001797 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001798 }
1799 }
1800
1801 // Don't read the directive history for a module; we don't have anywhere
1802 // to put it.
1803 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1804 return;
1805
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001806 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001807 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001808 unsigned Idx = 0, N = Record.size();
1809 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001810 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001811 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001812 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1813 switch (K) {
1814 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001815 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001816 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001817 break;
1818 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001819 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001820 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001821 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001822 }
1823 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001824 bool isPublic = Record[Idx++];
1825 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1826 break;
1827 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001828
1829 if (!Latest)
1830 Latest = MD;
1831 if (Earliest)
1832 Earliest->setPrevious(MD);
1833 Earliest = MD;
1834 }
1835
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001836 if (Latest)
1837 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001838}
1839
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001840ASTReader::InputFileInfo
1841ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001842 // Go find this input file.
1843 BitstreamCursor &Cursor = F.InputFilesCursor;
1844 SavedStreamPosition SavedPosition(Cursor);
1845 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1846
1847 unsigned Code = Cursor.ReadCode();
1848 RecordData Record;
1849 StringRef Blob;
1850
1851 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1852 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1853 "invalid record type for input file");
1854 (void)Result;
1855
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001856 std::string Filename;
1857 off_t StoredSize;
1858 time_t StoredTime;
1859 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001860
Ben Langmuir198c1682014-03-07 07:27:49 +00001861 assert(Record[0] == ID && "Bogus stored ID or offset");
1862 StoredSize = static_cast<off_t>(Record[1]);
1863 StoredTime = static_cast<time_t>(Record[2]);
1864 Overridden = static_cast<bool>(Record[3]);
1865 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001866 ResolveImportedPath(F, Filename);
1867
Hans Wennborg73945142014-03-14 17:45:06 +00001868 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1869 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001870}
1871
1872std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001873 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00001874}
1875
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001876InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001877 // If this ID is bogus, just return an empty input file.
1878 if (ID == 0 || ID > F.InputFilesLoaded.size())
1879 return InputFile();
1880
1881 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001882 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001883 return F.InputFilesLoaded[ID-1];
1884
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001885 if (F.InputFilesLoaded[ID-1].isNotFound())
1886 return InputFile();
1887
Guy Benyei11169dd2012-12-18 14:30:41 +00001888 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001889 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001890 SavedStreamPosition SavedPosition(Cursor);
1891 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1892
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001893 InputFileInfo FI = readInputFileInfo(F, ID);
1894 off_t StoredSize = FI.StoredSize;
1895 time_t StoredTime = FI.StoredTime;
1896 bool Overridden = FI.Overridden;
1897 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001898
Ben Langmuir198c1682014-03-07 07:27:49 +00001899 const FileEntry *File
1900 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1901 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1902
1903 // If we didn't find the file, resolve it relative to the
1904 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001905 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001906 F.OriginalDir != CurrentDir) {
1907 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1908 F.OriginalDir,
1909 CurrentDir);
1910 if (!Resolved.empty())
1911 File = FileMgr.getFile(Resolved);
1912 }
1913
1914 // For an overridden file, create a virtual file with the stored
1915 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001916 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001917 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1918 }
1919
Craig Toppera13603a2014-05-22 05:54:18 +00001920 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001921 if (Complain) {
1922 std::string ErrorStr = "could not find file '";
1923 ErrorStr += Filename;
1924 ErrorStr += "' referenced by AST file";
1925 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001926 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001927 // Record that we didn't find the file.
1928 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1929 return InputFile();
1930 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001931
Ben Langmuir198c1682014-03-07 07:27:49 +00001932 // Check if there was a request to override the contents of the file
1933 // that was part of the precompiled header. Overridding such a file
1934 // can lead to problems when lexing using the source locations from the
1935 // PCH.
1936 SourceManager &SM = getSourceManager();
1937 if (!Overridden && SM.isFileOverridden(File)) {
1938 if (Complain)
1939 Error(diag::err_fe_pch_file_overridden, Filename);
1940 // After emitting the diagnostic, recover by disabling the override so
1941 // that the original file will be used.
1942 SM.disableFileContentsOverride(File);
1943 // The FileEntry is a virtual file entry with the size of the contents
1944 // that would override the original contents. Set it to the original's
1945 // size/time.
1946 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1947 StoredSize, StoredTime);
1948 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001949
Ben Langmuir198c1682014-03-07 07:27:49 +00001950 bool IsOutOfDate = false;
1951
1952 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001953 if (!Overridden && //
1954 (StoredSize != File->getSize() ||
1955#if defined(LLVM_ON_WIN32)
1956 false
1957#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001958 // In our regression testing, the Windows file system seems to
1959 // have inconsistent modification times that sometimes
1960 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001961 //
1962 // This also happens in networked file systems, so disable this
1963 // check if validation is disabled or if we have an explicitly
1964 // built PCM file.
1965 //
1966 // FIXME: Should we also do this for PCH files? They could also
1967 // reasonably get shared across a network during a distributed build.
1968 (StoredTime != File->getModificationTime() && !DisableValidation &&
1969 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001970#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001971 )) {
1972 if (Complain) {
1973 // Build a list of the PCH imports that got us here (in reverse).
1974 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1975 while (ImportStack.back()->ImportedBy.size() > 0)
1976 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001977
Ben Langmuir198c1682014-03-07 07:27:49 +00001978 // The top-level PCH is stale.
1979 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1980 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00001981
Ben Langmuir198c1682014-03-07 07:27:49 +00001982 // Print the import stack.
1983 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1984 Diag(diag::note_pch_required_by)
1985 << Filename << ImportStack[0]->FileName;
1986 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00001987 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00001988 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00001989 }
1990
Ben Langmuir198c1682014-03-07 07:27:49 +00001991 if (!Diags.isDiagnosticInFlight())
1992 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00001993 }
1994
Ben Langmuir198c1682014-03-07 07:27:49 +00001995 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001996 }
1997
Ben Langmuir198c1682014-03-07 07:27:49 +00001998 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
1999
2000 // Note that we've loaded this input file.
2001 F.InputFilesLoaded[ID-1] = IF;
2002 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002003}
2004
Richard Smith7ed1bc92014-12-05 22:42:13 +00002005/// \brief If we are loading a relocatable PCH or module file, and the filename
2006/// is not an absolute path, add the system or module root to the beginning of
2007/// the file name.
2008void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2009 // Resolve relative to the base directory, if we have one.
2010 if (!M.BaseDirectory.empty())
2011 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002012}
2013
Richard Smith7ed1bc92014-12-05 22:42:13 +00002014void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002015 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2016 return;
2017
Richard Smith7ed1bc92014-12-05 22:42:13 +00002018 SmallString<128> Buffer;
2019 llvm::sys::path::append(Buffer, Prefix, Filename);
2020 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002021}
2022
2023ASTReader::ASTReadResult
2024ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002025 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002026 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002027 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002028 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002029
2030 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2031 Error("malformed block record in AST file");
2032 return Failure;
2033 }
2034
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002035 // Should we allow the configuration of the module file to differ from the
2036 // configuration of the current translation unit in a compatible way?
2037 //
2038 // FIXME: Allow this for files explicitly specified with -include-pch too.
2039 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2040
Guy Benyei11169dd2012-12-18 14:30:41 +00002041 // Read all of the records and blocks in the control block.
2042 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002043 unsigned NumInputs = 0;
2044 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002045 while (1) {
2046 llvm::BitstreamEntry Entry = Stream.advance();
2047
2048 switch (Entry.Kind) {
2049 case llvm::BitstreamEntry::Error:
2050 Error("malformed block record in AST file");
2051 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002052 case llvm::BitstreamEntry::EndBlock: {
2053 // Validate input files.
2054 const HeaderSearchOptions &HSOpts =
2055 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002056
Richard Smitha1825302014-10-23 22:18:29 +00002057 // All user input files reside at the index range [0, NumUserInputs), and
2058 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002059 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002060 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002061
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002062 // If we are reading a module, we will create a verification timestamp,
2063 // so we verify all input files. Otherwise, verify only user input
2064 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002065
2066 unsigned N = NumUserInputs;
2067 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002068 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002069 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002070 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002071 N = NumInputs;
2072
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002073 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002074 InputFile IF = getInputFile(F, I+1, Complain);
2075 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002076 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002077 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002078 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002079
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002080 if (Listener)
2081 Listener->visitModuleFile(F.FileName);
2082
Ben Langmuircb69b572014-03-07 06:40:32 +00002083 if (Listener && Listener->needsInputFileVisitation()) {
2084 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2085 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002086 for (unsigned I = 0; I < N; ++I) {
2087 bool IsSystem = I >= NumUserInputs;
2088 InputFileInfo FI = readInputFileInfo(F, I+1);
2089 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2090 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002091 }
2092
Guy Benyei11169dd2012-12-18 14:30:41 +00002093 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002094 }
2095
Chris Lattnere7b154b2013-01-19 21:39:22 +00002096 case llvm::BitstreamEntry::SubBlock:
2097 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002098 case INPUT_FILES_BLOCK_ID:
2099 F.InputFilesCursor = Stream;
2100 if (Stream.SkipBlock() || // Skip with the main cursor
2101 // Read the abbreviations
2102 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2103 Error("malformed block record in AST file");
2104 return Failure;
2105 }
2106 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002107
Guy Benyei11169dd2012-12-18 14:30:41 +00002108 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002109 if (Stream.SkipBlock()) {
2110 Error("malformed block record in AST file");
2111 return Failure;
2112 }
2113 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002114 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002115
2116 case llvm::BitstreamEntry::Record:
2117 // The interesting case.
2118 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002119 }
2120
2121 // Read and process a record.
2122 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002123 StringRef Blob;
2124 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002125 case METADATA: {
2126 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2127 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002128 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2129 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002130 return VersionMismatch;
2131 }
2132
2133 bool hasErrors = Record[5];
2134 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2135 Diag(diag::err_pch_with_compiler_errors);
2136 return HadErrors;
2137 }
2138
2139 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002140 // Relative paths in a relocatable PCH are relative to our sysroot.
2141 if (F.RelocatablePCH)
2142 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002143
2144 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002145 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002146 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2147 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002148 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002149 return VersionMismatch;
2150 }
2151 break;
2152 }
2153
Ben Langmuir487ea142014-10-23 18:05:36 +00002154 case SIGNATURE:
2155 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2156 F.Signature = Record[0];
2157 break;
2158
Guy Benyei11169dd2012-12-18 14:30:41 +00002159 case IMPORTS: {
2160 // Load each of the imported PCH files.
2161 unsigned Idx = 0, N = Record.size();
2162 while (Idx < N) {
2163 // Read information about the AST file.
2164 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2165 // The import location will be the local one for now; we will adjust
2166 // all import locations of module imports after the global source
2167 // location info are setup.
2168 SourceLocation ImportLoc =
2169 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002170 off_t StoredSize = (off_t)Record[Idx++];
2171 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002172 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002173 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002174
2175 // Load the AST file.
2176 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002177 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002178 ClientLoadCapabilities)) {
2179 case Failure: return Failure;
2180 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002181 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002182 case OutOfDate: return OutOfDate;
2183 case VersionMismatch: return VersionMismatch;
2184 case ConfigurationMismatch: return ConfigurationMismatch;
2185 case HadErrors: return HadErrors;
2186 case Success: break;
2187 }
2188 }
2189 break;
2190 }
2191
Richard Smith7f330cd2015-03-18 01:42:29 +00002192 case KNOWN_MODULE_FILES:
2193 break;
2194
Guy Benyei11169dd2012-12-18 14:30:41 +00002195 case LANGUAGE_OPTIONS: {
2196 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002197 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002198 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002199 ParseLanguageOptions(Record, Complain, *Listener,
2200 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002201 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002202 return ConfigurationMismatch;
2203 break;
2204 }
2205
2206 case TARGET_OPTIONS: {
2207 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2208 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002209 ParseTargetOptions(Record, Complain, *Listener,
2210 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002211 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002212 return ConfigurationMismatch;
2213 break;
2214 }
2215
2216 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002217 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002218 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002219 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002220 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002221 !DisableValidation)
2222 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002223 break;
2224 }
2225
2226 case FILE_SYSTEM_OPTIONS: {
2227 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2228 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002229 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002230 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002231 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002232 return ConfigurationMismatch;
2233 break;
2234 }
2235
2236 case HEADER_SEARCH_OPTIONS: {
2237 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2238 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002239 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002240 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002241 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002242 return ConfigurationMismatch;
2243 break;
2244 }
2245
2246 case PREPROCESSOR_OPTIONS: {
2247 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2248 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002249 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002250 ParsePreprocessorOptions(Record, Complain, *Listener,
2251 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002252 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002253 return ConfigurationMismatch;
2254 break;
2255 }
2256
2257 case ORIGINAL_FILE:
2258 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002259 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002260 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002261 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002262 break;
2263
2264 case ORIGINAL_FILE_ID:
2265 F.OriginalSourceFileID = FileID::get(Record[0]);
2266 break;
2267
2268 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002269 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002270 break;
2271
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002272 case MODULE_NAME:
2273 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002274 if (Listener)
2275 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002276 break;
2277
Richard Smith223d3f22014-12-06 03:21:08 +00002278 case MODULE_DIRECTORY: {
2279 assert(!F.ModuleName.empty() &&
2280 "MODULE_DIRECTORY found before MODULE_NAME");
2281 // If we've already loaded a module map file covering this module, we may
2282 // have a better path for it (relative to the current build).
2283 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2284 if (M && M->Directory) {
2285 // If we're implicitly loading a module, the base directory can't
2286 // change between the build and use.
2287 if (F.Kind != MK_ExplicitModule) {
2288 const DirectoryEntry *BuildDir =
2289 PP.getFileManager().getDirectory(Blob);
2290 if (!BuildDir || BuildDir != M->Directory) {
2291 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2292 Diag(diag::err_imported_module_relocated)
2293 << F.ModuleName << Blob << M->Directory->getName();
2294 return OutOfDate;
2295 }
2296 }
2297 F.BaseDirectory = M->Directory->getName();
2298 } else {
2299 F.BaseDirectory = Blob;
2300 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002301 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002302 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002303
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002304 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002305 if (ASTReadResult Result =
2306 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2307 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002308 break;
2309
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002310 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002311 NumInputs = Record[0];
2312 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002313 F.InputFileOffsets =
2314 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002315 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002316 break;
2317 }
2318 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002319}
2320
Ben Langmuir2c9af442014-04-10 17:57:43 +00002321ASTReader::ASTReadResult
2322ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002323 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002324
2325 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2326 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002327 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002328 }
2329
2330 // Read all of the records and blocks for the AST file.
2331 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002332 while (1) {
2333 llvm::BitstreamEntry Entry = Stream.advance();
2334
2335 switch (Entry.Kind) {
2336 case llvm::BitstreamEntry::Error:
2337 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002338 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002339 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002340 // Outside of C++, we do not store a lookup map for the translation unit.
2341 // Instead, mark it as needing a lookup map to be built if this module
2342 // contains any declarations lexically within it (which it always does!).
2343 // This usually has no cost, since we very rarely need the lookup map for
2344 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002345 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002346 if (DC->hasExternalLexicalStorage() &&
2347 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002348 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002349
Ben Langmuir2c9af442014-04-10 17:57:43 +00002350 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002351 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002352 case llvm::BitstreamEntry::SubBlock:
2353 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002354 case DECLTYPES_BLOCK_ID:
2355 // We lazily load the decls block, but we want to set up the
2356 // DeclsCursor cursor to point into it. Clone our current bitcode
2357 // cursor to it, enter the block and read the abbrevs in that block.
2358 // With the main cursor, we just skip over it.
2359 F.DeclsCursor = Stream;
2360 if (Stream.SkipBlock() || // Skip with the main cursor.
2361 // Read the abbrevs.
2362 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2363 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002364 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002365 }
2366 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002367
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 case PREPROCESSOR_BLOCK_ID:
2369 F.MacroCursor = Stream;
2370 if (!PP.getExternalSource())
2371 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002372
Guy Benyei11169dd2012-12-18 14:30:41 +00002373 if (Stream.SkipBlock() ||
2374 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2375 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002376 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002377 }
2378 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2379 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002380
Guy Benyei11169dd2012-12-18 14:30:41 +00002381 case PREPROCESSOR_DETAIL_BLOCK_ID:
2382 F.PreprocessorDetailCursor = Stream;
2383 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002384 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002385 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002386 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002387 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002388 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002390 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2391
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 if (!PP.getPreprocessingRecord())
2393 PP.createPreprocessingRecord();
2394 if (!PP.getPreprocessingRecord()->getExternalSource())
2395 PP.getPreprocessingRecord()->SetExternalSource(*this);
2396 break;
2397
2398 case SOURCE_MANAGER_BLOCK_ID:
2399 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002400 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002401 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002402
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002404 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2405 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002406 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002407
Guy Benyei11169dd2012-12-18 14:30:41 +00002408 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002409 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 if (Stream.SkipBlock() ||
2411 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2412 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002413 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 }
2415 CommentsCursors.push_back(std::make_pair(C, &F));
2416 break;
2417 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002418
Guy Benyei11169dd2012-12-18 14:30:41 +00002419 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002420 if (Stream.SkipBlock()) {
2421 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002422 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002423 }
2424 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002425 }
2426 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002427
2428 case llvm::BitstreamEntry::Record:
2429 // The interesting case.
2430 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002431 }
2432
2433 // Read and process a record.
2434 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002435 StringRef Blob;
2436 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002437 default: // Default behavior: ignore.
2438 break;
2439
2440 case TYPE_OFFSET: {
2441 if (F.LocalNumTypes != 0) {
2442 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002443 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002444 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002445 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002446 F.LocalNumTypes = Record[0];
2447 unsigned LocalBaseTypeIndex = Record[1];
2448 F.BaseTypeIndex = getTotalNumTypes();
2449
2450 if (F.LocalNumTypes > 0) {
2451 // Introduce the global -> local mapping for types within this module.
2452 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2453
2454 // Introduce the local -> global mapping for types within this module.
2455 F.TypeRemap.insertOrReplace(
2456 std::make_pair(LocalBaseTypeIndex,
2457 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002458
2459 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002460 }
2461 break;
2462 }
2463
2464 case DECL_OFFSET: {
2465 if (F.LocalNumDecls != 0) {
2466 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002467 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002468 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002469 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002470 F.LocalNumDecls = Record[0];
2471 unsigned LocalBaseDeclID = Record[1];
2472 F.BaseDeclID = getTotalNumDecls();
2473
2474 if (F.LocalNumDecls > 0) {
2475 // Introduce the global -> local mapping for declarations within this
2476 // module.
2477 GlobalDeclMap.insert(
2478 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2479
2480 // Introduce the local -> global mapping for declarations within this
2481 // module.
2482 F.DeclRemap.insertOrReplace(
2483 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2484
2485 // Introduce the global -> local mapping for declarations within this
2486 // module.
2487 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002488
Ben Langmuir52ca6782014-10-20 16:27:32 +00002489 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2490 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 break;
2492 }
2493
2494 case TU_UPDATE_LEXICAL: {
2495 DeclContext *TU = Context.getTranslationUnitDecl();
2496 DeclContextInfo &Info = F.DeclContextInfos[TU];
Richard Smith787c0e42015-07-23 00:53:59 +00002497 Info.LexicalDecls = llvm::makeArrayRef(
2498 reinterpret_cast<const KindDeclIDPair *>(Blob.data()),
2499 static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002500 TU->setHasExternalLexicalStorage(true);
2501 break;
2502 }
2503
2504 case UPDATE_VISIBLE: {
2505 unsigned Idx = 0;
2506 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2507 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002508 ASTDeclContextNameLookupTable::Create(
2509 (const unsigned char *)Blob.data() + Record[Idx++],
2510 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2511 (const unsigned char *)Blob.data(),
2512 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002513 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002514 auto *DC = cast<DeclContext>(D);
2515 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002516 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2517 delete LookupTable;
2518 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 } else
2520 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2521 break;
2522 }
2523
2524 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002525 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002527 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2528 (const unsigned char *)F.IdentifierTableData + Record[0],
2529 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2530 (const unsigned char *)F.IdentifierTableData,
2531 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002532
2533 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2534 }
2535 break;
2536
2537 case IDENTIFIER_OFFSET: {
2538 if (F.LocalNumIdentifiers != 0) {
2539 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002540 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002541 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002542 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002543 F.LocalNumIdentifiers = Record[0];
2544 unsigned LocalBaseIdentifierID = Record[1];
2545 F.BaseIdentifierID = getTotalNumIdentifiers();
2546
2547 if (F.LocalNumIdentifiers > 0) {
2548 // Introduce the global -> local mapping for identifiers within this
2549 // module.
2550 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2551 &F));
2552
2553 // Introduce the local -> global mapping for identifiers within this
2554 // module.
2555 F.IdentifierRemap.insertOrReplace(
2556 std::make_pair(LocalBaseIdentifierID,
2557 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002558
Ben Langmuir52ca6782014-10-20 16:27:32 +00002559 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2560 + F.LocalNumIdentifiers);
2561 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 break;
2563 }
2564
Richard Smith33e0f7e2015-07-22 02:08:40 +00002565 case INTERESTING_IDENTIFIERS:
2566 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2567 break;
2568
Ben Langmuir332aafe2014-01-31 01:06:56 +00002569 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002570 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2571 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002573 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 break;
2575
2576 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002577 if (SpecialTypes.empty()) {
2578 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2579 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2580 break;
2581 }
2582
2583 if (SpecialTypes.size() != Record.size()) {
2584 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002585 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002586 }
2587
2588 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2589 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2590 if (!SpecialTypes[I])
2591 SpecialTypes[I] = ID;
2592 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2593 // merge step?
2594 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 break;
2596
2597 case STATISTICS:
2598 TotalNumStatements += Record[0];
2599 TotalNumMacros += Record[1];
2600 TotalLexicalDeclContexts += Record[2];
2601 TotalVisibleDeclContexts += Record[3];
2602 break;
2603
2604 case UNUSED_FILESCOPED_DECLS:
2605 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2606 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2607 break;
2608
2609 case DELEGATING_CTORS:
2610 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2611 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2612 break;
2613
2614 case WEAK_UNDECLARED_IDENTIFIERS:
2615 if (Record.size() % 4 != 0) {
2616 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002617 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 }
2619
2620 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2621 // files. This isn't the way to do it :)
2622 WeakUndeclaredIdentifiers.clear();
2623
2624 // Translate the weak, undeclared identifiers into global IDs.
2625 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2626 WeakUndeclaredIdentifiers.push_back(
2627 getGlobalIdentifierID(F, Record[I++]));
2628 WeakUndeclaredIdentifiers.push_back(
2629 getGlobalIdentifierID(F, Record[I++]));
2630 WeakUndeclaredIdentifiers.push_back(
2631 ReadSourceLocation(F, Record, I).getRawEncoding());
2632 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2633 }
2634 break;
2635
Guy Benyei11169dd2012-12-18 14:30:41 +00002636 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002637 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 F.LocalNumSelectors = Record[0];
2639 unsigned LocalBaseSelectorID = Record[1];
2640 F.BaseSelectorID = getTotalNumSelectors();
2641
2642 if (F.LocalNumSelectors > 0) {
2643 // Introduce the global -> local mapping for selectors within this
2644 // module.
2645 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2646
2647 // Introduce the local -> global mapping for selectors within this
2648 // module.
2649 F.SelectorRemap.insertOrReplace(
2650 std::make_pair(LocalBaseSelectorID,
2651 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002652
2653 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 }
2655 break;
2656 }
2657
2658 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002659 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 if (Record[0])
2661 F.SelectorLookupTable
2662 = ASTSelectorLookupTable::Create(
2663 F.SelectorLookupTableData + Record[0],
2664 F.SelectorLookupTableData,
2665 ASTSelectorLookupTrait(*this, F));
2666 TotalNumMethodPoolEntries += Record[1];
2667 break;
2668
2669 case REFERENCED_SELECTOR_POOL:
2670 if (!Record.empty()) {
2671 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2672 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2673 Record[Idx++]));
2674 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2675 getRawEncoding());
2676 }
2677 }
2678 break;
2679
2680 case PP_COUNTER_VALUE:
2681 if (!Record.empty() && Listener)
2682 Listener->ReadCounter(F, Record[0]);
2683 break;
2684
2685 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002686 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 F.NumFileSortedDecls = Record[0];
2688 break;
2689
2690 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002691 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002692 F.LocalNumSLocEntries = Record[0];
2693 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002694 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002695 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 SLocSpaceSize);
2697 // Make our entry in the range map. BaseID is negative and growing, so
2698 // we invert it. Because we invert it, though, we need the other end of
2699 // the range.
2700 unsigned RangeStart =
2701 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2702 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2703 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2704
2705 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2706 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2707 GlobalSLocOffsetMap.insert(
2708 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2709 - SLocSpaceSize,&F));
2710
2711 // Initialize the remapping table.
2712 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002713 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002714 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002715 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2717
2718 TotalNumSLocEntries += F.LocalNumSLocEntries;
2719 break;
2720 }
2721
2722 case MODULE_OFFSET_MAP: {
2723 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002724 const unsigned char *Data = (const unsigned char*)Blob.data();
2725 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002726
2727 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2728 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2729 F.SLocRemap.insert(std::make_pair(0U, 0));
2730 F.SLocRemap.insert(std::make_pair(2U, 1));
2731 }
2732
Guy Benyei11169dd2012-12-18 14:30:41 +00002733 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002734 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2735 RemapBuilder;
2736 RemapBuilder SLocRemap(F.SLocRemap);
2737 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2738 RemapBuilder MacroRemap(F.MacroRemap);
2739 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2740 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2741 RemapBuilder SelectorRemap(F.SelectorRemap);
2742 RemapBuilder DeclRemap(F.DeclRemap);
2743 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002744
2745 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002746 using namespace llvm::support;
2747 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 StringRef Name = StringRef((const char*)Data, Len);
2749 Data += Len;
2750 ModuleFile *OM = ModuleMgr.lookup(Name);
2751 if (!OM) {
2752 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002753 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002754 }
2755
Justin Bogner57ba0b22014-03-28 22:03:24 +00002756 uint32_t SLocOffset =
2757 endian::readNext<uint32_t, little, unaligned>(Data);
2758 uint32_t IdentifierIDOffset =
2759 endian::readNext<uint32_t, little, unaligned>(Data);
2760 uint32_t MacroIDOffset =
2761 endian::readNext<uint32_t, little, unaligned>(Data);
2762 uint32_t PreprocessedEntityIDOffset =
2763 endian::readNext<uint32_t, little, unaligned>(Data);
2764 uint32_t SubmoduleIDOffset =
2765 endian::readNext<uint32_t, little, unaligned>(Data);
2766 uint32_t SelectorIDOffset =
2767 endian::readNext<uint32_t, little, unaligned>(Data);
2768 uint32_t DeclIDOffset =
2769 endian::readNext<uint32_t, little, unaligned>(Data);
2770 uint32_t TypeIndexOffset =
2771 endian::readNext<uint32_t, little, unaligned>(Data);
2772
Ben Langmuir785180e2014-10-20 16:27:30 +00002773 uint32_t None = std::numeric_limits<uint32_t>::max();
2774
2775 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2776 RemapBuilder &Remap) {
2777 if (Offset != None)
2778 Remap.insert(std::make_pair(Offset,
2779 static_cast<int>(BaseOffset - Offset)));
2780 };
2781 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2782 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2783 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2784 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2785 PreprocessedEntityRemap);
2786 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2787 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2788 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2789 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002790
2791 // Global -> local mappings.
2792 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2793 }
2794 break;
2795 }
2796
2797 case SOURCE_MANAGER_LINE_TABLE:
2798 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002799 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002800 break;
2801
2802 case SOURCE_LOCATION_PRELOADS: {
2803 // Need to transform from the local view (1-based IDs) to the global view,
2804 // which is based off F.SLocEntryBaseID.
2805 if (!F.PreloadSLocEntries.empty()) {
2806 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002807 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002808 }
2809
2810 F.PreloadSLocEntries.swap(Record);
2811 break;
2812 }
2813
2814 case EXT_VECTOR_DECLS:
2815 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2816 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2817 break;
2818
2819 case VTABLE_USES:
2820 if (Record.size() % 3 != 0) {
2821 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002822 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002823 }
2824
2825 // Later tables overwrite earlier ones.
2826 // FIXME: Modules will have some trouble with this. This is clearly not
2827 // the right way to do this.
2828 VTableUses.clear();
2829
2830 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2831 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2832 VTableUses.push_back(
2833 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2834 VTableUses.push_back(Record[Idx++]);
2835 }
2836 break;
2837
Guy Benyei11169dd2012-12-18 14:30:41 +00002838 case PENDING_IMPLICIT_INSTANTIATIONS:
2839 if (PendingInstantiations.size() % 2 != 0) {
2840 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002841 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002842 }
2843
2844 if (Record.size() % 2 != 0) {
2845 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002846 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 }
2848
2849 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2850 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2851 PendingInstantiations.push_back(
2852 ReadSourceLocation(F, Record, I).getRawEncoding());
2853 }
2854 break;
2855
2856 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002857 if (Record.size() != 2) {
2858 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002859 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002860 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002861 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2862 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2863 break;
2864
2865 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002866 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2867 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2868 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002869
2870 unsigned LocalBasePreprocessedEntityID = Record[0];
2871
2872 unsigned StartingID;
2873 if (!PP.getPreprocessingRecord())
2874 PP.createPreprocessingRecord();
2875 if (!PP.getPreprocessingRecord()->getExternalSource())
2876 PP.getPreprocessingRecord()->SetExternalSource(*this);
2877 StartingID
2878 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002879 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002880 F.BasePreprocessedEntityID = StartingID;
2881
2882 if (F.NumPreprocessedEntities > 0) {
2883 // Introduce the global -> local mapping for preprocessed entities in
2884 // this module.
2885 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2886
2887 // Introduce the local -> global mapping for preprocessed entities in
2888 // this module.
2889 F.PreprocessedEntityRemap.insertOrReplace(
2890 std::make_pair(LocalBasePreprocessedEntityID,
2891 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2892 }
2893
2894 break;
2895 }
2896
2897 case DECL_UPDATE_OFFSETS: {
2898 if (Record.size() % 2 != 0) {
2899 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002900 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002901 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002902 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2903 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2904 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2905
2906 // If we've already loaded the decl, perform the updates when we finish
2907 // loading this block.
2908 if (Decl *D = GetExistingDecl(ID))
2909 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2910 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002911 break;
2912 }
2913
2914 case DECL_REPLACEMENTS: {
2915 if (Record.size() % 3 != 0) {
2916 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002917 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002918 }
2919 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2920 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2921 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2922 break;
2923 }
2924
2925 case OBJC_CATEGORIES_MAP: {
2926 if (F.LocalNumObjCCategoriesInMap != 0) {
2927 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002928 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002929 }
2930
2931 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002932 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 break;
2934 }
2935
2936 case OBJC_CATEGORIES:
2937 F.ObjCCategories.swap(Record);
2938 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00002939
Guy Benyei11169dd2012-12-18 14:30:41 +00002940 case CXX_BASE_SPECIFIER_OFFSETS: {
2941 if (F.LocalNumCXXBaseSpecifiers != 0) {
2942 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002943 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 }
Richard Smithc2bb8182015-03-24 06:36:48 +00002945
Guy Benyei11169dd2012-12-18 14:30:41 +00002946 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002947 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00002948 break;
2949 }
2950
2951 case CXX_CTOR_INITIALIZERS_OFFSETS: {
2952 if (F.LocalNumCXXCtorInitializers != 0) {
2953 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2954 return Failure;
2955 }
2956
2957 F.LocalNumCXXCtorInitializers = Record[0];
2958 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002959 break;
2960 }
2961
2962 case DIAG_PRAGMA_MAPPINGS:
2963 if (F.PragmaDiagMappings.empty())
2964 F.PragmaDiagMappings.swap(Record);
2965 else
2966 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2967 Record.begin(), Record.end());
2968 break;
2969
2970 case CUDA_SPECIAL_DECL_REFS:
2971 // Later tables overwrite earlier ones.
2972 // FIXME: Modules will have trouble with this.
2973 CUDASpecialDeclRefs.clear();
2974 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2975 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2976 break;
2977
2978 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002979 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002980 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 if (Record[0]) {
2982 F.HeaderFileInfoTable
2983 = HeaderFileInfoLookupTable::Create(
2984 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2985 (const unsigned char *)F.HeaderFileInfoTableData,
2986 HeaderFileInfoTrait(*this, F,
2987 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002988 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002989
2990 PP.getHeaderSearchInfo().SetExternalSource(this);
2991 if (!PP.getHeaderSearchInfo().getExternalLookup())
2992 PP.getHeaderSearchInfo().SetExternalLookup(this);
2993 }
2994 break;
2995 }
2996
2997 case FP_PRAGMA_OPTIONS:
2998 // Later tables overwrite earlier ones.
2999 FPPragmaOptions.swap(Record);
3000 break;
3001
3002 case OPENCL_EXTENSIONS:
3003 // Later tables overwrite earlier ones.
3004 OpenCLExtensions.swap(Record);
3005 break;
3006
3007 case TENTATIVE_DEFINITIONS:
3008 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3009 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3010 break;
3011
3012 case KNOWN_NAMESPACES:
3013 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3014 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3015 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003016
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003017 case UNDEFINED_BUT_USED:
3018 if (UndefinedButUsed.size() % 2 != 0) {
3019 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003020 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003021 }
3022
3023 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003024 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003025 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003026 }
3027 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003028 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3029 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003030 ReadSourceLocation(F, Record, I).getRawEncoding());
3031 }
3032 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003033 case DELETE_EXPRS_TO_ANALYZE:
3034 for (unsigned I = 0, N = Record.size(); I != N;) {
3035 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3036 const uint64_t Count = Record[I++];
3037 DelayedDeleteExprs.push_back(Count);
3038 for (uint64_t C = 0; C < Count; ++C) {
3039 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3040 bool IsArrayForm = Record[I++] == 1;
3041 DelayedDeleteExprs.push_back(IsArrayForm);
3042 }
3043 }
3044 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003045
Guy Benyei11169dd2012-12-18 14:30:41 +00003046 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003047 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003048 // If we aren't loading a module (which has its own exports), make
3049 // all of the imported modules visible.
3050 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003051 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3052 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3053 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3054 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003055 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003056 }
3057 }
3058 break;
3059 }
3060
3061 case LOCAL_REDECLARATIONS: {
3062 F.RedeclarationChains.swap(Record);
3063 break;
3064 }
3065
3066 case LOCAL_REDECLARATIONS_MAP: {
3067 if (F.LocalNumRedeclarationsInMap != 0) {
3068 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003069 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003070 }
3071
3072 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003073 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003074 break;
3075 }
3076
Guy Benyei11169dd2012-12-18 14:30:41 +00003077 case MACRO_OFFSET: {
3078 if (F.LocalNumMacros != 0) {
3079 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003080 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003081 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003082 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003083 F.LocalNumMacros = Record[0];
3084 unsigned LocalBaseMacroID = Record[1];
3085 F.BaseMacroID = getTotalNumMacros();
3086
3087 if (F.LocalNumMacros > 0) {
3088 // Introduce the global -> local mapping for macros within this module.
3089 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3090
3091 // Introduce the local -> global mapping for macros within this module.
3092 F.MacroRemap.insertOrReplace(
3093 std::make_pair(LocalBaseMacroID,
3094 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003095
3096 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003097 }
3098 break;
3099 }
3100
Richard Smithe40f2ba2013-08-07 21:41:30 +00003101 case LATE_PARSED_TEMPLATE: {
3102 LateParsedTemplates.append(Record.begin(), Record.end());
3103 break;
3104 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003105
3106 case OPTIMIZE_PRAGMA_OPTIONS:
3107 if (Record.size() != 1) {
3108 Error("invalid pragma optimize record");
3109 return Failure;
3110 }
3111 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3112 break;
Nico Weber72889432014-09-06 01:25:55 +00003113
3114 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3115 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3116 UnusedLocalTypedefNameCandidates.push_back(
3117 getGlobalDeclID(F, Record[I]));
3118 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003119 }
3120 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003121}
3122
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003123ASTReader::ASTReadResult
3124ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3125 const ModuleFile *ImportedBy,
3126 unsigned ClientLoadCapabilities) {
3127 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003128 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003129
Richard Smithe842a472014-10-22 02:05:46 +00003130 if (F.Kind == MK_ExplicitModule) {
3131 // For an explicitly-loaded module, we don't care whether the original
3132 // module map file exists or matches.
3133 return Success;
3134 }
3135
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003136 // Try to resolve ModuleName in the current header search context and
3137 // verify that it is found in the same module map file as we saved. If the
3138 // top-level AST file is a main file, skip this check because there is no
3139 // usable header search context.
3140 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003141 "MODULE_NAME should come before MODULE_MAP_FILE");
3142 if (F.Kind == MK_ImplicitModule &&
3143 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3144 // An implicitly-loaded module file should have its module listed in some
3145 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003146 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003147 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3148 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3149 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003150 assert(ImportedBy && "top-level import should be verified");
3151 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003152 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3153 << ImportedBy->FileName
3154 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003155 return Missing;
3156 }
3157
Richard Smithe842a472014-10-22 02:05:46 +00003158 assert(M->Name == F.ModuleName && "found module with different name");
3159
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003160 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003161 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003162 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3163 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003164 assert(ImportedBy && "top-level import should be verified");
3165 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3166 Diag(diag::err_imported_module_modmap_changed)
3167 << F.ModuleName << ImportedBy->FileName
3168 << ModMap->getName() << F.ModuleMapPath;
3169 return OutOfDate;
3170 }
3171
3172 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3173 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3174 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003175 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003176 const FileEntry *F =
3177 FileMgr.getFile(Filename, false, false);
3178 if (F == nullptr) {
3179 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3180 Error("could not find file '" + Filename +"' referenced by AST file");
3181 return OutOfDate;
3182 }
3183 AdditionalStoredMaps.insert(F);
3184 }
3185
3186 // Check any additional module map files (e.g. module.private.modulemap)
3187 // that are not in the pcm.
3188 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3189 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3190 // Remove files that match
3191 // Note: SmallPtrSet::erase is really remove
3192 if (!AdditionalStoredMaps.erase(ModMap)) {
3193 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3194 Diag(diag::err_module_different_modmap)
3195 << F.ModuleName << /*new*/0 << ModMap->getName();
3196 return OutOfDate;
3197 }
3198 }
3199 }
3200
3201 // Check any additional module map files that are in the pcm, but not
3202 // found in header search. Cases that match are already removed.
3203 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3204 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3205 Diag(diag::err_module_different_modmap)
3206 << F.ModuleName << /*not new*/1 << ModMap->getName();
3207 return OutOfDate;
3208 }
3209 }
3210
3211 if (Listener)
3212 Listener->ReadModuleMapFile(F.ModuleMapPath);
3213 return Success;
3214}
3215
3216
Douglas Gregorc1489562013-02-12 23:36:21 +00003217/// \brief Move the given method to the back of the global list of methods.
3218static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3219 // Find the entry for this selector in the method pool.
3220 Sema::GlobalMethodPool::iterator Known
3221 = S.MethodPool.find(Method->getSelector());
3222 if (Known == S.MethodPool.end())
3223 return;
3224
3225 // Retrieve the appropriate method list.
3226 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3227 : Known->second.second;
3228 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003229 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003230 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003231 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003232 Found = true;
3233 } else {
3234 // Keep searching.
3235 continue;
3236 }
3237 }
3238
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003239 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003240 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003241 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003242 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003243 }
3244}
3245
Richard Smithde711422015-04-23 21:20:19 +00003246void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003247 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003248 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003249 bool wasHidden = D->Hidden;
3250 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003251
Richard Smith49f906a2014-03-01 00:08:04 +00003252 if (wasHidden && SemaObj) {
3253 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3254 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003255 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003256 }
3257 }
3258}
3259
Richard Smith49f906a2014-03-01 00:08:04 +00003260void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003261 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003262 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003263 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003264 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003265 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003266 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003267 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003268
3269 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003270 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003271 // there is nothing more to do.
3272 continue;
3273 }
Richard Smith49f906a2014-03-01 00:08:04 +00003274
Guy Benyei11169dd2012-12-18 14:30:41 +00003275 if (!Mod->isAvailable()) {
3276 // Modules that aren't available cannot be made visible.
3277 continue;
3278 }
3279
3280 // Update the module's name visibility.
3281 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003282
Guy Benyei11169dd2012-12-18 14:30:41 +00003283 // If we've already deserialized any names from this module,
3284 // mark them as visible.
3285 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3286 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003287 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003288 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003289 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003290 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3291 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003292 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003293
Guy Benyei11169dd2012-12-18 14:30:41 +00003294 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003295 SmallVector<Module *, 16> Exports;
3296 Mod->getExportedModules(Exports);
3297 for (SmallVectorImpl<Module *>::iterator
3298 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3299 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003300 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003301 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003302 }
3303 }
3304}
3305
Douglas Gregore060e572013-01-25 01:03:03 +00003306bool ASTReader::loadGlobalIndex() {
3307 if (GlobalIndex)
3308 return false;
3309
3310 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3311 !Context.getLangOpts().Modules)
3312 return true;
3313
3314 // Try to load the global index.
3315 TriedLoadingGlobalIndex = true;
3316 StringRef ModuleCachePath
3317 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3318 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003319 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003320 if (!Result.first)
3321 return true;
3322
3323 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003324 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003325 return false;
3326}
3327
3328bool ASTReader::isGlobalIndexUnavailable() const {
3329 return Context.getLangOpts().Modules && UseGlobalIndex &&
3330 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3331}
3332
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003333static void updateModuleTimestamp(ModuleFile &MF) {
3334 // Overwrite the timestamp file contents so that file's mtime changes.
3335 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003336 std::error_code EC;
3337 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3338 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003339 return;
3340 OS << "Timestamp file\n";
3341}
3342
Guy Benyei11169dd2012-12-18 14:30:41 +00003343ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3344 ModuleKind Type,
3345 SourceLocation ImportLoc,
3346 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003347 llvm::SaveAndRestore<SourceLocation>
3348 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3349
Richard Smithd1c46742014-04-30 02:24:17 +00003350 // Defer any pending actions until we get to the end of reading the AST file.
3351 Deserializing AnASTFile(this);
3352
Guy Benyei11169dd2012-12-18 14:30:41 +00003353 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003354 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003355
3356 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003357 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003358 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003359 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003360 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003361 ClientLoadCapabilities)) {
3362 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003363 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003364 case OutOfDate:
3365 case VersionMismatch:
3366 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003367 case HadErrors: {
3368 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3369 for (const ImportedModule &IM : Loaded)
3370 LoadedSet.insert(IM.Mod);
3371
Douglas Gregor7029ce12013-03-19 00:28:20 +00003372 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003373 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003374 Context.getLangOpts().Modules
3375 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003376 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003377
3378 // If we find that any modules are unusable, the global index is going
3379 // to be out-of-date. Just remove it.
3380 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003381 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003382 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003383 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003384 case Success:
3385 break;
3386 }
3387
3388 // Here comes stuff that we only do once the entire chain is loaded.
3389
3390 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003391 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3392 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003393 M != MEnd; ++M) {
3394 ModuleFile &F = *M->Mod;
3395
3396 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003397 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3398 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003399
3400 // Once read, set the ModuleFile bit base offset and update the size in
3401 // bits of all files we've seen.
3402 F.GlobalBitOffset = TotalModulesSizeInBits;
3403 TotalModulesSizeInBits += F.SizeInBits;
3404 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3405
3406 // Preload SLocEntries.
3407 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3408 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3409 // Load it through the SourceManager and don't call ReadSLocEntry()
3410 // directly because the entry may have already been loaded in which case
3411 // calling ReadSLocEntry() directly would trigger an assertion in
3412 // SourceManager.
3413 SourceMgr.getLoadedSLocEntryByID(Index);
3414 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003415
3416 // Preload all the pending interesting identifiers by marking them out of
3417 // date.
3418 for (auto Offset : F.PreloadIdentifierOffsets) {
3419 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3420 F.IdentifierTableData + Offset);
3421
3422 ASTIdentifierLookupTrait Trait(*this, F);
3423 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3424 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3425 PP.getIdentifierTable().getOwn(Key).setOutOfDate(true);
3426 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003427 }
3428
Douglas Gregor603cd862013-03-22 18:50:14 +00003429 // Setup the import locations and notify the module manager that we've
3430 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003431 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3432 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003433 M != MEnd; ++M) {
3434 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003435
3436 ModuleMgr.moduleFileAccepted(&F);
3437
3438 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003439 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003440 if (!M->ImportedBy)
3441 F.ImportLoc = M->ImportLoc;
3442 else
3443 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3444 M->ImportLoc.getRawEncoding());
3445 }
3446
Richard Smith33e0f7e2015-07-22 02:08:40 +00003447 if (!Context.getLangOpts().CPlusPlus ||
3448 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3449 // Mark all of the identifiers in the identifier table as being out of date,
3450 // so that various accessors know to check the loaded modules when the
3451 // identifier is used.
3452 //
3453 // For C++ modules, we don't need information on many identifiers (just
3454 // those that provide macros or are poisoned), so we mark all of
3455 // the interesting ones via PreloadIdentifierOffsets.
3456 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3457 IdEnd = PP.getIdentifierTable().end();
3458 Id != IdEnd; ++Id)
3459 Id->second->setOutOfDate(true);
3460 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003461
3462 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003463 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3464 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003465 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3466 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003467
3468 switch (Unresolved.Kind) {
3469 case UnresolvedModuleRef::Conflict:
3470 if (ResolvedMod) {
3471 Module::Conflict Conflict;
3472 Conflict.Other = ResolvedMod;
3473 Conflict.Message = Unresolved.String.str();
3474 Unresolved.Mod->Conflicts.push_back(Conflict);
3475 }
3476 continue;
3477
3478 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003479 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003480 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003481 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003482
Douglas Gregorfb912652013-03-20 21:10:35 +00003483 case UnresolvedModuleRef::Export:
3484 if (ResolvedMod || Unresolved.IsWildcard)
3485 Unresolved.Mod->Exports.push_back(
3486 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3487 continue;
3488 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003489 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003490 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003491
3492 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3493 // Might be unnecessary as use declarations are only used to build the
3494 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003495
3496 InitializeContext();
3497
Richard Smith3d8e97e2013-10-18 06:54:39 +00003498 if (SemaObj)
3499 UpdateSema();
3500
Guy Benyei11169dd2012-12-18 14:30:41 +00003501 if (DeserializationListener)
3502 DeserializationListener->ReaderInitialized(this);
3503
3504 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3505 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3506 PrimaryModule.OriginalSourceFileID
3507 = FileID::get(PrimaryModule.SLocEntryBaseID
3508 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3509
3510 // If this AST file is a precompiled preamble, then set the
3511 // preamble file ID of the source manager to the file source file
3512 // from which the preamble was built.
3513 if (Type == MK_Preamble) {
3514 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3515 } else if (Type == MK_MainFile) {
3516 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3517 }
3518 }
3519
3520 // For any Objective-C class definitions we have already loaded, make sure
3521 // that we load any additional categories.
3522 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3523 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3524 ObjCClassesLoaded[I],
3525 PreviousGeneration);
3526 }
Douglas Gregore060e572013-01-25 01:03:03 +00003527
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003528 if (PP.getHeaderSearchInfo()
3529 .getHeaderSearchOpts()
3530 .ModulesValidateOncePerBuildSession) {
3531 // Now we are certain that the module and all modules it depends on are
3532 // up to date. Create or update timestamp files for modules that are
3533 // located in the module cache (not for PCH files that could be anywhere
3534 // in the filesystem).
3535 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3536 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003537 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003538 updateModuleTimestamp(*M.Mod);
3539 }
3540 }
3541 }
3542
Guy Benyei11169dd2012-12-18 14:30:41 +00003543 return Success;
3544}
3545
Ben Langmuir487ea142014-10-23 18:05:36 +00003546static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3547
Ben Langmuir70a1b812015-03-24 04:43:52 +00003548/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3549static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3550 return Stream.Read(8) == 'C' &&
3551 Stream.Read(8) == 'P' &&
3552 Stream.Read(8) == 'C' &&
3553 Stream.Read(8) == 'H';
3554}
3555
Guy Benyei11169dd2012-12-18 14:30:41 +00003556ASTReader::ASTReadResult
3557ASTReader::ReadASTCore(StringRef FileName,
3558 ModuleKind Type,
3559 SourceLocation ImportLoc,
3560 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003561 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003562 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003563 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003564 unsigned ClientLoadCapabilities) {
3565 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003566 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003567 ModuleManager::AddModuleResult AddResult
3568 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003569 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003570 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003571 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003572
Douglas Gregor7029ce12013-03-19 00:28:20 +00003573 switch (AddResult) {
3574 case ModuleManager::AlreadyLoaded:
3575 return Success;
3576
3577 case ModuleManager::NewlyLoaded:
3578 // Load module file below.
3579 break;
3580
3581 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003582 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003583 // it.
3584 if (ClientLoadCapabilities & ARR_Missing)
3585 return Missing;
3586
3587 // Otherwise, return an error.
3588 {
3589 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3590 + ErrorStr;
3591 Error(Msg);
3592 }
3593 return Failure;
3594
3595 case ModuleManager::OutOfDate:
3596 // We couldn't load the module file because it is out-of-date. If the
3597 // client can handle out-of-date, return it.
3598 if (ClientLoadCapabilities & ARR_OutOfDate)
3599 return OutOfDate;
3600
3601 // Otherwise, return an error.
3602 {
3603 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3604 + ErrorStr;
3605 Error(Msg);
3606 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003607 return Failure;
3608 }
3609
Douglas Gregor7029ce12013-03-19 00:28:20 +00003610 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003611
3612 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3613 // module?
3614 if (FileName != "-") {
3615 CurrentDir = llvm::sys::path::parent_path(FileName);
3616 if (CurrentDir.empty()) CurrentDir = ".";
3617 }
3618
3619 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003620 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003621 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003622 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003623 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3624
Guy Benyei11169dd2012-12-18 14:30:41 +00003625 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003626 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 Diag(diag::err_not_a_pch_file) << FileName;
3628 return Failure;
3629 }
3630
3631 // This is used for compatibility with older PCH formats.
3632 bool HaveReadControlBlock = false;
3633
Chris Lattnerefa77172013-01-20 00:00:22 +00003634 while (1) {
3635 llvm::BitstreamEntry Entry = Stream.advance();
3636
3637 switch (Entry.Kind) {
3638 case llvm::BitstreamEntry::Error:
3639 case llvm::BitstreamEntry::EndBlock:
3640 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003641 Error("invalid record at top-level of AST file");
3642 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003643
3644 case llvm::BitstreamEntry::SubBlock:
3645 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003646 }
3647
Guy Benyei11169dd2012-12-18 14:30:41 +00003648 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003649 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003650 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3651 if (Stream.ReadBlockInfoBlock()) {
3652 Error("malformed BlockInfoBlock in AST file");
3653 return Failure;
3654 }
3655 break;
3656 case CONTROL_BLOCK_ID:
3657 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003658 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003659 case Success:
3660 break;
3661
3662 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003663 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003664 case OutOfDate: return OutOfDate;
3665 case VersionMismatch: return VersionMismatch;
3666 case ConfigurationMismatch: return ConfigurationMismatch;
3667 case HadErrors: return HadErrors;
3668 }
3669 break;
3670 case AST_BLOCK_ID:
3671 if (!HaveReadControlBlock) {
3672 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003673 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003674 return VersionMismatch;
3675 }
3676
3677 // Record that we've loaded this module.
3678 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3679 return Success;
3680
3681 default:
3682 if (Stream.SkipBlock()) {
3683 Error("malformed block record in AST file");
3684 return Failure;
3685 }
3686 break;
3687 }
3688 }
3689
3690 return Success;
3691}
3692
Richard Smitha7e2cc62015-05-01 01:53:09 +00003693void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003694 // If there's a listener, notify them that we "read" the translation unit.
3695 if (DeserializationListener)
3696 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3697 Context.getTranslationUnitDecl());
3698
Guy Benyei11169dd2012-12-18 14:30:41 +00003699 // FIXME: Find a better way to deal with collisions between these
3700 // built-in types. Right now, we just ignore the problem.
3701
3702 // Load the special types.
3703 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3704 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3705 if (!Context.CFConstantStringTypeDecl)
3706 Context.setCFConstantStringType(GetType(String));
3707 }
3708
3709 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3710 QualType FileType = GetType(File);
3711 if (FileType.isNull()) {
3712 Error("FILE type is NULL");
3713 return;
3714 }
3715
3716 if (!Context.FILEDecl) {
3717 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3718 Context.setFILEDecl(Typedef->getDecl());
3719 else {
3720 const TagType *Tag = FileType->getAs<TagType>();
3721 if (!Tag) {
3722 Error("Invalid FILE type in AST file");
3723 return;
3724 }
3725 Context.setFILEDecl(Tag->getDecl());
3726 }
3727 }
3728 }
3729
3730 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3731 QualType Jmp_bufType = GetType(Jmp_buf);
3732 if (Jmp_bufType.isNull()) {
3733 Error("jmp_buf type is NULL");
3734 return;
3735 }
3736
3737 if (!Context.jmp_bufDecl) {
3738 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3739 Context.setjmp_bufDecl(Typedef->getDecl());
3740 else {
3741 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3742 if (!Tag) {
3743 Error("Invalid jmp_buf type in AST file");
3744 return;
3745 }
3746 Context.setjmp_bufDecl(Tag->getDecl());
3747 }
3748 }
3749 }
3750
3751 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3752 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3753 if (Sigjmp_bufType.isNull()) {
3754 Error("sigjmp_buf type is NULL");
3755 return;
3756 }
3757
3758 if (!Context.sigjmp_bufDecl) {
3759 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3760 Context.setsigjmp_bufDecl(Typedef->getDecl());
3761 else {
3762 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3763 assert(Tag && "Invalid sigjmp_buf type in AST file");
3764 Context.setsigjmp_bufDecl(Tag->getDecl());
3765 }
3766 }
3767 }
3768
3769 if (unsigned ObjCIdRedef
3770 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3771 if (Context.ObjCIdRedefinitionType.isNull())
3772 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3773 }
3774
3775 if (unsigned ObjCClassRedef
3776 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3777 if (Context.ObjCClassRedefinitionType.isNull())
3778 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3779 }
3780
3781 if (unsigned ObjCSelRedef
3782 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3783 if (Context.ObjCSelRedefinitionType.isNull())
3784 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3785 }
3786
3787 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3788 QualType Ucontext_tType = GetType(Ucontext_t);
3789 if (Ucontext_tType.isNull()) {
3790 Error("ucontext_t type is NULL");
3791 return;
3792 }
3793
3794 if (!Context.ucontext_tDecl) {
3795 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3796 Context.setucontext_tDecl(Typedef->getDecl());
3797 else {
3798 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3799 assert(Tag && "Invalid ucontext_t type in AST file");
3800 Context.setucontext_tDecl(Tag->getDecl());
3801 }
3802 }
3803 }
3804 }
3805
3806 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3807
3808 // If there were any CUDA special declarations, deserialize them.
3809 if (!CUDASpecialDeclRefs.empty()) {
3810 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3811 Context.setcudaConfigureCallDecl(
3812 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3813 }
Richard Smith56be7542014-03-21 00:33:59 +00003814
Guy Benyei11169dd2012-12-18 14:30:41 +00003815 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003816 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003817 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003818 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003819 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003820 /*ImportLoc=*/Import.ImportLoc);
3821 PP.makeModuleVisible(Imported, Import.ImportLoc);
3822 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003823 }
3824 ImportedModules.clear();
3825}
3826
3827void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003828 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003829}
3830
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003831/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3832/// cursor into the start of the given block ID, returning false on success and
3833/// true on failure.
3834static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003835 while (1) {
3836 llvm::BitstreamEntry Entry = Cursor.advance();
3837 switch (Entry.Kind) {
3838 case llvm::BitstreamEntry::Error:
3839 case llvm::BitstreamEntry::EndBlock:
3840 return true;
3841
3842 case llvm::BitstreamEntry::Record:
3843 // Ignore top-level records.
3844 Cursor.skipRecord(Entry.ID);
3845 break;
3846
3847 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003848 if (Entry.ID == BlockID) {
3849 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003850 return true;
3851 // Found it!
3852 return false;
3853 }
3854
3855 if (Cursor.SkipBlock())
3856 return true;
3857 }
3858 }
3859}
3860
Ben Langmuir70a1b812015-03-24 04:43:52 +00003861/// \brief Reads and return the signature record from \p StreamFile's control
3862/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003863static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3864 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003865 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003866 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003867
3868 // Scan for the CONTROL_BLOCK_ID block.
3869 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3870 return 0;
3871
3872 // Scan for SIGNATURE inside the control block.
3873 ASTReader::RecordData Record;
3874 while (1) {
3875 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3876 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3877 Entry.Kind != llvm::BitstreamEntry::Record)
3878 return 0;
3879
3880 Record.clear();
3881 StringRef Blob;
3882 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3883 return Record[0];
3884 }
3885}
3886
Guy Benyei11169dd2012-12-18 14:30:41 +00003887/// \brief Retrieve the name of the original source file name
3888/// directly from the AST file, without actually loading the AST
3889/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003890std::string ASTReader::getOriginalSourceFile(
3891 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003892 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003893 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00003894 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00003895 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00003896 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3897 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00003898 return std::string();
3899 }
3900
3901 // Initialize the stream
3902 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003903 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003904 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003905
3906 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003907 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003908 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3909 return std::string();
3910 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003911
Chris Lattnere7b154b2013-01-19 21:39:22 +00003912 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003913 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003914 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3915 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003916 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003917
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003918 // Scan for ORIGINAL_FILE inside the control block.
3919 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003920 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003921 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003922 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3923 return std::string();
3924
3925 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3926 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3927 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003928 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003929
Guy Benyei11169dd2012-12-18 14:30:41 +00003930 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003931 StringRef Blob;
3932 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3933 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003934 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003935}
3936
3937namespace {
3938 class SimplePCHValidator : public ASTReaderListener {
3939 const LangOptions &ExistingLangOpts;
3940 const TargetOptions &ExistingTargetOpts;
3941 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003942 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00003943 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003944
Guy Benyei11169dd2012-12-18 14:30:41 +00003945 public:
3946 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3947 const TargetOptions &ExistingTargetOpts,
3948 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003949 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00003950 FileManager &FileMgr)
3951 : ExistingLangOpts(ExistingLangOpts),
3952 ExistingTargetOpts(ExistingTargetOpts),
3953 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003954 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00003955 FileMgr(FileMgr)
3956 {
3957 }
3958
Richard Smith1e2cf0d2014-10-31 02:28:58 +00003959 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
3960 bool AllowCompatibleDifferences) override {
3961 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
3962 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003963 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00003964 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
3965 bool AllowCompatibleDifferences) override {
3966 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
3967 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003968 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003969 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
3970 StringRef SpecificModuleCachePath,
3971 bool Complain) override {
3972 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
3973 ExistingModuleCachePath,
3974 nullptr, ExistingLangOpts);
3975 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003976 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3977 bool Complain,
3978 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00003979 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003980 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003981 }
3982 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003983}
Guy Benyei11169dd2012-12-18 14:30:41 +00003984
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003985bool ASTReader::readASTFileControlBlock(
3986 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003987 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003988 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003989 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00003990 // FIXME: This allows use of the VFS; we do not allow use of the
3991 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00003992 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00003993 if (!Buffer) {
3994 return true;
3995 }
3996
3997 // Initialize the stream
3998 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003999 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004000 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004001
4002 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004003 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004004 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004005
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004006 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004007 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004008 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004009
4010 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004011 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004012 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004013 BitstreamCursor InputFilesCursor;
4014 if (NeedsInputFiles) {
4015 InputFilesCursor = Stream;
4016 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4017 return true;
4018
4019 // Read the abbreviations
4020 while (true) {
4021 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4022 unsigned Code = InputFilesCursor.ReadCode();
4023
4024 // We expect all abbrevs to be at the start of the block.
4025 if (Code != llvm::bitc::DEFINE_ABBREV) {
4026 InputFilesCursor.JumpToBit(Offset);
4027 break;
4028 }
4029 InputFilesCursor.ReadAbbrevRecord();
4030 }
4031 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004032
4033 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004034 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004035 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004036 while (1) {
4037 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4038 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4039 return false;
4040
4041 if (Entry.Kind != llvm::BitstreamEntry::Record)
4042 return true;
4043
Guy Benyei11169dd2012-12-18 14:30:41 +00004044 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004045 StringRef Blob;
4046 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004047 switch ((ControlRecordTypes)RecCode) {
4048 case METADATA: {
4049 if (Record[0] != VERSION_MAJOR)
4050 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004051
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004052 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004053 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004054
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004055 break;
4056 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004057 case MODULE_NAME:
4058 Listener.ReadModuleName(Blob);
4059 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004060 case MODULE_DIRECTORY:
4061 ModuleDir = Blob;
4062 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004063 case MODULE_MAP_FILE: {
4064 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004065 auto Path = ReadString(Record, Idx);
4066 ResolveImportedPath(Path, ModuleDir);
4067 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004068 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004069 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004070 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004071 if (ParseLanguageOptions(Record, false, Listener,
4072 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004073 return true;
4074 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004075
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004076 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004077 if (ParseTargetOptions(Record, false, Listener,
4078 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004079 return true;
4080 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004081
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004082 case DIAGNOSTIC_OPTIONS:
4083 if (ParseDiagnosticOptions(Record, false, Listener))
4084 return true;
4085 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004086
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004087 case FILE_SYSTEM_OPTIONS:
4088 if (ParseFileSystemOptions(Record, false, Listener))
4089 return true;
4090 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004091
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004092 case HEADER_SEARCH_OPTIONS:
4093 if (ParseHeaderSearchOptions(Record, false, Listener))
4094 return true;
4095 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004096
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004097 case PREPROCESSOR_OPTIONS: {
4098 std::string IgnoredSuggestedPredefines;
4099 if (ParsePreprocessorOptions(Record, false, Listener,
4100 IgnoredSuggestedPredefines))
4101 return true;
4102 break;
4103 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004104
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004105 case INPUT_FILE_OFFSETS: {
4106 if (!NeedsInputFiles)
4107 break;
4108
4109 unsigned NumInputFiles = Record[0];
4110 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004111 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004112 for (unsigned I = 0; I != NumInputFiles; ++I) {
4113 // Go find this input file.
4114 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004115
4116 if (isSystemFile && !NeedsSystemInputFiles)
4117 break; // the rest are system input files
4118
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004119 BitstreamCursor &Cursor = InputFilesCursor;
4120 SavedStreamPosition SavedPosition(Cursor);
4121 Cursor.JumpToBit(InputFileOffs[I]);
4122
4123 unsigned Code = Cursor.ReadCode();
4124 RecordData Record;
4125 StringRef Blob;
4126 bool shouldContinue = false;
4127 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4128 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004129 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004130 std::string Filename = Blob;
4131 ResolveImportedPath(Filename, ModuleDir);
4132 shouldContinue =
4133 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004134 break;
4135 }
4136 if (!shouldContinue)
4137 break;
4138 }
4139 break;
4140 }
4141
Richard Smithd4b230b2014-10-27 23:01:16 +00004142 case IMPORTS: {
4143 if (!NeedsImports)
4144 break;
4145
4146 unsigned Idx = 0, N = Record.size();
4147 while (Idx < N) {
4148 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004149 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004150 std::string Filename = ReadString(Record, Idx);
4151 ResolveImportedPath(Filename, ModuleDir);
4152 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004153 }
4154 break;
4155 }
4156
Richard Smith7f330cd2015-03-18 01:42:29 +00004157 case KNOWN_MODULE_FILES: {
4158 // Known-but-not-technically-used module files are treated as imports.
4159 if (!NeedsImports)
4160 break;
4161
4162 unsigned Idx = 0, N = Record.size();
4163 while (Idx < N) {
4164 std::string Filename = ReadString(Record, Idx);
4165 ResolveImportedPath(Filename, ModuleDir);
4166 Listener.visitImport(Filename);
4167 }
4168 break;
4169 }
4170
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004171 default:
4172 // No other validation to perform.
4173 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004174 }
4175 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004176}
4177
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004178bool ASTReader::isAcceptableASTFile(
4179 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004180 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004181 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4182 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004183 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4184 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004185 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004186 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004187}
4188
Ben Langmuir2c9af442014-04-10 17:57:43 +00004189ASTReader::ASTReadResult
4190ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004191 // Enter the submodule block.
4192 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4193 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004194 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004195 }
4196
4197 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4198 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004199 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004200 RecordData Record;
4201 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004202 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4203
4204 switch (Entry.Kind) {
4205 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4206 case llvm::BitstreamEntry::Error:
4207 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004208 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004209 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004210 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004211 case llvm::BitstreamEntry::Record:
4212 // The interesting case.
4213 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004214 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004215
Guy Benyei11169dd2012-12-18 14:30:41 +00004216 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004217 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004218 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004219 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4220
4221 if ((Kind == SUBMODULE_METADATA) != First) {
4222 Error("submodule metadata record should be at beginning of block");
4223 return Failure;
4224 }
4225 First = false;
4226
4227 // Submodule information is only valid if we have a current module.
4228 // FIXME: Should we error on these cases?
4229 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4230 Kind != SUBMODULE_DEFINITION)
4231 continue;
4232
4233 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004234 default: // Default behavior: ignore.
4235 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004236
Richard Smith03478d92014-10-23 22:12:14 +00004237 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004238 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004239 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004240 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004241 }
Richard Smith03478d92014-10-23 22:12:14 +00004242
Chris Lattner0e6c9402013-01-20 02:38:54 +00004243 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004244 unsigned Idx = 0;
4245 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4246 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4247 bool IsFramework = Record[Idx++];
4248 bool IsExplicit = Record[Idx++];
4249 bool IsSystem = Record[Idx++];
4250 bool IsExternC = Record[Idx++];
4251 bool InferSubmodules = Record[Idx++];
4252 bool InferExplicitSubmodules = Record[Idx++];
4253 bool InferExportWildcard = Record[Idx++];
4254 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004255
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004256 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004257 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004258 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004259
Guy Benyei11169dd2012-12-18 14:30:41 +00004260 // Retrieve this (sub)module from the module map, creating it if
4261 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004262 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004263 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004264
4265 // FIXME: set the definition loc for CurrentModule, or call
4266 // ModMap.setInferredModuleAllowedBy()
4267
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4269 if (GlobalIndex >= SubmodulesLoaded.size() ||
4270 SubmodulesLoaded[GlobalIndex]) {
4271 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004272 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004273 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004274
Douglas Gregor7029ce12013-03-19 00:28:20 +00004275 if (!ParentModule) {
4276 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4277 if (CurFile != F.File) {
4278 if (!Diags.isDiagnosticInFlight()) {
4279 Diag(diag::err_module_file_conflict)
4280 << CurrentModule->getTopLevelModuleName()
4281 << CurFile->getName()
4282 << F.File->getName();
4283 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004284 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004285 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004286 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004287
4288 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004289 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004290
Adrian Prantl15bcf702015-06-30 17:39:43 +00004291 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004292 CurrentModule->IsFromModuleFile = true;
4293 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004294 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004295 CurrentModule->InferSubmodules = InferSubmodules;
4296 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4297 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004298 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004299 if (DeserializationListener)
4300 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4301
4302 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004303
Douglas Gregorfb912652013-03-20 21:10:35 +00004304 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004305 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004306 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004307 CurrentModule->UnresolvedConflicts.clear();
4308 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004309 break;
4310 }
4311
4312 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004313 std::string Filename = Blob;
4314 ResolveImportedPath(F, Filename);
4315 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004316 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004317 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4318 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004319 // This can be a spurious difference caused by changing the VFS to
4320 // point to a different copy of the file, and it is too late to
4321 // to rebuild safely.
4322 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4323 // after input file validation only real problems would remain and we
4324 // could just error. For now, assume it's okay.
4325 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004326 }
4327 }
4328 break;
4329 }
4330
Richard Smith202210b2014-10-24 20:23:01 +00004331 case SUBMODULE_HEADER:
4332 case SUBMODULE_EXCLUDED_HEADER:
4333 case SUBMODULE_PRIVATE_HEADER:
4334 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004335 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4336 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004337 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004338
Richard Smith202210b2014-10-24 20:23:01 +00004339 case SUBMODULE_TEXTUAL_HEADER:
4340 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4341 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4342 // them here.
4343 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004344
Guy Benyei11169dd2012-12-18 14:30:41 +00004345 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004346 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 break;
4348 }
4349
4350 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004351 std::string Dirname = Blob;
4352 ResolveImportedPath(F, Dirname);
4353 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004354 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004355 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4356 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004357 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4358 Error("mismatched umbrella directories in submodule");
4359 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004360 }
4361 }
4362 break;
4363 }
4364
4365 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004366 F.BaseSubmoduleID = getTotalNumSubmodules();
4367 F.LocalNumSubmodules = Record[0];
4368 unsigned LocalBaseSubmoduleID = Record[1];
4369 if (F.LocalNumSubmodules > 0) {
4370 // Introduce the global -> local mapping for submodules within this
4371 // module.
4372 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4373
4374 // Introduce the local -> global mapping for submodules within this
4375 // module.
4376 F.SubmoduleRemap.insertOrReplace(
4377 std::make_pair(LocalBaseSubmoduleID,
4378 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004379
Ben Langmuir52ca6782014-10-20 16:27:32 +00004380 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4381 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004382 break;
4383 }
4384
4385 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004386 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004387 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004388 Unresolved.File = &F;
4389 Unresolved.Mod = CurrentModule;
4390 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004391 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004392 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004393 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 }
4395 break;
4396 }
4397
4398 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004399 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004400 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004401 Unresolved.File = &F;
4402 Unresolved.Mod = CurrentModule;
4403 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004404 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004405 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004406 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004407 }
4408
4409 // Once we've loaded the set of exports, there's no reason to keep
4410 // the parsed, unresolved exports around.
4411 CurrentModule->UnresolvedExports.clear();
4412 break;
4413 }
4414 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004415 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004416 Context.getTargetInfo());
4417 break;
4418 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004419
4420 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004421 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004422 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004423 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004424
4425 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004426 CurrentModule->ConfigMacros.push_back(Blob.str());
4427 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004428
4429 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004430 UnresolvedModuleRef Unresolved;
4431 Unresolved.File = &F;
4432 Unresolved.Mod = CurrentModule;
4433 Unresolved.ID = Record[0];
4434 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4435 Unresolved.IsWildcard = false;
4436 Unresolved.String = Blob;
4437 UnresolvedModuleRefs.push_back(Unresolved);
4438 break;
4439 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004440 }
4441 }
4442}
4443
4444/// \brief Parse the record that corresponds to a LangOptions data
4445/// structure.
4446///
4447/// This routine parses the language options from the AST file and then gives
4448/// them to the AST listener if one is set.
4449///
4450/// \returns true if the listener deems the file unacceptable, false otherwise.
4451bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4452 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004453 ASTReaderListener &Listener,
4454 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004455 LangOptions LangOpts;
4456 unsigned Idx = 0;
4457#define LANGOPT(Name, Bits, Default, Description) \
4458 LangOpts.Name = Record[Idx++];
4459#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4460 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4461#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004462#define SANITIZER(NAME, ID) \
4463 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004464#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004465
Ben Langmuircd98cb72015-06-23 18:20:18 +00004466 for (unsigned N = Record[Idx++]; N; --N)
4467 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4468
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4470 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4471 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004472
Ben Langmuird4a667a2015-06-23 18:20:23 +00004473 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004474
4475 // Comment options.
4476 for (unsigned N = Record[Idx++]; N; --N) {
4477 LangOpts.CommentOpts.BlockCommandNames.push_back(
4478 ReadString(Record, Idx));
4479 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004480 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004481
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004482 return Listener.ReadLanguageOptions(LangOpts, Complain,
4483 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004484}
4485
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004486bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4487 ASTReaderListener &Listener,
4488 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004489 unsigned Idx = 0;
4490 TargetOptions TargetOpts;
4491 TargetOpts.Triple = ReadString(Record, Idx);
4492 TargetOpts.CPU = ReadString(Record, Idx);
4493 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004494 for (unsigned N = Record[Idx++]; N; --N) {
4495 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4496 }
4497 for (unsigned N = Record[Idx++]; N; --N) {
4498 TargetOpts.Features.push_back(ReadString(Record, Idx));
4499 }
4500
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004501 return Listener.ReadTargetOptions(TargetOpts, Complain,
4502 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004503}
4504
4505bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4506 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004507 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004508 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004509#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004510#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004511 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004512#include "clang/Basic/DiagnosticOptions.def"
4513
Richard Smith3be1cb22014-08-07 00:24:21 +00004514 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004515 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004516 for (unsigned N = Record[Idx++]; N; --N)
4517 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004518
4519 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4520}
4521
4522bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4523 ASTReaderListener &Listener) {
4524 FileSystemOptions FSOpts;
4525 unsigned Idx = 0;
4526 FSOpts.WorkingDir = ReadString(Record, Idx);
4527 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4528}
4529
4530bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4531 bool Complain,
4532 ASTReaderListener &Listener) {
4533 HeaderSearchOptions HSOpts;
4534 unsigned Idx = 0;
4535 HSOpts.Sysroot = ReadString(Record, Idx);
4536
4537 // Include entries.
4538 for (unsigned N = Record[Idx++]; N; --N) {
4539 std::string Path = ReadString(Record, Idx);
4540 frontend::IncludeDirGroup Group
4541 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004542 bool IsFramework = Record[Idx++];
4543 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004544 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4545 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004546 }
4547
4548 // System header prefixes.
4549 for (unsigned N = Record[Idx++]; N; --N) {
4550 std::string Prefix = ReadString(Record, Idx);
4551 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004552 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 }
4554
4555 HSOpts.ResourceDir = ReadString(Record, Idx);
4556 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004557 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004558 HSOpts.DisableModuleHash = Record[Idx++];
4559 HSOpts.UseBuiltinIncludes = Record[Idx++];
4560 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4561 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4562 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004563 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004564
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004565 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4566 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004567}
4568
4569bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4570 bool Complain,
4571 ASTReaderListener &Listener,
4572 std::string &SuggestedPredefines) {
4573 PreprocessorOptions PPOpts;
4574 unsigned Idx = 0;
4575
4576 // Macro definitions/undefs
4577 for (unsigned N = Record[Idx++]; N; --N) {
4578 std::string Macro = ReadString(Record, Idx);
4579 bool IsUndef = Record[Idx++];
4580 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4581 }
4582
4583 // Includes
4584 for (unsigned N = Record[Idx++]; N; --N) {
4585 PPOpts.Includes.push_back(ReadString(Record, Idx));
4586 }
4587
4588 // Macro Includes
4589 for (unsigned N = Record[Idx++]; N; --N) {
4590 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4591 }
4592
4593 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004594 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4596 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4597 PPOpts.ObjCXXARCStandardLibrary =
4598 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4599 SuggestedPredefines.clear();
4600 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4601 SuggestedPredefines);
4602}
4603
4604std::pair<ModuleFile *, unsigned>
4605ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4606 GlobalPreprocessedEntityMapType::iterator
4607 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4608 assert(I != GlobalPreprocessedEntityMap.end() &&
4609 "Corrupted global preprocessed entity map");
4610 ModuleFile *M = I->second;
4611 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4612 return std::make_pair(M, LocalIndex);
4613}
4614
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004615llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004616ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4617 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4618 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4619 Mod.NumPreprocessedEntities);
4620
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004621 return llvm::make_range(PreprocessingRecord::iterator(),
4622 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004623}
4624
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004625llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004626ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004627 return llvm::make_range(
4628 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4629 ModuleDeclIterator(this, &Mod,
4630 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004631}
4632
4633PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4634 PreprocessedEntityID PPID = Index+1;
4635 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4636 ModuleFile &M = *PPInfo.first;
4637 unsigned LocalIndex = PPInfo.second;
4638 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4639
Guy Benyei11169dd2012-12-18 14:30:41 +00004640 if (!PP.getPreprocessingRecord()) {
4641 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004642 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004643 }
4644
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004645 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4646 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4647
4648 llvm::BitstreamEntry Entry =
4649 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4650 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004651 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004652
Guy Benyei11169dd2012-12-18 14:30:41 +00004653 // Read the record.
4654 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4655 ReadSourceLocation(M, PPOffs.End));
4656 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004657 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004658 RecordData Record;
4659 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004660 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4661 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004662 switch (RecType) {
4663 case PPD_MACRO_EXPANSION: {
4664 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004665 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004666 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 if (isBuiltin)
4668 Name = getLocalIdentifier(M, Record[1]);
4669 else {
Richard Smith66a81862015-05-04 02:25:31 +00004670 PreprocessedEntityID GlobalID =
4671 getGlobalPreprocessedEntityID(M, Record[1]);
4672 Def = cast<MacroDefinitionRecord>(
4673 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004674 }
4675
4676 MacroExpansion *ME;
4677 if (isBuiltin)
4678 ME = new (PPRec) MacroExpansion(Name, Range);
4679 else
4680 ME = new (PPRec) MacroExpansion(Def, Range);
4681
4682 return ME;
4683 }
4684
4685 case PPD_MACRO_DEFINITION: {
4686 // Decode the identifier info and then check again; if the macro is
4687 // still defined and associated with the identifier,
4688 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004689 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004690
4691 if (DeserializationListener)
4692 DeserializationListener->MacroDefinitionRead(PPID, MD);
4693
4694 return MD;
4695 }
4696
4697 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004698 const char *FullFileNameStart = Blob.data() + Record[0];
4699 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004700 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004701 if (!FullFileName.empty())
4702 File = PP.getFileManager().getFile(FullFileName);
4703
4704 // FIXME: Stable encoding
4705 InclusionDirective::InclusionKind Kind
4706 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4707 InclusionDirective *ID
4708 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004709 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004710 Record[1], Record[3],
4711 File,
4712 Range);
4713 return ID;
4714 }
4715 }
4716
4717 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4718}
4719
4720/// \brief \arg SLocMapI points at a chunk of a module that contains no
4721/// preprocessed entities or the entities it contains are not the ones we are
4722/// looking for. Find the next module that contains entities and return the ID
4723/// of the first entry.
4724PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4725 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4726 ++SLocMapI;
4727 for (GlobalSLocOffsetMapType::const_iterator
4728 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4729 ModuleFile &M = *SLocMapI->second;
4730 if (M.NumPreprocessedEntities)
4731 return M.BasePreprocessedEntityID;
4732 }
4733
4734 return getTotalNumPreprocessedEntities();
4735}
4736
4737namespace {
4738
4739template <unsigned PPEntityOffset::*PPLoc>
4740struct PPEntityComp {
4741 const ASTReader &Reader;
4742 ModuleFile &M;
4743
4744 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4745
4746 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4747 SourceLocation LHS = getLoc(L);
4748 SourceLocation RHS = getLoc(R);
4749 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4750 }
4751
4752 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4753 SourceLocation LHS = getLoc(L);
4754 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4755 }
4756
4757 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4758 SourceLocation RHS = getLoc(R);
4759 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4760 }
4761
4762 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4763 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4764 }
4765};
4766
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004767}
Guy Benyei11169dd2012-12-18 14:30:41 +00004768
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004769PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4770 bool EndsAfter) const {
4771 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004772 return getTotalNumPreprocessedEntities();
4773
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004774 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4775 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004776 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4777 "Corrupted global sloc offset map");
4778
4779 if (SLocMapI->second->NumPreprocessedEntities == 0)
4780 return findNextPreprocessedEntity(SLocMapI);
4781
4782 ModuleFile &M = *SLocMapI->second;
4783 typedef const PPEntityOffset *pp_iterator;
4784 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4785 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4786
4787 size_t Count = M.NumPreprocessedEntities;
4788 size_t Half;
4789 pp_iterator First = pp_begin;
4790 pp_iterator PPI;
4791
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004792 if (EndsAfter) {
4793 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4794 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4795 } else {
4796 // Do a binary search manually instead of using std::lower_bound because
4797 // The end locations of entities may be unordered (when a macro expansion
4798 // is inside another macro argument), but for this case it is not important
4799 // whether we get the first macro expansion or its containing macro.
4800 while (Count > 0) {
4801 Half = Count / 2;
4802 PPI = First;
4803 std::advance(PPI, Half);
4804 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4805 Loc)) {
4806 First = PPI;
4807 ++First;
4808 Count = Count - Half - 1;
4809 } else
4810 Count = Half;
4811 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004812 }
4813
4814 if (PPI == pp_end)
4815 return findNextPreprocessedEntity(SLocMapI);
4816
4817 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4818}
4819
Guy Benyei11169dd2012-12-18 14:30:41 +00004820/// \brief Returns a pair of [Begin, End) indices of preallocated
4821/// preprocessed entities that \arg Range encompasses.
4822std::pair<unsigned, unsigned>
4823 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4824 if (Range.isInvalid())
4825 return std::make_pair(0,0);
4826 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4827
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004828 PreprocessedEntityID BeginID =
4829 findPreprocessedEntity(Range.getBegin(), false);
4830 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004831 return std::make_pair(BeginID, EndID);
4832}
4833
4834/// \brief Optionally returns true or false if the preallocated preprocessed
4835/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004836Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004837 FileID FID) {
4838 if (FID.isInvalid())
4839 return false;
4840
4841 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4842 ModuleFile &M = *PPInfo.first;
4843 unsigned LocalIndex = PPInfo.second;
4844 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4845
4846 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4847 if (Loc.isInvalid())
4848 return false;
4849
4850 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4851 return true;
4852 else
4853 return false;
4854}
4855
4856namespace {
4857 /// \brief Visitor used to search for information about a header file.
4858 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004859 const FileEntry *FE;
4860
David Blaikie05785d12013-02-20 22:23:23 +00004861 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004862
4863 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004864 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4865 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004866
4867 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004868 HeaderFileInfoLookupTable *Table
4869 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4870 if (!Table)
4871 return false;
4872
4873 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00004874 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004875 if (Pos == Table->end())
4876 return false;
4877
Richard Smithbdf2d932015-07-30 03:37:16 +00004878 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00004879 return true;
4880 }
4881
David Blaikie05785d12013-02-20 22:23:23 +00004882 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004883 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004884}
Guy Benyei11169dd2012-12-18 14:30:41 +00004885
4886HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004887 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004888 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004889 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004890 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004891
4892 return HeaderFileInfo();
4893}
4894
4895void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4896 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004897 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004898 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4899 ModuleFile &F = *(*I);
4900 unsigned Idx = 0;
4901 DiagStates.clear();
4902 assert(!Diag.DiagStates.empty());
4903 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4904 while (Idx < F.PragmaDiagMappings.size()) {
4905 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4906 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4907 if (DiagStateID != 0) {
4908 Diag.DiagStatePoints.push_back(
4909 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4910 FullSourceLoc(Loc, SourceMgr)));
4911 continue;
4912 }
4913
4914 assert(DiagStateID == 0);
4915 // A new DiagState was created here.
4916 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4917 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4918 DiagStates.push_back(NewState);
4919 Diag.DiagStatePoints.push_back(
4920 DiagnosticsEngine::DiagStatePoint(NewState,
4921 FullSourceLoc(Loc, SourceMgr)));
4922 while (1) {
4923 assert(Idx < F.PragmaDiagMappings.size() &&
4924 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4925 if (Idx >= F.PragmaDiagMappings.size()) {
4926 break; // Something is messed up but at least avoid infinite loop in
4927 // release build.
4928 }
4929 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4930 if (DiagID == (unsigned)-1) {
4931 break; // no more diag/map pairs for this location.
4932 }
Alp Tokerc726c362014-06-10 09:31:37 +00004933 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4934 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4935 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00004936 }
4937 }
4938 }
4939}
4940
4941/// \brief Get the correct cursor and offset for loading a type.
4942ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4943 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4944 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4945 ModuleFile *M = I->second;
4946 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4947}
4948
4949/// \brief Read and return the type with the given index..
4950///
4951/// The index is the type ID, shifted and minus the number of predefs. This
4952/// routine actually reads the record corresponding to the type at the given
4953/// location. It is a helper routine for GetType, which deals with reading type
4954/// IDs.
4955QualType ASTReader::readTypeRecord(unsigned Index) {
4956 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004957 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004958
4959 // Keep track of where we are in the stream, then jump back there
4960 // after reading this type.
4961 SavedStreamPosition SavedPosition(DeclsCursor);
4962
4963 ReadingKindTracker ReadingKind(Read_Type, *this);
4964
4965 // Note that we are loading a type record.
4966 Deserializing AType(this);
4967
4968 unsigned Idx = 0;
4969 DeclsCursor.JumpToBit(Loc.Offset);
4970 RecordData Record;
4971 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004972 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004973 case TYPE_EXT_QUAL: {
4974 if (Record.size() != 2) {
4975 Error("Incorrect encoding of extended qualifier type");
4976 return QualType();
4977 }
4978 QualType Base = readType(*Loc.F, Record, Idx);
4979 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4980 return Context.getQualifiedType(Base, Quals);
4981 }
4982
4983 case TYPE_COMPLEX: {
4984 if (Record.size() != 1) {
4985 Error("Incorrect encoding of complex type");
4986 return QualType();
4987 }
4988 QualType ElemType = readType(*Loc.F, Record, Idx);
4989 return Context.getComplexType(ElemType);
4990 }
4991
4992 case TYPE_POINTER: {
4993 if (Record.size() != 1) {
4994 Error("Incorrect encoding of pointer type");
4995 return QualType();
4996 }
4997 QualType PointeeType = readType(*Loc.F, Record, Idx);
4998 return Context.getPointerType(PointeeType);
4999 }
5000
Reid Kleckner8a365022013-06-24 17:51:48 +00005001 case TYPE_DECAYED: {
5002 if (Record.size() != 1) {
5003 Error("Incorrect encoding of decayed type");
5004 return QualType();
5005 }
5006 QualType OriginalType = readType(*Loc.F, Record, Idx);
5007 QualType DT = Context.getAdjustedParameterType(OriginalType);
5008 if (!isa<DecayedType>(DT))
5009 Error("Decayed type does not decay");
5010 return DT;
5011 }
5012
Reid Kleckner0503a872013-12-05 01:23:43 +00005013 case TYPE_ADJUSTED: {
5014 if (Record.size() != 2) {
5015 Error("Incorrect encoding of adjusted type");
5016 return QualType();
5017 }
5018 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5019 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5020 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5021 }
5022
Guy Benyei11169dd2012-12-18 14:30:41 +00005023 case TYPE_BLOCK_POINTER: {
5024 if (Record.size() != 1) {
5025 Error("Incorrect encoding of block pointer type");
5026 return QualType();
5027 }
5028 QualType PointeeType = readType(*Loc.F, Record, Idx);
5029 return Context.getBlockPointerType(PointeeType);
5030 }
5031
5032 case TYPE_LVALUE_REFERENCE: {
5033 if (Record.size() != 2) {
5034 Error("Incorrect encoding of lvalue reference type");
5035 return QualType();
5036 }
5037 QualType PointeeType = readType(*Loc.F, Record, Idx);
5038 return Context.getLValueReferenceType(PointeeType, Record[1]);
5039 }
5040
5041 case TYPE_RVALUE_REFERENCE: {
5042 if (Record.size() != 1) {
5043 Error("Incorrect encoding of rvalue reference type");
5044 return QualType();
5045 }
5046 QualType PointeeType = readType(*Loc.F, Record, Idx);
5047 return Context.getRValueReferenceType(PointeeType);
5048 }
5049
5050 case TYPE_MEMBER_POINTER: {
5051 if (Record.size() != 2) {
5052 Error("Incorrect encoding of member pointer type");
5053 return QualType();
5054 }
5055 QualType PointeeType = readType(*Loc.F, Record, Idx);
5056 QualType ClassType = readType(*Loc.F, Record, Idx);
5057 if (PointeeType.isNull() || ClassType.isNull())
5058 return QualType();
5059
5060 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5061 }
5062
5063 case TYPE_CONSTANT_ARRAY: {
5064 QualType ElementType = readType(*Loc.F, Record, Idx);
5065 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5066 unsigned IndexTypeQuals = Record[2];
5067 unsigned Idx = 3;
5068 llvm::APInt Size = ReadAPInt(Record, Idx);
5069 return Context.getConstantArrayType(ElementType, Size,
5070 ASM, IndexTypeQuals);
5071 }
5072
5073 case TYPE_INCOMPLETE_ARRAY: {
5074 QualType ElementType = readType(*Loc.F, Record, Idx);
5075 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5076 unsigned IndexTypeQuals = Record[2];
5077 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5078 }
5079
5080 case TYPE_VARIABLE_ARRAY: {
5081 QualType ElementType = readType(*Loc.F, Record, Idx);
5082 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5083 unsigned IndexTypeQuals = Record[2];
5084 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5085 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5086 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5087 ASM, IndexTypeQuals,
5088 SourceRange(LBLoc, RBLoc));
5089 }
5090
5091 case TYPE_VECTOR: {
5092 if (Record.size() != 3) {
5093 Error("incorrect encoding of vector type in AST file");
5094 return QualType();
5095 }
5096
5097 QualType ElementType = readType(*Loc.F, Record, Idx);
5098 unsigned NumElements = Record[1];
5099 unsigned VecKind = Record[2];
5100 return Context.getVectorType(ElementType, NumElements,
5101 (VectorType::VectorKind)VecKind);
5102 }
5103
5104 case TYPE_EXT_VECTOR: {
5105 if (Record.size() != 3) {
5106 Error("incorrect encoding of extended vector type in AST file");
5107 return QualType();
5108 }
5109
5110 QualType ElementType = readType(*Loc.F, Record, Idx);
5111 unsigned NumElements = Record[1];
5112 return Context.getExtVectorType(ElementType, NumElements);
5113 }
5114
5115 case TYPE_FUNCTION_NO_PROTO: {
5116 if (Record.size() != 6) {
5117 Error("incorrect encoding of no-proto function type");
5118 return QualType();
5119 }
5120 QualType ResultType = readType(*Loc.F, Record, Idx);
5121 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5122 (CallingConv)Record[4], Record[5]);
5123 return Context.getFunctionNoProtoType(ResultType, Info);
5124 }
5125
5126 case TYPE_FUNCTION_PROTO: {
5127 QualType ResultType = readType(*Loc.F, Record, Idx);
5128
5129 FunctionProtoType::ExtProtoInfo EPI;
5130 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5131 /*hasregparm*/ Record[2],
5132 /*regparm*/ Record[3],
5133 static_cast<CallingConv>(Record[4]),
5134 /*produces*/ Record[5]);
5135
5136 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005137
5138 EPI.Variadic = Record[Idx++];
5139 EPI.HasTrailingReturn = Record[Idx++];
5140 EPI.TypeQuals = Record[Idx++];
5141 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005142 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005143 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005144
5145 unsigned NumParams = Record[Idx++];
5146 SmallVector<QualType, 16> ParamTypes;
5147 for (unsigned I = 0; I != NumParams; ++I)
5148 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5149
Jordan Rose5c382722013-03-08 21:51:21 +00005150 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 }
5152
5153 case TYPE_UNRESOLVED_USING: {
5154 unsigned Idx = 0;
5155 return Context.getTypeDeclType(
5156 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5157 }
5158
5159 case TYPE_TYPEDEF: {
5160 if (Record.size() != 2) {
5161 Error("incorrect encoding of typedef type");
5162 return QualType();
5163 }
5164 unsigned Idx = 0;
5165 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5166 QualType Canonical = readType(*Loc.F, Record, Idx);
5167 if (!Canonical.isNull())
5168 Canonical = Context.getCanonicalType(Canonical);
5169 return Context.getTypedefType(Decl, Canonical);
5170 }
5171
5172 case TYPE_TYPEOF_EXPR:
5173 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5174
5175 case TYPE_TYPEOF: {
5176 if (Record.size() != 1) {
5177 Error("incorrect encoding of typeof(type) in AST file");
5178 return QualType();
5179 }
5180 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5181 return Context.getTypeOfType(UnderlyingType);
5182 }
5183
5184 case TYPE_DECLTYPE: {
5185 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5186 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5187 }
5188
5189 case TYPE_UNARY_TRANSFORM: {
5190 QualType BaseType = readType(*Loc.F, Record, Idx);
5191 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5192 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5193 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5194 }
5195
Richard Smith74aeef52013-04-26 16:15:35 +00005196 case TYPE_AUTO: {
5197 QualType Deduced = readType(*Loc.F, Record, Idx);
5198 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005199 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005200 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005201 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005202
5203 case TYPE_RECORD: {
5204 if (Record.size() != 2) {
5205 Error("incorrect encoding of record type");
5206 return QualType();
5207 }
5208 unsigned Idx = 0;
5209 bool IsDependent = Record[Idx++];
5210 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5211 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5212 QualType T = Context.getRecordType(RD);
5213 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5214 return T;
5215 }
5216
5217 case TYPE_ENUM: {
5218 if (Record.size() != 2) {
5219 Error("incorrect encoding of enum type");
5220 return QualType();
5221 }
5222 unsigned Idx = 0;
5223 bool IsDependent = Record[Idx++];
5224 QualType T
5225 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5226 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5227 return T;
5228 }
5229
5230 case TYPE_ATTRIBUTED: {
5231 if (Record.size() != 3) {
5232 Error("incorrect encoding of attributed type");
5233 return QualType();
5234 }
5235 QualType modifiedType = readType(*Loc.F, Record, Idx);
5236 QualType equivalentType = readType(*Loc.F, Record, Idx);
5237 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5238 return Context.getAttributedType(kind, modifiedType, equivalentType);
5239 }
5240
5241 case TYPE_PAREN: {
5242 if (Record.size() != 1) {
5243 Error("incorrect encoding of paren type");
5244 return QualType();
5245 }
5246 QualType InnerType = readType(*Loc.F, Record, Idx);
5247 return Context.getParenType(InnerType);
5248 }
5249
5250 case TYPE_PACK_EXPANSION: {
5251 if (Record.size() != 2) {
5252 Error("incorrect encoding of pack expansion type");
5253 return QualType();
5254 }
5255 QualType Pattern = readType(*Loc.F, Record, Idx);
5256 if (Pattern.isNull())
5257 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005258 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005259 if (Record[1])
5260 NumExpansions = Record[1] - 1;
5261 return Context.getPackExpansionType(Pattern, NumExpansions);
5262 }
5263
5264 case TYPE_ELABORATED: {
5265 unsigned Idx = 0;
5266 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5267 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5268 QualType NamedType = readType(*Loc.F, Record, Idx);
5269 return Context.getElaboratedType(Keyword, NNS, NamedType);
5270 }
5271
5272 case TYPE_OBJC_INTERFACE: {
5273 unsigned Idx = 0;
5274 ObjCInterfaceDecl *ItfD
5275 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5276 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5277 }
5278
5279 case TYPE_OBJC_OBJECT: {
5280 unsigned Idx = 0;
5281 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005282 unsigned NumTypeArgs = Record[Idx++];
5283 SmallVector<QualType, 4> TypeArgs;
5284 for (unsigned I = 0; I != NumTypeArgs; ++I)
5285 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005286 unsigned NumProtos = Record[Idx++];
5287 SmallVector<ObjCProtocolDecl*, 4> Protos;
5288 for (unsigned I = 0; I != NumProtos; ++I)
5289 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005290 bool IsKindOf = Record[Idx++];
5291 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 }
5293
5294 case TYPE_OBJC_OBJECT_POINTER: {
5295 unsigned Idx = 0;
5296 QualType Pointee = readType(*Loc.F, Record, Idx);
5297 return Context.getObjCObjectPointerType(Pointee);
5298 }
5299
5300 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5301 unsigned Idx = 0;
5302 QualType Parm = readType(*Loc.F, Record, Idx);
5303 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005304 return Context.getSubstTemplateTypeParmType(
5305 cast<TemplateTypeParmType>(Parm),
5306 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005307 }
5308
5309 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5310 unsigned Idx = 0;
5311 QualType Parm = readType(*Loc.F, Record, Idx);
5312 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5313 return Context.getSubstTemplateTypeParmPackType(
5314 cast<TemplateTypeParmType>(Parm),
5315 ArgPack);
5316 }
5317
5318 case TYPE_INJECTED_CLASS_NAME: {
5319 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5320 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5321 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5322 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005323 const Type *T = nullptr;
5324 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5325 if (const Type *Existing = DI->getTypeForDecl()) {
5326 T = Existing;
5327 break;
5328 }
5329 }
5330 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005331 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005332 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5333 DI->setTypeForDecl(T);
5334 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005335 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005336 }
5337
5338 case TYPE_TEMPLATE_TYPE_PARM: {
5339 unsigned Idx = 0;
5340 unsigned Depth = Record[Idx++];
5341 unsigned Index = Record[Idx++];
5342 bool Pack = Record[Idx++];
5343 TemplateTypeParmDecl *D
5344 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5345 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5346 }
5347
5348 case TYPE_DEPENDENT_NAME: {
5349 unsigned Idx = 0;
5350 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5351 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005352 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005353 QualType Canon = readType(*Loc.F, Record, Idx);
5354 if (!Canon.isNull())
5355 Canon = Context.getCanonicalType(Canon);
5356 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5357 }
5358
5359 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5360 unsigned Idx = 0;
5361 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5362 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005363 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005364 unsigned NumArgs = Record[Idx++];
5365 SmallVector<TemplateArgument, 8> Args;
5366 Args.reserve(NumArgs);
5367 while (NumArgs--)
5368 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5369 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5370 Args.size(), Args.data());
5371 }
5372
5373 case TYPE_DEPENDENT_SIZED_ARRAY: {
5374 unsigned Idx = 0;
5375
5376 // ArrayType
5377 QualType ElementType = readType(*Loc.F, Record, Idx);
5378 ArrayType::ArraySizeModifier ASM
5379 = (ArrayType::ArraySizeModifier)Record[Idx++];
5380 unsigned IndexTypeQuals = Record[Idx++];
5381
5382 // DependentSizedArrayType
5383 Expr *NumElts = ReadExpr(*Loc.F);
5384 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5385
5386 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5387 IndexTypeQuals, Brackets);
5388 }
5389
5390 case TYPE_TEMPLATE_SPECIALIZATION: {
5391 unsigned Idx = 0;
5392 bool IsDependent = Record[Idx++];
5393 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5394 SmallVector<TemplateArgument, 8> Args;
5395 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5396 QualType Underlying = readType(*Loc.F, Record, Idx);
5397 QualType T;
5398 if (Underlying.isNull())
5399 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5400 Args.size());
5401 else
5402 T = Context.getTemplateSpecializationType(Name, Args.data(),
5403 Args.size(), Underlying);
5404 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5405 return T;
5406 }
5407
5408 case TYPE_ATOMIC: {
5409 if (Record.size() != 1) {
5410 Error("Incorrect encoding of atomic type");
5411 return QualType();
5412 }
5413 QualType ValueType = readType(*Loc.F, Record, Idx);
5414 return Context.getAtomicType(ValueType);
5415 }
5416 }
5417 llvm_unreachable("Invalid TypeCode!");
5418}
5419
Richard Smith564417a2014-03-20 21:47:22 +00005420void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5421 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005422 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005423 const RecordData &Record, unsigned &Idx) {
5424 ExceptionSpecificationType EST =
5425 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005426 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005427 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005428 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005429 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005430 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005431 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005432 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005433 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005434 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5435 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005436 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005437 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005438 }
5439}
5440
Guy Benyei11169dd2012-12-18 14:30:41 +00005441class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5442 ASTReader &Reader;
5443 ModuleFile &F;
5444 const ASTReader::RecordData &Record;
5445 unsigned &Idx;
5446
5447 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5448 unsigned &I) {
5449 return Reader.ReadSourceLocation(F, R, I);
5450 }
5451
5452 template<typename T>
5453 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5454 return Reader.ReadDeclAs<T>(F, Record, Idx);
5455 }
5456
5457public:
5458 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5459 const ASTReader::RecordData &Record, unsigned &Idx)
5460 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5461 { }
5462
5463 // We want compile-time assurance that we've enumerated all of
5464 // these, so unfortunately we have to declare them first, then
5465 // define them out-of-line.
5466#define ABSTRACT_TYPELOC(CLASS, PARENT)
5467#define TYPELOC(CLASS, PARENT) \
5468 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5469#include "clang/AST/TypeLocNodes.def"
5470
5471 void VisitFunctionTypeLoc(FunctionTypeLoc);
5472 void VisitArrayTypeLoc(ArrayTypeLoc);
5473};
5474
5475void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5476 // nothing to do
5477}
5478void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5479 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5480 if (TL.needsExtraLocalData()) {
5481 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5482 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5483 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5484 TL.setModeAttr(Record[Idx++]);
5485 }
5486}
5487void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5488 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5489}
5490void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5491 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5492}
Reid Kleckner8a365022013-06-24 17:51:48 +00005493void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5494 // nothing to do
5495}
Reid Kleckner0503a872013-12-05 01:23:43 +00005496void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5497 // nothing to do
5498}
Guy Benyei11169dd2012-12-18 14:30:41 +00005499void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5500 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5501}
5502void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5503 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5504}
5505void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5506 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5507}
5508void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5509 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5510 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5511}
5512void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5513 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5514 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5515 if (Record[Idx++])
5516 TL.setSizeExpr(Reader.ReadExpr(F));
5517 else
Craig Toppera13603a2014-05-22 05:54:18 +00005518 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005519}
5520void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5521 VisitArrayTypeLoc(TL);
5522}
5523void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5524 VisitArrayTypeLoc(TL);
5525}
5526void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5527 VisitArrayTypeLoc(TL);
5528}
5529void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5530 DependentSizedArrayTypeLoc TL) {
5531 VisitArrayTypeLoc(TL);
5532}
5533void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5534 DependentSizedExtVectorTypeLoc TL) {
5535 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5536}
5537void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5538 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5539}
5540void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5541 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5542}
5543void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5544 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5545 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5546 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5547 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005548 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5549 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005550 }
5551}
5552void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5553 VisitFunctionTypeLoc(TL);
5554}
5555void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5556 VisitFunctionTypeLoc(TL);
5557}
5558void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5559 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5560}
5561void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5562 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5563}
5564void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5565 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5566 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5567 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5568}
5569void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5570 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5571 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5572 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5573 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5574}
5575void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5576 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5577}
5578void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5579 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5580 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5581 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5582 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5583}
5584void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5585 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5586}
5587void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5588 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5589}
5590void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5591 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5592}
5593void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5594 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5595 if (TL.hasAttrOperand()) {
5596 SourceRange range;
5597 range.setBegin(ReadSourceLocation(Record, Idx));
5598 range.setEnd(ReadSourceLocation(Record, Idx));
5599 TL.setAttrOperandParensRange(range);
5600 }
5601 if (TL.hasAttrExprOperand()) {
5602 if (Record[Idx++])
5603 TL.setAttrExprOperand(Reader.ReadExpr(F));
5604 else
Craig Toppera13603a2014-05-22 05:54:18 +00005605 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005606 } else if (TL.hasAttrEnumOperand())
5607 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5608}
5609void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5610 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5611}
5612void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5613 SubstTemplateTypeParmTypeLoc TL) {
5614 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5615}
5616void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5617 SubstTemplateTypeParmPackTypeLoc TL) {
5618 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5619}
5620void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5621 TemplateSpecializationTypeLoc TL) {
5622 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5623 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5624 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5625 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5626 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5627 TL.setArgLocInfo(i,
5628 Reader.GetTemplateArgumentLocInfo(F,
5629 TL.getTypePtr()->getArg(i).getKind(),
5630 Record, Idx));
5631}
5632void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5633 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5634 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5635}
5636void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5637 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5638 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5639}
5640void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5641 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5642}
5643void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5644 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5645 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5646 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5647}
5648void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5649 DependentTemplateSpecializationTypeLoc TL) {
5650 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5651 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5652 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5653 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5654 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5655 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5656 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5657 TL.setArgLocInfo(I,
5658 Reader.GetTemplateArgumentLocInfo(F,
5659 TL.getTypePtr()->getArg(I).getKind(),
5660 Record, Idx));
5661}
5662void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5663 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5664}
5665void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5666 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5667}
5668void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5669 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005670 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5671 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5672 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5673 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5674 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5675 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005676 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5677 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5678}
5679void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5680 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5681}
5682void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5683 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5684 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5685 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5686}
5687
5688TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5689 const RecordData &Record,
5690 unsigned &Idx) {
5691 QualType InfoTy = readType(F, Record, Idx);
5692 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005693 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005694
5695 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5696 TypeLocReader TLR(*this, F, Record, Idx);
5697 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5698 TLR.Visit(TL);
5699 return TInfo;
5700}
5701
5702QualType ASTReader::GetType(TypeID ID) {
5703 unsigned FastQuals = ID & Qualifiers::FastMask;
5704 unsigned Index = ID >> Qualifiers::FastWidth;
5705
5706 if (Index < NUM_PREDEF_TYPE_IDS) {
5707 QualType T;
5708 switch ((PredefinedTypeIDs)Index) {
5709 case PREDEF_TYPE_NULL_ID: return QualType();
5710 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5711 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5712
5713 case PREDEF_TYPE_CHAR_U_ID:
5714 case PREDEF_TYPE_CHAR_S_ID:
5715 // FIXME: Check that the signedness of CharTy is correct!
5716 T = Context.CharTy;
5717 break;
5718
5719 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5720 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5721 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5722 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5723 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5724 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5725 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5726 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5727 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5728 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5729 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5730 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5731 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5732 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5733 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5734 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5735 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5736 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5737 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5738 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5739 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5740 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5741 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5742 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5743 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5744 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5745 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5746 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005747 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5748 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5749 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5750 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5751 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5752 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005753 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005754 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005755 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5756
5757 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5758 T = Context.getAutoRRefDeductType();
5759 break;
5760
5761 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5762 T = Context.ARCUnbridgedCastTy;
5763 break;
5764
Guy Benyei11169dd2012-12-18 14:30:41 +00005765 case PREDEF_TYPE_BUILTIN_FN:
5766 T = Context.BuiltinFnTy;
5767 break;
5768 }
5769
5770 assert(!T.isNull() && "Unknown predefined type");
5771 return T.withFastQualifiers(FastQuals);
5772 }
5773
5774 Index -= NUM_PREDEF_TYPE_IDS;
5775 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5776 if (TypesLoaded[Index].isNull()) {
5777 TypesLoaded[Index] = readTypeRecord(Index);
5778 if (TypesLoaded[Index].isNull())
5779 return QualType();
5780
5781 TypesLoaded[Index]->setFromAST();
5782 if (DeserializationListener)
5783 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5784 TypesLoaded[Index]);
5785 }
5786
5787 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5788}
5789
5790QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5791 return GetType(getGlobalTypeID(F, LocalID));
5792}
5793
5794serialization::TypeID
5795ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5796 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5797 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5798
5799 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5800 return LocalID;
5801
5802 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5803 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5804 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5805
5806 unsigned GlobalIndex = LocalIndex + I->second;
5807 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5808}
5809
5810TemplateArgumentLocInfo
5811ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5812 TemplateArgument::ArgKind Kind,
5813 const RecordData &Record,
5814 unsigned &Index) {
5815 switch (Kind) {
5816 case TemplateArgument::Expression:
5817 return ReadExpr(F);
5818 case TemplateArgument::Type:
5819 return GetTypeSourceInfo(F, Record, Index);
5820 case TemplateArgument::Template: {
5821 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5822 Index);
5823 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5824 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5825 SourceLocation());
5826 }
5827 case TemplateArgument::TemplateExpansion: {
5828 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5829 Index);
5830 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5831 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5832 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5833 EllipsisLoc);
5834 }
5835 case TemplateArgument::Null:
5836 case TemplateArgument::Integral:
5837 case TemplateArgument::Declaration:
5838 case TemplateArgument::NullPtr:
5839 case TemplateArgument::Pack:
5840 // FIXME: Is this right?
5841 return TemplateArgumentLocInfo();
5842 }
5843 llvm_unreachable("unexpected template argument loc");
5844}
5845
5846TemplateArgumentLoc
5847ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5848 const RecordData &Record, unsigned &Index) {
5849 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5850
5851 if (Arg.getKind() == TemplateArgument::Expression) {
5852 if (Record[Index++]) // bool InfoHasSameExpr.
5853 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5854 }
5855 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5856 Record, Index));
5857}
5858
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005859const ASTTemplateArgumentListInfo*
5860ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5861 const RecordData &Record,
5862 unsigned &Index) {
5863 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5864 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5865 unsigned NumArgsAsWritten = Record[Index++];
5866 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5867 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5868 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5869 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5870}
5871
Guy Benyei11169dd2012-12-18 14:30:41 +00005872Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5873 return GetDecl(ID);
5874}
5875
Richard Smith50895422015-01-31 03:04:55 +00005876template<typename TemplateSpecializationDecl>
5877static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5878 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5879 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5880}
5881
Richard Smith053f6c62014-05-16 23:01:30 +00005882void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005883 if (NumCurrentElementsDeserializing) {
5884 // We arrange to not care about the complete redeclaration chain while we're
5885 // deserializing. Just remember that the AST has marked this one as complete
5886 // but that it's not actually complete yet, so we know we still need to
5887 // complete it later.
5888 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5889 return;
5890 }
5891
Richard Smith053f6c62014-05-16 23:01:30 +00005892 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5893
Richard Smith053f6c62014-05-16 23:01:30 +00005894 // If this is a named declaration, complete it by looking it up
5895 // within its context.
5896 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005897 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005898 // all mergeable entities within it.
5899 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5900 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5901 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00005902 if (!getContext().getLangOpts().CPlusPlus &&
5903 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00005904 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00005905 // the identifier instead. (For C++ modules, we don't store decls
5906 // in the serialized identifier table, so we do the lookup in the TU.)
5907 auto *II = Name.getAsIdentifierInfo();
5908 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00005909 if (II->isOutOfDate())
5910 updateOutOfDateIdentifier(*II);
5911 } else
5912 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005913 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
5914 // FIXME: It'd be nice to do something a bit more targeted here.
5915 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00005916 }
5917 }
Richard Smith50895422015-01-31 03:04:55 +00005918
5919 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5920 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5921 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5922 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5923 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5924 if (auto *Template = FD->getPrimaryTemplate())
5925 Template->LoadLazySpecializations();
5926 }
Richard Smith053f6c62014-05-16 23:01:30 +00005927}
5928
Richard Smithc2bb8182015-03-24 06:36:48 +00005929uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5930 const RecordData &Record,
5931 unsigned &Idx) {
5932 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5933 Error("malformed AST file: missing C++ ctor initializers");
5934 return 0;
5935 }
5936
5937 unsigned LocalID = Record[Idx++];
5938 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
5939}
5940
5941CXXCtorInitializer **
5942ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
5943 RecordLocation Loc = getLocalBitOffset(Offset);
5944 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
5945 SavedStreamPosition SavedPosition(Cursor);
5946 Cursor.JumpToBit(Loc.Offset);
5947 ReadingKindTracker ReadingKind(Read_Decl, *this);
5948
5949 RecordData Record;
5950 unsigned Code = Cursor.ReadCode();
5951 unsigned RecCode = Cursor.readRecord(Code, Record);
5952 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
5953 Error("malformed AST file: missing C++ ctor initializers");
5954 return nullptr;
5955 }
5956
5957 unsigned Idx = 0;
5958 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
5959}
5960
Richard Smithcd45dbc2014-04-19 03:48:30 +00005961uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5962 const RecordData &Record,
5963 unsigned &Idx) {
5964 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5965 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005966 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005967 }
5968
Guy Benyei11169dd2012-12-18 14:30:41 +00005969 unsigned LocalID = Record[Idx++];
5970 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5971}
5972
5973CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5974 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005975 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005976 SavedStreamPosition SavedPosition(Cursor);
5977 Cursor.JumpToBit(Loc.Offset);
5978 ReadingKindTracker ReadingKind(Read_Decl, *this);
5979 RecordData Record;
5980 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005981 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005982 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005983 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00005984 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005985 }
5986
5987 unsigned Idx = 0;
5988 unsigned NumBases = Record[Idx++];
5989 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5990 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5991 for (unsigned I = 0; I != NumBases; ++I)
5992 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5993 return Bases;
5994}
5995
5996serialization::DeclID
5997ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5998 if (LocalID < NUM_PREDEF_DECL_IDS)
5999 return LocalID;
6000
6001 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6002 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6003 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6004
6005 return LocalID + I->second;
6006}
6007
6008bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6009 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006010 // Predefined decls aren't from any module.
6011 if (ID < NUM_PREDEF_DECL_IDS)
6012 return false;
6013
Richard Smithbcda1a92015-07-12 23:51:20 +00006014 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6015 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006016}
6017
Douglas Gregor9f782892013-01-21 15:25:38 +00006018ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006019 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006020 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006021 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6022 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6023 return I->second;
6024}
6025
6026SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6027 if (ID < NUM_PREDEF_DECL_IDS)
6028 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006029
Guy Benyei11169dd2012-12-18 14:30:41 +00006030 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6031
6032 if (Index > DeclsLoaded.size()) {
6033 Error("declaration ID out-of-range for AST file");
6034 return SourceLocation();
6035 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006036
Guy Benyei11169dd2012-12-18 14:30:41 +00006037 if (Decl *D = DeclsLoaded[Index])
6038 return D->getLocation();
6039
6040 unsigned RawLocation = 0;
6041 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6042 return ReadSourceLocation(*Rec.F, RawLocation);
6043}
6044
Richard Smithfe620d22015-03-05 23:24:12 +00006045static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6046 switch (ID) {
6047 case PREDEF_DECL_NULL_ID:
6048 return nullptr;
6049
6050 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6051 return Context.getTranslationUnitDecl();
6052
6053 case PREDEF_DECL_OBJC_ID_ID:
6054 return Context.getObjCIdDecl();
6055
6056 case PREDEF_DECL_OBJC_SEL_ID:
6057 return Context.getObjCSelDecl();
6058
6059 case PREDEF_DECL_OBJC_CLASS_ID:
6060 return Context.getObjCClassDecl();
6061
6062 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6063 return Context.getObjCProtocolDecl();
6064
6065 case PREDEF_DECL_INT_128_ID:
6066 return Context.getInt128Decl();
6067
6068 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6069 return Context.getUInt128Decl();
6070
6071 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6072 return Context.getObjCInstanceTypeDecl();
6073
6074 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6075 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006076
Richard Smith9b88a4c2015-07-27 05:40:23 +00006077 case PREDEF_DECL_VA_LIST_TAG:
6078 return Context.getVaListTagDecl();
6079
Richard Smithf19e1272015-03-07 00:04:49 +00006080 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6081 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006082 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006083 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006084}
6085
Richard Smithcd45dbc2014-04-19 03:48:30 +00006086Decl *ASTReader::GetExistingDecl(DeclID ID) {
6087 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006088 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6089 if (D) {
6090 // Track that we have merged the declaration with ID \p ID into the
6091 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006092 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006093 if (Merged.empty())
6094 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006095 }
Richard Smithfe620d22015-03-05 23:24:12 +00006096 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006097 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006098
Guy Benyei11169dd2012-12-18 14:30:41 +00006099 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6100
6101 if (Index >= DeclsLoaded.size()) {
6102 assert(0 && "declaration ID out-of-range for AST file");
6103 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006104 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006105 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006106
6107 return DeclsLoaded[Index];
6108}
6109
6110Decl *ASTReader::GetDecl(DeclID ID) {
6111 if (ID < NUM_PREDEF_DECL_IDS)
6112 return GetExistingDecl(ID);
6113
6114 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6115
6116 if (Index >= DeclsLoaded.size()) {
6117 assert(0 && "declaration ID out-of-range for AST file");
6118 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006119 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006120 }
6121
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 if (!DeclsLoaded[Index]) {
6123 ReadDeclRecord(ID);
6124 if (DeserializationListener)
6125 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6126 }
6127
6128 return DeclsLoaded[Index];
6129}
6130
6131DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6132 DeclID GlobalID) {
6133 if (GlobalID < NUM_PREDEF_DECL_IDS)
6134 return GlobalID;
6135
6136 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6137 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6138 ModuleFile *Owner = I->second;
6139
6140 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6141 = M.GlobalToLocalDeclIDs.find(Owner);
6142 if (Pos == M.GlobalToLocalDeclIDs.end())
6143 return 0;
6144
6145 return GlobalID - Owner->BaseDeclID + Pos->second;
6146}
6147
6148serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6149 const RecordData &Record,
6150 unsigned &Idx) {
6151 if (Idx >= Record.size()) {
6152 Error("Corrupted AST file");
6153 return 0;
6154 }
6155
6156 return getGlobalDeclID(F, Record[Idx++]);
6157}
6158
6159/// \brief Resolve the offset of a statement into a statement.
6160///
6161/// This operation will read a new statement from the external
6162/// source each time it is called, and is meant to be used via a
6163/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6164Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6165 // Switch case IDs are per Decl.
6166 ClearSwitchCaseIDs();
6167
6168 // Offset here is a global offset across the entire chain.
6169 RecordLocation Loc = getLocalBitOffset(Offset);
6170 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6171 return ReadStmtFromStream(*Loc.F);
6172}
6173
6174namespace {
6175 class FindExternalLexicalDeclsVisitor {
6176 ASTReader &Reader;
6177 const DeclContext *DC;
6178 bool (*isKindWeWant)(Decl::Kind);
6179
6180 SmallVectorImpl<Decl*> &Decls;
6181 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6182
6183 public:
6184 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6185 bool (*isKindWeWant)(Decl::Kind),
6186 SmallVectorImpl<Decl*> &Decls)
6187 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6188 {
6189 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6190 PredefsVisited[I] = false;
6191 }
6192
Manuel Klimek9eff8b12015-05-20 10:29:23 +00006193 static bool visitPostorder(ModuleFile &M, void *UserData) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006194 FindExternalLexicalDeclsVisitor *This
6195 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6196
6197 ModuleFile::DeclContextInfosMap::iterator Info
6198 = M.DeclContextInfos.find(This->DC);
Richard Smith787c0e42015-07-23 00:53:59 +00006199 if (Info == M.DeclContextInfos.end() || Info->second.LexicalDecls.empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006200 return false;
6201
6202 // Load all of the declaration IDs
Richard Smith787c0e42015-07-23 00:53:59 +00006203 for (const KindDeclIDPair &P : Info->second.LexicalDecls) {
6204 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)P.first))
Guy Benyei11169dd2012-12-18 14:30:41 +00006205 continue;
6206
6207 // Don't add predefined declarations to the lexical context more
6208 // than once.
Richard Smith787c0e42015-07-23 00:53:59 +00006209 if (P.second < NUM_PREDEF_DECL_IDS) {
6210 if (This->PredefsVisited[P.second])
Guy Benyei11169dd2012-12-18 14:30:41 +00006211 continue;
6212
Richard Smith787c0e42015-07-23 00:53:59 +00006213 This->PredefsVisited[P.second] = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006214 }
6215
Richard Smith787c0e42015-07-23 00:53:59 +00006216 if (Decl *D = This->Reader.GetLocalDecl(M, P.second)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006217 if (!This->DC->isDeclInLexicalTraversal(D))
6218 This->Decls.push_back(D);
6219 }
6220 }
6221
6222 return false;
6223 }
6224 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006225}
Guy Benyei11169dd2012-12-18 14:30:41 +00006226
6227ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6228 bool (*isKindWeWant)(Decl::Kind),
6229 SmallVectorImpl<Decl*> &Decls) {
6230 // There might be lexical decls in multiple modules, for the TU at
6231 // least. Walk all of the modules in the order they were loaded.
6232 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
Manuel Klimek9eff8b12015-05-20 10:29:23 +00006233 ModuleMgr.visitDepthFirst(
6234 nullptr, &FindExternalLexicalDeclsVisitor::visitPostorder, &Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006235 ++NumLexicalDeclContextsRead;
6236 return ELR_Success;
6237}
6238
6239namespace {
6240
6241class DeclIDComp {
6242 ASTReader &Reader;
6243 ModuleFile &Mod;
6244
6245public:
6246 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6247
6248 bool operator()(LocalDeclID L, LocalDeclID R) const {
6249 SourceLocation LHS = getLocation(L);
6250 SourceLocation RHS = getLocation(R);
6251 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6252 }
6253
6254 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6255 SourceLocation RHS = getLocation(R);
6256 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6257 }
6258
6259 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6260 SourceLocation LHS = getLocation(L);
6261 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6262 }
6263
6264 SourceLocation getLocation(LocalDeclID ID) const {
6265 return Reader.getSourceManager().getFileLoc(
6266 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6267 }
6268};
6269
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006270}
Guy Benyei11169dd2012-12-18 14:30:41 +00006271
6272void ASTReader::FindFileRegionDecls(FileID File,
6273 unsigned Offset, unsigned Length,
6274 SmallVectorImpl<Decl *> &Decls) {
6275 SourceManager &SM = getSourceManager();
6276
6277 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6278 if (I == FileDeclIDs.end())
6279 return;
6280
6281 FileDeclsInfo &DInfo = I->second;
6282 if (DInfo.Decls.empty())
6283 return;
6284
6285 SourceLocation
6286 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6287 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6288
6289 DeclIDComp DIDComp(*this, *DInfo.Mod);
6290 ArrayRef<serialization::LocalDeclID>::iterator
6291 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6292 BeginLoc, DIDComp);
6293 if (BeginIt != DInfo.Decls.begin())
6294 --BeginIt;
6295
6296 // If we are pointing at a top-level decl inside an objc container, we need
6297 // to backtrack until we find it otherwise we will fail to report that the
6298 // region overlaps with an objc container.
6299 while (BeginIt != DInfo.Decls.begin() &&
6300 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6301 ->isTopLevelDeclInObjCContainer())
6302 --BeginIt;
6303
6304 ArrayRef<serialization::LocalDeclID>::iterator
6305 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6306 EndLoc, DIDComp);
6307 if (EndIt != DInfo.Decls.end())
6308 ++EndIt;
6309
6310 for (ArrayRef<serialization::LocalDeclID>::iterator
6311 DIt = BeginIt; DIt != EndIt; ++DIt)
6312 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6313}
6314
Richard Smith3b637412015-07-14 18:42:41 +00006315/// \brief Retrieve the "definitive" module file for the definition of the
6316/// given declaration context, if there is one.
6317///
6318/// The "definitive" module file is the only place where we need to look to
6319/// find information about the declarations within the given declaration
6320/// context. For example, C++ and Objective-C classes, C structs/unions, and
6321/// Objective-C protocols, categories, and extensions are all defined in a
6322/// single place in the source code, so they have definitive module files
6323/// associated with them. C++ namespaces, on the other hand, can have
6324/// definitions in multiple different module files.
6325///
6326/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6327/// NDEBUG checking.
6328static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6329 ASTReader &Reader) {
6330 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6331 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6332
6333 return nullptr;
6334}
6335
Guy Benyei11169dd2012-12-18 14:30:41 +00006336namespace {
6337 /// \brief ModuleFile visitor used to perform name lookup into a
6338 /// declaration context.
6339 class DeclContextNameLookupVisitor {
6340 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006341 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006342 DeclarationName Name;
Richard Smith3b637412015-07-14 18:42:41 +00006343 ASTDeclContextNameLookupTrait::DeclNameKey NameKey;
6344 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00006345 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006346 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006347
6348 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006349 DeclContextNameLookupVisitor(ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006350 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006351 SmallVectorImpl<NamedDecl *> &Decls,
6352 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
Richard Smith3b637412015-07-14 18:42:41 +00006353 : Reader(Reader), Name(Name),
6354 NameKey(ASTDeclContextNameLookupTrait::GetInternalKey(Name)),
6355 NameHash(ASTDeclContextNameLookupTrait::ComputeHash(NameKey)),
6356 Decls(Decls), DeclSet(DeclSet) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006357
Richard Smith3b637412015-07-14 18:42:41 +00006358 void visitContexts(ArrayRef<const DeclContext*> Contexts) {
6359 if (Contexts.empty())
6360 return;
6361 this->Contexts = Contexts;
6362
6363 // If we can definitively determine which module file to look into,
6364 // only look there. Otherwise, look in all module files.
6365 ModuleFile *Definitive;
6366 if (Contexts.size() == 1 &&
6367 (Definitive = getDefinitiveModuleFileFor(Contexts[0], Reader))) {
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006368 (*this)(*Definitive);
Richard Smith3b637412015-07-14 18:42:41 +00006369 } else {
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006370 Reader.getModuleManager().visit(*this);
Richard Smith3b637412015-07-14 18:42:41 +00006371 }
6372 }
6373
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006374 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006375 // Check whether we have any visible declaration information for
6376 // this context in this module.
6377 ModuleFile::DeclContextInfosMap::iterator Info;
6378 bool FoundInfo = false;
Richard Smithbdf2d932015-07-30 03:37:16 +00006379 for (auto *DC : Contexts) {
Richard Smith8c913ec2014-08-14 02:21:01 +00006380 Info = M.DeclContextInfos.find(DC);
6381 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006382 Info->second.NameLookupTableData) {
6383 FoundInfo = true;
6384 break;
6385 }
6386 }
6387
6388 if (!FoundInfo)
6389 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006390
Guy Benyei11169dd2012-12-18 14:30:41 +00006391 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006392 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006393 Info->second.NameLookupTableData;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006394 ASTDeclContextNameLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00006395 LookupTable->find_hashed(NameKey, NameHash);
Guy Benyei11169dd2012-12-18 14:30:41 +00006396 if (Pos == LookupTable->end())
6397 return false;
6398
6399 bool FoundAnything = false;
6400 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6401 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006402 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006403 if (!ND)
6404 continue;
6405
Richard Smithbdf2d932015-07-30 03:37:16 +00006406 if (ND->getDeclName() != Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006407 // A name might be null because the decl's redeclarable part is
6408 // currently read before reading its name. The lookup is triggered by
6409 // building that decl (likely indirectly), and so it is later in the
6410 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006411 // FIXME: This should not happen; deserializing declarations should
6412 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006413 continue;
6414 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006415
Guy Benyei11169dd2012-12-18 14:30:41 +00006416 // Record this declaration.
6417 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006418 if (DeclSet.insert(ND).second)
6419 Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006420 }
6421
6422 return FoundAnything;
6423 }
6424 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006425}
Guy Benyei11169dd2012-12-18 14:30:41 +00006426
Richard Smith9ce12e32013-02-07 03:30:24 +00006427bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006428ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6429 DeclarationName Name) {
6430 assert(DC->hasExternalVisibleStorage() &&
6431 "DeclContext has no visible decls in storage");
6432 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006433 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006434
Richard Smith8c913ec2014-08-14 02:21:01 +00006435 Deserializing LookupResults(this);
6436
Guy Benyei11169dd2012-12-18 14:30:41 +00006437 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006438 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006439
Guy Benyei11169dd2012-12-18 14:30:41 +00006440 // Compute the declaration contexts we need to look into. Multiple such
6441 // declaration contexts occur when two declaration contexts from disjoint
6442 // modules get merged, e.g., when two namespaces with the same name are
6443 // independently defined in separate modules.
6444 SmallVector<const DeclContext *, 2> Contexts;
6445 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006446
Guy Benyei11169dd2012-12-18 14:30:41 +00006447 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006448 auto Key = KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6449 if (Key != KeyDecls.end()) {
6450 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6451 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006452 }
6453 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006454
Richard Smith3b637412015-07-14 18:42:41 +00006455 DeclContextNameLookupVisitor Visitor(*this, Name, Decls, DeclSet);
6456 Visitor.visitContexts(Contexts);
Richard Smith8c913ec2014-08-14 02:21:01 +00006457
6458 // If this might be an implicit special member function, then also search
6459 // all merged definitions of the surrounding class. We need to search them
6460 // individually, because finding an entity in one of them doesn't imply that
6461 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006462 if (isa<CXXRecordDecl>(DC)) {
Richard Smith02793752015-03-27 21:16:39 +00006463 auto Merged = MergedLookups.find(DC);
6464 if (Merged != MergedLookups.end()) {
6465 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6466 const DeclContext *Context = Merged->second[I];
Richard Smith3b637412015-07-14 18:42:41 +00006467 Visitor.visitContexts(Context);
Richard Smith02793752015-03-27 21:16:39 +00006468 // We might have just added some more merged lookups. If so, our
6469 // iterator is now invalid, so grab a fresh one before continuing.
6470 Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006471 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006472 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006473 }
6474
Guy Benyei11169dd2012-12-18 14:30:41 +00006475 ++NumVisibleDeclContextsRead;
6476 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006477 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006478}
6479
6480namespace {
6481 /// \brief ModuleFile visitor used to retrieve all visible names in a
6482 /// declaration context.
6483 class DeclContextAllNamesVisitor {
6484 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006485 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006486 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006487 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006488 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006489
6490 public:
6491 DeclContextAllNamesVisitor(ASTReader &Reader,
6492 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006493 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006494 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006495
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006496 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006497 // Check whether we have any visible declaration information for
6498 // this context in this module.
6499 ModuleFile::DeclContextInfosMap::iterator Info;
6500 bool FoundInfo = false;
Richard Smithbdf2d932015-07-30 03:37:16 +00006501 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
6502 Info = M.DeclContextInfos.find(Contexts[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006503 if (Info != M.DeclContextInfos.end() &&
6504 Info->second.NameLookupTableData) {
6505 FoundInfo = true;
6506 break;
6507 }
6508 }
6509
6510 if (!FoundInfo)
6511 return false;
6512
Richard Smith52e3fba2014-03-11 07:17:35 +00006513 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006514 Info->second.NameLookupTableData;
6515 bool FoundAnything = false;
6516 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006517 I = LookupTable->data_begin(), E = LookupTable->data_end();
6518 I != E;
6519 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006520 ASTDeclContextNameLookupTrait::data_type Data = *I;
6521 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006522 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006523 if (!ND)
6524 continue;
6525
6526 // Record this declaration.
6527 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006528 if (DeclSet.insert(ND).second)
6529 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006530 }
6531 }
6532
Richard Smithbdf2d932015-07-30 03:37:16 +00006533 return FoundAnything && !VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006534 }
6535 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006536}
Guy Benyei11169dd2012-12-18 14:30:41 +00006537
6538void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6539 if (!DC->hasExternalVisibleStorage())
6540 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006541 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006542
6543 // Compute the declaration contexts we need to look into. Multiple such
6544 // declaration contexts occur when two declaration contexts from disjoint
6545 // modules get merged, e.g., when two namespaces with the same name are
6546 // independently defined in separate modules.
6547 SmallVector<const DeclContext *, 2> Contexts;
6548 Contexts.push_back(DC);
6549
6550 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006551 KeyDeclsMap::iterator Key =
6552 KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6553 if (Key != KeyDecls.end()) {
6554 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6555 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006556 }
6557 }
6558
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006559 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6560 /*VisitAll=*/DC->isFileContext());
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006561 ModuleMgr.visit(Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006562 ++NumVisibleDeclContextsRead;
6563
Craig Topper79be4cd2013-07-05 04:33:53 +00006564 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006565 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6566 }
6567 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6568}
6569
6570/// \brief Under non-PCH compilation the consumer receives the objc methods
6571/// before receiving the implementation, and codegen depends on this.
6572/// We simulate this by deserializing and passing to consumer the methods of the
6573/// implementation before passing the deserialized implementation decl.
6574static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6575 ASTConsumer *Consumer) {
6576 assert(ImplD && Consumer);
6577
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006578 for (auto *I : ImplD->methods())
6579 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006580
6581 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6582}
6583
6584void ASTReader::PassInterestingDeclsToConsumer() {
6585 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006586
6587 if (PassingDeclsToConsumer)
6588 return;
6589
6590 // Guard variable to avoid recursively redoing the process of passing
6591 // decls to consumer.
6592 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6593 true);
6594
Richard Smith9e2341d2015-03-23 03:25:59 +00006595 // Ensure that we've loaded all potentially-interesting declarations
6596 // that need to be eagerly loaded.
6597 for (auto ID : EagerlyDeserializedDecls)
6598 GetDecl(ID);
6599 EagerlyDeserializedDecls.clear();
6600
Guy Benyei11169dd2012-12-18 14:30:41 +00006601 while (!InterestingDecls.empty()) {
6602 Decl *D = InterestingDecls.front();
6603 InterestingDecls.pop_front();
6604
6605 PassInterestingDeclToConsumer(D);
6606 }
6607}
6608
6609void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6610 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6611 PassObjCImplDeclToConsumer(ImplD, Consumer);
6612 else
6613 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6614}
6615
6616void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6617 this->Consumer = Consumer;
6618
Richard Smith9e2341d2015-03-23 03:25:59 +00006619 if (Consumer)
6620 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006621
6622 if (DeserializationListener)
6623 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006624}
6625
6626void ASTReader::PrintStats() {
6627 std::fprintf(stderr, "*** AST File Statistics:\n");
6628
6629 unsigned NumTypesLoaded
6630 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6631 QualType());
6632 unsigned NumDeclsLoaded
6633 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006634 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006635 unsigned NumIdentifiersLoaded
6636 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6637 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006638 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006639 unsigned NumMacrosLoaded
6640 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6641 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006642 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006643 unsigned NumSelectorsLoaded
6644 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6645 SelectorsLoaded.end(),
6646 Selector());
6647
6648 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6649 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6650 NumSLocEntriesRead, TotalNumSLocEntries,
6651 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6652 if (!TypesLoaded.empty())
6653 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6654 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6655 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6656 if (!DeclsLoaded.empty())
6657 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6658 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6659 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6660 if (!IdentifiersLoaded.empty())
6661 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6662 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6663 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6664 if (!MacrosLoaded.empty())
6665 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6666 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6667 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6668 if (!SelectorsLoaded.empty())
6669 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6670 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6671 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6672 if (TotalNumStatements)
6673 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6674 NumStatementsRead, TotalNumStatements,
6675 ((float)NumStatementsRead/TotalNumStatements * 100));
6676 if (TotalNumMacros)
6677 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6678 NumMacrosRead, TotalNumMacros,
6679 ((float)NumMacrosRead/TotalNumMacros * 100));
6680 if (TotalLexicalDeclContexts)
6681 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6682 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6683 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6684 * 100));
6685 if (TotalVisibleDeclContexts)
6686 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6687 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6688 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6689 * 100));
6690 if (TotalNumMethodPoolEntries) {
6691 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6692 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6693 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6694 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006695 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006696 if (NumMethodPoolLookups) {
6697 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6698 NumMethodPoolHits, NumMethodPoolLookups,
6699 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6700 }
6701 if (NumMethodPoolTableLookups) {
6702 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6703 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6704 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6705 * 100.0));
6706 }
6707
Douglas Gregor00a50f72013-01-25 00:38:33 +00006708 if (NumIdentifierLookupHits) {
6709 std::fprintf(stderr,
6710 " %u / %u identifier table lookups succeeded (%f%%)\n",
6711 NumIdentifierLookupHits, NumIdentifierLookups,
6712 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6713 }
6714
Douglas Gregore060e572013-01-25 01:03:03 +00006715 if (GlobalIndex) {
6716 std::fprintf(stderr, "\n");
6717 GlobalIndex->printStats();
6718 }
6719
Guy Benyei11169dd2012-12-18 14:30:41 +00006720 std::fprintf(stderr, "\n");
6721 dump();
6722 std::fprintf(stderr, "\n");
6723}
6724
6725template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6726static void
6727dumpModuleIDMap(StringRef Name,
6728 const ContinuousRangeMap<Key, ModuleFile *,
6729 InitialCapacity> &Map) {
6730 if (Map.begin() == Map.end())
6731 return;
6732
6733 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6734 llvm::errs() << Name << ":\n";
6735 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6736 I != IEnd; ++I) {
6737 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6738 << "\n";
6739 }
6740}
6741
6742void ASTReader::dump() {
6743 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6744 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6745 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6746 dumpModuleIDMap("Global type map", GlobalTypeMap);
6747 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6748 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6749 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6750 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6751 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6752 dumpModuleIDMap("Global preprocessed entity map",
6753 GlobalPreprocessedEntityMap);
6754
6755 llvm::errs() << "\n*** PCH/Modules Loaded:";
6756 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6757 MEnd = ModuleMgr.end();
6758 M != MEnd; ++M)
6759 (*M)->dump();
6760}
6761
6762/// Return the amount of memory used by memory buffers, breaking down
6763/// by heap-backed versus mmap'ed memory.
6764void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6765 for (ModuleConstIterator I = ModuleMgr.begin(),
6766 E = ModuleMgr.end(); I != E; ++I) {
6767 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6768 size_t bytes = buf->getBufferSize();
6769 switch (buf->getBufferKind()) {
6770 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6771 sizes.malloc_bytes += bytes;
6772 break;
6773 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6774 sizes.mmap_bytes += bytes;
6775 break;
6776 }
6777 }
6778 }
6779}
6780
6781void ASTReader::InitializeSema(Sema &S) {
6782 SemaObj = &S;
6783 S.addExternalSource(this);
6784
6785 // Makes sure any declarations that were deserialized "too early"
6786 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006787 for (uint64_t ID : PreloadedDeclIDs) {
6788 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6789 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006790 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006791 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006792
Richard Smith3d8e97e2013-10-18 06:54:39 +00006793 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006794 if (!FPPragmaOptions.empty()) {
6795 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6796 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6797 }
6798
Richard Smith3d8e97e2013-10-18 06:54:39 +00006799 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006800 if (!OpenCLExtensions.empty()) {
6801 unsigned I = 0;
6802#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6803#include "clang/Basic/OpenCLExtensions.def"
6804
6805 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6806 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006807
6808 UpdateSema();
6809}
6810
6811void ASTReader::UpdateSema() {
6812 assert(SemaObj && "no Sema to update");
6813
6814 // Load the offsets of the declarations that Sema references.
6815 // They will be lazily deserialized when needed.
6816 if (!SemaDeclRefs.empty()) {
6817 assert(SemaDeclRefs.size() % 2 == 0);
6818 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6819 if (!SemaObj->StdNamespace)
6820 SemaObj->StdNamespace = SemaDeclRefs[I];
6821 if (!SemaObj->StdBadAlloc)
6822 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6823 }
6824 SemaDeclRefs.clear();
6825 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006826
6827 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6828 // encountered the pragma in the source.
6829 if(OptimizeOffPragmaLocation.isValid())
6830 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006831}
6832
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006833IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006834 // Note that we are loading an identifier.
6835 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006836
Douglas Gregor7211ac12013-01-25 23:32:03 +00006837 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006838 NumIdentifierLookups,
6839 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006840
6841 // We don't need to do identifier table lookups in C++ modules (we preload
6842 // all interesting declarations, and don't need to use the scope for name
6843 // lookups). Perform the lookup in PCH files, though, since we don't build
6844 // a complete initial identifier table if we're carrying on from a PCH.
6845 if (Context.getLangOpts().CPlusPlus) {
6846 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006847 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006848 break;
6849 } else {
6850 // If there is a global index, look there first to determine which modules
6851 // provably do not have any results for this identifier.
6852 GlobalModuleIndex::HitSet Hits;
6853 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6854 if (!loadGlobalIndex()) {
6855 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6856 HitsPtr = &Hits;
6857 }
6858 }
6859
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006860 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006861 }
6862
Guy Benyei11169dd2012-12-18 14:30:41 +00006863 IdentifierInfo *II = Visitor.getIdentifierInfo();
6864 markIdentifierUpToDate(II);
6865 return II;
6866}
6867
6868namespace clang {
6869 /// \brief An identifier-lookup iterator that enumerates all of the
6870 /// identifiers stored within a set of AST files.
6871 class ASTIdentifierIterator : public IdentifierIterator {
6872 /// \brief The AST reader whose identifiers are being enumerated.
6873 const ASTReader &Reader;
6874
6875 /// \brief The current index into the chain of AST files stored in
6876 /// the AST reader.
6877 unsigned Index;
6878
6879 /// \brief The current position within the identifier lookup table
6880 /// of the current AST file.
6881 ASTIdentifierLookupTable::key_iterator Current;
6882
6883 /// \brief The end position within the identifier lookup table of
6884 /// the current AST file.
6885 ASTIdentifierLookupTable::key_iterator End;
6886
6887 public:
6888 explicit ASTIdentifierIterator(const ASTReader &Reader);
6889
Craig Topper3e89dfe2014-03-13 02:13:41 +00006890 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006891 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006892}
Guy Benyei11169dd2012-12-18 14:30:41 +00006893
6894ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6895 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6896 ASTIdentifierLookupTable *IdTable
6897 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6898 Current = IdTable->key_begin();
6899 End = IdTable->key_end();
6900}
6901
6902StringRef ASTIdentifierIterator::Next() {
6903 while (Current == End) {
6904 // If we have exhausted all of our AST files, we're done.
6905 if (Index == 0)
6906 return StringRef();
6907
6908 --Index;
6909 ASTIdentifierLookupTable *IdTable
6910 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6911 IdentifierLookupTable;
6912 Current = IdTable->key_begin();
6913 End = IdTable->key_end();
6914 }
6915
6916 // We have any identifiers remaining in the current AST file; return
6917 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006918 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006919 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006920 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006921}
6922
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006923IdentifierIterator *ASTReader::getIdentifiers() {
6924 if (!loadGlobalIndex())
6925 return GlobalIndex->createIdentifierIterator();
6926
Guy Benyei11169dd2012-12-18 14:30:41 +00006927 return new ASTIdentifierIterator(*this);
6928}
6929
6930namespace clang { namespace serialization {
6931 class ReadMethodPoolVisitor {
6932 ASTReader &Reader;
6933 Selector Sel;
6934 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006935 unsigned InstanceBits;
6936 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006937 bool InstanceHasMoreThanOneDecl;
6938 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006939 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6940 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006941
6942 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006943 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006944 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006945 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006946 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6947 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006948
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006949 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006950 if (!M.SelectorLookupTable)
6951 return false;
6952
6953 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00006954 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00006955 return true;
6956
Richard Smithbdf2d932015-07-30 03:37:16 +00006957 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006958 ASTSelectorLookupTable *PoolTable
6959 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00006960 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00006961 if (Pos == PoolTable->end())
6962 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006963
Richard Smithbdf2d932015-07-30 03:37:16 +00006964 ++Reader.NumMethodPoolTableHits;
6965 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006966 // FIXME: Not quite happy with the statistics here. We probably should
6967 // disable this tracking when called via LoadSelector.
6968 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00006969 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006970 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00006971 if (Reader.DeserializationListener)
6972 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006973
Richard Smithbdf2d932015-07-30 03:37:16 +00006974 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6975 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6976 InstanceBits = Data.InstanceBits;
6977 FactoryBits = Data.FactoryBits;
6978 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6979 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006980 return true;
6981 }
6982
6983 /// \brief Retrieve the instance methods found by this visitor.
6984 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6985 return InstanceMethods;
6986 }
6987
6988 /// \brief Retrieve the instance methods found by this visitor.
6989 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6990 return FactoryMethods;
6991 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006992
6993 unsigned getInstanceBits() const { return InstanceBits; }
6994 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006995 bool instanceHasMoreThanOneDecl() const {
6996 return InstanceHasMoreThanOneDecl;
6997 }
6998 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006999 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007000} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00007001
7002/// \brief Add the given set of methods to the method list.
7003static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7004 ObjCMethodList &List) {
7005 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7006 S.addMethodToGlobalList(&List, Methods[I]);
7007 }
7008}
7009
7010void ASTReader::ReadMethodPool(Selector Sel) {
7011 // Get the selector generation and update it to the current generation.
7012 unsigned &Generation = SelectorGeneration[Sel];
7013 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007014 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007015
7016 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007017 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007018 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007019 ModuleMgr.visit(Visitor);
7020
Guy Benyei11169dd2012-12-18 14:30:41 +00007021 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007022 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007023 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007024
7025 ++NumMethodPoolHits;
7026
Guy Benyei11169dd2012-12-18 14:30:41 +00007027 if (!getSema())
7028 return;
7029
7030 Sema &S = *getSema();
7031 Sema::GlobalMethodPool::iterator Pos
7032 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007033
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007034 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007035 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007036 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007037 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007038
7039 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7040 // when building a module we keep every method individually and may need to
7041 // update hasMoreThanOneDecl as we add the methods.
7042 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7043 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007044}
7045
7046void ASTReader::ReadKnownNamespaces(
7047 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7048 Namespaces.clear();
7049
7050 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7051 if (NamespaceDecl *Namespace
7052 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7053 Namespaces.push_back(Namespace);
7054 }
7055}
7056
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007057void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007058 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007059 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7060 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007061 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007062 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007063 Undefined.insert(std::make_pair(D, Loc));
7064 }
7065}
Nick Lewycky8334af82013-01-26 00:35:08 +00007066
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007067void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7068 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7069 Exprs) {
7070 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7071 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7072 uint64_t Count = DelayedDeleteExprs[Idx++];
7073 for (uint64_t C = 0; C < Count; ++C) {
7074 SourceLocation DeleteLoc =
7075 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7076 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7077 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7078 }
7079 }
7080}
7081
Guy Benyei11169dd2012-12-18 14:30:41 +00007082void ASTReader::ReadTentativeDefinitions(
7083 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7084 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7085 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7086 if (Var)
7087 TentativeDefs.push_back(Var);
7088 }
7089 TentativeDefinitions.clear();
7090}
7091
7092void ASTReader::ReadUnusedFileScopedDecls(
7093 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7094 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7095 DeclaratorDecl *D
7096 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7097 if (D)
7098 Decls.push_back(D);
7099 }
7100 UnusedFileScopedDecls.clear();
7101}
7102
7103void ASTReader::ReadDelegatingConstructors(
7104 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7105 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7106 CXXConstructorDecl *D
7107 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7108 if (D)
7109 Decls.push_back(D);
7110 }
7111 DelegatingCtorDecls.clear();
7112}
7113
7114void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7115 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7116 TypedefNameDecl *D
7117 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7118 if (D)
7119 Decls.push_back(D);
7120 }
7121 ExtVectorDecls.clear();
7122}
7123
Nico Weber72889432014-09-06 01:25:55 +00007124void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7125 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7126 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7127 ++I) {
7128 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7129 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7130 if (D)
7131 Decls.insert(D);
7132 }
7133 UnusedLocalTypedefNameCandidates.clear();
7134}
7135
Guy Benyei11169dd2012-12-18 14:30:41 +00007136void ASTReader::ReadReferencedSelectors(
7137 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7138 if (ReferencedSelectorsData.empty())
7139 return;
7140
7141 // If there are @selector references added them to its pool. This is for
7142 // implementation of -Wselector.
7143 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7144 unsigned I = 0;
7145 while (I < DataSize) {
7146 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7147 SourceLocation SelLoc
7148 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7149 Sels.push_back(std::make_pair(Sel, SelLoc));
7150 }
7151 ReferencedSelectorsData.clear();
7152}
7153
7154void ASTReader::ReadWeakUndeclaredIdentifiers(
7155 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7156 if (WeakUndeclaredIdentifiers.empty())
7157 return;
7158
7159 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7160 IdentifierInfo *WeakId
7161 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7162 IdentifierInfo *AliasId
7163 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7164 SourceLocation Loc
7165 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7166 bool Used = WeakUndeclaredIdentifiers[I++];
7167 WeakInfo WI(AliasId, Loc);
7168 WI.setUsed(Used);
7169 WeakIDs.push_back(std::make_pair(WeakId, WI));
7170 }
7171 WeakUndeclaredIdentifiers.clear();
7172}
7173
7174void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7175 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7176 ExternalVTableUse VT;
7177 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7178 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7179 VT.DefinitionRequired = VTableUses[Idx++];
7180 VTables.push_back(VT);
7181 }
7182
7183 VTableUses.clear();
7184}
7185
7186void ASTReader::ReadPendingInstantiations(
7187 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7188 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7189 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7190 SourceLocation Loc
7191 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7192
7193 Pending.push_back(std::make_pair(D, Loc));
7194 }
7195 PendingInstantiations.clear();
7196}
7197
Richard Smithe40f2ba2013-08-07 21:41:30 +00007198void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007199 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007200 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7201 /* In loop */) {
7202 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7203
7204 LateParsedTemplate *LT = new LateParsedTemplate;
7205 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7206
7207 ModuleFile *F = getOwningModuleFile(LT->D);
7208 assert(F && "No module");
7209
7210 unsigned TokN = LateParsedTemplates[Idx++];
7211 LT->Toks.reserve(TokN);
7212 for (unsigned T = 0; T < TokN; ++T)
7213 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7214
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007215 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007216 }
7217
7218 LateParsedTemplates.clear();
7219}
7220
Guy Benyei11169dd2012-12-18 14:30:41 +00007221void ASTReader::LoadSelector(Selector Sel) {
7222 // It would be complicated to avoid reading the methods anyway. So don't.
7223 ReadMethodPool(Sel);
7224}
7225
7226void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7227 assert(ID && "Non-zero identifier ID required");
7228 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7229 IdentifiersLoaded[ID - 1] = II;
7230 if (DeserializationListener)
7231 DeserializationListener->IdentifierRead(ID, II);
7232}
7233
7234/// \brief Set the globally-visible declarations associated with the given
7235/// identifier.
7236///
7237/// If the AST reader is currently in a state where the given declaration IDs
7238/// cannot safely be resolved, they are queued until it is safe to resolve
7239/// them.
7240///
7241/// \param II an IdentifierInfo that refers to one or more globally-visible
7242/// declarations.
7243///
7244/// \param DeclIDs the set of declaration IDs with the name @p II that are
7245/// visible at global scope.
7246///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007247/// \param Decls if non-null, this vector will be populated with the set of
7248/// deserialized declarations. These declarations will not be pushed into
7249/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007250void
7251ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7252 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007253 SmallVectorImpl<Decl *> *Decls) {
7254 if (NumCurrentElementsDeserializing && !Decls) {
7255 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007256 return;
7257 }
7258
7259 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007260 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007261 // Queue this declaration so that it will be added to the
7262 // translation unit scope and identifier's declaration chain
7263 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007264 PreloadedDeclIDs.push_back(DeclIDs[I]);
7265 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007266 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007267
7268 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7269
7270 // If we're simply supposed to record the declarations, do so now.
7271 if (Decls) {
7272 Decls->push_back(D);
7273 continue;
7274 }
7275
7276 // Introduce this declaration into the translation-unit scope
7277 // and add it to the declaration chain for this identifier, so
7278 // that (unqualified) name lookup will find it.
7279 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007280 }
7281}
7282
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007283IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007284 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007285 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007286
7287 if (IdentifiersLoaded.empty()) {
7288 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007289 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007290 }
7291
7292 ID -= 1;
7293 if (!IdentifiersLoaded[ID]) {
7294 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7295 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7296 ModuleFile *M = I->second;
7297 unsigned Index = ID - M->BaseIdentifierID;
7298 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7299
7300 // All of the strings in the AST file are preceded by a 16-bit length.
7301 // Extract that 16-bit length to avoid having to execute strlen().
7302 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7303 // unsigned integers. This is important to avoid integer overflow when
7304 // we cast them to 'unsigned'.
7305 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7306 unsigned StrLen = (((unsigned) StrLenPtr[0])
7307 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007308 IdentifiersLoaded[ID]
7309 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007310 if (DeserializationListener)
7311 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7312 }
7313
7314 return IdentifiersLoaded[ID];
7315}
7316
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007317IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7318 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007319}
7320
7321IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7322 if (LocalID < NUM_PREDEF_IDENT_IDS)
7323 return LocalID;
7324
7325 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7326 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7327 assert(I != M.IdentifierRemap.end()
7328 && "Invalid index into identifier index remap");
7329
7330 return LocalID + I->second;
7331}
7332
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007333MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007334 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007335 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007336
7337 if (MacrosLoaded.empty()) {
7338 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007339 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007340 }
7341
7342 ID -= NUM_PREDEF_MACRO_IDS;
7343 if (!MacrosLoaded[ID]) {
7344 GlobalMacroMapType::iterator I
7345 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7346 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7347 ModuleFile *M = I->second;
7348 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007349 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7350
7351 if (DeserializationListener)
7352 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7353 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007354 }
7355
7356 return MacrosLoaded[ID];
7357}
7358
7359MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7360 if (LocalID < NUM_PREDEF_MACRO_IDS)
7361 return LocalID;
7362
7363 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7364 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7365 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7366
7367 return LocalID + I->second;
7368}
7369
7370serialization::SubmoduleID
7371ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7372 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7373 return LocalID;
7374
7375 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7376 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7377 assert(I != M.SubmoduleRemap.end()
7378 && "Invalid index into submodule index remap");
7379
7380 return LocalID + I->second;
7381}
7382
7383Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7384 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7385 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007386 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007387 }
7388
7389 if (GlobalID > SubmodulesLoaded.size()) {
7390 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007391 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007392 }
7393
7394 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7395}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007396
7397Module *ASTReader::getModule(unsigned ID) {
7398 return getSubmodule(ID);
7399}
7400
Adrian Prantl15bcf702015-06-30 17:39:43 +00007401ExternalASTSource::ASTSourceDescriptor
7402ASTReader::getSourceDescriptor(const Module &M) {
7403 StringRef Dir, Filename;
7404 if (M.Directory)
7405 Dir = M.Directory->getName();
7406 if (auto *File = M.getASTFile())
7407 Filename = File->getName();
7408 return ASTReader::ASTSourceDescriptor{
7409 M.getFullModuleName(), Dir, Filename,
7410 M.Signature
7411 };
7412}
7413
7414llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7415ASTReader::getSourceDescriptor(unsigned ID) {
7416 if (const Module *M = getSubmodule(ID))
7417 return getSourceDescriptor(*M);
7418
7419 // If there is only a single PCH, return it instead.
7420 // Chained PCH are not suported.
7421 if (ModuleMgr.size() == 1) {
7422 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7423 return ASTReader::ASTSourceDescriptor{
7424 MF.OriginalSourceFileName, MF.OriginalDir,
7425 MF.FileName,
7426 MF.Signature
7427 };
7428 }
7429 return None;
7430}
7431
Guy Benyei11169dd2012-12-18 14:30:41 +00007432Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7433 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7434}
7435
7436Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7437 if (ID == 0)
7438 return Selector();
7439
7440 if (ID > SelectorsLoaded.size()) {
7441 Error("selector ID out of range in AST file");
7442 return Selector();
7443 }
7444
Craig Toppera13603a2014-05-22 05:54:18 +00007445 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007446 // Load this selector from the selector table.
7447 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7448 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7449 ModuleFile &M = *I->second;
7450 ASTSelectorLookupTrait Trait(*this, M);
7451 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7452 SelectorsLoaded[ID - 1] =
7453 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7454 if (DeserializationListener)
7455 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7456 }
7457
7458 return SelectorsLoaded[ID - 1];
7459}
7460
7461Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7462 return DecodeSelector(ID);
7463}
7464
7465uint32_t ASTReader::GetNumExternalSelectors() {
7466 // ID 0 (the null selector) is considered an external selector.
7467 return getTotalNumSelectors() + 1;
7468}
7469
7470serialization::SelectorID
7471ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7472 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7473 return LocalID;
7474
7475 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7476 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7477 assert(I != M.SelectorRemap.end()
7478 && "Invalid index into selector index remap");
7479
7480 return LocalID + I->second;
7481}
7482
7483DeclarationName
7484ASTReader::ReadDeclarationName(ModuleFile &F,
7485 const RecordData &Record, unsigned &Idx) {
7486 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7487 switch (Kind) {
7488 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007489 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007490
7491 case DeclarationName::ObjCZeroArgSelector:
7492 case DeclarationName::ObjCOneArgSelector:
7493 case DeclarationName::ObjCMultiArgSelector:
7494 return DeclarationName(ReadSelector(F, Record, Idx));
7495
7496 case DeclarationName::CXXConstructorName:
7497 return Context.DeclarationNames.getCXXConstructorName(
7498 Context.getCanonicalType(readType(F, Record, Idx)));
7499
7500 case DeclarationName::CXXDestructorName:
7501 return Context.DeclarationNames.getCXXDestructorName(
7502 Context.getCanonicalType(readType(F, Record, Idx)));
7503
7504 case DeclarationName::CXXConversionFunctionName:
7505 return Context.DeclarationNames.getCXXConversionFunctionName(
7506 Context.getCanonicalType(readType(F, Record, Idx)));
7507
7508 case DeclarationName::CXXOperatorName:
7509 return Context.DeclarationNames.getCXXOperatorName(
7510 (OverloadedOperatorKind)Record[Idx++]);
7511
7512 case DeclarationName::CXXLiteralOperatorName:
7513 return Context.DeclarationNames.getCXXLiteralOperatorName(
7514 GetIdentifierInfo(F, Record, Idx));
7515
7516 case DeclarationName::CXXUsingDirective:
7517 return DeclarationName::getUsingDirectiveName();
7518 }
7519
7520 llvm_unreachable("Invalid NameKind!");
7521}
7522
7523void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7524 DeclarationNameLoc &DNLoc,
7525 DeclarationName Name,
7526 const RecordData &Record, unsigned &Idx) {
7527 switch (Name.getNameKind()) {
7528 case DeclarationName::CXXConstructorName:
7529 case DeclarationName::CXXDestructorName:
7530 case DeclarationName::CXXConversionFunctionName:
7531 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7532 break;
7533
7534 case DeclarationName::CXXOperatorName:
7535 DNLoc.CXXOperatorName.BeginOpNameLoc
7536 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7537 DNLoc.CXXOperatorName.EndOpNameLoc
7538 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7539 break;
7540
7541 case DeclarationName::CXXLiteralOperatorName:
7542 DNLoc.CXXLiteralOperatorName.OpNameLoc
7543 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7544 break;
7545
7546 case DeclarationName::Identifier:
7547 case DeclarationName::ObjCZeroArgSelector:
7548 case DeclarationName::ObjCOneArgSelector:
7549 case DeclarationName::ObjCMultiArgSelector:
7550 case DeclarationName::CXXUsingDirective:
7551 break;
7552 }
7553}
7554
7555void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7556 DeclarationNameInfo &NameInfo,
7557 const RecordData &Record, unsigned &Idx) {
7558 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7559 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7560 DeclarationNameLoc DNLoc;
7561 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7562 NameInfo.setInfo(DNLoc);
7563}
7564
7565void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7566 const RecordData &Record, unsigned &Idx) {
7567 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7568 unsigned NumTPLists = Record[Idx++];
7569 Info.NumTemplParamLists = NumTPLists;
7570 if (NumTPLists) {
7571 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7572 for (unsigned i=0; i != NumTPLists; ++i)
7573 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7574 }
7575}
7576
7577TemplateName
7578ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7579 unsigned &Idx) {
7580 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7581 switch (Kind) {
7582 case TemplateName::Template:
7583 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7584
7585 case TemplateName::OverloadedTemplate: {
7586 unsigned size = Record[Idx++];
7587 UnresolvedSet<8> Decls;
7588 while (size--)
7589 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7590
7591 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7592 }
7593
7594 case TemplateName::QualifiedTemplate: {
7595 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7596 bool hasTemplKeyword = Record[Idx++];
7597 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7598 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7599 }
7600
7601 case TemplateName::DependentTemplate: {
7602 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7603 if (Record[Idx++]) // isIdentifier
7604 return Context.getDependentTemplateName(NNS,
7605 GetIdentifierInfo(F, Record,
7606 Idx));
7607 return Context.getDependentTemplateName(NNS,
7608 (OverloadedOperatorKind)Record[Idx++]);
7609 }
7610
7611 case TemplateName::SubstTemplateTemplateParm: {
7612 TemplateTemplateParmDecl *param
7613 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7614 if (!param) return TemplateName();
7615 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7616 return Context.getSubstTemplateTemplateParm(param, replacement);
7617 }
7618
7619 case TemplateName::SubstTemplateTemplateParmPack: {
7620 TemplateTemplateParmDecl *Param
7621 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7622 if (!Param)
7623 return TemplateName();
7624
7625 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7626 if (ArgPack.getKind() != TemplateArgument::Pack)
7627 return TemplateName();
7628
7629 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7630 }
7631 }
7632
7633 llvm_unreachable("Unhandled template name kind!");
7634}
7635
7636TemplateArgument
7637ASTReader::ReadTemplateArgument(ModuleFile &F,
7638 const RecordData &Record, unsigned &Idx) {
7639 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7640 switch (Kind) {
7641 case TemplateArgument::Null:
7642 return TemplateArgument();
7643 case TemplateArgument::Type:
7644 return TemplateArgument(readType(F, Record, Idx));
7645 case TemplateArgument::Declaration: {
7646 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007647 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007648 }
7649 case TemplateArgument::NullPtr:
7650 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7651 case TemplateArgument::Integral: {
7652 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7653 QualType T = readType(F, Record, Idx);
7654 return TemplateArgument(Context, Value, T);
7655 }
7656 case TemplateArgument::Template:
7657 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7658 case TemplateArgument::TemplateExpansion: {
7659 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007660 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007661 if (unsigned NumExpansions = Record[Idx++])
7662 NumTemplateExpansions = NumExpansions - 1;
7663 return TemplateArgument(Name, NumTemplateExpansions);
7664 }
7665 case TemplateArgument::Expression:
7666 return TemplateArgument(ReadExpr(F));
7667 case TemplateArgument::Pack: {
7668 unsigned NumArgs = Record[Idx++];
7669 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7670 for (unsigned I = 0; I != NumArgs; ++I)
7671 Args[I] = ReadTemplateArgument(F, Record, Idx);
7672 return TemplateArgument(Args, NumArgs);
7673 }
7674 }
7675
7676 llvm_unreachable("Unhandled template argument kind!");
7677}
7678
7679TemplateParameterList *
7680ASTReader::ReadTemplateParameterList(ModuleFile &F,
7681 const RecordData &Record, unsigned &Idx) {
7682 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7683 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7684 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7685
7686 unsigned NumParams = Record[Idx++];
7687 SmallVector<NamedDecl *, 16> Params;
7688 Params.reserve(NumParams);
7689 while (NumParams--)
7690 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7691
7692 TemplateParameterList* TemplateParams =
7693 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7694 Params.data(), Params.size(), RAngleLoc);
7695 return TemplateParams;
7696}
7697
7698void
7699ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007700ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007701 ModuleFile &F, const RecordData &Record,
7702 unsigned &Idx) {
7703 unsigned NumTemplateArgs = Record[Idx++];
7704 TemplArgs.reserve(NumTemplateArgs);
7705 while (NumTemplateArgs--)
7706 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7707}
7708
7709/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007710void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007711 const RecordData &Record, unsigned &Idx) {
7712 unsigned NumDecls = Record[Idx++];
7713 Set.reserve(Context, NumDecls);
7714 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007715 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007716 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007717 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007718 }
7719}
7720
7721CXXBaseSpecifier
7722ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7723 const RecordData &Record, unsigned &Idx) {
7724 bool isVirtual = static_cast<bool>(Record[Idx++]);
7725 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7726 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7727 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7728 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7729 SourceRange Range = ReadSourceRange(F, Record, Idx);
7730 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7731 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7732 EllipsisLoc);
7733 Result.setInheritConstructors(inheritConstructors);
7734 return Result;
7735}
7736
Richard Smithc2bb8182015-03-24 06:36:48 +00007737CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007738ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7739 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007740 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007741 assert(NumInitializers && "wrote ctor initializers but have no inits");
7742 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7743 for (unsigned i = 0; i != NumInitializers; ++i) {
7744 TypeSourceInfo *TInfo = nullptr;
7745 bool IsBaseVirtual = false;
7746 FieldDecl *Member = nullptr;
7747 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007748
Richard Smithc2bb8182015-03-24 06:36:48 +00007749 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7750 switch (Type) {
7751 case CTOR_INITIALIZER_BASE:
7752 TInfo = GetTypeSourceInfo(F, Record, Idx);
7753 IsBaseVirtual = Record[Idx++];
7754 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007755
Richard Smithc2bb8182015-03-24 06:36:48 +00007756 case CTOR_INITIALIZER_DELEGATING:
7757 TInfo = GetTypeSourceInfo(F, Record, Idx);
7758 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007759
Richard Smithc2bb8182015-03-24 06:36:48 +00007760 case CTOR_INITIALIZER_MEMBER:
7761 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7762 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007763
Richard Smithc2bb8182015-03-24 06:36:48 +00007764 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7765 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7766 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007767 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007768
7769 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7770 Expr *Init = ReadExpr(F);
7771 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7772 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7773 bool IsWritten = Record[Idx++];
7774 unsigned SourceOrderOrNumArrayIndices;
7775 SmallVector<VarDecl *, 8> Indices;
7776 if (IsWritten) {
7777 SourceOrderOrNumArrayIndices = Record[Idx++];
7778 } else {
7779 SourceOrderOrNumArrayIndices = Record[Idx++];
7780 Indices.reserve(SourceOrderOrNumArrayIndices);
7781 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7782 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7783 }
7784
7785 CXXCtorInitializer *BOMInit;
7786 if (Type == CTOR_INITIALIZER_BASE) {
7787 BOMInit = new (Context)
7788 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7789 RParenLoc, MemberOrEllipsisLoc);
7790 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7791 BOMInit = new (Context)
7792 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7793 } else if (IsWritten) {
7794 if (Member)
7795 BOMInit = new (Context) CXXCtorInitializer(
7796 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7797 else
7798 BOMInit = new (Context)
7799 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7800 LParenLoc, Init, RParenLoc);
7801 } else {
7802 if (IndirectMember) {
7803 assert(Indices.empty() && "Indirect field improperly initialized");
7804 BOMInit = new (Context)
7805 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7806 LParenLoc, Init, RParenLoc);
7807 } else {
7808 BOMInit = CXXCtorInitializer::Create(
7809 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7810 Indices.data(), Indices.size());
7811 }
7812 }
7813
7814 if (IsWritten)
7815 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7816 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007817 }
7818
Richard Smithc2bb8182015-03-24 06:36:48 +00007819 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007820}
7821
7822NestedNameSpecifier *
7823ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7824 const RecordData &Record, unsigned &Idx) {
7825 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007826 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007827 for (unsigned I = 0; I != N; ++I) {
7828 NestedNameSpecifier::SpecifierKind Kind
7829 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7830 switch (Kind) {
7831 case NestedNameSpecifier::Identifier: {
7832 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7833 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7834 break;
7835 }
7836
7837 case NestedNameSpecifier::Namespace: {
7838 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7839 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7840 break;
7841 }
7842
7843 case NestedNameSpecifier::NamespaceAlias: {
7844 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7845 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7846 break;
7847 }
7848
7849 case NestedNameSpecifier::TypeSpec:
7850 case NestedNameSpecifier::TypeSpecWithTemplate: {
7851 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7852 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007853 return nullptr;
7854
Guy Benyei11169dd2012-12-18 14:30:41 +00007855 bool Template = Record[Idx++];
7856 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7857 break;
7858 }
7859
7860 case NestedNameSpecifier::Global: {
7861 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7862 // No associated value, and there can't be a prefix.
7863 break;
7864 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007865
7866 case NestedNameSpecifier::Super: {
7867 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7868 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7869 break;
7870 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007871 }
7872 Prev = NNS;
7873 }
7874 return NNS;
7875}
7876
7877NestedNameSpecifierLoc
7878ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7879 unsigned &Idx) {
7880 unsigned N = Record[Idx++];
7881 NestedNameSpecifierLocBuilder Builder;
7882 for (unsigned I = 0; I != N; ++I) {
7883 NestedNameSpecifier::SpecifierKind Kind
7884 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7885 switch (Kind) {
7886 case NestedNameSpecifier::Identifier: {
7887 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7888 SourceRange Range = ReadSourceRange(F, Record, Idx);
7889 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7890 break;
7891 }
7892
7893 case NestedNameSpecifier::Namespace: {
7894 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7895 SourceRange Range = ReadSourceRange(F, Record, Idx);
7896 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7897 break;
7898 }
7899
7900 case NestedNameSpecifier::NamespaceAlias: {
7901 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7902 SourceRange Range = ReadSourceRange(F, Record, Idx);
7903 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7904 break;
7905 }
7906
7907 case NestedNameSpecifier::TypeSpec:
7908 case NestedNameSpecifier::TypeSpecWithTemplate: {
7909 bool Template = Record[Idx++];
7910 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7911 if (!T)
7912 return NestedNameSpecifierLoc();
7913 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7914
7915 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7916 Builder.Extend(Context,
7917 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7918 T->getTypeLoc(), ColonColonLoc);
7919 break;
7920 }
7921
7922 case NestedNameSpecifier::Global: {
7923 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7924 Builder.MakeGlobal(Context, ColonColonLoc);
7925 break;
7926 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007927
7928 case NestedNameSpecifier::Super: {
7929 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7930 SourceRange Range = ReadSourceRange(F, Record, Idx);
7931 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7932 break;
7933 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007934 }
7935 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007936
Guy Benyei11169dd2012-12-18 14:30:41 +00007937 return Builder.getWithLocInContext(Context);
7938}
7939
7940SourceRange
7941ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7942 unsigned &Idx) {
7943 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7944 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7945 return SourceRange(beg, end);
7946}
7947
7948/// \brief Read an integral value
7949llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7950 unsigned BitWidth = Record[Idx++];
7951 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7952 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7953 Idx += NumWords;
7954 return Result;
7955}
7956
7957/// \brief Read a signed integral value
7958llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7959 bool isUnsigned = Record[Idx++];
7960 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7961}
7962
7963/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007964llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7965 const llvm::fltSemantics &Sem,
7966 unsigned &Idx) {
7967 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007968}
7969
7970// \brief Read a string
7971std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7972 unsigned Len = Record[Idx++];
7973 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7974 Idx += Len;
7975 return Result;
7976}
7977
Richard Smith7ed1bc92014-12-05 22:42:13 +00007978std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7979 unsigned &Idx) {
7980 std::string Filename = ReadString(Record, Idx);
7981 ResolveImportedPath(F, Filename);
7982 return Filename;
7983}
7984
Guy Benyei11169dd2012-12-18 14:30:41 +00007985VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7986 unsigned &Idx) {
7987 unsigned Major = Record[Idx++];
7988 unsigned Minor = Record[Idx++];
7989 unsigned Subminor = Record[Idx++];
7990 if (Minor == 0)
7991 return VersionTuple(Major);
7992 if (Subminor == 0)
7993 return VersionTuple(Major, Minor - 1);
7994 return VersionTuple(Major, Minor - 1, Subminor - 1);
7995}
7996
7997CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7998 const RecordData &Record,
7999 unsigned &Idx) {
8000 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8001 return CXXTemporary::Create(Context, Decl);
8002}
8003
8004DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008005 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008006}
8007
8008DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8009 return Diags.Report(Loc, DiagID);
8010}
8011
8012/// \brief Retrieve the identifier table associated with the
8013/// preprocessor.
8014IdentifierTable &ASTReader::getIdentifierTable() {
8015 return PP.getIdentifierTable();
8016}
8017
8018/// \brief Record that the given ID maps to the given switch-case
8019/// statement.
8020void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008021 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008022 "Already have a SwitchCase with this ID");
8023 (*CurrSwitchCaseStmts)[ID] = SC;
8024}
8025
8026/// \brief Retrieve the switch-case statement with the given ID.
8027SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008028 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008029 return (*CurrSwitchCaseStmts)[ID];
8030}
8031
8032void ASTReader::ClearSwitchCaseIDs() {
8033 CurrSwitchCaseStmts->clear();
8034}
8035
8036void ASTReader::ReadComments() {
8037 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008038 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008039 serialization::ModuleFile *> >::iterator
8040 I = CommentsCursors.begin(),
8041 E = CommentsCursors.end();
8042 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008043 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008044 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008045 serialization::ModuleFile &F = *I->second;
8046 SavedStreamPosition SavedPosition(Cursor);
8047
8048 RecordData Record;
8049 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008050 llvm::BitstreamEntry Entry =
8051 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008052
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008053 switch (Entry.Kind) {
8054 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8055 case llvm::BitstreamEntry::Error:
8056 Error("malformed block record in AST file");
8057 return;
8058 case llvm::BitstreamEntry::EndBlock:
8059 goto NextCursor;
8060 case llvm::BitstreamEntry::Record:
8061 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008062 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008063 }
8064
8065 // Read a record.
8066 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008067 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008068 case COMMENTS_RAW_COMMENT: {
8069 unsigned Idx = 0;
8070 SourceRange SR = ReadSourceRange(F, Record, Idx);
8071 RawComment::CommentKind Kind =
8072 (RawComment::CommentKind) Record[Idx++];
8073 bool IsTrailingComment = Record[Idx++];
8074 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008075 Comments.push_back(new (Context) RawComment(
8076 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8077 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008078 break;
8079 }
8080 }
8081 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008082 NextCursor:
8083 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008084 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008085}
8086
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008087void ASTReader::getInputFiles(ModuleFile &F,
8088 SmallVectorImpl<serialization::InputFile> &Files) {
8089 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8090 unsigned ID = I+1;
8091 Files.push_back(getInputFile(F, ID));
8092 }
8093}
8094
Richard Smithcd45dbc2014-04-19 03:48:30 +00008095std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8096 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008097 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008098 return M->getFullModuleName();
8099
8100 // Otherwise, use the name of the top-level module the decl is within.
8101 if (ModuleFile *M = getOwningModuleFile(D))
8102 return M->ModuleName;
8103
8104 // Not from a module.
8105 return "";
8106}
8107
Guy Benyei11169dd2012-12-18 14:30:41 +00008108void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008109 while (!PendingIdentifierInfos.empty() ||
8110 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008111 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008112 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008113 // If any identifiers with corresponding top-level declarations have
8114 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008115 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8116 TopLevelDeclsMap;
8117 TopLevelDeclsMap TopLevelDecls;
8118
Guy Benyei11169dd2012-12-18 14:30:41 +00008119 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008120 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008121 SmallVector<uint32_t, 4> DeclIDs =
8122 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008123 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008124
8125 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008126 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008127
Richard Smith851072e2014-05-19 20:59:20 +00008128 // For each decl chain that we wanted to complete while deserializing, mark
8129 // it as "still needs to be completed".
8130 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8131 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8132 }
8133 PendingIncompleteDeclChains.clear();
8134
Guy Benyei11169dd2012-12-18 14:30:41 +00008135 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008136 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008137 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008138 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008139 }
8140 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008141 PendingDeclChains.clear();
8142
Richard Smith9b88a4c2015-07-27 05:40:23 +00008143 assert(RedeclsDeserialized.empty() && "some redecls not wired up");
8144
Douglas Gregor6168bd22013-02-18 15:53:43 +00008145 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008146 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8147 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008148 IdentifierInfo *II = TLD->first;
8149 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008150 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008151 }
8152 }
8153
Guy Benyei11169dd2012-12-18 14:30:41 +00008154 // Load any pending macro definitions.
8155 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008156 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8157 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8158 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8159 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008160 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008161 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008162 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008163 if (Info.M->Kind != MK_ImplicitModule &&
8164 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008165 resolvePendingMacro(II, Info);
8166 }
8167 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008168 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008169 ++IDIdx) {
8170 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008171 if (Info.M->Kind == MK_ImplicitModule ||
8172 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008173 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008174 }
8175 }
8176 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008177
8178 // Wire up the DeclContexts for Decls that we delayed setting until
8179 // recursive loading is completed.
8180 while (!PendingDeclContextInfos.empty()) {
8181 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8182 PendingDeclContextInfos.pop_front();
8183 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8184 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8185 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8186 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008187
Richard Smithd1c46742014-04-30 02:24:17 +00008188 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008189 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008190 auto Update = PendingUpdateRecords.pop_back_val();
8191 ReadingKindTracker ReadingKind(Read_Decl, *this);
8192 loadDeclUpdateRecords(Update.first, Update.second);
8193 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008194 }
Richard Smith8a639892015-01-24 01:07:20 +00008195
8196 // At this point, all update records for loaded decls are in place, so any
8197 // fake class definitions should have become real.
8198 assert(PendingFakeDefinitionData.empty() &&
8199 "faked up a class definition but never saw the real one");
8200
Guy Benyei11169dd2012-12-18 14:30:41 +00008201 // If we deserialized any C++ or Objective-C class definitions, any
8202 // Objective-C protocol definitions, or any redeclarable templates, make sure
8203 // that all redeclarations point to the definitions. Note that this can only
8204 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008205 for (Decl *D : PendingDefinitions) {
8206 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008207 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008208 // Make sure that the TagType points at the definition.
8209 const_cast<TagType*>(TagT)->decl = TD;
8210 }
Richard Smith8ce51082015-03-11 01:44:51 +00008211
Craig Topperc6914d02014-08-25 04:15:02 +00008212 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008213 for (auto *R = getMostRecentExistingDecl(RD); R;
8214 R = R->getPreviousDecl()) {
8215 assert((R == D) ==
8216 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008217 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008218 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008219 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008220 }
8221
8222 continue;
8223 }
Richard Smith8ce51082015-03-11 01:44:51 +00008224
Craig Topperc6914d02014-08-25 04:15:02 +00008225 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008226 // Make sure that the ObjCInterfaceType points at the definition.
8227 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8228 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008229
8230 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8231 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8232
Guy Benyei11169dd2012-12-18 14:30:41 +00008233 continue;
8234 }
Richard Smith8ce51082015-03-11 01:44:51 +00008235
Craig Topperc6914d02014-08-25 04:15:02 +00008236 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008237 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8238 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8239
Guy Benyei11169dd2012-12-18 14:30:41 +00008240 continue;
8241 }
Richard Smith8ce51082015-03-11 01:44:51 +00008242
Craig Topperc6914d02014-08-25 04:15:02 +00008243 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008244 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8245 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008246 }
8247 PendingDefinitions.clear();
8248
8249 // Load the bodies of any functions or methods we've encountered. We do
8250 // this now (delayed) so that we can be sure that the declaration chains
8251 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008252 // FIXME: There seems to be no point in delaying this, it does not depend
8253 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008254 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8255 PBEnd = PendingBodies.end();
8256 PB != PBEnd; ++PB) {
8257 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8258 // FIXME: Check for =delete/=default?
8259 // FIXME: Complain about ODR violations here?
8260 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8261 FD->setLazyBody(PB->second);
8262 continue;
8263 }
8264
8265 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8266 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8267 MD->setLazyBody(PB->second);
8268 }
8269 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008270
8271 // Do some cleanup.
8272 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8273 getContext().deduplicateMergedDefinitonsFor(ND);
8274 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008275}
8276
8277void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008278 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8279 return;
8280
Richard Smitha0ce9c42014-07-29 23:23:27 +00008281 // Trigger the import of the full definition of each class that had any
8282 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008283 // These updates may in turn find and diagnose some ODR failures, so take
8284 // ownership of the set first.
8285 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8286 PendingOdrMergeFailures.clear();
8287 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008288 Merge.first->buildLookup();
8289 Merge.first->decls_begin();
8290 Merge.first->bases_begin();
8291 Merge.first->vbases_begin();
8292 for (auto *RD : Merge.second) {
8293 RD->decls_begin();
8294 RD->bases_begin();
8295 RD->vbases_begin();
8296 }
8297 }
8298
8299 // For each declaration from a merged context, check that the canonical
8300 // definition of that context also contains a declaration of the same
8301 // entity.
8302 //
8303 // Caution: this loop does things that might invalidate iterators into
8304 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8305 while (!PendingOdrMergeChecks.empty()) {
8306 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8307
8308 // FIXME: Skip over implicit declarations for now. This matters for things
8309 // like implicitly-declared special member functions. This isn't entirely
8310 // correct; we can end up with multiple unmerged declarations of the same
8311 // implicit entity.
8312 if (D->isImplicit())
8313 continue;
8314
8315 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008316
8317 bool Found = false;
8318 const Decl *DCanon = D->getCanonicalDecl();
8319
Richard Smith01bdb7a2014-08-28 05:44:07 +00008320 for (auto RI : D->redecls()) {
8321 if (RI->getLexicalDeclContext() == CanonDef) {
8322 Found = true;
8323 break;
8324 }
8325 }
8326 if (Found)
8327 continue;
8328
Richard Smitha0ce9c42014-07-29 23:23:27 +00008329 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008330 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008331 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8332 !Found && I != E; ++I) {
8333 for (auto RI : (*I)->redecls()) {
8334 if (RI->getLexicalDeclContext() == CanonDef) {
8335 // This declaration is present in the canonical definition. If it's
8336 // in the same redecl chain, it's the one we're looking for.
8337 if (RI->getCanonicalDecl() == DCanon)
8338 Found = true;
8339 else
8340 Candidates.push_back(cast<NamedDecl>(RI));
8341 break;
8342 }
8343 }
8344 }
8345
8346 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008347 // The AST doesn't like TagDecls becoming invalid after they've been
8348 // completed. We only really need to mark FieldDecls as invalid here.
8349 if (!isa<TagDecl>(D))
8350 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008351
8352 // Ensure we don't accidentally recursively enter deserialization while
8353 // we're producing our diagnostic.
8354 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008355
8356 std::string CanonDefModule =
8357 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8358 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8359 << D << getOwningModuleNameForDiagnostic(D)
8360 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8361
8362 if (Candidates.empty())
8363 Diag(cast<Decl>(CanonDef)->getLocation(),
8364 diag::note_module_odr_violation_no_possible_decls) << D;
8365 else {
8366 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8367 Diag(Candidates[I]->getLocation(),
8368 diag::note_module_odr_violation_possible_decl)
8369 << Candidates[I];
8370 }
8371
8372 DiagnosedOdrMergeFailures.insert(CanonDef);
8373 }
8374 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008375
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008376 if (OdrMergeFailures.empty())
8377 return;
8378
8379 // Ensure we don't accidentally recursively enter deserialization while
8380 // we're producing our diagnostics.
8381 Deserializing RecursionGuard(this);
8382
Richard Smithcd45dbc2014-04-19 03:48:30 +00008383 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008384 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008385 // If we've already pointed out a specific problem with this class, don't
8386 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008387 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008388 continue;
8389
8390 bool Diagnosed = false;
8391 for (auto *RD : Merge.second) {
8392 // Multiple different declarations got merged together; tell the user
8393 // where they came from.
8394 if (Merge.first != RD) {
8395 // FIXME: Walk the definition, figure out what's different,
8396 // and diagnose that.
8397 if (!Diagnosed) {
8398 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8399 Diag(Merge.first->getLocation(),
8400 diag::err_module_odr_violation_different_definitions)
8401 << Merge.first << Module.empty() << Module;
8402 Diagnosed = true;
8403 }
8404
8405 Diag(RD->getLocation(),
8406 diag::note_module_odr_violation_different_definitions)
8407 << getOwningModuleNameForDiagnostic(RD);
8408 }
8409 }
8410
8411 if (!Diagnosed) {
8412 // All definitions are updates to the same declaration. This happens if a
8413 // module instantiates the declaration of a class template specialization
8414 // and two or more other modules instantiate its definition.
8415 //
8416 // FIXME: Indicate which modules had instantiations of this definition.
8417 // FIXME: How can this even happen?
8418 Diag(Merge.first->getLocation(),
8419 diag::err_module_odr_violation_different_instantiations)
8420 << Merge.first;
8421 }
8422 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008423}
8424
Richard Smithce18a182015-07-14 00:26:00 +00008425void ASTReader::StartedDeserializing() {
8426 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8427 ReadTimer->startTimer();
8428}
8429
Guy Benyei11169dd2012-12-18 14:30:41 +00008430void ASTReader::FinishedDeserializing() {
8431 assert(NumCurrentElementsDeserializing &&
8432 "FinishedDeserializing not paired with StartedDeserializing");
8433 if (NumCurrentElementsDeserializing == 1) {
8434 // We decrease NumCurrentElementsDeserializing only after pending actions
8435 // are finished, to avoid recursively re-calling finishPendingActions().
8436 finishPendingActions();
8437 }
8438 --NumCurrentElementsDeserializing;
8439
Richard Smitha0ce9c42014-07-29 23:23:27 +00008440 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008441 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008442 while (!PendingExceptionSpecUpdates.empty()) {
8443 auto Updates = std::move(PendingExceptionSpecUpdates);
8444 PendingExceptionSpecUpdates.clear();
8445 for (auto Update : Updates) {
8446 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8447 SemaObj->UpdateExceptionSpec(Update.second,
8448 FPT->getExtProtoInfo().ExceptionSpec);
8449 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008450 }
8451
Richard Smitha0ce9c42014-07-29 23:23:27 +00008452 diagnoseOdrViolations();
8453
Richard Smithce18a182015-07-14 00:26:00 +00008454 if (ReadTimer)
8455 ReadTimer->stopTimer();
8456
Richard Smith04d05b52014-03-23 00:27:18 +00008457 // We are not in recursive loading, so it's safe to pass the "interesting"
8458 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008459 if (Consumer)
8460 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008461 }
8462}
8463
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008464void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008465 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8466 // Remove any fake results before adding any real ones.
8467 auto It = PendingFakeLookupResults.find(II);
8468 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008469 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008470 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008471 // FIXME: this works around module+PCH performance issue.
8472 // Rather than erase the result from the map, which is O(n), just clear
8473 // the vector of NamedDecls.
8474 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008475 }
8476 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008477
8478 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8479 SemaObj->TUScope->AddDecl(D);
8480 } else if (SemaObj->TUScope) {
8481 // Adding the decl to IdResolver may have failed because it was already in
8482 // (even though it was not added in scope). If it is already in, make sure
8483 // it gets in the scope as well.
8484 if (std::find(SemaObj->IdResolver.begin(Name),
8485 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8486 SemaObj->TUScope->AddDecl(D);
8487 }
8488}
8489
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008490ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008491 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008492 StringRef isysroot, bool DisableValidation,
8493 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008494 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Richard Smithce18a182015-07-14 00:26:00 +00008495 bool UseGlobalIndex,
8496 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008497 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008498 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008499 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008500 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008501 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008502 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008503 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008504 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8505 AllowConfigurationMismatch(AllowConfigurationMismatch),
8506 ValidateSystemInputs(ValidateSystemInputs),
8507 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008508 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8509 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8510 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8511 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008512 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8513 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8514 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8515 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8516 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8517 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008518 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008519 SourceMgr.setExternalSLocEntrySource(this);
8520}
8521
8522ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008523 if (OwnsDeserializationListener)
8524 delete DeserializationListener;
8525
Guy Benyei11169dd2012-12-18 14:30:41 +00008526 for (DeclContextVisibleUpdatesPending::iterator
8527 I = PendingVisibleUpdates.begin(),
8528 E = PendingVisibleUpdates.end();
8529 I != E; ++I) {
8530 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8531 F = I->second.end();
8532 J != F; ++J)
8533 delete J->first;
8534 }
8535}