blob: c6fe363d7b56079b386557e41de48dce848756d9 [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
947ASTDeclContextNameLookupTrait::data_type
948ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
949 const unsigned char* d,
950 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000951 using namespace llvm::support;
952 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
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
Chris Lattner0e6c9402013-01-20 02:38:54 +0000976 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
977 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 }
979
980 // Now the lookup table.
981 if (Offsets.second != 0) {
982 Cursor.JumpToBit(Offsets.second);
983
984 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000985 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000986 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000987 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000988 if (RecCode != DECL_CONTEXT_VISIBLE) {
989 Error("Expected visible lookup table block");
990 return true;
991 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000992 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
993 (const unsigned char *)Blob.data() + Record[0],
994 (const unsigned char *)Blob.data() + sizeof(uint32_t),
995 (const unsigned char *)Blob.data(),
996 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000997 }
998
999 return false;
1000}
1001
1002void ASTReader::Error(StringRef Msg) {
1003 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001004 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1005 Diag(diag::note_module_cache_path)
1006 << PP.getHeaderSearchInfo().getModuleCachePath();
1007 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001008}
1009
1010void ASTReader::Error(unsigned DiagID,
1011 StringRef Arg1, StringRef Arg2) {
1012 if (Diags.isDiagnosticInFlight())
1013 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1014 else
1015 Diag(DiagID) << Arg1 << Arg2;
1016}
1017
1018//===----------------------------------------------------------------------===//
1019// Source Manager Deserialization
1020//===----------------------------------------------------------------------===//
1021
1022/// \brief Read the line table in the source manager block.
1023/// \returns true if there was an error.
1024bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001025 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001026 unsigned Idx = 0;
1027 LineTableInfo &LineTable = SourceMgr.getLineTable();
1028
1029 // Parse the file names
1030 std::map<int, int> FileIDs;
1031 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1032 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001033 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001034 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1035 }
1036
1037 // Parse the line entries
1038 std::vector<LineEntry> Entries;
1039 while (Idx < Record.size()) {
1040 int FID = Record[Idx++];
1041 assert(FID >= 0 && "Serialized line entries for non-local file.");
1042 // Remap FileID from 1-based old view.
1043 FID += F.SLocEntryBaseID - 1;
1044
1045 // Extract the line entries
1046 unsigned NumEntries = Record[Idx++];
1047 assert(NumEntries && "Numentries is 00000");
1048 Entries.clear();
1049 Entries.reserve(NumEntries);
1050 for (unsigned I = 0; I != NumEntries; ++I) {
1051 unsigned FileOffset = Record[Idx++];
1052 unsigned LineNo = Record[Idx++];
1053 int FilenameID = FileIDs[Record[Idx++]];
1054 SrcMgr::CharacteristicKind FileKind
1055 = (SrcMgr::CharacteristicKind)Record[Idx++];
1056 unsigned IncludeOffset = Record[Idx++];
1057 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1058 FileKind, IncludeOffset));
1059 }
1060 LineTable.AddEntry(FileID::get(FID), Entries);
1061 }
1062
1063 return false;
1064}
1065
1066/// \brief Read a source manager block
1067bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1068 using namespace SrcMgr;
1069
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001070 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001071
1072 // Set the source-location entry cursor to the current position in
1073 // the stream. This cursor will be used to read the contents of the
1074 // source manager block initially, and then lazily read
1075 // source-location entries as needed.
1076 SLocEntryCursor = F.Stream;
1077
1078 // The stream itself is going to skip over the source manager block.
1079 if (F.Stream.SkipBlock()) {
1080 Error("malformed block record in AST file");
1081 return true;
1082 }
1083
1084 // Enter the source manager block.
1085 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1086 Error("malformed source manager block record in AST file");
1087 return true;
1088 }
1089
1090 RecordData Record;
1091 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001092 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1093
1094 switch (E.Kind) {
1095 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1096 case llvm::BitstreamEntry::Error:
1097 Error("malformed block record in AST file");
1098 return true;
1099 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001100 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001101 case llvm::BitstreamEntry::Record:
1102 // The interesting case.
1103 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001105
Guy Benyei11169dd2012-12-18 14:30:41 +00001106 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001107 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001108 StringRef Blob;
1109 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001110 default: // Default behavior: ignore.
1111 break;
1112
1113 case SM_SLOC_FILE_ENTRY:
1114 case SM_SLOC_BUFFER_ENTRY:
1115 case SM_SLOC_EXPANSION_ENTRY:
1116 // Once we hit one of the source location entries, we're done.
1117 return false;
1118 }
1119 }
1120}
1121
1122/// \brief If a header file is not found at the path that we expect it to be
1123/// and the PCH file was moved from its original location, try to resolve the
1124/// file by assuming that header+PCH were moved together and the header is in
1125/// the same place relative to the PCH.
1126static std::string
1127resolveFileRelativeToOriginalDir(const std::string &Filename,
1128 const std::string &OriginalDir,
1129 const std::string &CurrDir) {
1130 assert(OriginalDir != CurrDir &&
1131 "No point trying to resolve the file if the PCH dir didn't change");
1132 using namespace llvm::sys;
1133 SmallString<128> filePath(Filename);
1134 fs::make_absolute(filePath);
1135 assert(path::is_absolute(OriginalDir));
1136 SmallString<128> currPCHPath(CurrDir);
1137
1138 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1139 fileDirE = path::end(path::parent_path(filePath));
1140 path::const_iterator origDirI = path::begin(OriginalDir),
1141 origDirE = path::end(OriginalDir);
1142 // Skip the common path components from filePath and OriginalDir.
1143 while (fileDirI != fileDirE && origDirI != origDirE &&
1144 *fileDirI == *origDirI) {
1145 ++fileDirI;
1146 ++origDirI;
1147 }
1148 for (; origDirI != origDirE; ++origDirI)
1149 path::append(currPCHPath, "..");
1150 path::append(currPCHPath, fileDirI, fileDirE);
1151 path::append(currPCHPath, path::filename(Filename));
1152 return currPCHPath.str();
1153}
1154
1155bool ASTReader::ReadSLocEntry(int ID) {
1156 if (ID == 0)
1157 return false;
1158
1159 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1160 Error("source location entry ID out-of-range for AST file");
1161 return true;
1162 }
1163
1164 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1165 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001166 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001167 unsigned BaseOffset = F->SLocEntryBaseOffset;
1168
1169 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001170 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1171 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001172 Error("incorrectly-formatted source location entry in AST file");
1173 return true;
1174 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001175
Guy Benyei11169dd2012-12-18 14:30:41 +00001176 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001177 StringRef Blob;
1178 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001179 default:
1180 Error("incorrectly-formatted source location entry in AST file");
1181 return true;
1182
1183 case SM_SLOC_FILE_ENTRY: {
1184 // We will detect whether a file changed and return 'Failure' for it, but
1185 // we will also try to fail gracefully by setting up the SLocEntry.
1186 unsigned InputID = Record[4];
1187 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001188 const FileEntry *File = IF.getFile();
1189 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001190
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001191 // Note that we only check if a File was returned. If it was out-of-date
1192 // we have complained but we will continue creating a FileID to recover
1193 // gracefully.
1194 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001195 return true;
1196
1197 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1198 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1199 // This is the module's main file.
1200 IncludeLoc = getImportLocation(F);
1201 }
1202 SrcMgr::CharacteristicKind
1203 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1204 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1205 ID, BaseOffset + Record[0]);
1206 SrcMgr::FileInfo &FileInfo =
1207 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1208 FileInfo.NumCreatedFIDs = Record[5];
1209 if (Record[3])
1210 FileInfo.setHasLineDirectives();
1211
1212 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1213 unsigned NumFileDecls = Record[7];
1214 if (NumFileDecls) {
1215 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1216 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1217 NumFileDecls));
1218 }
1219
1220 const SrcMgr::ContentCache *ContentCache
1221 = SourceMgr.getOrCreateContentCache(File,
1222 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1223 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1224 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1225 unsigned Code = SLocEntryCursor.ReadCode();
1226 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001227 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001228
1229 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1230 Error("AST record has invalid code");
1231 return true;
1232 }
1233
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001234 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001235 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001236 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001237 }
1238
1239 break;
1240 }
1241
1242 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001243 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001244 unsigned Offset = Record[0];
1245 SrcMgr::CharacteristicKind
1246 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1247 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001248 if (IncludeLoc.isInvalid() &&
1249 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001250 IncludeLoc = getImportLocation(F);
1251 }
1252 unsigned Code = SLocEntryCursor.ReadCode();
1253 Record.clear();
1254 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001255 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001256
1257 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1258 Error("AST record has invalid code");
1259 return true;
1260 }
1261
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001262 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1263 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001264 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001265 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001266 break;
1267 }
1268
1269 case SM_SLOC_EXPANSION_ENTRY: {
1270 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1271 SourceMgr.createExpansionLoc(SpellingLoc,
1272 ReadSourceLocation(*F, Record[2]),
1273 ReadSourceLocation(*F, Record[3]),
1274 Record[4],
1275 ID,
1276 BaseOffset + Record[0]);
1277 break;
1278 }
1279 }
1280
1281 return false;
1282}
1283
1284std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1285 if (ID == 0)
1286 return std::make_pair(SourceLocation(), "");
1287
1288 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1289 Error("source location entry ID out-of-range for AST file");
1290 return std::make_pair(SourceLocation(), "");
1291 }
1292
1293 // Find which module file this entry lands in.
1294 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001295 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001296 return std::make_pair(SourceLocation(), "");
1297
1298 // FIXME: Can we map this down to a particular submodule? That would be
1299 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001300 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001301}
1302
1303/// \brief Find the location where the module F is imported.
1304SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1305 if (F->ImportLoc.isValid())
1306 return F->ImportLoc;
1307
1308 // Otherwise we have a PCH. It's considered to be "imported" at the first
1309 // location of its includer.
1310 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001311 // Main file is the importer.
1312 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1313 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001314 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001315 return F->ImportedBy[0]->FirstLoc;
1316}
1317
1318/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1319/// specified cursor. Read the abbreviations that are at the top of the block
1320/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001321bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001322 if (Cursor.EnterSubBlock(BlockID)) {
1323 Error("malformed block record in AST file");
1324 return Failure;
1325 }
1326
1327 while (true) {
1328 uint64_t Offset = Cursor.GetCurrentBitNo();
1329 unsigned Code = Cursor.ReadCode();
1330
1331 // We expect all abbrevs to be at the start of the block.
1332 if (Code != llvm::bitc::DEFINE_ABBREV) {
1333 Cursor.JumpToBit(Offset);
1334 return false;
1335 }
1336 Cursor.ReadAbbrevRecord();
1337 }
1338}
1339
Richard Smithe40f2ba2013-08-07 21:41:30 +00001340Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001341 unsigned &Idx) {
1342 Token Tok;
1343 Tok.startToken();
1344 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1345 Tok.setLength(Record[Idx++]);
1346 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1347 Tok.setIdentifierInfo(II);
1348 Tok.setKind((tok::TokenKind)Record[Idx++]);
1349 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1350 return Tok;
1351}
1352
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001353MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001354 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001355
1356 // Keep track of where we are in the stream, then jump back there
1357 // after reading this macro.
1358 SavedStreamPosition SavedPosition(Stream);
1359
1360 Stream.JumpToBit(Offset);
1361 RecordData Record;
1362 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001363 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001364
Guy Benyei11169dd2012-12-18 14:30:41 +00001365 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001366 // Advance to the next record, but if we get to the end of the block, don't
1367 // pop it (removing all the abbreviations from the cursor) since we want to
1368 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001369 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001370 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1371
1372 switch (Entry.Kind) {
1373 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1374 case llvm::BitstreamEntry::Error:
1375 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001376 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001377 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001378 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001379 case llvm::BitstreamEntry::Record:
1380 // The interesting case.
1381 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001382 }
1383
1384 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001385 Record.clear();
1386 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001387 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001388 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001389 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001390 case PP_MACRO_DIRECTIVE_HISTORY:
1391 return Macro;
1392
Guy Benyei11169dd2012-12-18 14:30:41 +00001393 case PP_MACRO_OBJECT_LIKE:
1394 case PP_MACRO_FUNCTION_LIKE: {
1395 // If we already have a macro, that means that we've hit the end
1396 // of the definition of the macro we were looking for. We're
1397 // done.
1398 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001399 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001400
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001401 unsigned NextIndex = 1; // Skip identifier ID.
1402 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001403 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001404 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001405 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001406 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001407 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001408
Guy Benyei11169dd2012-12-18 14:30:41 +00001409 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1410 // Decode function-like macro info.
1411 bool isC99VarArgs = Record[NextIndex++];
1412 bool isGNUVarArgs = Record[NextIndex++];
1413 bool hasCommaPasting = Record[NextIndex++];
1414 MacroArgs.clear();
1415 unsigned NumArgs = Record[NextIndex++];
1416 for (unsigned i = 0; i != NumArgs; ++i)
1417 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1418
1419 // Install function-like macro info.
1420 MI->setIsFunctionLike();
1421 if (isC99VarArgs) MI->setIsC99Varargs();
1422 if (isGNUVarArgs) MI->setIsGNUVarargs();
1423 if (hasCommaPasting) MI->setHasCommaPasting();
1424 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1425 PP.getPreprocessorAllocator());
1426 }
1427
Guy Benyei11169dd2012-12-18 14:30:41 +00001428 // Remember that we saw this macro last so that we add the tokens that
1429 // form its body to it.
1430 Macro = MI;
1431
1432 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1433 Record[NextIndex]) {
1434 // We have a macro definition. Register the association
1435 PreprocessedEntityID
1436 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1437 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001438 PreprocessingRecord::PPEntityID PPID =
1439 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1440 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1441 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001442 if (PPDef)
1443 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001444 }
1445
1446 ++NumMacrosRead;
1447 break;
1448 }
1449
1450 case PP_TOKEN: {
1451 // If we see a TOKEN before a PP_MACRO_*, then the file is
1452 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001453 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001454
John McCallf413f5e2013-05-03 00:10:13 +00001455 unsigned Idx = 0;
1456 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001457 Macro->AddTokenToBody(Tok);
1458 break;
1459 }
1460 }
1461 }
1462}
1463
1464PreprocessedEntityID
1465ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1466 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1467 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1468 assert(I != M.PreprocessedEntityRemap.end()
1469 && "Invalid index into preprocessed entity index remap");
1470
1471 return LocalID + I->second;
1472}
1473
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001474unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1475 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001476}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001477
Guy Benyei11169dd2012-12-18 14:30:41 +00001478HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001479HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1480 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001481 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001482 return ikey;
1483}
Guy Benyei11169dd2012-12-18 14:30:41 +00001484
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001485bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1486 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001487 return false;
1488
Richard Smith7ed1bc92014-12-05 22:42:13 +00001489 if (llvm::sys::path::is_absolute(a.Filename) &&
1490 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001491 return true;
1492
Guy Benyei11169dd2012-12-18 14:30:41 +00001493 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001494 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001495 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1496 if (!Key.Imported)
1497 return FileMgr.getFile(Key.Filename);
1498
1499 std::string Resolved = Key.Filename;
1500 Reader.ResolveImportedPath(M, Resolved);
1501 return FileMgr.getFile(Resolved);
1502 };
1503
1504 const FileEntry *FEA = GetFile(a);
1505 const FileEntry *FEB = GetFile(b);
1506 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001507}
1508
1509std::pair<unsigned, unsigned>
1510HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001511 using namespace llvm::support;
1512 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001513 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001514 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001515}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001516
1517HeaderFileInfoTrait::internal_key_type
1518HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001519 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001520 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001521 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1522 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001523 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001524 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001525 return ikey;
1526}
1527
Guy Benyei11169dd2012-12-18 14:30:41 +00001528HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001529HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001530 unsigned DataLen) {
1531 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001532 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001533 HeaderFileInfo HFI;
1534 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001535 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1536 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001537 HFI.isImport = (Flags >> 5) & 0x01;
1538 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1539 HFI.DirInfo = (Flags >> 2) & 0x03;
1540 HFI.Resolved = (Flags >> 1) & 0x01;
1541 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001542 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1543 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1544 M, endian::readNext<uint32_t, little, unaligned>(d));
1545 if (unsigned FrameworkOffset =
1546 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001547 // The framework offset is 1 greater than the actual offset,
1548 // since 0 is used as an indicator for "no framework name".
1549 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1550 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1551 }
1552
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001553 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001554 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001555 if (LocalSMID) {
1556 // This header is part of a module. Associate it with the module to enable
1557 // implicit module import.
1558 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1559 Module *Mod = Reader.getSubmodule(GlobalSMID);
1560 HFI.isModuleHeader = true;
1561 FileManager &FileMgr = Reader.getFileManager();
1562 ModuleMap &ModMap =
1563 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001564 // FIXME: This information should be propagated through the
1565 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001566 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001567 std::string Filename = key.Filename;
1568 if (key.Imported)
1569 Reader.ResolveImportedPath(M, Filename);
1570 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001571 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001572 }
1573 }
1574
Guy Benyei11169dd2012-12-18 14:30:41 +00001575 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1576 (void)End;
1577
1578 // This HeaderFileInfo was externally loaded.
1579 HFI.External = true;
1580 return HFI;
1581}
1582
Richard Smithd7329392015-04-21 21:46:32 +00001583void ASTReader::addPendingMacro(IdentifierInfo *II,
1584 ModuleFile *M,
1585 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001586 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1587 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001588}
1589
1590void ASTReader::ReadDefinedMacros() {
1591 // Note that we are loading defined macros.
1592 Deserializing Macros(this);
1593
1594 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1595 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001596 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001597
1598 // If there was no preprocessor block, skip this file.
1599 if (!MacroCursor.getBitStreamReader())
1600 continue;
1601
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001602 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001603 Cursor.JumpToBit((*I)->MacroStartOffset);
1604
1605 RecordData Record;
1606 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001607 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1608
1609 switch (E.Kind) {
1610 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1611 case llvm::BitstreamEntry::Error:
1612 Error("malformed block record in AST file");
1613 return;
1614 case llvm::BitstreamEntry::EndBlock:
1615 goto NextCursor;
1616
1617 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001618 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001619 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001620 default: // Default behavior: ignore.
1621 break;
1622
1623 case PP_MACRO_OBJECT_LIKE:
1624 case PP_MACRO_FUNCTION_LIKE:
1625 getLocalIdentifier(**I, Record[0]);
1626 break;
1627
1628 case PP_TOKEN:
1629 // Ignore tokens.
1630 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001631 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001632 break;
1633 }
1634 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001635 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001636 }
1637}
1638
1639namespace {
1640 /// \brief Visitor class used to look up identifirs in an AST file.
1641 class IdentifierLookupVisitor {
1642 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001643 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001644 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001645 unsigned &NumIdentifierLookups;
1646 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001647 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001648
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001650 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1651 unsigned &NumIdentifierLookups,
1652 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001653 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1654 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001655 NumIdentifierLookups(NumIdentifierLookups),
1656 NumIdentifierLookupHits(NumIdentifierLookupHits),
1657 Found()
1658 {
1659 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001660
1661 static bool visit(ModuleFile &M, void *UserData) {
1662 IdentifierLookupVisitor *This
1663 = static_cast<IdentifierLookupVisitor *>(UserData);
1664
1665 // If we've already searched this module file, skip it now.
1666 if (M.Generation <= This->PriorGeneration)
1667 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001668
Guy Benyei11169dd2012-12-18 14:30:41 +00001669 ASTIdentifierLookupTable *IdTable
1670 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1671 if (!IdTable)
1672 return false;
1673
1674 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1675 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001676 ++This->NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001677 ASTIdentifierLookupTable::iterator Pos =
1678 IdTable->find_hashed(This->Name, This->NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001679 if (Pos == IdTable->end())
1680 return false;
1681
1682 // Dereferencing the iterator has the effect of building the
1683 // IdentifierInfo node and populating it with the various
1684 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001685 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001686 This->Found = *Pos;
1687 return true;
1688 }
1689
1690 // \brief Retrieve the identifier info found within the module
1691 // files.
1692 IdentifierInfo *getIdentifierInfo() const { return Found; }
1693 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001694}
Guy Benyei11169dd2012-12-18 14:30:41 +00001695
1696void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1697 // Note that we are loading an identifier.
1698 Deserializing AnIdentifier(this);
1699
1700 unsigned PriorGeneration = 0;
1701 if (getContext().getLangOpts().Modules)
1702 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001703
1704 // If there is a global index, look there first to determine which modules
1705 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001706 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001707 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001708 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001709 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1710 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001711 }
1712 }
1713
Douglas Gregor7211ac12013-01-25 23:32:03 +00001714 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001715 NumIdentifierLookups,
1716 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001717 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001718 markIdentifierUpToDate(&II);
1719}
1720
1721void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1722 if (!II)
1723 return;
1724
1725 II->setOutOfDate(false);
1726
1727 // Update the generation for this identifier.
1728 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001729 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001730}
1731
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001732void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1733 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001734 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001735
1736 BitstreamCursor &Cursor = M.MacroCursor;
1737 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001738 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001739
Richard Smith713369b2015-04-23 20:40:50 +00001740 struct ModuleMacroRecord {
1741 SubmoduleID SubModID;
1742 MacroInfo *MI;
1743 SmallVector<SubmoduleID, 8> Overrides;
1744 };
1745 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001746
Richard Smithd7329392015-04-21 21:46:32 +00001747 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1748 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1749 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001750 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001751 while (true) {
1752 llvm::BitstreamEntry Entry =
1753 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1754 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1755 Error("malformed block record in AST file");
1756 return;
1757 }
1758
1759 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001760 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001761 case PP_MACRO_DIRECTIVE_HISTORY:
1762 break;
1763
1764 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001765 ModuleMacros.push_back(ModuleMacroRecord());
1766 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001767 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1768 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001769 for (int I = 2, N = Record.size(); I != N; ++I)
1770 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001771 continue;
1772 }
1773
1774 default:
1775 Error("malformed block record in AST file");
1776 return;
1777 }
1778
1779 // We found the macro directive history; that's the last record
1780 // for this macro.
1781 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001782 }
1783
Richard Smithd7329392015-04-21 21:46:32 +00001784 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001785 {
1786 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001787 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001788 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001789 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001790 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001791 Module *Mod = getSubmodule(ModID);
1792 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001793 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001794 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001795 }
1796
1797 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001798 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001799 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001800 }
1801 }
1802
1803 // Don't read the directive history for a module; we don't have anywhere
1804 // to put it.
1805 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1806 return;
1807
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001808 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001809 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001810 unsigned Idx = 0, N = Record.size();
1811 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001812 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001813 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001814 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1815 switch (K) {
1816 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001817 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001818 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001819 break;
1820 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001821 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001822 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001823 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001824 }
1825 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001826 bool isPublic = Record[Idx++];
1827 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1828 break;
1829 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001830
1831 if (!Latest)
1832 Latest = MD;
1833 if (Earliest)
1834 Earliest->setPrevious(MD);
1835 Earliest = MD;
1836 }
1837
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001838 if (Latest)
1839 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001840}
1841
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001842ASTReader::InputFileInfo
1843ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001844 // Go find this input file.
1845 BitstreamCursor &Cursor = F.InputFilesCursor;
1846 SavedStreamPosition SavedPosition(Cursor);
1847 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1848
1849 unsigned Code = Cursor.ReadCode();
1850 RecordData Record;
1851 StringRef Blob;
1852
1853 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1854 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1855 "invalid record type for input file");
1856 (void)Result;
1857
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001858 std::string Filename;
1859 off_t StoredSize;
1860 time_t StoredTime;
1861 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001862
Ben Langmuir198c1682014-03-07 07:27:49 +00001863 assert(Record[0] == ID && "Bogus stored ID or offset");
1864 StoredSize = static_cast<off_t>(Record[1]);
1865 StoredTime = static_cast<time_t>(Record[2]);
1866 Overridden = static_cast<bool>(Record[3]);
1867 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001868 ResolveImportedPath(F, Filename);
1869
Hans Wennborg73945142014-03-14 17:45:06 +00001870 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1871 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001872}
1873
1874std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001875 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00001876}
1877
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001878InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001879 // If this ID is bogus, just return an empty input file.
1880 if (ID == 0 || ID > F.InputFilesLoaded.size())
1881 return InputFile();
1882
1883 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001884 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001885 return F.InputFilesLoaded[ID-1];
1886
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001887 if (F.InputFilesLoaded[ID-1].isNotFound())
1888 return InputFile();
1889
Guy Benyei11169dd2012-12-18 14:30:41 +00001890 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001891 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001892 SavedStreamPosition SavedPosition(Cursor);
1893 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1894
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001895 InputFileInfo FI = readInputFileInfo(F, ID);
1896 off_t StoredSize = FI.StoredSize;
1897 time_t StoredTime = FI.StoredTime;
1898 bool Overridden = FI.Overridden;
1899 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001900
Ben Langmuir198c1682014-03-07 07:27:49 +00001901 const FileEntry *File
1902 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1903 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1904
1905 // If we didn't find the file, resolve it relative to the
1906 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001907 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001908 F.OriginalDir != CurrentDir) {
1909 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1910 F.OriginalDir,
1911 CurrentDir);
1912 if (!Resolved.empty())
1913 File = FileMgr.getFile(Resolved);
1914 }
1915
1916 // For an overridden file, create a virtual file with the stored
1917 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001918 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001919 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1920 }
1921
Craig Toppera13603a2014-05-22 05:54:18 +00001922 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001923 if (Complain) {
1924 std::string ErrorStr = "could not find file '";
1925 ErrorStr += Filename;
1926 ErrorStr += "' referenced by AST file";
1927 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001928 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001929 // Record that we didn't find the file.
1930 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1931 return InputFile();
1932 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001933
Ben Langmuir198c1682014-03-07 07:27:49 +00001934 // Check if there was a request to override the contents of the file
1935 // that was part of the precompiled header. Overridding such a file
1936 // can lead to problems when lexing using the source locations from the
1937 // PCH.
1938 SourceManager &SM = getSourceManager();
1939 if (!Overridden && SM.isFileOverridden(File)) {
1940 if (Complain)
1941 Error(diag::err_fe_pch_file_overridden, Filename);
1942 // After emitting the diagnostic, recover by disabling the override so
1943 // that the original file will be used.
1944 SM.disableFileContentsOverride(File);
1945 // The FileEntry is a virtual file entry with the size of the contents
1946 // that would override the original contents. Set it to the original's
1947 // size/time.
1948 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1949 StoredSize, StoredTime);
1950 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001951
Ben Langmuir198c1682014-03-07 07:27:49 +00001952 bool IsOutOfDate = false;
1953
1954 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001955 if (!Overridden && //
1956 (StoredSize != File->getSize() ||
1957#if defined(LLVM_ON_WIN32)
1958 false
1959#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001960 // In our regression testing, the Windows file system seems to
1961 // have inconsistent modification times that sometimes
1962 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001963 //
1964 // This also happens in networked file systems, so disable this
1965 // check if validation is disabled or if we have an explicitly
1966 // built PCM file.
1967 //
1968 // FIXME: Should we also do this for PCH files? They could also
1969 // reasonably get shared across a network during a distributed build.
1970 (StoredTime != File->getModificationTime() && !DisableValidation &&
1971 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001972#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001973 )) {
1974 if (Complain) {
1975 // Build a list of the PCH imports that got us here (in reverse).
1976 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1977 while (ImportStack.back()->ImportedBy.size() > 0)
1978 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001979
Ben Langmuir198c1682014-03-07 07:27:49 +00001980 // The top-level PCH is stale.
1981 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1982 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00001983
Ben Langmuir198c1682014-03-07 07:27:49 +00001984 // Print the import stack.
1985 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1986 Diag(diag::note_pch_required_by)
1987 << Filename << ImportStack[0]->FileName;
1988 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00001989 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00001990 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00001991 }
1992
Ben Langmuir198c1682014-03-07 07:27:49 +00001993 if (!Diags.isDiagnosticInFlight())
1994 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00001995 }
1996
Ben Langmuir198c1682014-03-07 07:27:49 +00001997 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001998 }
1999
Ben Langmuir198c1682014-03-07 07:27:49 +00002000 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2001
2002 // Note that we've loaded this input file.
2003 F.InputFilesLoaded[ID-1] = IF;
2004 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002005}
2006
Richard Smith7ed1bc92014-12-05 22:42:13 +00002007/// \brief If we are loading a relocatable PCH or module file, and the filename
2008/// is not an absolute path, add the system or module root to the beginning of
2009/// the file name.
2010void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2011 // Resolve relative to the base directory, if we have one.
2012 if (!M.BaseDirectory.empty())
2013 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002014}
2015
Richard Smith7ed1bc92014-12-05 22:42:13 +00002016void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002017 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2018 return;
2019
Richard Smith7ed1bc92014-12-05 22:42:13 +00002020 SmallString<128> Buffer;
2021 llvm::sys::path::append(Buffer, Prefix, Filename);
2022 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002023}
2024
2025ASTReader::ASTReadResult
2026ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002027 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002028 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002029 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002030 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002031
2032 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2033 Error("malformed block record in AST file");
2034 return Failure;
2035 }
2036
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002037 // Should we allow the configuration of the module file to differ from the
2038 // configuration of the current translation unit in a compatible way?
2039 //
2040 // FIXME: Allow this for files explicitly specified with -include-pch too.
2041 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2042
Guy Benyei11169dd2012-12-18 14:30:41 +00002043 // Read all of the records and blocks in the control block.
2044 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002045 unsigned NumInputs = 0;
2046 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002047 while (1) {
2048 llvm::BitstreamEntry Entry = Stream.advance();
2049
2050 switch (Entry.Kind) {
2051 case llvm::BitstreamEntry::Error:
2052 Error("malformed block record in AST file");
2053 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002054 case llvm::BitstreamEntry::EndBlock: {
2055 // Validate input files.
2056 const HeaderSearchOptions &HSOpts =
2057 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002058
Richard Smitha1825302014-10-23 22:18:29 +00002059 // All user input files reside at the index range [0, NumUserInputs), and
2060 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002061 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002062 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002063
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002064 // If we are reading a module, we will create a verification timestamp,
2065 // so we verify all input files. Otherwise, verify only user input
2066 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002067
2068 unsigned N = NumUserInputs;
2069 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002070 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002071 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002072 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002073 N = NumInputs;
2074
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002075 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002076 InputFile IF = getInputFile(F, I+1, Complain);
2077 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002078 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002079 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002080 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002081
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002082 if (Listener)
2083 Listener->visitModuleFile(F.FileName);
2084
Ben Langmuircb69b572014-03-07 06:40:32 +00002085 if (Listener && Listener->needsInputFileVisitation()) {
2086 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2087 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002088 for (unsigned I = 0; I < N; ++I) {
2089 bool IsSystem = I >= NumUserInputs;
2090 InputFileInfo FI = readInputFileInfo(F, I+1);
2091 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2092 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002093 }
2094
Guy Benyei11169dd2012-12-18 14:30:41 +00002095 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002096 }
2097
Chris Lattnere7b154b2013-01-19 21:39:22 +00002098 case llvm::BitstreamEntry::SubBlock:
2099 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002100 case INPUT_FILES_BLOCK_ID:
2101 F.InputFilesCursor = Stream;
2102 if (Stream.SkipBlock() || // Skip with the main cursor
2103 // Read the abbreviations
2104 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2105 Error("malformed block record in AST file");
2106 return Failure;
2107 }
2108 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002109
Guy Benyei11169dd2012-12-18 14:30:41 +00002110 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002111 if (Stream.SkipBlock()) {
2112 Error("malformed block record in AST file");
2113 return Failure;
2114 }
2115 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002116 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002117
2118 case llvm::BitstreamEntry::Record:
2119 // The interesting case.
2120 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002121 }
2122
2123 // Read and process a record.
2124 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002125 StringRef Blob;
2126 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002127 case METADATA: {
2128 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2129 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002130 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2131 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002132 return VersionMismatch;
2133 }
2134
2135 bool hasErrors = Record[5];
2136 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2137 Diag(diag::err_pch_with_compiler_errors);
2138 return HadErrors;
2139 }
2140
2141 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002142 // Relative paths in a relocatable PCH are relative to our sysroot.
2143 if (F.RelocatablePCH)
2144 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002145
2146 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002147 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002148 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2149 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002150 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002151 return VersionMismatch;
2152 }
2153 break;
2154 }
2155
Ben Langmuir487ea142014-10-23 18:05:36 +00002156 case SIGNATURE:
2157 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2158 F.Signature = Record[0];
2159 break;
2160
Guy Benyei11169dd2012-12-18 14:30:41 +00002161 case IMPORTS: {
2162 // Load each of the imported PCH files.
2163 unsigned Idx = 0, N = Record.size();
2164 while (Idx < N) {
2165 // Read information about the AST file.
2166 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2167 // The import location will be the local one for now; we will adjust
2168 // all import locations of module imports after the global source
2169 // location info are setup.
2170 SourceLocation ImportLoc =
2171 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002172 off_t StoredSize = (off_t)Record[Idx++];
2173 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002174 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002175 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002176
2177 // Load the AST file.
2178 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002179 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002180 ClientLoadCapabilities)) {
2181 case Failure: return Failure;
2182 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002183 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002184 case OutOfDate: return OutOfDate;
2185 case VersionMismatch: return VersionMismatch;
2186 case ConfigurationMismatch: return ConfigurationMismatch;
2187 case HadErrors: return HadErrors;
2188 case Success: break;
2189 }
2190 }
2191 break;
2192 }
2193
Richard Smith7f330cd2015-03-18 01:42:29 +00002194 case KNOWN_MODULE_FILES:
2195 break;
2196
Guy Benyei11169dd2012-12-18 14:30:41 +00002197 case LANGUAGE_OPTIONS: {
2198 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002199 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002200 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002201 ParseLanguageOptions(Record, Complain, *Listener,
2202 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002203 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002204 return ConfigurationMismatch;
2205 break;
2206 }
2207
2208 case TARGET_OPTIONS: {
2209 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2210 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002211 ParseTargetOptions(Record, Complain, *Listener,
2212 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002213 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002214 return ConfigurationMismatch;
2215 break;
2216 }
2217
2218 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002219 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002220 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002221 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002222 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002223 !DisableValidation)
2224 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002225 break;
2226 }
2227
2228 case FILE_SYSTEM_OPTIONS: {
2229 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2230 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002231 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002232 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002233 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002234 return ConfigurationMismatch;
2235 break;
2236 }
2237
2238 case HEADER_SEARCH_OPTIONS: {
2239 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2240 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002241 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002242 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002243 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002244 return ConfigurationMismatch;
2245 break;
2246 }
2247
2248 case PREPROCESSOR_OPTIONS: {
2249 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2250 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002251 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002252 ParsePreprocessorOptions(Record, Complain, *Listener,
2253 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002254 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002255 return ConfigurationMismatch;
2256 break;
2257 }
2258
2259 case ORIGINAL_FILE:
2260 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002261 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002262 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002263 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002264 break;
2265
2266 case ORIGINAL_FILE_ID:
2267 F.OriginalSourceFileID = FileID::get(Record[0]);
2268 break;
2269
2270 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002271 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002272 break;
2273
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002274 case MODULE_NAME:
2275 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002276 if (Listener)
2277 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002278 break;
2279
Richard Smith223d3f22014-12-06 03:21:08 +00002280 case MODULE_DIRECTORY: {
2281 assert(!F.ModuleName.empty() &&
2282 "MODULE_DIRECTORY found before MODULE_NAME");
2283 // If we've already loaded a module map file covering this module, we may
2284 // have a better path for it (relative to the current build).
2285 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2286 if (M && M->Directory) {
2287 // If we're implicitly loading a module, the base directory can't
2288 // change between the build and use.
2289 if (F.Kind != MK_ExplicitModule) {
2290 const DirectoryEntry *BuildDir =
2291 PP.getFileManager().getDirectory(Blob);
2292 if (!BuildDir || BuildDir != M->Directory) {
2293 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2294 Diag(diag::err_imported_module_relocated)
2295 << F.ModuleName << Blob << M->Directory->getName();
2296 return OutOfDate;
2297 }
2298 }
2299 F.BaseDirectory = M->Directory->getName();
2300 } else {
2301 F.BaseDirectory = Blob;
2302 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002303 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002304 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002305
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002306 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002307 if (ASTReadResult Result =
2308 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2309 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002310 break;
2311
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002312 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002313 NumInputs = Record[0];
2314 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002315 F.InputFileOffsets =
2316 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002317 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002318 break;
2319 }
2320 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002321}
2322
Ben Langmuir2c9af442014-04-10 17:57:43 +00002323ASTReader::ASTReadResult
2324ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002325 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002326
2327 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2328 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002329 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002330 }
2331
2332 // Read all of the records and blocks for the AST file.
2333 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002334 while (1) {
2335 llvm::BitstreamEntry Entry = Stream.advance();
2336
2337 switch (Entry.Kind) {
2338 case llvm::BitstreamEntry::Error:
2339 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002340 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002341 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002342 // Outside of C++, we do not store a lookup map for the translation unit.
2343 // Instead, mark it as needing a lookup map to be built if this module
2344 // contains any declarations lexically within it (which it always does!).
2345 // This usually has no cost, since we very rarely need the lookup map for
2346 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002347 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002348 if (DC->hasExternalLexicalStorage() &&
2349 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002350 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002351
Ben Langmuir2c9af442014-04-10 17:57:43 +00002352 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002354 case llvm::BitstreamEntry::SubBlock:
2355 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002356 case DECLTYPES_BLOCK_ID:
2357 // We lazily load the decls block, but we want to set up the
2358 // DeclsCursor cursor to point into it. Clone our current bitcode
2359 // cursor to it, enter the block and read the abbrevs in that block.
2360 // With the main cursor, we just skip over it.
2361 F.DeclsCursor = Stream;
2362 if (Stream.SkipBlock() || // Skip with the main cursor.
2363 // Read the abbrevs.
2364 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2365 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002366 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002367 }
2368 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002369
Guy Benyei11169dd2012-12-18 14:30:41 +00002370 case PREPROCESSOR_BLOCK_ID:
2371 F.MacroCursor = Stream;
2372 if (!PP.getExternalSource())
2373 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002374
Guy Benyei11169dd2012-12-18 14:30:41 +00002375 if (Stream.SkipBlock() ||
2376 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2377 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002378 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002379 }
2380 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2381 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002382
Guy Benyei11169dd2012-12-18 14:30:41 +00002383 case PREPROCESSOR_DETAIL_BLOCK_ID:
2384 F.PreprocessorDetailCursor = Stream;
2385 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002386 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002387 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002388 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002389 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002390 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002391 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002392 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2393
Guy Benyei11169dd2012-12-18 14:30:41 +00002394 if (!PP.getPreprocessingRecord())
2395 PP.createPreprocessingRecord();
2396 if (!PP.getPreprocessingRecord()->getExternalSource())
2397 PP.getPreprocessingRecord()->SetExternalSource(*this);
2398 break;
2399
2400 case SOURCE_MANAGER_BLOCK_ID:
2401 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002402 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002404
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002406 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2407 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002408 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002409
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002411 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 if (Stream.SkipBlock() ||
2413 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2414 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002415 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002416 }
2417 CommentsCursors.push_back(std::make_pair(C, &F));
2418 break;
2419 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002420
Guy Benyei11169dd2012-12-18 14:30:41 +00002421 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002422 if (Stream.SkipBlock()) {
2423 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002424 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002425 }
2426 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002427 }
2428 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002429
2430 case llvm::BitstreamEntry::Record:
2431 // The interesting case.
2432 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002433 }
2434
2435 // Read and process a record.
2436 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002437 StringRef Blob;
2438 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002439 default: // Default behavior: ignore.
2440 break;
2441
2442 case TYPE_OFFSET: {
2443 if (F.LocalNumTypes != 0) {
2444 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002445 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002446 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002447 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002448 F.LocalNumTypes = Record[0];
2449 unsigned LocalBaseTypeIndex = Record[1];
2450 F.BaseTypeIndex = getTotalNumTypes();
2451
2452 if (F.LocalNumTypes > 0) {
2453 // Introduce the global -> local mapping for types within this module.
2454 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2455
2456 // Introduce the local -> global mapping for types within this module.
2457 F.TypeRemap.insertOrReplace(
2458 std::make_pair(LocalBaseTypeIndex,
2459 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002460
2461 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002462 }
2463 break;
2464 }
2465
2466 case DECL_OFFSET: {
2467 if (F.LocalNumDecls != 0) {
2468 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002469 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002470 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002471 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 F.LocalNumDecls = Record[0];
2473 unsigned LocalBaseDeclID = Record[1];
2474 F.BaseDeclID = getTotalNumDecls();
2475
2476 if (F.LocalNumDecls > 0) {
2477 // Introduce the global -> local mapping for declarations within this
2478 // module.
2479 GlobalDeclMap.insert(
2480 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2481
2482 // Introduce the local -> global mapping for declarations within this
2483 // module.
2484 F.DeclRemap.insertOrReplace(
2485 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2486
2487 // Introduce the global -> local mapping for declarations within this
2488 // module.
2489 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002490
Ben Langmuir52ca6782014-10-20 16:27:32 +00002491 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2492 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 break;
2494 }
2495
2496 case TU_UPDATE_LEXICAL: {
2497 DeclContext *TU = Context.getTranslationUnitDecl();
2498 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002499 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002500 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002501 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 TU->setHasExternalLexicalStorage(true);
2503 break;
2504 }
2505
2506 case UPDATE_VISIBLE: {
2507 unsigned Idx = 0;
2508 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2509 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002510 ASTDeclContextNameLookupTable::Create(
2511 (const unsigned char *)Blob.data() + Record[Idx++],
2512 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2513 (const unsigned char *)Blob.data(),
2514 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002515 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002516 auto *DC = cast<DeclContext>(D);
2517 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002518 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2519 delete LookupTable;
2520 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002521 } else
2522 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2523 break;
2524 }
2525
2526 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002527 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002528 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002529 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2530 (const unsigned char *)F.IdentifierTableData + Record[0],
2531 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2532 (const unsigned char *)F.IdentifierTableData,
2533 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002534
2535 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2536 }
2537 break;
2538
2539 case IDENTIFIER_OFFSET: {
2540 if (F.LocalNumIdentifiers != 0) {
2541 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002542 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002543 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002544 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002545 F.LocalNumIdentifiers = Record[0];
2546 unsigned LocalBaseIdentifierID = Record[1];
2547 F.BaseIdentifierID = getTotalNumIdentifiers();
2548
2549 if (F.LocalNumIdentifiers > 0) {
2550 // Introduce the global -> local mapping for identifiers within this
2551 // module.
2552 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2553 &F));
2554
2555 // Introduce the local -> global mapping for identifiers within this
2556 // module.
2557 F.IdentifierRemap.insertOrReplace(
2558 std::make_pair(LocalBaseIdentifierID,
2559 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002560
Ben Langmuir52ca6782014-10-20 16:27:32 +00002561 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2562 + F.LocalNumIdentifiers);
2563 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 break;
2565 }
2566
Richard Smith33e0f7e2015-07-22 02:08:40 +00002567 case INTERESTING_IDENTIFIERS:
2568 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2569 break;
2570
Ben Langmuir332aafe2014-01-31 01:06:56 +00002571 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002572 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2573 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002575 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 break;
2577
2578 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002579 if (SpecialTypes.empty()) {
2580 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2581 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2582 break;
2583 }
2584
2585 if (SpecialTypes.size() != Record.size()) {
2586 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002587 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002588 }
2589
2590 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2591 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2592 if (!SpecialTypes[I])
2593 SpecialTypes[I] = ID;
2594 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2595 // merge step?
2596 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 break;
2598
2599 case STATISTICS:
2600 TotalNumStatements += Record[0];
2601 TotalNumMacros += Record[1];
2602 TotalLexicalDeclContexts += Record[2];
2603 TotalVisibleDeclContexts += Record[3];
2604 break;
2605
2606 case UNUSED_FILESCOPED_DECLS:
2607 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2608 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2609 break;
2610
2611 case DELEGATING_CTORS:
2612 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2613 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2614 break;
2615
2616 case WEAK_UNDECLARED_IDENTIFIERS:
2617 if (Record.size() % 4 != 0) {
2618 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002619 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 }
2621
2622 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2623 // files. This isn't the way to do it :)
2624 WeakUndeclaredIdentifiers.clear();
2625
2626 // Translate the weak, undeclared identifiers into global IDs.
2627 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2628 WeakUndeclaredIdentifiers.push_back(
2629 getGlobalIdentifierID(F, Record[I++]));
2630 WeakUndeclaredIdentifiers.push_back(
2631 getGlobalIdentifierID(F, Record[I++]));
2632 WeakUndeclaredIdentifiers.push_back(
2633 ReadSourceLocation(F, Record, I).getRawEncoding());
2634 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2635 }
2636 break;
2637
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002639 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 F.LocalNumSelectors = Record[0];
2641 unsigned LocalBaseSelectorID = Record[1];
2642 F.BaseSelectorID = getTotalNumSelectors();
2643
2644 if (F.LocalNumSelectors > 0) {
2645 // Introduce the global -> local mapping for selectors within this
2646 // module.
2647 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2648
2649 // Introduce the local -> global mapping for selectors within this
2650 // module.
2651 F.SelectorRemap.insertOrReplace(
2652 std::make_pair(LocalBaseSelectorID,
2653 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002654
2655 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 }
2657 break;
2658 }
2659
2660 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002661 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002662 if (Record[0])
2663 F.SelectorLookupTable
2664 = ASTSelectorLookupTable::Create(
2665 F.SelectorLookupTableData + Record[0],
2666 F.SelectorLookupTableData,
2667 ASTSelectorLookupTrait(*this, F));
2668 TotalNumMethodPoolEntries += Record[1];
2669 break;
2670
2671 case REFERENCED_SELECTOR_POOL:
2672 if (!Record.empty()) {
2673 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2674 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2675 Record[Idx++]));
2676 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2677 getRawEncoding());
2678 }
2679 }
2680 break;
2681
2682 case PP_COUNTER_VALUE:
2683 if (!Record.empty() && Listener)
2684 Listener->ReadCounter(F, Record[0]);
2685 break;
2686
2687 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002688 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 F.NumFileSortedDecls = Record[0];
2690 break;
2691
2692 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002693 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 F.LocalNumSLocEntries = Record[0];
2695 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002696 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002697 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 SLocSpaceSize);
2699 // Make our entry in the range map. BaseID is negative and growing, so
2700 // we invert it. Because we invert it, though, we need the other end of
2701 // the range.
2702 unsigned RangeStart =
2703 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2704 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2705 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2706
2707 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2708 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2709 GlobalSLocOffsetMap.insert(
2710 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2711 - SLocSpaceSize,&F));
2712
2713 // Initialize the remapping table.
2714 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002715 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002717 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002718 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2719
2720 TotalNumSLocEntries += F.LocalNumSLocEntries;
2721 break;
2722 }
2723
2724 case MODULE_OFFSET_MAP: {
2725 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002726 const unsigned char *Data = (const unsigned char*)Blob.data();
2727 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002728
2729 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2730 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2731 F.SLocRemap.insert(std::make_pair(0U, 0));
2732 F.SLocRemap.insert(std::make_pair(2U, 1));
2733 }
2734
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002736 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2737 RemapBuilder;
2738 RemapBuilder SLocRemap(F.SLocRemap);
2739 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2740 RemapBuilder MacroRemap(F.MacroRemap);
2741 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2742 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2743 RemapBuilder SelectorRemap(F.SelectorRemap);
2744 RemapBuilder DeclRemap(F.DeclRemap);
2745 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002746
2747 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002748 using namespace llvm::support;
2749 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002750 StringRef Name = StringRef((const char*)Data, Len);
2751 Data += Len;
2752 ModuleFile *OM = ModuleMgr.lookup(Name);
2753 if (!OM) {
2754 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002755 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002756 }
2757
Justin Bogner57ba0b22014-03-28 22:03:24 +00002758 uint32_t SLocOffset =
2759 endian::readNext<uint32_t, little, unaligned>(Data);
2760 uint32_t IdentifierIDOffset =
2761 endian::readNext<uint32_t, little, unaligned>(Data);
2762 uint32_t MacroIDOffset =
2763 endian::readNext<uint32_t, little, unaligned>(Data);
2764 uint32_t PreprocessedEntityIDOffset =
2765 endian::readNext<uint32_t, little, unaligned>(Data);
2766 uint32_t SubmoduleIDOffset =
2767 endian::readNext<uint32_t, little, unaligned>(Data);
2768 uint32_t SelectorIDOffset =
2769 endian::readNext<uint32_t, little, unaligned>(Data);
2770 uint32_t DeclIDOffset =
2771 endian::readNext<uint32_t, little, unaligned>(Data);
2772 uint32_t TypeIndexOffset =
2773 endian::readNext<uint32_t, little, unaligned>(Data);
2774
Ben Langmuir785180e2014-10-20 16:27:30 +00002775 uint32_t None = std::numeric_limits<uint32_t>::max();
2776
2777 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2778 RemapBuilder &Remap) {
2779 if (Offset != None)
2780 Remap.insert(std::make_pair(Offset,
2781 static_cast<int>(BaseOffset - Offset)));
2782 };
2783 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2784 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2785 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2786 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2787 PreprocessedEntityRemap);
2788 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2789 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2790 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2791 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002792
2793 // Global -> local mappings.
2794 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2795 }
2796 break;
2797 }
2798
2799 case SOURCE_MANAGER_LINE_TABLE:
2800 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002801 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002802 break;
2803
2804 case SOURCE_LOCATION_PRELOADS: {
2805 // Need to transform from the local view (1-based IDs) to the global view,
2806 // which is based off F.SLocEntryBaseID.
2807 if (!F.PreloadSLocEntries.empty()) {
2808 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002809 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002810 }
2811
2812 F.PreloadSLocEntries.swap(Record);
2813 break;
2814 }
2815
2816 case EXT_VECTOR_DECLS:
2817 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2818 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2819 break;
2820
2821 case VTABLE_USES:
2822 if (Record.size() % 3 != 0) {
2823 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002824 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002825 }
2826
2827 // Later tables overwrite earlier ones.
2828 // FIXME: Modules will have some trouble with this. This is clearly not
2829 // the right way to do this.
2830 VTableUses.clear();
2831
2832 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2833 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2834 VTableUses.push_back(
2835 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2836 VTableUses.push_back(Record[Idx++]);
2837 }
2838 break;
2839
Guy Benyei11169dd2012-12-18 14:30:41 +00002840 case PENDING_IMPLICIT_INSTANTIATIONS:
2841 if (PendingInstantiations.size() % 2 != 0) {
2842 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002843 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002844 }
2845
2846 if (Record.size() % 2 != 0) {
2847 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002848 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002849 }
2850
2851 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2852 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2853 PendingInstantiations.push_back(
2854 ReadSourceLocation(F, Record, I).getRawEncoding());
2855 }
2856 break;
2857
2858 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002859 if (Record.size() != 2) {
2860 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002861 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002862 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002863 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2864 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2865 break;
2866
2867 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002868 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2869 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2870 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002871
2872 unsigned LocalBasePreprocessedEntityID = Record[0];
2873
2874 unsigned StartingID;
2875 if (!PP.getPreprocessingRecord())
2876 PP.createPreprocessingRecord();
2877 if (!PP.getPreprocessingRecord()->getExternalSource())
2878 PP.getPreprocessingRecord()->SetExternalSource(*this);
2879 StartingID
2880 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002881 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002882 F.BasePreprocessedEntityID = StartingID;
2883
2884 if (F.NumPreprocessedEntities > 0) {
2885 // Introduce the global -> local mapping for preprocessed entities in
2886 // this module.
2887 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2888
2889 // Introduce the local -> global mapping for preprocessed entities in
2890 // this module.
2891 F.PreprocessedEntityRemap.insertOrReplace(
2892 std::make_pair(LocalBasePreprocessedEntityID,
2893 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2894 }
2895
2896 break;
2897 }
2898
2899 case DECL_UPDATE_OFFSETS: {
2900 if (Record.size() % 2 != 0) {
2901 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002902 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002903 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002904 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2905 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2906 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2907
2908 // If we've already loaded the decl, perform the updates when we finish
2909 // loading this block.
2910 if (Decl *D = GetExistingDecl(ID))
2911 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2912 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002913 break;
2914 }
2915
2916 case DECL_REPLACEMENTS: {
2917 if (Record.size() % 3 != 0) {
2918 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002919 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002920 }
2921 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2922 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2923 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2924 break;
2925 }
2926
2927 case OBJC_CATEGORIES_MAP: {
2928 if (F.LocalNumObjCCategoriesInMap != 0) {
2929 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002930 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002931 }
2932
2933 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002934 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002935 break;
2936 }
2937
2938 case OBJC_CATEGORIES:
2939 F.ObjCCategories.swap(Record);
2940 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00002941
Guy Benyei11169dd2012-12-18 14:30:41 +00002942 case CXX_BASE_SPECIFIER_OFFSETS: {
2943 if (F.LocalNumCXXBaseSpecifiers != 0) {
2944 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002945 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002946 }
Richard Smithc2bb8182015-03-24 06:36:48 +00002947
Guy Benyei11169dd2012-12-18 14:30:41 +00002948 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002949 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00002950 break;
2951 }
2952
2953 case CXX_CTOR_INITIALIZERS_OFFSETS: {
2954 if (F.LocalNumCXXCtorInitializers != 0) {
2955 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2956 return Failure;
2957 }
2958
2959 F.LocalNumCXXCtorInitializers = Record[0];
2960 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002961 break;
2962 }
2963
2964 case DIAG_PRAGMA_MAPPINGS:
2965 if (F.PragmaDiagMappings.empty())
2966 F.PragmaDiagMappings.swap(Record);
2967 else
2968 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2969 Record.begin(), Record.end());
2970 break;
2971
2972 case CUDA_SPECIAL_DECL_REFS:
2973 // Later tables overwrite earlier ones.
2974 // FIXME: Modules will have trouble with this.
2975 CUDASpecialDeclRefs.clear();
2976 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2977 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2978 break;
2979
2980 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002981 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002982 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002983 if (Record[0]) {
2984 F.HeaderFileInfoTable
2985 = HeaderFileInfoLookupTable::Create(
2986 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2987 (const unsigned char *)F.HeaderFileInfoTableData,
2988 HeaderFileInfoTrait(*this, F,
2989 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002990 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002991
2992 PP.getHeaderSearchInfo().SetExternalSource(this);
2993 if (!PP.getHeaderSearchInfo().getExternalLookup())
2994 PP.getHeaderSearchInfo().SetExternalLookup(this);
2995 }
2996 break;
2997 }
2998
2999 case FP_PRAGMA_OPTIONS:
3000 // Later tables overwrite earlier ones.
3001 FPPragmaOptions.swap(Record);
3002 break;
3003
3004 case OPENCL_EXTENSIONS:
3005 // Later tables overwrite earlier ones.
3006 OpenCLExtensions.swap(Record);
3007 break;
3008
3009 case TENTATIVE_DEFINITIONS:
3010 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3011 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3012 break;
3013
3014 case KNOWN_NAMESPACES:
3015 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3016 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3017 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003018
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003019 case UNDEFINED_BUT_USED:
3020 if (UndefinedButUsed.size() % 2 != 0) {
3021 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003022 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003023 }
3024
3025 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003026 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003027 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003028 }
3029 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003030 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3031 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003032 ReadSourceLocation(F, Record, I).getRawEncoding());
3033 }
3034 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003035 case DELETE_EXPRS_TO_ANALYZE:
3036 for (unsigned I = 0, N = Record.size(); I != N;) {
3037 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3038 const uint64_t Count = Record[I++];
3039 DelayedDeleteExprs.push_back(Count);
3040 for (uint64_t C = 0; C < Count; ++C) {
3041 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3042 bool IsArrayForm = Record[I++] == 1;
3043 DelayedDeleteExprs.push_back(IsArrayForm);
3044 }
3045 }
3046 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003047
Guy Benyei11169dd2012-12-18 14:30:41 +00003048 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003049 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003050 // If we aren't loading a module (which has its own exports), make
3051 // all of the imported modules visible.
3052 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003053 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3054 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3055 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3056 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003057 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003058 }
3059 }
3060 break;
3061 }
3062
3063 case LOCAL_REDECLARATIONS: {
3064 F.RedeclarationChains.swap(Record);
3065 break;
3066 }
3067
3068 case LOCAL_REDECLARATIONS_MAP: {
3069 if (F.LocalNumRedeclarationsInMap != 0) {
3070 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003071 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003072 }
3073
3074 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003075 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 break;
3077 }
3078
Guy Benyei11169dd2012-12-18 14:30:41 +00003079 case MACRO_OFFSET: {
3080 if (F.LocalNumMacros != 0) {
3081 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003082 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003083 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003084 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003085 F.LocalNumMacros = Record[0];
3086 unsigned LocalBaseMacroID = Record[1];
3087 F.BaseMacroID = getTotalNumMacros();
3088
3089 if (F.LocalNumMacros > 0) {
3090 // Introduce the global -> local mapping for macros within this module.
3091 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3092
3093 // Introduce the local -> global mapping for macros within this module.
3094 F.MacroRemap.insertOrReplace(
3095 std::make_pair(LocalBaseMacroID,
3096 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003097
3098 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003099 }
3100 break;
3101 }
3102
Richard Smithe40f2ba2013-08-07 21:41:30 +00003103 case LATE_PARSED_TEMPLATE: {
3104 LateParsedTemplates.append(Record.begin(), Record.end());
3105 break;
3106 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003107
3108 case OPTIMIZE_PRAGMA_OPTIONS:
3109 if (Record.size() != 1) {
3110 Error("invalid pragma optimize record");
3111 return Failure;
3112 }
3113 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3114 break;
Nico Weber72889432014-09-06 01:25:55 +00003115
3116 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3117 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3118 UnusedLocalTypedefNameCandidates.push_back(
3119 getGlobalDeclID(F, Record[I]));
3120 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003121 }
3122 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003123}
3124
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003125ASTReader::ASTReadResult
3126ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3127 const ModuleFile *ImportedBy,
3128 unsigned ClientLoadCapabilities) {
3129 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003130 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003131
Richard Smithe842a472014-10-22 02:05:46 +00003132 if (F.Kind == MK_ExplicitModule) {
3133 // For an explicitly-loaded module, we don't care whether the original
3134 // module map file exists or matches.
3135 return Success;
3136 }
3137
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003138 // Try to resolve ModuleName in the current header search context and
3139 // verify that it is found in the same module map file as we saved. If the
3140 // top-level AST file is a main file, skip this check because there is no
3141 // usable header search context.
3142 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003143 "MODULE_NAME should come before MODULE_MAP_FILE");
3144 if (F.Kind == MK_ImplicitModule &&
3145 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3146 // An implicitly-loaded module file should have its module listed in some
3147 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003148 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003149 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3150 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3151 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003152 assert(ImportedBy && "top-level import should be verified");
3153 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003154 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3155 << ImportedBy->FileName
3156 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003157 return Missing;
3158 }
3159
Richard Smithe842a472014-10-22 02:05:46 +00003160 assert(M->Name == F.ModuleName && "found module with different name");
3161
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003162 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003163 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003164 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3165 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003166 assert(ImportedBy && "top-level import should be verified");
3167 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3168 Diag(diag::err_imported_module_modmap_changed)
3169 << F.ModuleName << ImportedBy->FileName
3170 << ModMap->getName() << F.ModuleMapPath;
3171 return OutOfDate;
3172 }
3173
3174 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3175 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3176 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003177 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003178 const FileEntry *F =
3179 FileMgr.getFile(Filename, false, false);
3180 if (F == nullptr) {
3181 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3182 Error("could not find file '" + Filename +"' referenced by AST file");
3183 return OutOfDate;
3184 }
3185 AdditionalStoredMaps.insert(F);
3186 }
3187
3188 // Check any additional module map files (e.g. module.private.modulemap)
3189 // that are not in the pcm.
3190 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3191 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3192 // Remove files that match
3193 // Note: SmallPtrSet::erase is really remove
3194 if (!AdditionalStoredMaps.erase(ModMap)) {
3195 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3196 Diag(diag::err_module_different_modmap)
3197 << F.ModuleName << /*new*/0 << ModMap->getName();
3198 return OutOfDate;
3199 }
3200 }
3201 }
3202
3203 // Check any additional module map files that are in the pcm, but not
3204 // found in header search. Cases that match are already removed.
3205 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3206 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3207 Diag(diag::err_module_different_modmap)
3208 << F.ModuleName << /*not new*/1 << ModMap->getName();
3209 return OutOfDate;
3210 }
3211 }
3212
3213 if (Listener)
3214 Listener->ReadModuleMapFile(F.ModuleMapPath);
3215 return Success;
3216}
3217
3218
Douglas Gregorc1489562013-02-12 23:36:21 +00003219/// \brief Move the given method to the back of the global list of methods.
3220static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3221 // Find the entry for this selector in the method pool.
3222 Sema::GlobalMethodPool::iterator Known
3223 = S.MethodPool.find(Method->getSelector());
3224 if (Known == S.MethodPool.end())
3225 return;
3226
3227 // Retrieve the appropriate method list.
3228 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3229 : Known->second.second;
3230 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003231 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003232 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003233 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003234 Found = true;
3235 } else {
3236 // Keep searching.
3237 continue;
3238 }
3239 }
3240
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003241 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003242 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003243 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003244 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003245 }
3246}
3247
Richard Smithde711422015-04-23 21:20:19 +00003248void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003249 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003250 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003251 bool wasHidden = D->Hidden;
3252 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003253
Richard Smith49f906a2014-03-01 00:08:04 +00003254 if (wasHidden && SemaObj) {
3255 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3256 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003257 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003258 }
3259 }
3260}
3261
Richard Smith49f906a2014-03-01 00:08:04 +00003262void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003263 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003264 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003265 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003266 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003267 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003268 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003269 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003270
3271 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003272 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003273 // there is nothing more to do.
3274 continue;
3275 }
Richard Smith49f906a2014-03-01 00:08:04 +00003276
Guy Benyei11169dd2012-12-18 14:30:41 +00003277 if (!Mod->isAvailable()) {
3278 // Modules that aren't available cannot be made visible.
3279 continue;
3280 }
3281
3282 // Update the module's name visibility.
3283 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003284
Guy Benyei11169dd2012-12-18 14:30:41 +00003285 // If we've already deserialized any names from this module,
3286 // mark them as visible.
3287 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3288 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003289 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003290 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003291 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003292 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3293 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003294 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003295
Guy Benyei11169dd2012-12-18 14:30:41 +00003296 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003297 SmallVector<Module *, 16> Exports;
3298 Mod->getExportedModules(Exports);
3299 for (SmallVectorImpl<Module *>::iterator
3300 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3301 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003302 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003303 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003304 }
3305 }
3306}
3307
Douglas Gregore060e572013-01-25 01:03:03 +00003308bool ASTReader::loadGlobalIndex() {
3309 if (GlobalIndex)
3310 return false;
3311
3312 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3313 !Context.getLangOpts().Modules)
3314 return true;
3315
3316 // Try to load the global index.
3317 TriedLoadingGlobalIndex = true;
3318 StringRef ModuleCachePath
3319 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3320 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003321 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003322 if (!Result.first)
3323 return true;
3324
3325 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003326 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003327 return false;
3328}
3329
3330bool ASTReader::isGlobalIndexUnavailable() const {
3331 return Context.getLangOpts().Modules && UseGlobalIndex &&
3332 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3333}
3334
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003335static void updateModuleTimestamp(ModuleFile &MF) {
3336 // Overwrite the timestamp file contents so that file's mtime changes.
3337 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003338 std::error_code EC;
3339 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3340 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003341 return;
3342 OS << "Timestamp file\n";
3343}
3344
Guy Benyei11169dd2012-12-18 14:30:41 +00003345ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3346 ModuleKind Type,
3347 SourceLocation ImportLoc,
3348 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003349 llvm::SaveAndRestore<SourceLocation>
3350 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3351
Richard Smithd1c46742014-04-30 02:24:17 +00003352 // Defer any pending actions until we get to the end of reading the AST file.
3353 Deserializing AnASTFile(this);
3354
Guy Benyei11169dd2012-12-18 14:30:41 +00003355 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003356 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003357
3358 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003359 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003360 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003361 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003362 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003363 ClientLoadCapabilities)) {
3364 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003365 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003366 case OutOfDate:
3367 case VersionMismatch:
3368 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003369 case HadErrors: {
3370 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3371 for (const ImportedModule &IM : Loaded)
3372 LoadedSet.insert(IM.Mod);
3373
Douglas Gregor7029ce12013-03-19 00:28:20 +00003374 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003375 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003376 Context.getLangOpts().Modules
3377 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003378 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003379
3380 // If we find that any modules are unusable, the global index is going
3381 // to be out-of-date. Just remove it.
3382 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003383 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003384 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003385 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003386 case Success:
3387 break;
3388 }
3389
3390 // Here comes stuff that we only do once the entire chain is loaded.
3391
3392 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003393 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3394 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003395 M != MEnd; ++M) {
3396 ModuleFile &F = *M->Mod;
3397
3398 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003399 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3400 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003401
3402 // Once read, set the ModuleFile bit base offset and update the size in
3403 // bits of all files we've seen.
3404 F.GlobalBitOffset = TotalModulesSizeInBits;
3405 TotalModulesSizeInBits += F.SizeInBits;
3406 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3407
3408 // Preload SLocEntries.
3409 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3410 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3411 // Load it through the SourceManager and don't call ReadSLocEntry()
3412 // directly because the entry may have already been loaded in which case
3413 // calling ReadSLocEntry() directly would trigger an assertion in
3414 // SourceManager.
3415 SourceMgr.getLoadedSLocEntryByID(Index);
3416 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003417
3418 // Preload all the pending interesting identifiers by marking them out of
3419 // date.
3420 for (auto Offset : F.PreloadIdentifierOffsets) {
3421 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3422 F.IdentifierTableData + Offset);
3423
3424 ASTIdentifierLookupTrait Trait(*this, F);
3425 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3426 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3427 PP.getIdentifierTable().getOwn(Key).setOutOfDate(true);
3428 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003429 }
3430
Douglas Gregor603cd862013-03-22 18:50:14 +00003431 // Setup the import locations and notify the module manager that we've
3432 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003433 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3434 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003435 M != MEnd; ++M) {
3436 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003437
3438 ModuleMgr.moduleFileAccepted(&F);
3439
3440 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003441 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003442 if (!M->ImportedBy)
3443 F.ImportLoc = M->ImportLoc;
3444 else
3445 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3446 M->ImportLoc.getRawEncoding());
3447 }
3448
Richard Smith33e0f7e2015-07-22 02:08:40 +00003449 if (!Context.getLangOpts().CPlusPlus ||
3450 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3451 // Mark all of the identifiers in the identifier table as being out of date,
3452 // so that various accessors know to check the loaded modules when the
3453 // identifier is used.
3454 //
3455 // For C++ modules, we don't need information on many identifiers (just
3456 // those that provide macros or are poisoned), so we mark all of
3457 // the interesting ones via PreloadIdentifierOffsets.
3458 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3459 IdEnd = PP.getIdentifierTable().end();
3460 Id != IdEnd; ++Id)
3461 Id->second->setOutOfDate(true);
3462 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003463
3464 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003465 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3466 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003467 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3468 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003469
3470 switch (Unresolved.Kind) {
3471 case UnresolvedModuleRef::Conflict:
3472 if (ResolvedMod) {
3473 Module::Conflict Conflict;
3474 Conflict.Other = ResolvedMod;
3475 Conflict.Message = Unresolved.String.str();
3476 Unresolved.Mod->Conflicts.push_back(Conflict);
3477 }
3478 continue;
3479
3480 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003481 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003482 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003483 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003484
Douglas Gregorfb912652013-03-20 21:10:35 +00003485 case UnresolvedModuleRef::Export:
3486 if (ResolvedMod || Unresolved.IsWildcard)
3487 Unresolved.Mod->Exports.push_back(
3488 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3489 continue;
3490 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003491 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003492 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003493
3494 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3495 // Might be unnecessary as use declarations are only used to build the
3496 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003497
3498 InitializeContext();
3499
Richard Smith3d8e97e2013-10-18 06:54:39 +00003500 if (SemaObj)
3501 UpdateSema();
3502
Guy Benyei11169dd2012-12-18 14:30:41 +00003503 if (DeserializationListener)
3504 DeserializationListener->ReaderInitialized(this);
3505
3506 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3507 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3508 PrimaryModule.OriginalSourceFileID
3509 = FileID::get(PrimaryModule.SLocEntryBaseID
3510 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3511
3512 // If this AST file is a precompiled preamble, then set the
3513 // preamble file ID of the source manager to the file source file
3514 // from which the preamble was built.
3515 if (Type == MK_Preamble) {
3516 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3517 } else if (Type == MK_MainFile) {
3518 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3519 }
3520 }
3521
3522 // For any Objective-C class definitions we have already loaded, make sure
3523 // that we load any additional categories.
3524 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3525 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3526 ObjCClassesLoaded[I],
3527 PreviousGeneration);
3528 }
Douglas Gregore060e572013-01-25 01:03:03 +00003529
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003530 if (PP.getHeaderSearchInfo()
3531 .getHeaderSearchOpts()
3532 .ModulesValidateOncePerBuildSession) {
3533 // Now we are certain that the module and all modules it depends on are
3534 // up to date. Create or update timestamp files for modules that are
3535 // located in the module cache (not for PCH files that could be anywhere
3536 // in the filesystem).
3537 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3538 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003539 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003540 updateModuleTimestamp(*M.Mod);
3541 }
3542 }
3543 }
3544
Guy Benyei11169dd2012-12-18 14:30:41 +00003545 return Success;
3546}
3547
Ben Langmuir487ea142014-10-23 18:05:36 +00003548static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3549
Ben Langmuir70a1b812015-03-24 04:43:52 +00003550/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3551static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3552 return Stream.Read(8) == 'C' &&
3553 Stream.Read(8) == 'P' &&
3554 Stream.Read(8) == 'C' &&
3555 Stream.Read(8) == 'H';
3556}
3557
Guy Benyei11169dd2012-12-18 14:30:41 +00003558ASTReader::ASTReadResult
3559ASTReader::ReadASTCore(StringRef FileName,
3560 ModuleKind Type,
3561 SourceLocation ImportLoc,
3562 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003563 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003564 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003565 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003566 unsigned ClientLoadCapabilities) {
3567 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003568 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003569 ModuleManager::AddModuleResult AddResult
3570 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003571 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003572 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003573 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003574
Douglas Gregor7029ce12013-03-19 00:28:20 +00003575 switch (AddResult) {
3576 case ModuleManager::AlreadyLoaded:
3577 return Success;
3578
3579 case ModuleManager::NewlyLoaded:
3580 // Load module file below.
3581 break;
3582
3583 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003584 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003585 // it.
3586 if (ClientLoadCapabilities & ARR_Missing)
3587 return Missing;
3588
3589 // Otherwise, return an error.
3590 {
3591 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3592 + ErrorStr;
3593 Error(Msg);
3594 }
3595 return Failure;
3596
3597 case ModuleManager::OutOfDate:
3598 // We couldn't load the module file because it is out-of-date. If the
3599 // client can handle out-of-date, return it.
3600 if (ClientLoadCapabilities & ARR_OutOfDate)
3601 return OutOfDate;
3602
3603 // Otherwise, return an error.
3604 {
3605 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3606 + ErrorStr;
3607 Error(Msg);
3608 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003609 return Failure;
3610 }
3611
Douglas Gregor7029ce12013-03-19 00:28:20 +00003612 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003613
3614 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3615 // module?
3616 if (FileName != "-") {
3617 CurrentDir = llvm::sys::path::parent_path(FileName);
3618 if (CurrentDir.empty()) CurrentDir = ".";
3619 }
3620
3621 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003622 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003623 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003624 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003625 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3626
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003628 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003629 Diag(diag::err_not_a_pch_file) << FileName;
3630 return Failure;
3631 }
3632
3633 // This is used for compatibility with older PCH formats.
3634 bool HaveReadControlBlock = false;
3635
Chris Lattnerefa77172013-01-20 00:00:22 +00003636 while (1) {
3637 llvm::BitstreamEntry Entry = Stream.advance();
3638
3639 switch (Entry.Kind) {
3640 case llvm::BitstreamEntry::Error:
3641 case llvm::BitstreamEntry::EndBlock:
3642 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003643 Error("invalid record at top-level of AST file");
3644 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003645
3646 case llvm::BitstreamEntry::SubBlock:
3647 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003648 }
3649
Guy Benyei11169dd2012-12-18 14:30:41 +00003650 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003651 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003652 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3653 if (Stream.ReadBlockInfoBlock()) {
3654 Error("malformed BlockInfoBlock in AST file");
3655 return Failure;
3656 }
3657 break;
3658 case CONTROL_BLOCK_ID:
3659 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003660 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003661 case Success:
3662 break;
3663
3664 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003665 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003666 case OutOfDate: return OutOfDate;
3667 case VersionMismatch: return VersionMismatch;
3668 case ConfigurationMismatch: return ConfigurationMismatch;
3669 case HadErrors: return HadErrors;
3670 }
3671 break;
3672 case AST_BLOCK_ID:
3673 if (!HaveReadControlBlock) {
3674 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003675 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003676 return VersionMismatch;
3677 }
3678
3679 // Record that we've loaded this module.
3680 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3681 return Success;
3682
3683 default:
3684 if (Stream.SkipBlock()) {
3685 Error("malformed block record in AST file");
3686 return Failure;
3687 }
3688 break;
3689 }
3690 }
3691
3692 return Success;
3693}
3694
Richard Smitha7e2cc62015-05-01 01:53:09 +00003695void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003696 // If there's a listener, notify them that we "read" the translation unit.
3697 if (DeserializationListener)
3698 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3699 Context.getTranslationUnitDecl());
3700
Guy Benyei11169dd2012-12-18 14:30:41 +00003701 // FIXME: Find a better way to deal with collisions between these
3702 // built-in types. Right now, we just ignore the problem.
3703
3704 // Load the special types.
3705 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3706 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3707 if (!Context.CFConstantStringTypeDecl)
3708 Context.setCFConstantStringType(GetType(String));
3709 }
3710
3711 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3712 QualType FileType = GetType(File);
3713 if (FileType.isNull()) {
3714 Error("FILE type is NULL");
3715 return;
3716 }
3717
3718 if (!Context.FILEDecl) {
3719 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3720 Context.setFILEDecl(Typedef->getDecl());
3721 else {
3722 const TagType *Tag = FileType->getAs<TagType>();
3723 if (!Tag) {
3724 Error("Invalid FILE type in AST file");
3725 return;
3726 }
3727 Context.setFILEDecl(Tag->getDecl());
3728 }
3729 }
3730 }
3731
3732 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3733 QualType Jmp_bufType = GetType(Jmp_buf);
3734 if (Jmp_bufType.isNull()) {
3735 Error("jmp_buf type is NULL");
3736 return;
3737 }
3738
3739 if (!Context.jmp_bufDecl) {
3740 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3741 Context.setjmp_bufDecl(Typedef->getDecl());
3742 else {
3743 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3744 if (!Tag) {
3745 Error("Invalid jmp_buf type in AST file");
3746 return;
3747 }
3748 Context.setjmp_bufDecl(Tag->getDecl());
3749 }
3750 }
3751 }
3752
3753 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3754 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3755 if (Sigjmp_bufType.isNull()) {
3756 Error("sigjmp_buf type is NULL");
3757 return;
3758 }
3759
3760 if (!Context.sigjmp_bufDecl) {
3761 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3762 Context.setsigjmp_bufDecl(Typedef->getDecl());
3763 else {
3764 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3765 assert(Tag && "Invalid sigjmp_buf type in AST file");
3766 Context.setsigjmp_bufDecl(Tag->getDecl());
3767 }
3768 }
3769 }
3770
3771 if (unsigned ObjCIdRedef
3772 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3773 if (Context.ObjCIdRedefinitionType.isNull())
3774 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3775 }
3776
3777 if (unsigned ObjCClassRedef
3778 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3779 if (Context.ObjCClassRedefinitionType.isNull())
3780 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3781 }
3782
3783 if (unsigned ObjCSelRedef
3784 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3785 if (Context.ObjCSelRedefinitionType.isNull())
3786 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3787 }
3788
3789 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3790 QualType Ucontext_tType = GetType(Ucontext_t);
3791 if (Ucontext_tType.isNull()) {
3792 Error("ucontext_t type is NULL");
3793 return;
3794 }
3795
3796 if (!Context.ucontext_tDecl) {
3797 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3798 Context.setucontext_tDecl(Typedef->getDecl());
3799 else {
3800 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3801 assert(Tag && "Invalid ucontext_t type in AST file");
3802 Context.setucontext_tDecl(Tag->getDecl());
3803 }
3804 }
3805 }
3806 }
3807
3808 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3809
3810 // If there were any CUDA special declarations, deserialize them.
3811 if (!CUDASpecialDeclRefs.empty()) {
3812 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3813 Context.setcudaConfigureCallDecl(
3814 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3815 }
Richard Smith56be7542014-03-21 00:33:59 +00003816
Guy Benyei11169dd2012-12-18 14:30:41 +00003817 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003818 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003819 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003820 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003821 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003822 /*ImportLoc=*/Import.ImportLoc);
3823 PP.makeModuleVisible(Imported, Import.ImportLoc);
3824 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003825 }
3826 ImportedModules.clear();
3827}
3828
3829void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003830 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003831}
3832
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003833/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3834/// cursor into the start of the given block ID, returning false on success and
3835/// true on failure.
3836static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003837 while (1) {
3838 llvm::BitstreamEntry Entry = Cursor.advance();
3839 switch (Entry.Kind) {
3840 case llvm::BitstreamEntry::Error:
3841 case llvm::BitstreamEntry::EndBlock:
3842 return true;
3843
3844 case llvm::BitstreamEntry::Record:
3845 // Ignore top-level records.
3846 Cursor.skipRecord(Entry.ID);
3847 break;
3848
3849 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003850 if (Entry.ID == BlockID) {
3851 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003852 return true;
3853 // Found it!
3854 return false;
3855 }
3856
3857 if (Cursor.SkipBlock())
3858 return true;
3859 }
3860 }
3861}
3862
Ben Langmuir70a1b812015-03-24 04:43:52 +00003863/// \brief Reads and return the signature record from \p StreamFile's control
3864/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003865static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3866 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003867 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003868 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003869
3870 // Scan for the CONTROL_BLOCK_ID block.
3871 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3872 return 0;
3873
3874 // Scan for SIGNATURE inside the control block.
3875 ASTReader::RecordData Record;
3876 while (1) {
3877 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3878 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3879 Entry.Kind != llvm::BitstreamEntry::Record)
3880 return 0;
3881
3882 Record.clear();
3883 StringRef Blob;
3884 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3885 return Record[0];
3886 }
3887}
3888
Guy Benyei11169dd2012-12-18 14:30:41 +00003889/// \brief Retrieve the name of the original source file name
3890/// directly from the AST file, without actually loading the AST
3891/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003892std::string ASTReader::getOriginalSourceFile(
3893 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003894 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003895 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00003896 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00003897 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00003898 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3899 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00003900 return std::string();
3901 }
3902
3903 // Initialize the stream
3904 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003905 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003906 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003907
3908 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003909 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003910 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3911 return std::string();
3912 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003913
Chris Lattnere7b154b2013-01-19 21:39:22 +00003914 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003915 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003916 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3917 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003918 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003919
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003920 // Scan for ORIGINAL_FILE inside the control block.
3921 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003922 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003923 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003924 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3925 return std::string();
3926
3927 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3928 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3929 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003930 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003931
Guy Benyei11169dd2012-12-18 14:30:41 +00003932 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003933 StringRef Blob;
3934 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3935 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003936 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003937}
3938
3939namespace {
3940 class SimplePCHValidator : public ASTReaderListener {
3941 const LangOptions &ExistingLangOpts;
3942 const TargetOptions &ExistingTargetOpts;
3943 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003944 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00003945 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003946
Guy Benyei11169dd2012-12-18 14:30:41 +00003947 public:
3948 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3949 const TargetOptions &ExistingTargetOpts,
3950 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003951 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00003952 FileManager &FileMgr)
3953 : ExistingLangOpts(ExistingLangOpts),
3954 ExistingTargetOpts(ExistingTargetOpts),
3955 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003956 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00003957 FileMgr(FileMgr)
3958 {
3959 }
3960
Richard Smith1e2cf0d2014-10-31 02:28:58 +00003961 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
3962 bool AllowCompatibleDifferences) override {
3963 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
3964 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003965 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00003966 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
3967 bool AllowCompatibleDifferences) override {
3968 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
3969 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003970 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003971 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
3972 StringRef SpecificModuleCachePath,
3973 bool Complain) override {
3974 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
3975 ExistingModuleCachePath,
3976 nullptr, ExistingLangOpts);
3977 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003978 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3979 bool Complain,
3980 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00003981 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003982 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003983 }
3984 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003985}
Guy Benyei11169dd2012-12-18 14:30:41 +00003986
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003987bool ASTReader::readASTFileControlBlock(
3988 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003989 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003990 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003991 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00003992 // FIXME: This allows use of the VFS; we do not allow use of the
3993 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00003994 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00003995 if (!Buffer) {
3996 return true;
3997 }
3998
3999 // Initialize the stream
4000 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004001 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004002 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004003
4004 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004005 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004006 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004007
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004008 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004009 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004010 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004011
4012 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004013 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004014 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004015 BitstreamCursor InputFilesCursor;
4016 if (NeedsInputFiles) {
4017 InputFilesCursor = Stream;
4018 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4019 return true;
4020
4021 // Read the abbreviations
4022 while (true) {
4023 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4024 unsigned Code = InputFilesCursor.ReadCode();
4025
4026 // We expect all abbrevs to be at the start of the block.
4027 if (Code != llvm::bitc::DEFINE_ABBREV) {
4028 InputFilesCursor.JumpToBit(Offset);
4029 break;
4030 }
4031 InputFilesCursor.ReadAbbrevRecord();
4032 }
4033 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004034
4035 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004036 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004037 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004038 while (1) {
4039 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4040 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4041 return false;
4042
4043 if (Entry.Kind != llvm::BitstreamEntry::Record)
4044 return true;
4045
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004047 StringRef Blob;
4048 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004049 switch ((ControlRecordTypes)RecCode) {
4050 case METADATA: {
4051 if (Record[0] != VERSION_MAJOR)
4052 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004053
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004054 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004055 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004056
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004057 break;
4058 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004059 case MODULE_NAME:
4060 Listener.ReadModuleName(Blob);
4061 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004062 case MODULE_DIRECTORY:
4063 ModuleDir = Blob;
4064 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004065 case MODULE_MAP_FILE: {
4066 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004067 auto Path = ReadString(Record, Idx);
4068 ResolveImportedPath(Path, ModuleDir);
4069 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004070 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004071 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004072 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004073 if (ParseLanguageOptions(Record, false, Listener,
4074 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004075 return true;
4076 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004077
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004078 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004079 if (ParseTargetOptions(Record, false, Listener,
4080 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004081 return true;
4082 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004083
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004084 case DIAGNOSTIC_OPTIONS:
4085 if (ParseDiagnosticOptions(Record, false, Listener))
4086 return true;
4087 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004088
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004089 case FILE_SYSTEM_OPTIONS:
4090 if (ParseFileSystemOptions(Record, false, Listener))
4091 return true;
4092 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004093
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004094 case HEADER_SEARCH_OPTIONS:
4095 if (ParseHeaderSearchOptions(Record, false, Listener))
4096 return true;
4097 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004098
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004099 case PREPROCESSOR_OPTIONS: {
4100 std::string IgnoredSuggestedPredefines;
4101 if (ParsePreprocessorOptions(Record, false, Listener,
4102 IgnoredSuggestedPredefines))
4103 return true;
4104 break;
4105 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004106
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004107 case INPUT_FILE_OFFSETS: {
4108 if (!NeedsInputFiles)
4109 break;
4110
4111 unsigned NumInputFiles = Record[0];
4112 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004113 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004114 for (unsigned I = 0; I != NumInputFiles; ++I) {
4115 // Go find this input file.
4116 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004117
4118 if (isSystemFile && !NeedsSystemInputFiles)
4119 break; // the rest are system input files
4120
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004121 BitstreamCursor &Cursor = InputFilesCursor;
4122 SavedStreamPosition SavedPosition(Cursor);
4123 Cursor.JumpToBit(InputFileOffs[I]);
4124
4125 unsigned Code = Cursor.ReadCode();
4126 RecordData Record;
4127 StringRef Blob;
4128 bool shouldContinue = false;
4129 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4130 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004131 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004132 std::string Filename = Blob;
4133 ResolveImportedPath(Filename, ModuleDir);
4134 shouldContinue =
4135 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004136 break;
4137 }
4138 if (!shouldContinue)
4139 break;
4140 }
4141 break;
4142 }
4143
Richard Smithd4b230b2014-10-27 23:01:16 +00004144 case IMPORTS: {
4145 if (!NeedsImports)
4146 break;
4147
4148 unsigned Idx = 0, N = Record.size();
4149 while (Idx < N) {
4150 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004151 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004152 std::string Filename = ReadString(Record, Idx);
4153 ResolveImportedPath(Filename, ModuleDir);
4154 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004155 }
4156 break;
4157 }
4158
Richard Smith7f330cd2015-03-18 01:42:29 +00004159 case KNOWN_MODULE_FILES: {
4160 // Known-but-not-technically-used module files are treated as imports.
4161 if (!NeedsImports)
4162 break;
4163
4164 unsigned Idx = 0, N = Record.size();
4165 while (Idx < N) {
4166 std::string Filename = ReadString(Record, Idx);
4167 ResolveImportedPath(Filename, ModuleDir);
4168 Listener.visitImport(Filename);
4169 }
4170 break;
4171 }
4172
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004173 default:
4174 // No other validation to perform.
4175 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004176 }
4177 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004178}
4179
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004180bool ASTReader::isAcceptableASTFile(
4181 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004182 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004183 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4184 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004185 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4186 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004187 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004188 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004189}
4190
Ben Langmuir2c9af442014-04-10 17:57:43 +00004191ASTReader::ASTReadResult
4192ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004193 // Enter the submodule block.
4194 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4195 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004196 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004197 }
4198
4199 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4200 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004201 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004202 RecordData Record;
4203 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004204 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4205
4206 switch (Entry.Kind) {
4207 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4208 case llvm::BitstreamEntry::Error:
4209 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004210 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004211 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004212 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004213 case llvm::BitstreamEntry::Record:
4214 // The interesting case.
4215 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004216 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004217
Guy Benyei11169dd2012-12-18 14:30:41 +00004218 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004219 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004220 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004221 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4222
4223 if ((Kind == SUBMODULE_METADATA) != First) {
4224 Error("submodule metadata record should be at beginning of block");
4225 return Failure;
4226 }
4227 First = false;
4228
4229 // Submodule information is only valid if we have a current module.
4230 // FIXME: Should we error on these cases?
4231 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4232 Kind != SUBMODULE_DEFINITION)
4233 continue;
4234
4235 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004236 default: // Default behavior: ignore.
4237 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004238
Richard Smith03478d92014-10-23 22:12:14 +00004239 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004240 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004241 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004242 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004243 }
Richard Smith03478d92014-10-23 22:12:14 +00004244
Chris Lattner0e6c9402013-01-20 02:38:54 +00004245 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004246 unsigned Idx = 0;
4247 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4248 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4249 bool IsFramework = Record[Idx++];
4250 bool IsExplicit = Record[Idx++];
4251 bool IsSystem = Record[Idx++];
4252 bool IsExternC = Record[Idx++];
4253 bool InferSubmodules = Record[Idx++];
4254 bool InferExplicitSubmodules = Record[Idx++];
4255 bool InferExportWildcard = Record[Idx++];
4256 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004257
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004258 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004259 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004260 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004261
Guy Benyei11169dd2012-12-18 14:30:41 +00004262 // Retrieve this (sub)module from the module map, creating it if
4263 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004264 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004265 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004266
4267 // FIXME: set the definition loc for CurrentModule, or call
4268 // ModMap.setInferredModuleAllowedBy()
4269
Guy Benyei11169dd2012-12-18 14:30:41 +00004270 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4271 if (GlobalIndex >= SubmodulesLoaded.size() ||
4272 SubmodulesLoaded[GlobalIndex]) {
4273 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004274 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004275 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004276
Douglas Gregor7029ce12013-03-19 00:28:20 +00004277 if (!ParentModule) {
4278 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4279 if (CurFile != F.File) {
4280 if (!Diags.isDiagnosticInFlight()) {
4281 Diag(diag::err_module_file_conflict)
4282 << CurrentModule->getTopLevelModuleName()
4283 << CurFile->getName()
4284 << F.File->getName();
4285 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004286 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004287 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004288 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004289
4290 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004291 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004292
Adrian Prantl15bcf702015-06-30 17:39:43 +00004293 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004294 CurrentModule->IsFromModuleFile = true;
4295 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004296 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004297 CurrentModule->InferSubmodules = InferSubmodules;
4298 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4299 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004300 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004301 if (DeserializationListener)
4302 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4303
4304 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004305
Douglas Gregorfb912652013-03-20 21:10:35 +00004306 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004307 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004308 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004309 CurrentModule->UnresolvedConflicts.clear();
4310 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 break;
4312 }
4313
4314 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004315 std::string Filename = Blob;
4316 ResolveImportedPath(F, Filename);
4317 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004318 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004319 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4320 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004321 // This can be a spurious difference caused by changing the VFS to
4322 // point to a different copy of the file, and it is too late to
4323 // to rebuild safely.
4324 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4325 // after input file validation only real problems would remain and we
4326 // could just error. For now, assume it's okay.
4327 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004328 }
4329 }
4330 break;
4331 }
4332
Richard Smith202210b2014-10-24 20:23:01 +00004333 case SUBMODULE_HEADER:
4334 case SUBMODULE_EXCLUDED_HEADER:
4335 case SUBMODULE_PRIVATE_HEADER:
4336 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004337 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4338 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004339 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004340
Richard Smith202210b2014-10-24 20:23:01 +00004341 case SUBMODULE_TEXTUAL_HEADER:
4342 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4343 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4344 // them here.
4345 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004346
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004348 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 break;
4350 }
4351
4352 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004353 std::string Dirname = Blob;
4354 ResolveImportedPath(F, Dirname);
4355 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004356 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004357 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4358 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004359 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4360 Error("mismatched umbrella directories in submodule");
4361 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004362 }
4363 }
4364 break;
4365 }
4366
4367 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004368 F.BaseSubmoduleID = getTotalNumSubmodules();
4369 F.LocalNumSubmodules = Record[0];
4370 unsigned LocalBaseSubmoduleID = Record[1];
4371 if (F.LocalNumSubmodules > 0) {
4372 // Introduce the global -> local mapping for submodules within this
4373 // module.
4374 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4375
4376 // Introduce the local -> global mapping for submodules within this
4377 // module.
4378 F.SubmoduleRemap.insertOrReplace(
4379 std::make_pair(LocalBaseSubmoduleID,
4380 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004381
Ben Langmuir52ca6782014-10-20 16:27:32 +00004382 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4383 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004384 break;
4385 }
4386
4387 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004388 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004389 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004390 Unresolved.File = &F;
4391 Unresolved.Mod = CurrentModule;
4392 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004393 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004395 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004396 }
4397 break;
4398 }
4399
4400 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004401 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004402 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004403 Unresolved.File = &F;
4404 Unresolved.Mod = CurrentModule;
4405 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004406 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004407 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004408 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004409 }
4410
4411 // Once we've loaded the set of exports, there's no reason to keep
4412 // the parsed, unresolved exports around.
4413 CurrentModule->UnresolvedExports.clear();
4414 break;
4415 }
4416 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004417 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004418 Context.getTargetInfo());
4419 break;
4420 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004421
4422 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004423 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004424 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004425 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004426
4427 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004428 CurrentModule->ConfigMacros.push_back(Blob.str());
4429 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004430
4431 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004432 UnresolvedModuleRef Unresolved;
4433 Unresolved.File = &F;
4434 Unresolved.Mod = CurrentModule;
4435 Unresolved.ID = Record[0];
4436 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4437 Unresolved.IsWildcard = false;
4438 Unresolved.String = Blob;
4439 UnresolvedModuleRefs.push_back(Unresolved);
4440 break;
4441 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004442 }
4443 }
4444}
4445
4446/// \brief Parse the record that corresponds to a LangOptions data
4447/// structure.
4448///
4449/// This routine parses the language options from the AST file and then gives
4450/// them to the AST listener if one is set.
4451///
4452/// \returns true if the listener deems the file unacceptable, false otherwise.
4453bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4454 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004455 ASTReaderListener &Listener,
4456 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004457 LangOptions LangOpts;
4458 unsigned Idx = 0;
4459#define LANGOPT(Name, Bits, Default, Description) \
4460 LangOpts.Name = Record[Idx++];
4461#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4462 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4463#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004464#define SANITIZER(NAME, ID) \
4465 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004466#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004467
Ben Langmuircd98cb72015-06-23 18:20:18 +00004468 for (unsigned N = Record[Idx++]; N; --N)
4469 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4470
Guy Benyei11169dd2012-12-18 14:30:41 +00004471 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4472 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4473 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004474
Ben Langmuird4a667a2015-06-23 18:20:23 +00004475 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004476
4477 // Comment options.
4478 for (unsigned N = Record[Idx++]; N; --N) {
4479 LangOpts.CommentOpts.BlockCommandNames.push_back(
4480 ReadString(Record, Idx));
4481 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004482 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004483
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004484 return Listener.ReadLanguageOptions(LangOpts, Complain,
4485 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004486}
4487
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004488bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4489 ASTReaderListener &Listener,
4490 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004491 unsigned Idx = 0;
4492 TargetOptions TargetOpts;
4493 TargetOpts.Triple = ReadString(Record, Idx);
4494 TargetOpts.CPU = ReadString(Record, Idx);
4495 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004496 for (unsigned N = Record[Idx++]; N; --N) {
4497 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4498 }
4499 for (unsigned N = Record[Idx++]; N; --N) {
4500 TargetOpts.Features.push_back(ReadString(Record, Idx));
4501 }
4502
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004503 return Listener.ReadTargetOptions(TargetOpts, Complain,
4504 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004505}
4506
4507bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4508 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004509 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004510 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004511#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004512#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004513 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004514#include "clang/Basic/DiagnosticOptions.def"
4515
Richard Smith3be1cb22014-08-07 00:24:21 +00004516 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004517 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004518 for (unsigned N = Record[Idx++]; N; --N)
4519 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004520
4521 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4522}
4523
4524bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4525 ASTReaderListener &Listener) {
4526 FileSystemOptions FSOpts;
4527 unsigned Idx = 0;
4528 FSOpts.WorkingDir = ReadString(Record, Idx);
4529 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4530}
4531
4532bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4533 bool Complain,
4534 ASTReaderListener &Listener) {
4535 HeaderSearchOptions HSOpts;
4536 unsigned Idx = 0;
4537 HSOpts.Sysroot = ReadString(Record, Idx);
4538
4539 // Include entries.
4540 for (unsigned N = Record[Idx++]; N; --N) {
4541 std::string Path = ReadString(Record, Idx);
4542 frontend::IncludeDirGroup Group
4543 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004544 bool IsFramework = Record[Idx++];
4545 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004546 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4547 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004548 }
4549
4550 // System header prefixes.
4551 for (unsigned N = Record[Idx++]; N; --N) {
4552 std::string Prefix = ReadString(Record, Idx);
4553 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004554 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004555 }
4556
4557 HSOpts.ResourceDir = ReadString(Record, Idx);
4558 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004559 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004560 HSOpts.DisableModuleHash = Record[Idx++];
4561 HSOpts.UseBuiltinIncludes = Record[Idx++];
4562 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4563 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4564 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004565 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004566
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004567 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4568 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004569}
4570
4571bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4572 bool Complain,
4573 ASTReaderListener &Listener,
4574 std::string &SuggestedPredefines) {
4575 PreprocessorOptions PPOpts;
4576 unsigned Idx = 0;
4577
4578 // Macro definitions/undefs
4579 for (unsigned N = Record[Idx++]; N; --N) {
4580 std::string Macro = ReadString(Record, Idx);
4581 bool IsUndef = Record[Idx++];
4582 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4583 }
4584
4585 // Includes
4586 for (unsigned N = Record[Idx++]; N; --N) {
4587 PPOpts.Includes.push_back(ReadString(Record, Idx));
4588 }
4589
4590 // Macro Includes
4591 for (unsigned N = Record[Idx++]; N; --N) {
4592 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4593 }
4594
4595 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004596 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004597 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4598 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4599 PPOpts.ObjCXXARCStandardLibrary =
4600 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4601 SuggestedPredefines.clear();
4602 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4603 SuggestedPredefines);
4604}
4605
4606std::pair<ModuleFile *, unsigned>
4607ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4608 GlobalPreprocessedEntityMapType::iterator
4609 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4610 assert(I != GlobalPreprocessedEntityMap.end() &&
4611 "Corrupted global preprocessed entity map");
4612 ModuleFile *M = I->second;
4613 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4614 return std::make_pair(M, LocalIndex);
4615}
4616
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004617llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004618ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4619 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4620 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4621 Mod.NumPreprocessedEntities);
4622
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004623 return llvm::make_range(PreprocessingRecord::iterator(),
4624 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004625}
4626
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004627llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004628ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004629 return llvm::make_range(
4630 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4631 ModuleDeclIterator(this, &Mod,
4632 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004633}
4634
4635PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4636 PreprocessedEntityID PPID = Index+1;
4637 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4638 ModuleFile &M = *PPInfo.first;
4639 unsigned LocalIndex = PPInfo.second;
4640 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4641
Guy Benyei11169dd2012-12-18 14:30:41 +00004642 if (!PP.getPreprocessingRecord()) {
4643 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004644 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 }
4646
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004647 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4648 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4649
4650 llvm::BitstreamEntry Entry =
4651 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4652 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004653 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004654
Guy Benyei11169dd2012-12-18 14:30:41 +00004655 // Read the record.
4656 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4657 ReadSourceLocation(M, PPOffs.End));
4658 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004659 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004660 RecordData Record;
4661 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004662 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4663 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004664 switch (RecType) {
4665 case PPD_MACRO_EXPANSION: {
4666 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004667 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004668 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 if (isBuiltin)
4670 Name = getLocalIdentifier(M, Record[1]);
4671 else {
Richard Smith66a81862015-05-04 02:25:31 +00004672 PreprocessedEntityID GlobalID =
4673 getGlobalPreprocessedEntityID(M, Record[1]);
4674 Def = cast<MacroDefinitionRecord>(
4675 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004676 }
4677
4678 MacroExpansion *ME;
4679 if (isBuiltin)
4680 ME = new (PPRec) MacroExpansion(Name, Range);
4681 else
4682 ME = new (PPRec) MacroExpansion(Def, Range);
4683
4684 return ME;
4685 }
4686
4687 case PPD_MACRO_DEFINITION: {
4688 // Decode the identifier info and then check again; if the macro is
4689 // still defined and associated with the identifier,
4690 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004691 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004692
4693 if (DeserializationListener)
4694 DeserializationListener->MacroDefinitionRead(PPID, MD);
4695
4696 return MD;
4697 }
4698
4699 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004700 const char *FullFileNameStart = Blob.data() + Record[0];
4701 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004702 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004703 if (!FullFileName.empty())
4704 File = PP.getFileManager().getFile(FullFileName);
4705
4706 // FIXME: Stable encoding
4707 InclusionDirective::InclusionKind Kind
4708 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4709 InclusionDirective *ID
4710 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004711 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004712 Record[1], Record[3],
4713 File,
4714 Range);
4715 return ID;
4716 }
4717 }
4718
4719 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4720}
4721
4722/// \brief \arg SLocMapI points at a chunk of a module that contains no
4723/// preprocessed entities or the entities it contains are not the ones we are
4724/// looking for. Find the next module that contains entities and return the ID
4725/// of the first entry.
4726PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4727 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4728 ++SLocMapI;
4729 for (GlobalSLocOffsetMapType::const_iterator
4730 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4731 ModuleFile &M = *SLocMapI->second;
4732 if (M.NumPreprocessedEntities)
4733 return M.BasePreprocessedEntityID;
4734 }
4735
4736 return getTotalNumPreprocessedEntities();
4737}
4738
4739namespace {
4740
4741template <unsigned PPEntityOffset::*PPLoc>
4742struct PPEntityComp {
4743 const ASTReader &Reader;
4744 ModuleFile &M;
4745
4746 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4747
4748 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4749 SourceLocation LHS = getLoc(L);
4750 SourceLocation RHS = getLoc(R);
4751 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4752 }
4753
4754 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4755 SourceLocation LHS = getLoc(L);
4756 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4757 }
4758
4759 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4760 SourceLocation RHS = getLoc(R);
4761 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4762 }
4763
4764 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4765 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4766 }
4767};
4768
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004769}
Guy Benyei11169dd2012-12-18 14:30:41 +00004770
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004771PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4772 bool EndsAfter) const {
4773 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004774 return getTotalNumPreprocessedEntities();
4775
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004776 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4777 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004778 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4779 "Corrupted global sloc offset map");
4780
4781 if (SLocMapI->second->NumPreprocessedEntities == 0)
4782 return findNextPreprocessedEntity(SLocMapI);
4783
4784 ModuleFile &M = *SLocMapI->second;
4785 typedef const PPEntityOffset *pp_iterator;
4786 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4787 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4788
4789 size_t Count = M.NumPreprocessedEntities;
4790 size_t Half;
4791 pp_iterator First = pp_begin;
4792 pp_iterator PPI;
4793
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004794 if (EndsAfter) {
4795 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4796 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4797 } else {
4798 // Do a binary search manually instead of using std::lower_bound because
4799 // The end locations of entities may be unordered (when a macro expansion
4800 // is inside another macro argument), but for this case it is not important
4801 // whether we get the first macro expansion or its containing macro.
4802 while (Count > 0) {
4803 Half = Count / 2;
4804 PPI = First;
4805 std::advance(PPI, Half);
4806 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4807 Loc)) {
4808 First = PPI;
4809 ++First;
4810 Count = Count - Half - 1;
4811 } else
4812 Count = Half;
4813 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004814 }
4815
4816 if (PPI == pp_end)
4817 return findNextPreprocessedEntity(SLocMapI);
4818
4819 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4820}
4821
Guy Benyei11169dd2012-12-18 14:30:41 +00004822/// \brief Returns a pair of [Begin, End) indices of preallocated
4823/// preprocessed entities that \arg Range encompasses.
4824std::pair<unsigned, unsigned>
4825 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4826 if (Range.isInvalid())
4827 return std::make_pair(0,0);
4828 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4829
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004830 PreprocessedEntityID BeginID =
4831 findPreprocessedEntity(Range.getBegin(), false);
4832 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004833 return std::make_pair(BeginID, EndID);
4834}
4835
4836/// \brief Optionally returns true or false if the preallocated preprocessed
4837/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004838Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004839 FileID FID) {
4840 if (FID.isInvalid())
4841 return false;
4842
4843 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4844 ModuleFile &M = *PPInfo.first;
4845 unsigned LocalIndex = PPInfo.second;
4846 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4847
4848 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4849 if (Loc.isInvalid())
4850 return false;
4851
4852 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4853 return true;
4854 else
4855 return false;
4856}
4857
4858namespace {
4859 /// \brief Visitor used to search for information about a header file.
4860 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004861 const FileEntry *FE;
4862
David Blaikie05785d12013-02-20 22:23:23 +00004863 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004864
4865 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004866 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4867 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004868
4869 static bool visit(ModuleFile &M, void *UserData) {
4870 HeaderFileInfoVisitor *This
4871 = static_cast<HeaderFileInfoVisitor *>(UserData);
4872
Guy Benyei11169dd2012-12-18 14:30:41 +00004873 HeaderFileInfoLookupTable *Table
4874 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4875 if (!Table)
4876 return false;
4877
4878 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004879 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004880 if (Pos == Table->end())
4881 return false;
4882
4883 This->HFI = *Pos;
4884 return true;
4885 }
4886
David Blaikie05785d12013-02-20 22:23:23 +00004887 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004888 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004889}
Guy Benyei11169dd2012-12-18 14:30:41 +00004890
4891HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004892 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004893 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004894 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004895 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004896
4897 return HeaderFileInfo();
4898}
4899
4900void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4901 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004902 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004903 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4904 ModuleFile &F = *(*I);
4905 unsigned Idx = 0;
4906 DiagStates.clear();
4907 assert(!Diag.DiagStates.empty());
4908 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4909 while (Idx < F.PragmaDiagMappings.size()) {
4910 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4911 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4912 if (DiagStateID != 0) {
4913 Diag.DiagStatePoints.push_back(
4914 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4915 FullSourceLoc(Loc, SourceMgr)));
4916 continue;
4917 }
4918
4919 assert(DiagStateID == 0);
4920 // A new DiagState was created here.
4921 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4922 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4923 DiagStates.push_back(NewState);
4924 Diag.DiagStatePoints.push_back(
4925 DiagnosticsEngine::DiagStatePoint(NewState,
4926 FullSourceLoc(Loc, SourceMgr)));
4927 while (1) {
4928 assert(Idx < F.PragmaDiagMappings.size() &&
4929 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4930 if (Idx >= F.PragmaDiagMappings.size()) {
4931 break; // Something is messed up but at least avoid infinite loop in
4932 // release build.
4933 }
4934 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4935 if (DiagID == (unsigned)-1) {
4936 break; // no more diag/map pairs for this location.
4937 }
Alp Tokerc726c362014-06-10 09:31:37 +00004938 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4939 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4940 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00004941 }
4942 }
4943 }
4944}
4945
4946/// \brief Get the correct cursor and offset for loading a type.
4947ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4948 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4949 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4950 ModuleFile *M = I->second;
4951 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4952}
4953
4954/// \brief Read and return the type with the given index..
4955///
4956/// The index is the type ID, shifted and minus the number of predefs. This
4957/// routine actually reads the record corresponding to the type at the given
4958/// location. It is a helper routine for GetType, which deals with reading type
4959/// IDs.
4960QualType ASTReader::readTypeRecord(unsigned Index) {
4961 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004962 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004963
4964 // Keep track of where we are in the stream, then jump back there
4965 // after reading this type.
4966 SavedStreamPosition SavedPosition(DeclsCursor);
4967
4968 ReadingKindTracker ReadingKind(Read_Type, *this);
4969
4970 // Note that we are loading a type record.
4971 Deserializing AType(this);
4972
4973 unsigned Idx = 0;
4974 DeclsCursor.JumpToBit(Loc.Offset);
4975 RecordData Record;
4976 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004977 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004978 case TYPE_EXT_QUAL: {
4979 if (Record.size() != 2) {
4980 Error("Incorrect encoding of extended qualifier type");
4981 return QualType();
4982 }
4983 QualType Base = readType(*Loc.F, Record, Idx);
4984 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4985 return Context.getQualifiedType(Base, Quals);
4986 }
4987
4988 case TYPE_COMPLEX: {
4989 if (Record.size() != 1) {
4990 Error("Incorrect encoding of complex type");
4991 return QualType();
4992 }
4993 QualType ElemType = readType(*Loc.F, Record, Idx);
4994 return Context.getComplexType(ElemType);
4995 }
4996
4997 case TYPE_POINTER: {
4998 if (Record.size() != 1) {
4999 Error("Incorrect encoding of pointer type");
5000 return QualType();
5001 }
5002 QualType PointeeType = readType(*Loc.F, Record, Idx);
5003 return Context.getPointerType(PointeeType);
5004 }
5005
Reid Kleckner8a365022013-06-24 17:51:48 +00005006 case TYPE_DECAYED: {
5007 if (Record.size() != 1) {
5008 Error("Incorrect encoding of decayed type");
5009 return QualType();
5010 }
5011 QualType OriginalType = readType(*Loc.F, Record, Idx);
5012 QualType DT = Context.getAdjustedParameterType(OriginalType);
5013 if (!isa<DecayedType>(DT))
5014 Error("Decayed type does not decay");
5015 return DT;
5016 }
5017
Reid Kleckner0503a872013-12-05 01:23:43 +00005018 case TYPE_ADJUSTED: {
5019 if (Record.size() != 2) {
5020 Error("Incorrect encoding of adjusted type");
5021 return QualType();
5022 }
5023 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5024 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5025 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5026 }
5027
Guy Benyei11169dd2012-12-18 14:30:41 +00005028 case TYPE_BLOCK_POINTER: {
5029 if (Record.size() != 1) {
5030 Error("Incorrect encoding of block pointer type");
5031 return QualType();
5032 }
5033 QualType PointeeType = readType(*Loc.F, Record, Idx);
5034 return Context.getBlockPointerType(PointeeType);
5035 }
5036
5037 case TYPE_LVALUE_REFERENCE: {
5038 if (Record.size() != 2) {
5039 Error("Incorrect encoding of lvalue reference type");
5040 return QualType();
5041 }
5042 QualType PointeeType = readType(*Loc.F, Record, Idx);
5043 return Context.getLValueReferenceType(PointeeType, Record[1]);
5044 }
5045
5046 case TYPE_RVALUE_REFERENCE: {
5047 if (Record.size() != 1) {
5048 Error("Incorrect encoding of rvalue reference type");
5049 return QualType();
5050 }
5051 QualType PointeeType = readType(*Loc.F, Record, Idx);
5052 return Context.getRValueReferenceType(PointeeType);
5053 }
5054
5055 case TYPE_MEMBER_POINTER: {
5056 if (Record.size() != 2) {
5057 Error("Incorrect encoding of member pointer type");
5058 return QualType();
5059 }
5060 QualType PointeeType = readType(*Loc.F, Record, Idx);
5061 QualType ClassType = readType(*Loc.F, Record, Idx);
5062 if (PointeeType.isNull() || ClassType.isNull())
5063 return QualType();
5064
5065 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5066 }
5067
5068 case TYPE_CONSTANT_ARRAY: {
5069 QualType ElementType = readType(*Loc.F, Record, Idx);
5070 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5071 unsigned IndexTypeQuals = Record[2];
5072 unsigned Idx = 3;
5073 llvm::APInt Size = ReadAPInt(Record, Idx);
5074 return Context.getConstantArrayType(ElementType, Size,
5075 ASM, IndexTypeQuals);
5076 }
5077
5078 case TYPE_INCOMPLETE_ARRAY: {
5079 QualType ElementType = readType(*Loc.F, Record, Idx);
5080 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5081 unsigned IndexTypeQuals = Record[2];
5082 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5083 }
5084
5085 case TYPE_VARIABLE_ARRAY: {
5086 QualType ElementType = readType(*Loc.F, Record, Idx);
5087 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5088 unsigned IndexTypeQuals = Record[2];
5089 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5090 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5091 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5092 ASM, IndexTypeQuals,
5093 SourceRange(LBLoc, RBLoc));
5094 }
5095
5096 case TYPE_VECTOR: {
5097 if (Record.size() != 3) {
5098 Error("incorrect encoding of vector type in AST file");
5099 return QualType();
5100 }
5101
5102 QualType ElementType = readType(*Loc.F, Record, Idx);
5103 unsigned NumElements = Record[1];
5104 unsigned VecKind = Record[2];
5105 return Context.getVectorType(ElementType, NumElements,
5106 (VectorType::VectorKind)VecKind);
5107 }
5108
5109 case TYPE_EXT_VECTOR: {
5110 if (Record.size() != 3) {
5111 Error("incorrect encoding of extended vector type in AST file");
5112 return QualType();
5113 }
5114
5115 QualType ElementType = readType(*Loc.F, Record, Idx);
5116 unsigned NumElements = Record[1];
5117 return Context.getExtVectorType(ElementType, NumElements);
5118 }
5119
5120 case TYPE_FUNCTION_NO_PROTO: {
5121 if (Record.size() != 6) {
5122 Error("incorrect encoding of no-proto function type");
5123 return QualType();
5124 }
5125 QualType ResultType = readType(*Loc.F, Record, Idx);
5126 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5127 (CallingConv)Record[4], Record[5]);
5128 return Context.getFunctionNoProtoType(ResultType, Info);
5129 }
5130
5131 case TYPE_FUNCTION_PROTO: {
5132 QualType ResultType = readType(*Loc.F, Record, Idx);
5133
5134 FunctionProtoType::ExtProtoInfo EPI;
5135 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5136 /*hasregparm*/ Record[2],
5137 /*regparm*/ Record[3],
5138 static_cast<CallingConv>(Record[4]),
5139 /*produces*/ Record[5]);
5140
5141 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005142
5143 EPI.Variadic = Record[Idx++];
5144 EPI.HasTrailingReturn = Record[Idx++];
5145 EPI.TypeQuals = Record[Idx++];
5146 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005147 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005148 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005149
5150 unsigned NumParams = Record[Idx++];
5151 SmallVector<QualType, 16> ParamTypes;
5152 for (unsigned I = 0; I != NumParams; ++I)
5153 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5154
Jordan Rose5c382722013-03-08 21:51:21 +00005155 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005156 }
5157
5158 case TYPE_UNRESOLVED_USING: {
5159 unsigned Idx = 0;
5160 return Context.getTypeDeclType(
5161 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5162 }
5163
5164 case TYPE_TYPEDEF: {
5165 if (Record.size() != 2) {
5166 Error("incorrect encoding of typedef type");
5167 return QualType();
5168 }
5169 unsigned Idx = 0;
5170 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5171 QualType Canonical = readType(*Loc.F, Record, Idx);
5172 if (!Canonical.isNull())
5173 Canonical = Context.getCanonicalType(Canonical);
5174 return Context.getTypedefType(Decl, Canonical);
5175 }
5176
5177 case TYPE_TYPEOF_EXPR:
5178 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5179
5180 case TYPE_TYPEOF: {
5181 if (Record.size() != 1) {
5182 Error("incorrect encoding of typeof(type) in AST file");
5183 return QualType();
5184 }
5185 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5186 return Context.getTypeOfType(UnderlyingType);
5187 }
5188
5189 case TYPE_DECLTYPE: {
5190 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5191 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5192 }
5193
5194 case TYPE_UNARY_TRANSFORM: {
5195 QualType BaseType = readType(*Loc.F, Record, Idx);
5196 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5197 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5198 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5199 }
5200
Richard Smith74aeef52013-04-26 16:15:35 +00005201 case TYPE_AUTO: {
5202 QualType Deduced = readType(*Loc.F, Record, Idx);
5203 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005204 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005205 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005206 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005207
5208 case TYPE_RECORD: {
5209 if (Record.size() != 2) {
5210 Error("incorrect encoding of record type");
5211 return QualType();
5212 }
5213 unsigned Idx = 0;
5214 bool IsDependent = Record[Idx++];
5215 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5216 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5217 QualType T = Context.getRecordType(RD);
5218 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5219 return T;
5220 }
5221
5222 case TYPE_ENUM: {
5223 if (Record.size() != 2) {
5224 Error("incorrect encoding of enum type");
5225 return QualType();
5226 }
5227 unsigned Idx = 0;
5228 bool IsDependent = Record[Idx++];
5229 QualType T
5230 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5231 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5232 return T;
5233 }
5234
5235 case TYPE_ATTRIBUTED: {
5236 if (Record.size() != 3) {
5237 Error("incorrect encoding of attributed type");
5238 return QualType();
5239 }
5240 QualType modifiedType = readType(*Loc.F, Record, Idx);
5241 QualType equivalentType = readType(*Loc.F, Record, Idx);
5242 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5243 return Context.getAttributedType(kind, modifiedType, equivalentType);
5244 }
5245
5246 case TYPE_PAREN: {
5247 if (Record.size() != 1) {
5248 Error("incorrect encoding of paren type");
5249 return QualType();
5250 }
5251 QualType InnerType = readType(*Loc.F, Record, Idx);
5252 return Context.getParenType(InnerType);
5253 }
5254
5255 case TYPE_PACK_EXPANSION: {
5256 if (Record.size() != 2) {
5257 Error("incorrect encoding of pack expansion type");
5258 return QualType();
5259 }
5260 QualType Pattern = readType(*Loc.F, Record, Idx);
5261 if (Pattern.isNull())
5262 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005263 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005264 if (Record[1])
5265 NumExpansions = Record[1] - 1;
5266 return Context.getPackExpansionType(Pattern, NumExpansions);
5267 }
5268
5269 case TYPE_ELABORATED: {
5270 unsigned Idx = 0;
5271 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5272 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5273 QualType NamedType = readType(*Loc.F, Record, Idx);
5274 return Context.getElaboratedType(Keyword, NNS, NamedType);
5275 }
5276
5277 case TYPE_OBJC_INTERFACE: {
5278 unsigned Idx = 0;
5279 ObjCInterfaceDecl *ItfD
5280 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5281 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5282 }
5283
5284 case TYPE_OBJC_OBJECT: {
5285 unsigned Idx = 0;
5286 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005287 unsigned NumTypeArgs = Record[Idx++];
5288 SmallVector<QualType, 4> TypeArgs;
5289 for (unsigned I = 0; I != NumTypeArgs; ++I)
5290 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005291 unsigned NumProtos = Record[Idx++];
5292 SmallVector<ObjCProtocolDecl*, 4> Protos;
5293 for (unsigned I = 0; I != NumProtos; ++I)
5294 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005295 bool IsKindOf = Record[Idx++];
5296 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005297 }
5298
5299 case TYPE_OBJC_OBJECT_POINTER: {
5300 unsigned Idx = 0;
5301 QualType Pointee = readType(*Loc.F, Record, Idx);
5302 return Context.getObjCObjectPointerType(Pointee);
5303 }
5304
5305 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5306 unsigned Idx = 0;
5307 QualType Parm = readType(*Loc.F, Record, Idx);
5308 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005309 return Context.getSubstTemplateTypeParmType(
5310 cast<TemplateTypeParmType>(Parm),
5311 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005312 }
5313
5314 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5315 unsigned Idx = 0;
5316 QualType Parm = readType(*Loc.F, Record, Idx);
5317 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5318 return Context.getSubstTemplateTypeParmPackType(
5319 cast<TemplateTypeParmType>(Parm),
5320 ArgPack);
5321 }
5322
5323 case TYPE_INJECTED_CLASS_NAME: {
5324 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5325 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5326 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5327 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005328 const Type *T = nullptr;
5329 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5330 if (const Type *Existing = DI->getTypeForDecl()) {
5331 T = Existing;
5332 break;
5333 }
5334 }
5335 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005336 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005337 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5338 DI->setTypeForDecl(T);
5339 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005340 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005341 }
5342
5343 case TYPE_TEMPLATE_TYPE_PARM: {
5344 unsigned Idx = 0;
5345 unsigned Depth = Record[Idx++];
5346 unsigned Index = Record[Idx++];
5347 bool Pack = Record[Idx++];
5348 TemplateTypeParmDecl *D
5349 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5350 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5351 }
5352
5353 case TYPE_DEPENDENT_NAME: {
5354 unsigned Idx = 0;
5355 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5356 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5357 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5358 QualType Canon = readType(*Loc.F, Record, Idx);
5359 if (!Canon.isNull())
5360 Canon = Context.getCanonicalType(Canon);
5361 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5362 }
5363
5364 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5365 unsigned Idx = 0;
5366 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5367 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5368 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5369 unsigned NumArgs = Record[Idx++];
5370 SmallVector<TemplateArgument, 8> Args;
5371 Args.reserve(NumArgs);
5372 while (NumArgs--)
5373 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5374 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5375 Args.size(), Args.data());
5376 }
5377
5378 case TYPE_DEPENDENT_SIZED_ARRAY: {
5379 unsigned Idx = 0;
5380
5381 // ArrayType
5382 QualType ElementType = readType(*Loc.F, Record, Idx);
5383 ArrayType::ArraySizeModifier ASM
5384 = (ArrayType::ArraySizeModifier)Record[Idx++];
5385 unsigned IndexTypeQuals = Record[Idx++];
5386
5387 // DependentSizedArrayType
5388 Expr *NumElts = ReadExpr(*Loc.F);
5389 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5390
5391 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5392 IndexTypeQuals, Brackets);
5393 }
5394
5395 case TYPE_TEMPLATE_SPECIALIZATION: {
5396 unsigned Idx = 0;
5397 bool IsDependent = Record[Idx++];
5398 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5399 SmallVector<TemplateArgument, 8> Args;
5400 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5401 QualType Underlying = readType(*Loc.F, Record, Idx);
5402 QualType T;
5403 if (Underlying.isNull())
5404 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5405 Args.size());
5406 else
5407 T = Context.getTemplateSpecializationType(Name, Args.data(),
5408 Args.size(), Underlying);
5409 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5410 return T;
5411 }
5412
5413 case TYPE_ATOMIC: {
5414 if (Record.size() != 1) {
5415 Error("Incorrect encoding of atomic type");
5416 return QualType();
5417 }
5418 QualType ValueType = readType(*Loc.F, Record, Idx);
5419 return Context.getAtomicType(ValueType);
5420 }
5421 }
5422 llvm_unreachable("Invalid TypeCode!");
5423}
5424
Richard Smith564417a2014-03-20 21:47:22 +00005425void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5426 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005427 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005428 const RecordData &Record, unsigned &Idx) {
5429 ExceptionSpecificationType EST =
5430 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005431 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005432 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005433 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005434 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005435 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005436 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005437 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005438 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005439 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5440 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005441 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005442 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005443 }
5444}
5445
Guy Benyei11169dd2012-12-18 14:30:41 +00005446class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5447 ASTReader &Reader;
5448 ModuleFile &F;
5449 const ASTReader::RecordData &Record;
5450 unsigned &Idx;
5451
5452 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5453 unsigned &I) {
5454 return Reader.ReadSourceLocation(F, R, I);
5455 }
5456
5457 template<typename T>
5458 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5459 return Reader.ReadDeclAs<T>(F, Record, Idx);
5460 }
5461
5462public:
5463 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5464 const ASTReader::RecordData &Record, unsigned &Idx)
5465 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5466 { }
5467
5468 // We want compile-time assurance that we've enumerated all of
5469 // these, so unfortunately we have to declare them first, then
5470 // define them out-of-line.
5471#define ABSTRACT_TYPELOC(CLASS, PARENT)
5472#define TYPELOC(CLASS, PARENT) \
5473 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5474#include "clang/AST/TypeLocNodes.def"
5475
5476 void VisitFunctionTypeLoc(FunctionTypeLoc);
5477 void VisitArrayTypeLoc(ArrayTypeLoc);
5478};
5479
5480void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5481 // nothing to do
5482}
5483void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5484 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5485 if (TL.needsExtraLocalData()) {
5486 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5487 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5488 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5489 TL.setModeAttr(Record[Idx++]);
5490 }
5491}
5492void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5493 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5494}
5495void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5496 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5497}
Reid Kleckner8a365022013-06-24 17:51:48 +00005498void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5499 // nothing to do
5500}
Reid Kleckner0503a872013-12-05 01:23:43 +00005501void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5502 // nothing to do
5503}
Guy Benyei11169dd2012-12-18 14:30:41 +00005504void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5505 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5506}
5507void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5508 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5509}
5510void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5511 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5512}
5513void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5514 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5515 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5516}
5517void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5518 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5519 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5520 if (Record[Idx++])
5521 TL.setSizeExpr(Reader.ReadExpr(F));
5522 else
Craig Toppera13603a2014-05-22 05:54:18 +00005523 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005524}
5525void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5526 VisitArrayTypeLoc(TL);
5527}
5528void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5529 VisitArrayTypeLoc(TL);
5530}
5531void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5532 VisitArrayTypeLoc(TL);
5533}
5534void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5535 DependentSizedArrayTypeLoc TL) {
5536 VisitArrayTypeLoc(TL);
5537}
5538void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5539 DependentSizedExtVectorTypeLoc TL) {
5540 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5541}
5542void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5543 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5544}
5545void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5546 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5547}
5548void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5549 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5550 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5551 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5552 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005553 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5554 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005555 }
5556}
5557void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5558 VisitFunctionTypeLoc(TL);
5559}
5560void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5561 VisitFunctionTypeLoc(TL);
5562}
5563void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5564 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5565}
5566void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5567 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5568}
5569void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5570 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5571 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5572 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5573}
5574void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5575 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5576 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5577 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5578 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5579}
5580void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5581 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5582}
5583void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5584 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5585 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5586 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5587 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5588}
5589void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5590 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5591}
5592void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5593 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5594}
5595void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5596 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5597}
5598void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5599 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5600 if (TL.hasAttrOperand()) {
5601 SourceRange range;
5602 range.setBegin(ReadSourceLocation(Record, Idx));
5603 range.setEnd(ReadSourceLocation(Record, Idx));
5604 TL.setAttrOperandParensRange(range);
5605 }
5606 if (TL.hasAttrExprOperand()) {
5607 if (Record[Idx++])
5608 TL.setAttrExprOperand(Reader.ReadExpr(F));
5609 else
Craig Toppera13603a2014-05-22 05:54:18 +00005610 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005611 } else if (TL.hasAttrEnumOperand())
5612 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5613}
5614void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5615 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5616}
5617void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5618 SubstTemplateTypeParmTypeLoc TL) {
5619 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5620}
5621void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5622 SubstTemplateTypeParmPackTypeLoc TL) {
5623 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5624}
5625void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5626 TemplateSpecializationTypeLoc TL) {
5627 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5628 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5629 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5630 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5631 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5632 TL.setArgLocInfo(i,
5633 Reader.GetTemplateArgumentLocInfo(F,
5634 TL.getTypePtr()->getArg(i).getKind(),
5635 Record, Idx));
5636}
5637void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5638 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5639 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5640}
5641void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5642 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5643 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5644}
5645void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5646 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5647}
5648void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5649 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5650 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5651 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5652}
5653void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5654 DependentTemplateSpecializationTypeLoc TL) {
5655 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5656 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5657 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5658 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5659 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5660 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5661 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5662 TL.setArgLocInfo(I,
5663 Reader.GetTemplateArgumentLocInfo(F,
5664 TL.getTypePtr()->getArg(I).getKind(),
5665 Record, Idx));
5666}
5667void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5668 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5669}
5670void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5671 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5672}
5673void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5674 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005675 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5676 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5677 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5678 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5679 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5680 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005681 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5682 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5683}
5684void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5685 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5686}
5687void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5688 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5689 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5690 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5691}
5692
5693TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5694 const RecordData &Record,
5695 unsigned &Idx) {
5696 QualType InfoTy = readType(F, Record, Idx);
5697 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005698 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005699
5700 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5701 TypeLocReader TLR(*this, F, Record, Idx);
5702 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5703 TLR.Visit(TL);
5704 return TInfo;
5705}
5706
5707QualType ASTReader::GetType(TypeID ID) {
5708 unsigned FastQuals = ID & Qualifiers::FastMask;
5709 unsigned Index = ID >> Qualifiers::FastWidth;
5710
5711 if (Index < NUM_PREDEF_TYPE_IDS) {
5712 QualType T;
5713 switch ((PredefinedTypeIDs)Index) {
5714 case PREDEF_TYPE_NULL_ID: return QualType();
5715 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5716 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5717
5718 case PREDEF_TYPE_CHAR_U_ID:
5719 case PREDEF_TYPE_CHAR_S_ID:
5720 // FIXME: Check that the signedness of CharTy is correct!
5721 T = Context.CharTy;
5722 break;
5723
5724 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5725 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5726 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5727 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5728 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5729 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5730 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5731 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5732 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5733 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5734 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5735 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5736 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5737 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5738 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5739 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5740 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5741 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5742 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5743 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5744 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5745 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5746 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5747 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5748 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5749 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5750 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5751 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005752 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5753 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5754 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5755 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5756 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5757 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005758 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005759 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005760 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5761
5762 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5763 T = Context.getAutoRRefDeductType();
5764 break;
5765
5766 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5767 T = Context.ARCUnbridgedCastTy;
5768 break;
5769
5770 case PREDEF_TYPE_VA_LIST_TAG:
5771 T = Context.getVaListTagType();
5772 break;
5773
5774 case PREDEF_TYPE_BUILTIN_FN:
5775 T = Context.BuiltinFnTy;
5776 break;
5777 }
5778
5779 assert(!T.isNull() && "Unknown predefined type");
5780 return T.withFastQualifiers(FastQuals);
5781 }
5782
5783 Index -= NUM_PREDEF_TYPE_IDS;
5784 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5785 if (TypesLoaded[Index].isNull()) {
5786 TypesLoaded[Index] = readTypeRecord(Index);
5787 if (TypesLoaded[Index].isNull())
5788 return QualType();
5789
5790 TypesLoaded[Index]->setFromAST();
5791 if (DeserializationListener)
5792 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5793 TypesLoaded[Index]);
5794 }
5795
5796 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5797}
5798
5799QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5800 return GetType(getGlobalTypeID(F, LocalID));
5801}
5802
5803serialization::TypeID
5804ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5805 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5806 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5807
5808 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5809 return LocalID;
5810
5811 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5812 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5813 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5814
5815 unsigned GlobalIndex = LocalIndex + I->second;
5816 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5817}
5818
5819TemplateArgumentLocInfo
5820ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5821 TemplateArgument::ArgKind Kind,
5822 const RecordData &Record,
5823 unsigned &Index) {
5824 switch (Kind) {
5825 case TemplateArgument::Expression:
5826 return ReadExpr(F);
5827 case TemplateArgument::Type:
5828 return GetTypeSourceInfo(F, Record, Index);
5829 case TemplateArgument::Template: {
5830 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5831 Index);
5832 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5833 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5834 SourceLocation());
5835 }
5836 case TemplateArgument::TemplateExpansion: {
5837 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5838 Index);
5839 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5840 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5841 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5842 EllipsisLoc);
5843 }
5844 case TemplateArgument::Null:
5845 case TemplateArgument::Integral:
5846 case TemplateArgument::Declaration:
5847 case TemplateArgument::NullPtr:
5848 case TemplateArgument::Pack:
5849 // FIXME: Is this right?
5850 return TemplateArgumentLocInfo();
5851 }
5852 llvm_unreachable("unexpected template argument loc");
5853}
5854
5855TemplateArgumentLoc
5856ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5857 const RecordData &Record, unsigned &Index) {
5858 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5859
5860 if (Arg.getKind() == TemplateArgument::Expression) {
5861 if (Record[Index++]) // bool InfoHasSameExpr.
5862 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5863 }
5864 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5865 Record, Index));
5866}
5867
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005868const ASTTemplateArgumentListInfo*
5869ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5870 const RecordData &Record,
5871 unsigned &Index) {
5872 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5873 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5874 unsigned NumArgsAsWritten = Record[Index++];
5875 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5876 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5877 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5878 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5879}
5880
Guy Benyei11169dd2012-12-18 14:30:41 +00005881Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5882 return GetDecl(ID);
5883}
5884
Richard Smith50895422015-01-31 03:04:55 +00005885template<typename TemplateSpecializationDecl>
5886static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5887 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5888 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5889}
5890
Richard Smith053f6c62014-05-16 23:01:30 +00005891void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005892 if (NumCurrentElementsDeserializing) {
5893 // We arrange to not care about the complete redeclaration chain while we're
5894 // deserializing. Just remember that the AST has marked this one as complete
5895 // but that it's not actually complete yet, so we know we still need to
5896 // complete it later.
5897 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5898 return;
5899 }
5900
Richard Smith053f6c62014-05-16 23:01:30 +00005901 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5902
Richard Smith053f6c62014-05-16 23:01:30 +00005903 // If this is a named declaration, complete it by looking it up
5904 // within its context.
5905 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005906 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005907 // all mergeable entities within it.
5908 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5909 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5910 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00005911 if (!getContext().getLangOpts().CPlusPlus &&
5912 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00005913 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00005914 // the identifier instead. (For C++ modules, we don't store decls
5915 // in the serialized identifier table, so we do the lookup in the TU.)
5916 auto *II = Name.getAsIdentifierInfo();
5917 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00005918 if (II->isOutOfDate())
5919 updateOutOfDateIdentifier(*II);
5920 } else
5921 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005922 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
5923 // FIXME: It'd be nice to do something a bit more targeted here.
5924 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00005925 }
5926 }
Richard Smith50895422015-01-31 03:04:55 +00005927
5928 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5929 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5930 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5931 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5932 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5933 if (auto *Template = FD->getPrimaryTemplate())
5934 Template->LoadLazySpecializations();
5935 }
Richard Smith053f6c62014-05-16 23:01:30 +00005936}
5937
Richard Smithc2bb8182015-03-24 06:36:48 +00005938uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5939 const RecordData &Record,
5940 unsigned &Idx) {
5941 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5942 Error("malformed AST file: missing C++ ctor initializers");
5943 return 0;
5944 }
5945
5946 unsigned LocalID = Record[Idx++];
5947 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
5948}
5949
5950CXXCtorInitializer **
5951ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
5952 RecordLocation Loc = getLocalBitOffset(Offset);
5953 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
5954 SavedStreamPosition SavedPosition(Cursor);
5955 Cursor.JumpToBit(Loc.Offset);
5956 ReadingKindTracker ReadingKind(Read_Decl, *this);
5957
5958 RecordData Record;
5959 unsigned Code = Cursor.ReadCode();
5960 unsigned RecCode = Cursor.readRecord(Code, Record);
5961 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
5962 Error("malformed AST file: missing C++ ctor initializers");
5963 return nullptr;
5964 }
5965
5966 unsigned Idx = 0;
5967 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
5968}
5969
Richard Smithcd45dbc2014-04-19 03:48:30 +00005970uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5971 const RecordData &Record,
5972 unsigned &Idx) {
5973 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5974 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005975 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005976 }
5977
Guy Benyei11169dd2012-12-18 14:30:41 +00005978 unsigned LocalID = Record[Idx++];
5979 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5980}
5981
5982CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5983 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005984 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005985 SavedStreamPosition SavedPosition(Cursor);
5986 Cursor.JumpToBit(Loc.Offset);
5987 ReadingKindTracker ReadingKind(Read_Decl, *this);
5988 RecordData Record;
5989 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005990 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005991 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005992 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00005993 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005994 }
5995
5996 unsigned Idx = 0;
5997 unsigned NumBases = Record[Idx++];
5998 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5999 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6000 for (unsigned I = 0; I != NumBases; ++I)
6001 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6002 return Bases;
6003}
6004
6005serialization::DeclID
6006ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6007 if (LocalID < NUM_PREDEF_DECL_IDS)
6008 return LocalID;
6009
6010 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6011 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6012 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6013
6014 return LocalID + I->second;
6015}
6016
6017bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6018 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006019 // Predefined decls aren't from any module.
6020 if (ID < NUM_PREDEF_DECL_IDS)
6021 return false;
6022
Richard Smithbcda1a92015-07-12 23:51:20 +00006023 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6024 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006025}
6026
Douglas Gregor9f782892013-01-21 15:25:38 +00006027ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006028 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006029 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006030 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6031 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6032 return I->second;
6033}
6034
6035SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6036 if (ID < NUM_PREDEF_DECL_IDS)
6037 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006038
Guy Benyei11169dd2012-12-18 14:30:41 +00006039 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6040
6041 if (Index > DeclsLoaded.size()) {
6042 Error("declaration ID out-of-range for AST file");
6043 return SourceLocation();
6044 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006045
Guy Benyei11169dd2012-12-18 14:30:41 +00006046 if (Decl *D = DeclsLoaded[Index])
6047 return D->getLocation();
6048
6049 unsigned RawLocation = 0;
6050 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6051 return ReadSourceLocation(*Rec.F, RawLocation);
6052}
6053
Richard Smithfe620d22015-03-05 23:24:12 +00006054static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6055 switch (ID) {
6056 case PREDEF_DECL_NULL_ID:
6057 return nullptr;
6058
6059 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6060 return Context.getTranslationUnitDecl();
6061
6062 case PREDEF_DECL_OBJC_ID_ID:
6063 return Context.getObjCIdDecl();
6064
6065 case PREDEF_DECL_OBJC_SEL_ID:
6066 return Context.getObjCSelDecl();
6067
6068 case PREDEF_DECL_OBJC_CLASS_ID:
6069 return Context.getObjCClassDecl();
6070
6071 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6072 return Context.getObjCProtocolDecl();
6073
6074 case PREDEF_DECL_INT_128_ID:
6075 return Context.getInt128Decl();
6076
6077 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6078 return Context.getUInt128Decl();
6079
6080 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6081 return Context.getObjCInstanceTypeDecl();
6082
6083 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6084 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006085
6086 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6087 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006088 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006089 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006090}
6091
Richard Smithcd45dbc2014-04-19 03:48:30 +00006092Decl *ASTReader::GetExistingDecl(DeclID ID) {
6093 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006094 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6095 if (D) {
6096 // Track that we have merged the declaration with ID \p ID into the
6097 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006098 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006099 if (Merged.empty())
6100 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006101 }
Richard Smithfe620d22015-03-05 23:24:12 +00006102 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006103 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006104
Guy Benyei11169dd2012-12-18 14:30:41 +00006105 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6106
6107 if (Index >= DeclsLoaded.size()) {
6108 assert(0 && "declaration ID out-of-range for AST file");
6109 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006110 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006111 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006112
6113 return DeclsLoaded[Index];
6114}
6115
6116Decl *ASTReader::GetDecl(DeclID ID) {
6117 if (ID < NUM_PREDEF_DECL_IDS)
6118 return GetExistingDecl(ID);
6119
6120 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6121
6122 if (Index >= DeclsLoaded.size()) {
6123 assert(0 && "declaration ID out-of-range for AST file");
6124 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006125 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006126 }
6127
Guy Benyei11169dd2012-12-18 14:30:41 +00006128 if (!DeclsLoaded[Index]) {
6129 ReadDeclRecord(ID);
6130 if (DeserializationListener)
6131 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6132 }
6133
6134 return DeclsLoaded[Index];
6135}
6136
6137DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6138 DeclID GlobalID) {
6139 if (GlobalID < NUM_PREDEF_DECL_IDS)
6140 return GlobalID;
6141
6142 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6143 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6144 ModuleFile *Owner = I->second;
6145
6146 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6147 = M.GlobalToLocalDeclIDs.find(Owner);
6148 if (Pos == M.GlobalToLocalDeclIDs.end())
6149 return 0;
6150
6151 return GlobalID - Owner->BaseDeclID + Pos->second;
6152}
6153
6154serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6155 const RecordData &Record,
6156 unsigned &Idx) {
6157 if (Idx >= Record.size()) {
6158 Error("Corrupted AST file");
6159 return 0;
6160 }
6161
6162 return getGlobalDeclID(F, Record[Idx++]);
6163}
6164
6165/// \brief Resolve the offset of a statement into a statement.
6166///
6167/// This operation will read a new statement from the external
6168/// source each time it is called, and is meant to be used via a
6169/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6170Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6171 // Switch case IDs are per Decl.
6172 ClearSwitchCaseIDs();
6173
6174 // Offset here is a global offset across the entire chain.
6175 RecordLocation Loc = getLocalBitOffset(Offset);
6176 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6177 return ReadStmtFromStream(*Loc.F);
6178}
6179
6180namespace {
6181 class FindExternalLexicalDeclsVisitor {
6182 ASTReader &Reader;
6183 const DeclContext *DC;
6184 bool (*isKindWeWant)(Decl::Kind);
6185
6186 SmallVectorImpl<Decl*> &Decls;
6187 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6188
6189 public:
6190 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6191 bool (*isKindWeWant)(Decl::Kind),
6192 SmallVectorImpl<Decl*> &Decls)
6193 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6194 {
6195 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6196 PredefsVisited[I] = false;
6197 }
6198
Manuel Klimek9eff8b12015-05-20 10:29:23 +00006199 static bool visitPostorder(ModuleFile &M, void *UserData) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006200 FindExternalLexicalDeclsVisitor *This
6201 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6202
6203 ModuleFile::DeclContextInfosMap::iterator Info
6204 = M.DeclContextInfos.find(This->DC);
6205 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6206 return false;
6207
6208 // Load all of the declaration IDs
6209 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6210 *IDE = ID + Info->second.NumLexicalDecls;
6211 ID != IDE; ++ID) {
6212 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6213 continue;
6214
6215 // Don't add predefined declarations to the lexical context more
6216 // than once.
6217 if (ID->second < NUM_PREDEF_DECL_IDS) {
6218 if (This->PredefsVisited[ID->second])
6219 continue;
6220
6221 This->PredefsVisited[ID->second] = true;
6222 }
6223
6224 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6225 if (!This->DC->isDeclInLexicalTraversal(D))
6226 This->Decls.push_back(D);
6227 }
6228 }
6229
6230 return false;
6231 }
6232 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006233}
Guy Benyei11169dd2012-12-18 14:30:41 +00006234
6235ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6236 bool (*isKindWeWant)(Decl::Kind),
6237 SmallVectorImpl<Decl*> &Decls) {
6238 // There might be lexical decls in multiple modules, for the TU at
6239 // least. Walk all of the modules in the order they were loaded.
6240 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
Manuel Klimek9eff8b12015-05-20 10:29:23 +00006241 ModuleMgr.visitDepthFirst(
6242 nullptr, &FindExternalLexicalDeclsVisitor::visitPostorder, &Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006243 ++NumLexicalDeclContextsRead;
6244 return ELR_Success;
6245}
6246
6247namespace {
6248
6249class DeclIDComp {
6250 ASTReader &Reader;
6251 ModuleFile &Mod;
6252
6253public:
6254 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6255
6256 bool operator()(LocalDeclID L, LocalDeclID R) const {
6257 SourceLocation LHS = getLocation(L);
6258 SourceLocation RHS = getLocation(R);
6259 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6260 }
6261
6262 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6263 SourceLocation RHS = getLocation(R);
6264 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6265 }
6266
6267 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6268 SourceLocation LHS = getLocation(L);
6269 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6270 }
6271
6272 SourceLocation getLocation(LocalDeclID ID) const {
6273 return Reader.getSourceManager().getFileLoc(
6274 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6275 }
6276};
6277
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006278}
Guy Benyei11169dd2012-12-18 14:30:41 +00006279
6280void ASTReader::FindFileRegionDecls(FileID File,
6281 unsigned Offset, unsigned Length,
6282 SmallVectorImpl<Decl *> &Decls) {
6283 SourceManager &SM = getSourceManager();
6284
6285 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6286 if (I == FileDeclIDs.end())
6287 return;
6288
6289 FileDeclsInfo &DInfo = I->second;
6290 if (DInfo.Decls.empty())
6291 return;
6292
6293 SourceLocation
6294 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6295 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6296
6297 DeclIDComp DIDComp(*this, *DInfo.Mod);
6298 ArrayRef<serialization::LocalDeclID>::iterator
6299 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6300 BeginLoc, DIDComp);
6301 if (BeginIt != DInfo.Decls.begin())
6302 --BeginIt;
6303
6304 // If we are pointing at a top-level decl inside an objc container, we need
6305 // to backtrack until we find it otherwise we will fail to report that the
6306 // region overlaps with an objc container.
6307 while (BeginIt != DInfo.Decls.begin() &&
6308 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6309 ->isTopLevelDeclInObjCContainer())
6310 --BeginIt;
6311
6312 ArrayRef<serialization::LocalDeclID>::iterator
6313 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6314 EndLoc, DIDComp);
6315 if (EndIt != DInfo.Decls.end())
6316 ++EndIt;
6317
6318 for (ArrayRef<serialization::LocalDeclID>::iterator
6319 DIt = BeginIt; DIt != EndIt; ++DIt)
6320 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6321}
6322
Richard Smith3b637412015-07-14 18:42:41 +00006323/// \brief Retrieve the "definitive" module file for the definition of the
6324/// given declaration context, if there is one.
6325///
6326/// The "definitive" module file is the only place where we need to look to
6327/// find information about the declarations within the given declaration
6328/// context. For example, C++ and Objective-C classes, C structs/unions, and
6329/// Objective-C protocols, categories, and extensions are all defined in a
6330/// single place in the source code, so they have definitive module files
6331/// associated with them. C++ namespaces, on the other hand, can have
6332/// definitions in multiple different module files.
6333///
6334/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6335/// NDEBUG checking.
6336static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6337 ASTReader &Reader) {
6338 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6339 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6340
6341 return nullptr;
6342}
6343
Guy Benyei11169dd2012-12-18 14:30:41 +00006344namespace {
6345 /// \brief ModuleFile visitor used to perform name lookup into a
6346 /// declaration context.
6347 class DeclContextNameLookupVisitor {
6348 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006349 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006350 DeclarationName Name;
Richard Smith3b637412015-07-14 18:42:41 +00006351 ASTDeclContextNameLookupTrait::DeclNameKey NameKey;
6352 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00006353 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006354 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006355
6356 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006357 DeclContextNameLookupVisitor(ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006358 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006359 SmallVectorImpl<NamedDecl *> &Decls,
6360 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
Richard Smith3b637412015-07-14 18:42:41 +00006361 : Reader(Reader), Name(Name),
6362 NameKey(ASTDeclContextNameLookupTrait::GetInternalKey(Name)),
6363 NameHash(ASTDeclContextNameLookupTrait::ComputeHash(NameKey)),
6364 Decls(Decls), DeclSet(DeclSet) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006365
Richard Smith3b637412015-07-14 18:42:41 +00006366 void visitContexts(ArrayRef<const DeclContext*> Contexts) {
6367 if (Contexts.empty())
6368 return;
6369 this->Contexts = Contexts;
6370
6371 // If we can definitively determine which module file to look into,
6372 // only look there. Otherwise, look in all module files.
6373 ModuleFile *Definitive;
6374 if (Contexts.size() == 1 &&
6375 (Definitive = getDefinitiveModuleFileFor(Contexts[0], Reader))) {
6376 visit(*Definitive, this);
6377 } else {
6378 Reader.getModuleManager().visit(&visit, this);
6379 }
6380 }
6381
6382 private:
Guy Benyei11169dd2012-12-18 14:30:41 +00006383 static bool visit(ModuleFile &M, void *UserData) {
6384 DeclContextNameLookupVisitor *This
6385 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6386
6387 // Check whether we have any visible declaration information for
6388 // this context in this module.
6389 ModuleFile::DeclContextInfosMap::iterator Info;
6390 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006391 for (auto *DC : This->Contexts) {
6392 Info = M.DeclContextInfos.find(DC);
6393 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006394 Info->second.NameLookupTableData) {
6395 FoundInfo = true;
6396 break;
6397 }
6398 }
6399
6400 if (!FoundInfo)
6401 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006402
Guy Benyei11169dd2012-12-18 14:30:41 +00006403 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006404 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006405 Info->second.NameLookupTableData;
6406 ASTDeclContextNameLookupTable::iterator Pos
Richard Smith3b637412015-07-14 18:42:41 +00006407 = LookupTable->find_hashed(This->NameKey, This->NameHash);
Guy Benyei11169dd2012-12-18 14:30:41 +00006408 if (Pos == LookupTable->end())
6409 return false;
6410
6411 bool FoundAnything = false;
6412 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6413 for (; Data.first != Data.second; ++Data.first) {
6414 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6415 if (!ND)
6416 continue;
6417
6418 if (ND->getDeclName() != This->Name) {
6419 // A name might be null because the decl's redeclarable part is
6420 // currently read before reading its name. The lookup is triggered by
6421 // building that decl (likely indirectly), and so it is later in the
6422 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006423 // FIXME: This should not happen; deserializing declarations should
6424 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006425 continue;
6426 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006427
Guy Benyei11169dd2012-12-18 14:30:41 +00006428 // Record this declaration.
6429 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006430 if (This->DeclSet.insert(ND).second)
6431 This->Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006432 }
6433
6434 return FoundAnything;
6435 }
6436 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006437}
Guy Benyei11169dd2012-12-18 14:30:41 +00006438
Richard Smith9ce12e32013-02-07 03:30:24 +00006439bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006440ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6441 DeclarationName Name) {
6442 assert(DC->hasExternalVisibleStorage() &&
6443 "DeclContext has no visible decls in storage");
6444 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006445 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006446
Richard Smith8c913ec2014-08-14 02:21:01 +00006447 Deserializing LookupResults(this);
6448
Guy Benyei11169dd2012-12-18 14:30:41 +00006449 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006450 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006451
Guy Benyei11169dd2012-12-18 14:30:41 +00006452 // Compute the declaration contexts we need to look into. Multiple such
6453 // declaration contexts occur when two declaration contexts from disjoint
6454 // modules get merged, e.g., when two namespaces with the same name are
6455 // independently defined in separate modules.
6456 SmallVector<const DeclContext *, 2> Contexts;
6457 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006458
Guy Benyei11169dd2012-12-18 14:30:41 +00006459 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006460 auto Key = KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6461 if (Key != KeyDecls.end()) {
6462 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6463 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006464 }
6465 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006466
Richard Smith3b637412015-07-14 18:42:41 +00006467 DeclContextNameLookupVisitor Visitor(*this, Name, Decls, DeclSet);
6468 Visitor.visitContexts(Contexts);
Richard Smith8c913ec2014-08-14 02:21:01 +00006469
6470 // If this might be an implicit special member function, then also search
6471 // all merged definitions of the surrounding class. We need to search them
6472 // individually, because finding an entity in one of them doesn't imply that
6473 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006474 if (isa<CXXRecordDecl>(DC)) {
Richard Smith02793752015-03-27 21:16:39 +00006475 auto Merged = MergedLookups.find(DC);
6476 if (Merged != MergedLookups.end()) {
6477 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6478 const DeclContext *Context = Merged->second[I];
Richard Smith3b637412015-07-14 18:42:41 +00006479 Visitor.visitContexts(Context);
Richard Smith02793752015-03-27 21:16:39 +00006480 // We might have just added some more merged lookups. If so, our
6481 // iterator is now invalid, so grab a fresh one before continuing.
6482 Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006483 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006484 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006485 }
6486
Guy Benyei11169dd2012-12-18 14:30:41 +00006487 ++NumVisibleDeclContextsRead;
6488 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006489 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006490}
6491
6492namespace {
6493 /// \brief ModuleFile visitor used to retrieve all visible names in a
6494 /// declaration context.
6495 class DeclContextAllNamesVisitor {
6496 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006497 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006498 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006499 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006500 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006501
6502 public:
6503 DeclContextAllNamesVisitor(ASTReader &Reader,
6504 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006505 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006506 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006507
6508 static bool visit(ModuleFile &M, void *UserData) {
6509 DeclContextAllNamesVisitor *This
6510 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6511
6512 // Check whether we have any visible declaration information for
6513 // this context in this module.
6514 ModuleFile::DeclContextInfosMap::iterator Info;
6515 bool FoundInfo = false;
6516 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6517 Info = M.DeclContextInfos.find(This->Contexts[I]);
6518 if (Info != M.DeclContextInfos.end() &&
6519 Info->second.NameLookupTableData) {
6520 FoundInfo = true;
6521 break;
6522 }
6523 }
6524
6525 if (!FoundInfo)
6526 return false;
6527
Richard Smith52e3fba2014-03-11 07:17:35 +00006528 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006529 Info->second.NameLookupTableData;
6530 bool FoundAnything = false;
6531 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006532 I = LookupTable->data_begin(), E = LookupTable->data_end();
6533 I != E;
6534 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006535 ASTDeclContextNameLookupTrait::data_type Data = *I;
6536 for (; Data.first != Data.second; ++Data.first) {
6537 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6538 *Data.first);
6539 if (!ND)
6540 continue;
6541
6542 // Record this declaration.
6543 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006544 if (This->DeclSet.insert(ND).second)
6545 This->Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006546 }
6547 }
6548
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006549 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006550 }
6551 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006552}
Guy Benyei11169dd2012-12-18 14:30:41 +00006553
6554void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6555 if (!DC->hasExternalVisibleStorage())
6556 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006557 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006558
6559 // Compute the declaration contexts we need to look into. Multiple such
6560 // declaration contexts occur when two declaration contexts from disjoint
6561 // modules get merged, e.g., when two namespaces with the same name are
6562 // independently defined in separate modules.
6563 SmallVector<const DeclContext *, 2> Contexts;
6564 Contexts.push_back(DC);
6565
6566 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006567 KeyDeclsMap::iterator Key =
6568 KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6569 if (Key != KeyDecls.end()) {
6570 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6571 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006572 }
6573 }
6574
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006575 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6576 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006577 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6578 ++NumVisibleDeclContextsRead;
6579
Craig Topper79be4cd2013-07-05 04:33:53 +00006580 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006581 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6582 }
6583 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6584}
6585
6586/// \brief Under non-PCH compilation the consumer receives the objc methods
6587/// before receiving the implementation, and codegen depends on this.
6588/// We simulate this by deserializing and passing to consumer the methods of the
6589/// implementation before passing the deserialized implementation decl.
6590static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6591 ASTConsumer *Consumer) {
6592 assert(ImplD && Consumer);
6593
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006594 for (auto *I : ImplD->methods())
6595 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006596
6597 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6598}
6599
6600void ASTReader::PassInterestingDeclsToConsumer() {
6601 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006602
6603 if (PassingDeclsToConsumer)
6604 return;
6605
6606 // Guard variable to avoid recursively redoing the process of passing
6607 // decls to consumer.
6608 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6609 true);
6610
Richard Smith9e2341d2015-03-23 03:25:59 +00006611 // Ensure that we've loaded all potentially-interesting declarations
6612 // that need to be eagerly loaded.
6613 for (auto ID : EagerlyDeserializedDecls)
6614 GetDecl(ID);
6615 EagerlyDeserializedDecls.clear();
6616
Guy Benyei11169dd2012-12-18 14:30:41 +00006617 while (!InterestingDecls.empty()) {
6618 Decl *D = InterestingDecls.front();
6619 InterestingDecls.pop_front();
6620
6621 PassInterestingDeclToConsumer(D);
6622 }
6623}
6624
6625void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6626 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6627 PassObjCImplDeclToConsumer(ImplD, Consumer);
6628 else
6629 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6630}
6631
6632void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6633 this->Consumer = Consumer;
6634
Richard Smith9e2341d2015-03-23 03:25:59 +00006635 if (Consumer)
6636 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006637
6638 if (DeserializationListener)
6639 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006640}
6641
6642void ASTReader::PrintStats() {
6643 std::fprintf(stderr, "*** AST File Statistics:\n");
6644
6645 unsigned NumTypesLoaded
6646 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6647 QualType());
6648 unsigned NumDeclsLoaded
6649 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006650 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006651 unsigned NumIdentifiersLoaded
6652 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6653 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006654 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006655 unsigned NumMacrosLoaded
6656 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6657 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006658 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006659 unsigned NumSelectorsLoaded
6660 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6661 SelectorsLoaded.end(),
6662 Selector());
6663
6664 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6665 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6666 NumSLocEntriesRead, TotalNumSLocEntries,
6667 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6668 if (!TypesLoaded.empty())
6669 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6670 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6671 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6672 if (!DeclsLoaded.empty())
6673 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6674 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6675 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6676 if (!IdentifiersLoaded.empty())
6677 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6678 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6679 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6680 if (!MacrosLoaded.empty())
6681 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6682 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6683 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6684 if (!SelectorsLoaded.empty())
6685 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6686 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6687 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6688 if (TotalNumStatements)
6689 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6690 NumStatementsRead, TotalNumStatements,
6691 ((float)NumStatementsRead/TotalNumStatements * 100));
6692 if (TotalNumMacros)
6693 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6694 NumMacrosRead, TotalNumMacros,
6695 ((float)NumMacrosRead/TotalNumMacros * 100));
6696 if (TotalLexicalDeclContexts)
6697 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6698 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6699 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6700 * 100));
6701 if (TotalVisibleDeclContexts)
6702 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6703 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6704 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6705 * 100));
6706 if (TotalNumMethodPoolEntries) {
6707 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6708 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6709 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6710 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006711 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006712 if (NumMethodPoolLookups) {
6713 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6714 NumMethodPoolHits, NumMethodPoolLookups,
6715 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6716 }
6717 if (NumMethodPoolTableLookups) {
6718 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6719 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6720 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6721 * 100.0));
6722 }
6723
Douglas Gregor00a50f72013-01-25 00:38:33 +00006724 if (NumIdentifierLookupHits) {
6725 std::fprintf(stderr,
6726 " %u / %u identifier table lookups succeeded (%f%%)\n",
6727 NumIdentifierLookupHits, NumIdentifierLookups,
6728 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6729 }
6730
Douglas Gregore060e572013-01-25 01:03:03 +00006731 if (GlobalIndex) {
6732 std::fprintf(stderr, "\n");
6733 GlobalIndex->printStats();
6734 }
6735
Guy Benyei11169dd2012-12-18 14:30:41 +00006736 std::fprintf(stderr, "\n");
6737 dump();
6738 std::fprintf(stderr, "\n");
6739}
6740
6741template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6742static void
6743dumpModuleIDMap(StringRef Name,
6744 const ContinuousRangeMap<Key, ModuleFile *,
6745 InitialCapacity> &Map) {
6746 if (Map.begin() == Map.end())
6747 return;
6748
6749 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6750 llvm::errs() << Name << ":\n";
6751 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6752 I != IEnd; ++I) {
6753 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6754 << "\n";
6755 }
6756}
6757
6758void ASTReader::dump() {
6759 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6760 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6761 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6762 dumpModuleIDMap("Global type map", GlobalTypeMap);
6763 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6764 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6765 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6766 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6767 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6768 dumpModuleIDMap("Global preprocessed entity map",
6769 GlobalPreprocessedEntityMap);
6770
6771 llvm::errs() << "\n*** PCH/Modules Loaded:";
6772 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6773 MEnd = ModuleMgr.end();
6774 M != MEnd; ++M)
6775 (*M)->dump();
6776}
6777
6778/// Return the amount of memory used by memory buffers, breaking down
6779/// by heap-backed versus mmap'ed memory.
6780void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6781 for (ModuleConstIterator I = ModuleMgr.begin(),
6782 E = ModuleMgr.end(); I != E; ++I) {
6783 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6784 size_t bytes = buf->getBufferSize();
6785 switch (buf->getBufferKind()) {
6786 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6787 sizes.malloc_bytes += bytes;
6788 break;
6789 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6790 sizes.mmap_bytes += bytes;
6791 break;
6792 }
6793 }
6794 }
6795}
6796
6797void ASTReader::InitializeSema(Sema &S) {
6798 SemaObj = &S;
6799 S.addExternalSource(this);
6800
6801 // Makes sure any declarations that were deserialized "too early"
6802 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006803 for (uint64_t ID : PreloadedDeclIDs) {
6804 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6805 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006806 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006807 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006808
Richard Smith3d8e97e2013-10-18 06:54:39 +00006809 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006810 if (!FPPragmaOptions.empty()) {
6811 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6812 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6813 }
6814
Richard Smith3d8e97e2013-10-18 06:54:39 +00006815 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006816 if (!OpenCLExtensions.empty()) {
6817 unsigned I = 0;
6818#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6819#include "clang/Basic/OpenCLExtensions.def"
6820
6821 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6822 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006823
6824 UpdateSema();
6825}
6826
6827void ASTReader::UpdateSema() {
6828 assert(SemaObj && "no Sema to update");
6829
6830 // Load the offsets of the declarations that Sema references.
6831 // They will be lazily deserialized when needed.
6832 if (!SemaDeclRefs.empty()) {
6833 assert(SemaDeclRefs.size() % 2 == 0);
6834 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6835 if (!SemaObj->StdNamespace)
6836 SemaObj->StdNamespace = SemaDeclRefs[I];
6837 if (!SemaObj->StdBadAlloc)
6838 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6839 }
6840 SemaDeclRefs.clear();
6841 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006842
6843 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6844 // encountered the pragma in the source.
6845 if(OptimizeOffPragmaLocation.isValid())
6846 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006847}
6848
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006849IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006850 // Note that we are loading an identifier.
6851 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006852
Douglas Gregor7211ac12013-01-25 23:32:03 +00006853 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006854 NumIdentifierLookups,
6855 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006856
6857 // We don't need to do identifier table lookups in C++ modules (we preload
6858 // all interesting declarations, and don't need to use the scope for name
6859 // lookups). Perform the lookup in PCH files, though, since we don't build
6860 // a complete initial identifier table if we're carrying on from a PCH.
6861 if (Context.getLangOpts().CPlusPlus) {
6862 for (auto F : ModuleMgr.pch_modules())
6863 if (Visitor.visit(*F, &Visitor))
6864 break;
6865 } else {
6866 // If there is a global index, look there first to determine which modules
6867 // provably do not have any results for this identifier.
6868 GlobalModuleIndex::HitSet Hits;
6869 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6870 if (!loadGlobalIndex()) {
6871 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6872 HitsPtr = &Hits;
6873 }
6874 }
6875
6876 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
6877 }
6878
Guy Benyei11169dd2012-12-18 14:30:41 +00006879 IdentifierInfo *II = Visitor.getIdentifierInfo();
6880 markIdentifierUpToDate(II);
6881 return II;
6882}
6883
6884namespace clang {
6885 /// \brief An identifier-lookup iterator that enumerates all of the
6886 /// identifiers stored within a set of AST files.
6887 class ASTIdentifierIterator : public IdentifierIterator {
6888 /// \brief The AST reader whose identifiers are being enumerated.
6889 const ASTReader &Reader;
6890
6891 /// \brief The current index into the chain of AST files stored in
6892 /// the AST reader.
6893 unsigned Index;
6894
6895 /// \brief The current position within the identifier lookup table
6896 /// of the current AST file.
6897 ASTIdentifierLookupTable::key_iterator Current;
6898
6899 /// \brief The end position within the identifier lookup table of
6900 /// the current AST file.
6901 ASTIdentifierLookupTable::key_iterator End;
6902
6903 public:
6904 explicit ASTIdentifierIterator(const ASTReader &Reader);
6905
Craig Topper3e89dfe2014-03-13 02:13:41 +00006906 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006907 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006908}
Guy Benyei11169dd2012-12-18 14:30:41 +00006909
6910ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6911 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6912 ASTIdentifierLookupTable *IdTable
6913 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6914 Current = IdTable->key_begin();
6915 End = IdTable->key_end();
6916}
6917
6918StringRef ASTIdentifierIterator::Next() {
6919 while (Current == End) {
6920 // If we have exhausted all of our AST files, we're done.
6921 if (Index == 0)
6922 return StringRef();
6923
6924 --Index;
6925 ASTIdentifierLookupTable *IdTable
6926 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6927 IdentifierLookupTable;
6928 Current = IdTable->key_begin();
6929 End = IdTable->key_end();
6930 }
6931
6932 // We have any identifiers remaining in the current AST file; return
6933 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006934 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006935 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006936 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006937}
6938
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006939IdentifierIterator *ASTReader::getIdentifiers() {
6940 if (!loadGlobalIndex())
6941 return GlobalIndex->createIdentifierIterator();
6942
Guy Benyei11169dd2012-12-18 14:30:41 +00006943 return new ASTIdentifierIterator(*this);
6944}
6945
6946namespace clang { namespace serialization {
6947 class ReadMethodPoolVisitor {
6948 ASTReader &Reader;
6949 Selector Sel;
6950 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006951 unsigned InstanceBits;
6952 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006953 bool InstanceHasMoreThanOneDecl;
6954 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006955 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6956 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006957
6958 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006959 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006960 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006961 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006962 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6963 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006964
Guy Benyei11169dd2012-12-18 14:30:41 +00006965 static bool visit(ModuleFile &M, void *UserData) {
6966 ReadMethodPoolVisitor *This
6967 = static_cast<ReadMethodPoolVisitor *>(UserData);
6968
6969 if (!M.SelectorLookupTable)
6970 return false;
6971
6972 // If we've already searched this module file, skip it now.
6973 if (M.Generation <= This->PriorGeneration)
6974 return true;
6975
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006976 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006977 ASTSelectorLookupTable *PoolTable
6978 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6979 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6980 if (Pos == PoolTable->end())
6981 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006982
6983 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006984 ++This->Reader.NumSelectorsRead;
6985 // FIXME: Not quite happy with the statistics here. We probably should
6986 // disable this tracking when called via LoadSelector.
6987 // Also, should entries without methods count as misses?
6988 ++This->Reader.NumMethodPoolEntriesRead;
6989 ASTSelectorLookupTrait::data_type Data = *Pos;
6990 if (This->Reader.DeserializationListener)
6991 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6992 This->Sel);
6993
6994 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6995 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006996 This->InstanceBits = Data.InstanceBits;
6997 This->FactoryBits = Data.FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006998 This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6999 This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007000 return true;
7001 }
7002
7003 /// \brief Retrieve the instance methods found by this visitor.
7004 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7005 return InstanceMethods;
7006 }
7007
7008 /// \brief Retrieve the instance methods found by this visitor.
7009 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7010 return FactoryMethods;
7011 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007012
7013 unsigned getInstanceBits() const { return InstanceBits; }
7014 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007015 bool instanceHasMoreThanOneDecl() const {
7016 return InstanceHasMoreThanOneDecl;
7017 }
7018 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007019 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007020} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00007021
7022/// \brief Add the given set of methods to the method list.
7023static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7024 ObjCMethodList &List) {
7025 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7026 S.addMethodToGlobalList(&List, Methods[I]);
7027 }
7028}
7029
7030void ASTReader::ReadMethodPool(Selector Sel) {
7031 // Get the selector generation and update it to the current generation.
7032 unsigned &Generation = SelectorGeneration[Sel];
7033 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007034 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007035
7036 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007037 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007038 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7039 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7040
7041 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007042 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007043 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007044
7045 ++NumMethodPoolHits;
7046
Guy Benyei11169dd2012-12-18 14:30:41 +00007047 if (!getSema())
7048 return;
7049
7050 Sema &S = *getSema();
7051 Sema::GlobalMethodPool::iterator Pos
7052 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007053
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007054 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007055 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007056 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007057 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007058
7059 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7060 // when building a module we keep every method individually and may need to
7061 // update hasMoreThanOneDecl as we add the methods.
7062 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7063 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007064}
7065
7066void ASTReader::ReadKnownNamespaces(
7067 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7068 Namespaces.clear();
7069
7070 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7071 if (NamespaceDecl *Namespace
7072 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7073 Namespaces.push_back(Namespace);
7074 }
7075}
7076
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007077void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007078 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007079 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7080 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007081 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007082 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007083 Undefined.insert(std::make_pair(D, Loc));
7084 }
7085}
Nick Lewycky8334af82013-01-26 00:35:08 +00007086
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007087void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7088 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7089 Exprs) {
7090 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7091 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7092 uint64_t Count = DelayedDeleteExprs[Idx++];
7093 for (uint64_t C = 0; C < Count; ++C) {
7094 SourceLocation DeleteLoc =
7095 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7096 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7097 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7098 }
7099 }
7100}
7101
Guy Benyei11169dd2012-12-18 14:30:41 +00007102void ASTReader::ReadTentativeDefinitions(
7103 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7104 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7105 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7106 if (Var)
7107 TentativeDefs.push_back(Var);
7108 }
7109 TentativeDefinitions.clear();
7110}
7111
7112void ASTReader::ReadUnusedFileScopedDecls(
7113 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7114 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7115 DeclaratorDecl *D
7116 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7117 if (D)
7118 Decls.push_back(D);
7119 }
7120 UnusedFileScopedDecls.clear();
7121}
7122
7123void ASTReader::ReadDelegatingConstructors(
7124 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7125 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7126 CXXConstructorDecl *D
7127 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7128 if (D)
7129 Decls.push_back(D);
7130 }
7131 DelegatingCtorDecls.clear();
7132}
7133
7134void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7135 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7136 TypedefNameDecl *D
7137 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7138 if (D)
7139 Decls.push_back(D);
7140 }
7141 ExtVectorDecls.clear();
7142}
7143
Nico Weber72889432014-09-06 01:25:55 +00007144void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7145 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7146 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7147 ++I) {
7148 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7149 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7150 if (D)
7151 Decls.insert(D);
7152 }
7153 UnusedLocalTypedefNameCandidates.clear();
7154}
7155
Guy Benyei11169dd2012-12-18 14:30:41 +00007156void ASTReader::ReadReferencedSelectors(
7157 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7158 if (ReferencedSelectorsData.empty())
7159 return;
7160
7161 // If there are @selector references added them to its pool. This is for
7162 // implementation of -Wselector.
7163 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7164 unsigned I = 0;
7165 while (I < DataSize) {
7166 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7167 SourceLocation SelLoc
7168 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7169 Sels.push_back(std::make_pair(Sel, SelLoc));
7170 }
7171 ReferencedSelectorsData.clear();
7172}
7173
7174void ASTReader::ReadWeakUndeclaredIdentifiers(
7175 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7176 if (WeakUndeclaredIdentifiers.empty())
7177 return;
7178
7179 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7180 IdentifierInfo *WeakId
7181 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7182 IdentifierInfo *AliasId
7183 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7184 SourceLocation Loc
7185 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7186 bool Used = WeakUndeclaredIdentifiers[I++];
7187 WeakInfo WI(AliasId, Loc);
7188 WI.setUsed(Used);
7189 WeakIDs.push_back(std::make_pair(WeakId, WI));
7190 }
7191 WeakUndeclaredIdentifiers.clear();
7192}
7193
7194void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7195 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7196 ExternalVTableUse VT;
7197 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7198 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7199 VT.DefinitionRequired = VTableUses[Idx++];
7200 VTables.push_back(VT);
7201 }
7202
7203 VTableUses.clear();
7204}
7205
7206void ASTReader::ReadPendingInstantiations(
7207 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7208 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7209 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7210 SourceLocation Loc
7211 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7212
7213 Pending.push_back(std::make_pair(D, Loc));
7214 }
7215 PendingInstantiations.clear();
7216}
7217
Richard Smithe40f2ba2013-08-07 21:41:30 +00007218void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007219 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007220 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7221 /* In loop */) {
7222 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7223
7224 LateParsedTemplate *LT = new LateParsedTemplate;
7225 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7226
7227 ModuleFile *F = getOwningModuleFile(LT->D);
7228 assert(F && "No module");
7229
7230 unsigned TokN = LateParsedTemplates[Idx++];
7231 LT->Toks.reserve(TokN);
7232 for (unsigned T = 0; T < TokN; ++T)
7233 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7234
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007235 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007236 }
7237
7238 LateParsedTemplates.clear();
7239}
7240
Guy Benyei11169dd2012-12-18 14:30:41 +00007241void ASTReader::LoadSelector(Selector Sel) {
7242 // It would be complicated to avoid reading the methods anyway. So don't.
7243 ReadMethodPool(Sel);
7244}
7245
7246void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7247 assert(ID && "Non-zero identifier ID required");
7248 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7249 IdentifiersLoaded[ID - 1] = II;
7250 if (DeserializationListener)
7251 DeserializationListener->IdentifierRead(ID, II);
7252}
7253
7254/// \brief Set the globally-visible declarations associated with the given
7255/// identifier.
7256///
7257/// If the AST reader is currently in a state where the given declaration IDs
7258/// cannot safely be resolved, they are queued until it is safe to resolve
7259/// them.
7260///
7261/// \param II an IdentifierInfo that refers to one or more globally-visible
7262/// declarations.
7263///
7264/// \param DeclIDs the set of declaration IDs with the name @p II that are
7265/// visible at global scope.
7266///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007267/// \param Decls if non-null, this vector will be populated with the set of
7268/// deserialized declarations. These declarations will not be pushed into
7269/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007270void
7271ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7272 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007273 SmallVectorImpl<Decl *> *Decls) {
7274 if (NumCurrentElementsDeserializing && !Decls) {
7275 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007276 return;
7277 }
7278
7279 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007280 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007281 // Queue this declaration so that it will be added to the
7282 // translation unit scope and identifier's declaration chain
7283 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007284 PreloadedDeclIDs.push_back(DeclIDs[I]);
7285 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007286 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007287
7288 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7289
7290 // If we're simply supposed to record the declarations, do so now.
7291 if (Decls) {
7292 Decls->push_back(D);
7293 continue;
7294 }
7295
7296 // Introduce this declaration into the translation-unit scope
7297 // and add it to the declaration chain for this identifier, so
7298 // that (unqualified) name lookup will find it.
7299 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007300 }
7301}
7302
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007303IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007304 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007305 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007306
7307 if (IdentifiersLoaded.empty()) {
7308 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007309 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007310 }
7311
7312 ID -= 1;
7313 if (!IdentifiersLoaded[ID]) {
7314 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7315 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7316 ModuleFile *M = I->second;
7317 unsigned Index = ID - M->BaseIdentifierID;
7318 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7319
7320 // All of the strings in the AST file are preceded by a 16-bit length.
7321 // Extract that 16-bit length to avoid having to execute strlen().
7322 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7323 // unsigned integers. This is important to avoid integer overflow when
7324 // we cast them to 'unsigned'.
7325 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7326 unsigned StrLen = (((unsigned) StrLenPtr[0])
7327 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007328 IdentifiersLoaded[ID]
7329 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007330 if (DeserializationListener)
7331 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7332 }
7333
7334 return IdentifiersLoaded[ID];
7335}
7336
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007337IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7338 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007339}
7340
7341IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7342 if (LocalID < NUM_PREDEF_IDENT_IDS)
7343 return LocalID;
7344
7345 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7346 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7347 assert(I != M.IdentifierRemap.end()
7348 && "Invalid index into identifier index remap");
7349
7350 return LocalID + I->second;
7351}
7352
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007353MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007354 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007355 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007356
7357 if (MacrosLoaded.empty()) {
7358 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007359 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007360 }
7361
7362 ID -= NUM_PREDEF_MACRO_IDS;
7363 if (!MacrosLoaded[ID]) {
7364 GlobalMacroMapType::iterator I
7365 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7366 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7367 ModuleFile *M = I->second;
7368 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007369 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7370
7371 if (DeserializationListener)
7372 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7373 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007374 }
7375
7376 return MacrosLoaded[ID];
7377}
7378
7379MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7380 if (LocalID < NUM_PREDEF_MACRO_IDS)
7381 return LocalID;
7382
7383 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7384 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7385 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7386
7387 return LocalID + I->second;
7388}
7389
7390serialization::SubmoduleID
7391ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7392 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7393 return LocalID;
7394
7395 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7396 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7397 assert(I != M.SubmoduleRemap.end()
7398 && "Invalid index into submodule index remap");
7399
7400 return LocalID + I->second;
7401}
7402
7403Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7404 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7405 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007406 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007407 }
7408
7409 if (GlobalID > SubmodulesLoaded.size()) {
7410 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007411 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007412 }
7413
7414 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7415}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007416
7417Module *ASTReader::getModule(unsigned ID) {
7418 return getSubmodule(ID);
7419}
7420
Adrian Prantl15bcf702015-06-30 17:39:43 +00007421ExternalASTSource::ASTSourceDescriptor
7422ASTReader::getSourceDescriptor(const Module &M) {
7423 StringRef Dir, Filename;
7424 if (M.Directory)
7425 Dir = M.Directory->getName();
7426 if (auto *File = M.getASTFile())
7427 Filename = File->getName();
7428 return ASTReader::ASTSourceDescriptor{
7429 M.getFullModuleName(), Dir, Filename,
7430 M.Signature
7431 };
7432}
7433
7434llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7435ASTReader::getSourceDescriptor(unsigned ID) {
7436 if (const Module *M = getSubmodule(ID))
7437 return getSourceDescriptor(*M);
7438
7439 // If there is only a single PCH, return it instead.
7440 // Chained PCH are not suported.
7441 if (ModuleMgr.size() == 1) {
7442 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7443 return ASTReader::ASTSourceDescriptor{
7444 MF.OriginalSourceFileName, MF.OriginalDir,
7445 MF.FileName,
7446 MF.Signature
7447 };
7448 }
7449 return None;
7450}
7451
Guy Benyei11169dd2012-12-18 14:30:41 +00007452Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7453 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7454}
7455
7456Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7457 if (ID == 0)
7458 return Selector();
7459
7460 if (ID > SelectorsLoaded.size()) {
7461 Error("selector ID out of range in AST file");
7462 return Selector();
7463 }
7464
Craig Toppera13603a2014-05-22 05:54:18 +00007465 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007466 // Load this selector from the selector table.
7467 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7468 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7469 ModuleFile &M = *I->second;
7470 ASTSelectorLookupTrait Trait(*this, M);
7471 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7472 SelectorsLoaded[ID - 1] =
7473 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7474 if (DeserializationListener)
7475 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7476 }
7477
7478 return SelectorsLoaded[ID - 1];
7479}
7480
7481Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7482 return DecodeSelector(ID);
7483}
7484
7485uint32_t ASTReader::GetNumExternalSelectors() {
7486 // ID 0 (the null selector) is considered an external selector.
7487 return getTotalNumSelectors() + 1;
7488}
7489
7490serialization::SelectorID
7491ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7492 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7493 return LocalID;
7494
7495 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7496 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7497 assert(I != M.SelectorRemap.end()
7498 && "Invalid index into selector index remap");
7499
7500 return LocalID + I->second;
7501}
7502
7503DeclarationName
7504ASTReader::ReadDeclarationName(ModuleFile &F,
7505 const RecordData &Record, unsigned &Idx) {
7506 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7507 switch (Kind) {
7508 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007509 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007510
7511 case DeclarationName::ObjCZeroArgSelector:
7512 case DeclarationName::ObjCOneArgSelector:
7513 case DeclarationName::ObjCMultiArgSelector:
7514 return DeclarationName(ReadSelector(F, Record, Idx));
7515
7516 case DeclarationName::CXXConstructorName:
7517 return Context.DeclarationNames.getCXXConstructorName(
7518 Context.getCanonicalType(readType(F, Record, Idx)));
7519
7520 case DeclarationName::CXXDestructorName:
7521 return Context.DeclarationNames.getCXXDestructorName(
7522 Context.getCanonicalType(readType(F, Record, Idx)));
7523
7524 case DeclarationName::CXXConversionFunctionName:
7525 return Context.DeclarationNames.getCXXConversionFunctionName(
7526 Context.getCanonicalType(readType(F, Record, Idx)));
7527
7528 case DeclarationName::CXXOperatorName:
7529 return Context.DeclarationNames.getCXXOperatorName(
7530 (OverloadedOperatorKind)Record[Idx++]);
7531
7532 case DeclarationName::CXXLiteralOperatorName:
7533 return Context.DeclarationNames.getCXXLiteralOperatorName(
7534 GetIdentifierInfo(F, Record, Idx));
7535
7536 case DeclarationName::CXXUsingDirective:
7537 return DeclarationName::getUsingDirectiveName();
7538 }
7539
7540 llvm_unreachable("Invalid NameKind!");
7541}
7542
7543void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7544 DeclarationNameLoc &DNLoc,
7545 DeclarationName Name,
7546 const RecordData &Record, unsigned &Idx) {
7547 switch (Name.getNameKind()) {
7548 case DeclarationName::CXXConstructorName:
7549 case DeclarationName::CXXDestructorName:
7550 case DeclarationName::CXXConversionFunctionName:
7551 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7552 break;
7553
7554 case DeclarationName::CXXOperatorName:
7555 DNLoc.CXXOperatorName.BeginOpNameLoc
7556 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7557 DNLoc.CXXOperatorName.EndOpNameLoc
7558 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7559 break;
7560
7561 case DeclarationName::CXXLiteralOperatorName:
7562 DNLoc.CXXLiteralOperatorName.OpNameLoc
7563 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7564 break;
7565
7566 case DeclarationName::Identifier:
7567 case DeclarationName::ObjCZeroArgSelector:
7568 case DeclarationName::ObjCOneArgSelector:
7569 case DeclarationName::ObjCMultiArgSelector:
7570 case DeclarationName::CXXUsingDirective:
7571 break;
7572 }
7573}
7574
7575void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7576 DeclarationNameInfo &NameInfo,
7577 const RecordData &Record, unsigned &Idx) {
7578 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7579 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7580 DeclarationNameLoc DNLoc;
7581 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7582 NameInfo.setInfo(DNLoc);
7583}
7584
7585void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7586 const RecordData &Record, unsigned &Idx) {
7587 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7588 unsigned NumTPLists = Record[Idx++];
7589 Info.NumTemplParamLists = NumTPLists;
7590 if (NumTPLists) {
7591 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7592 for (unsigned i=0; i != NumTPLists; ++i)
7593 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7594 }
7595}
7596
7597TemplateName
7598ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7599 unsigned &Idx) {
7600 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7601 switch (Kind) {
7602 case TemplateName::Template:
7603 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7604
7605 case TemplateName::OverloadedTemplate: {
7606 unsigned size = Record[Idx++];
7607 UnresolvedSet<8> Decls;
7608 while (size--)
7609 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7610
7611 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7612 }
7613
7614 case TemplateName::QualifiedTemplate: {
7615 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7616 bool hasTemplKeyword = Record[Idx++];
7617 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7618 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7619 }
7620
7621 case TemplateName::DependentTemplate: {
7622 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7623 if (Record[Idx++]) // isIdentifier
7624 return Context.getDependentTemplateName(NNS,
7625 GetIdentifierInfo(F, Record,
7626 Idx));
7627 return Context.getDependentTemplateName(NNS,
7628 (OverloadedOperatorKind)Record[Idx++]);
7629 }
7630
7631 case TemplateName::SubstTemplateTemplateParm: {
7632 TemplateTemplateParmDecl *param
7633 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7634 if (!param) return TemplateName();
7635 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7636 return Context.getSubstTemplateTemplateParm(param, replacement);
7637 }
7638
7639 case TemplateName::SubstTemplateTemplateParmPack: {
7640 TemplateTemplateParmDecl *Param
7641 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7642 if (!Param)
7643 return TemplateName();
7644
7645 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7646 if (ArgPack.getKind() != TemplateArgument::Pack)
7647 return TemplateName();
7648
7649 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7650 }
7651 }
7652
7653 llvm_unreachable("Unhandled template name kind!");
7654}
7655
7656TemplateArgument
7657ASTReader::ReadTemplateArgument(ModuleFile &F,
7658 const RecordData &Record, unsigned &Idx) {
7659 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7660 switch (Kind) {
7661 case TemplateArgument::Null:
7662 return TemplateArgument();
7663 case TemplateArgument::Type:
7664 return TemplateArgument(readType(F, Record, Idx));
7665 case TemplateArgument::Declaration: {
7666 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007667 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007668 }
7669 case TemplateArgument::NullPtr:
7670 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7671 case TemplateArgument::Integral: {
7672 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7673 QualType T = readType(F, Record, Idx);
7674 return TemplateArgument(Context, Value, T);
7675 }
7676 case TemplateArgument::Template:
7677 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7678 case TemplateArgument::TemplateExpansion: {
7679 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007680 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007681 if (unsigned NumExpansions = Record[Idx++])
7682 NumTemplateExpansions = NumExpansions - 1;
7683 return TemplateArgument(Name, NumTemplateExpansions);
7684 }
7685 case TemplateArgument::Expression:
7686 return TemplateArgument(ReadExpr(F));
7687 case TemplateArgument::Pack: {
7688 unsigned NumArgs = Record[Idx++];
7689 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7690 for (unsigned I = 0; I != NumArgs; ++I)
7691 Args[I] = ReadTemplateArgument(F, Record, Idx);
7692 return TemplateArgument(Args, NumArgs);
7693 }
7694 }
7695
7696 llvm_unreachable("Unhandled template argument kind!");
7697}
7698
7699TemplateParameterList *
7700ASTReader::ReadTemplateParameterList(ModuleFile &F,
7701 const RecordData &Record, unsigned &Idx) {
7702 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7703 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7704 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7705
7706 unsigned NumParams = Record[Idx++];
7707 SmallVector<NamedDecl *, 16> Params;
7708 Params.reserve(NumParams);
7709 while (NumParams--)
7710 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7711
7712 TemplateParameterList* TemplateParams =
7713 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7714 Params.data(), Params.size(), RAngleLoc);
7715 return TemplateParams;
7716}
7717
7718void
7719ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007720ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007721 ModuleFile &F, const RecordData &Record,
7722 unsigned &Idx) {
7723 unsigned NumTemplateArgs = Record[Idx++];
7724 TemplArgs.reserve(NumTemplateArgs);
7725 while (NumTemplateArgs--)
7726 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7727}
7728
7729/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007730void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007731 const RecordData &Record, unsigned &Idx) {
7732 unsigned NumDecls = Record[Idx++];
7733 Set.reserve(Context, NumDecls);
7734 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007735 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007736 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007737 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007738 }
7739}
7740
7741CXXBaseSpecifier
7742ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7743 const RecordData &Record, unsigned &Idx) {
7744 bool isVirtual = static_cast<bool>(Record[Idx++]);
7745 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7746 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7747 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7748 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7749 SourceRange Range = ReadSourceRange(F, Record, Idx);
7750 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7751 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7752 EllipsisLoc);
7753 Result.setInheritConstructors(inheritConstructors);
7754 return Result;
7755}
7756
Richard Smithc2bb8182015-03-24 06:36:48 +00007757CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007758ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7759 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007760 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007761 assert(NumInitializers && "wrote ctor initializers but have no inits");
7762 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7763 for (unsigned i = 0; i != NumInitializers; ++i) {
7764 TypeSourceInfo *TInfo = nullptr;
7765 bool IsBaseVirtual = false;
7766 FieldDecl *Member = nullptr;
7767 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007768
Richard Smithc2bb8182015-03-24 06:36:48 +00007769 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7770 switch (Type) {
7771 case CTOR_INITIALIZER_BASE:
7772 TInfo = GetTypeSourceInfo(F, Record, Idx);
7773 IsBaseVirtual = Record[Idx++];
7774 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007775
Richard Smithc2bb8182015-03-24 06:36:48 +00007776 case CTOR_INITIALIZER_DELEGATING:
7777 TInfo = GetTypeSourceInfo(F, Record, Idx);
7778 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007779
Richard Smithc2bb8182015-03-24 06:36:48 +00007780 case CTOR_INITIALIZER_MEMBER:
7781 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7782 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007783
Richard Smithc2bb8182015-03-24 06:36:48 +00007784 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7785 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7786 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007787 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007788
7789 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7790 Expr *Init = ReadExpr(F);
7791 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7792 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7793 bool IsWritten = Record[Idx++];
7794 unsigned SourceOrderOrNumArrayIndices;
7795 SmallVector<VarDecl *, 8> Indices;
7796 if (IsWritten) {
7797 SourceOrderOrNumArrayIndices = Record[Idx++];
7798 } else {
7799 SourceOrderOrNumArrayIndices = Record[Idx++];
7800 Indices.reserve(SourceOrderOrNumArrayIndices);
7801 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7802 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7803 }
7804
7805 CXXCtorInitializer *BOMInit;
7806 if (Type == CTOR_INITIALIZER_BASE) {
7807 BOMInit = new (Context)
7808 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7809 RParenLoc, MemberOrEllipsisLoc);
7810 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7811 BOMInit = new (Context)
7812 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7813 } else if (IsWritten) {
7814 if (Member)
7815 BOMInit = new (Context) CXXCtorInitializer(
7816 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7817 else
7818 BOMInit = new (Context)
7819 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7820 LParenLoc, Init, RParenLoc);
7821 } else {
7822 if (IndirectMember) {
7823 assert(Indices.empty() && "Indirect field improperly initialized");
7824 BOMInit = new (Context)
7825 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7826 LParenLoc, Init, RParenLoc);
7827 } else {
7828 BOMInit = CXXCtorInitializer::Create(
7829 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7830 Indices.data(), Indices.size());
7831 }
7832 }
7833
7834 if (IsWritten)
7835 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7836 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007837 }
7838
Richard Smithc2bb8182015-03-24 06:36:48 +00007839 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007840}
7841
7842NestedNameSpecifier *
7843ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7844 const RecordData &Record, unsigned &Idx) {
7845 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007846 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007847 for (unsigned I = 0; I != N; ++I) {
7848 NestedNameSpecifier::SpecifierKind Kind
7849 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7850 switch (Kind) {
7851 case NestedNameSpecifier::Identifier: {
7852 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7853 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7854 break;
7855 }
7856
7857 case NestedNameSpecifier::Namespace: {
7858 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7859 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7860 break;
7861 }
7862
7863 case NestedNameSpecifier::NamespaceAlias: {
7864 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7865 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7866 break;
7867 }
7868
7869 case NestedNameSpecifier::TypeSpec:
7870 case NestedNameSpecifier::TypeSpecWithTemplate: {
7871 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7872 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007873 return nullptr;
7874
Guy Benyei11169dd2012-12-18 14:30:41 +00007875 bool Template = Record[Idx++];
7876 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7877 break;
7878 }
7879
7880 case NestedNameSpecifier::Global: {
7881 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7882 // No associated value, and there can't be a prefix.
7883 break;
7884 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007885
7886 case NestedNameSpecifier::Super: {
7887 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7888 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7889 break;
7890 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007891 }
7892 Prev = NNS;
7893 }
7894 return NNS;
7895}
7896
7897NestedNameSpecifierLoc
7898ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7899 unsigned &Idx) {
7900 unsigned N = Record[Idx++];
7901 NestedNameSpecifierLocBuilder Builder;
7902 for (unsigned I = 0; I != N; ++I) {
7903 NestedNameSpecifier::SpecifierKind Kind
7904 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7905 switch (Kind) {
7906 case NestedNameSpecifier::Identifier: {
7907 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7908 SourceRange Range = ReadSourceRange(F, Record, Idx);
7909 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7910 break;
7911 }
7912
7913 case NestedNameSpecifier::Namespace: {
7914 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7915 SourceRange Range = ReadSourceRange(F, Record, Idx);
7916 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7917 break;
7918 }
7919
7920 case NestedNameSpecifier::NamespaceAlias: {
7921 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7922 SourceRange Range = ReadSourceRange(F, Record, Idx);
7923 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7924 break;
7925 }
7926
7927 case NestedNameSpecifier::TypeSpec:
7928 case NestedNameSpecifier::TypeSpecWithTemplate: {
7929 bool Template = Record[Idx++];
7930 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7931 if (!T)
7932 return NestedNameSpecifierLoc();
7933 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7934
7935 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7936 Builder.Extend(Context,
7937 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7938 T->getTypeLoc(), ColonColonLoc);
7939 break;
7940 }
7941
7942 case NestedNameSpecifier::Global: {
7943 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7944 Builder.MakeGlobal(Context, ColonColonLoc);
7945 break;
7946 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007947
7948 case NestedNameSpecifier::Super: {
7949 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7950 SourceRange Range = ReadSourceRange(F, Record, Idx);
7951 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7952 break;
7953 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007954 }
7955 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007956
Guy Benyei11169dd2012-12-18 14:30:41 +00007957 return Builder.getWithLocInContext(Context);
7958}
7959
7960SourceRange
7961ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7962 unsigned &Idx) {
7963 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7964 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7965 return SourceRange(beg, end);
7966}
7967
7968/// \brief Read an integral value
7969llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7970 unsigned BitWidth = Record[Idx++];
7971 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7972 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7973 Idx += NumWords;
7974 return Result;
7975}
7976
7977/// \brief Read a signed integral value
7978llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7979 bool isUnsigned = Record[Idx++];
7980 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7981}
7982
7983/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007984llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7985 const llvm::fltSemantics &Sem,
7986 unsigned &Idx) {
7987 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007988}
7989
7990// \brief Read a string
7991std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7992 unsigned Len = Record[Idx++];
7993 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7994 Idx += Len;
7995 return Result;
7996}
7997
Richard Smith7ed1bc92014-12-05 22:42:13 +00007998std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7999 unsigned &Idx) {
8000 std::string Filename = ReadString(Record, Idx);
8001 ResolveImportedPath(F, Filename);
8002 return Filename;
8003}
8004
Guy Benyei11169dd2012-12-18 14:30:41 +00008005VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8006 unsigned &Idx) {
8007 unsigned Major = Record[Idx++];
8008 unsigned Minor = Record[Idx++];
8009 unsigned Subminor = Record[Idx++];
8010 if (Minor == 0)
8011 return VersionTuple(Major);
8012 if (Subminor == 0)
8013 return VersionTuple(Major, Minor - 1);
8014 return VersionTuple(Major, Minor - 1, Subminor - 1);
8015}
8016
8017CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8018 const RecordData &Record,
8019 unsigned &Idx) {
8020 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8021 return CXXTemporary::Create(Context, Decl);
8022}
8023
8024DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008025 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008026}
8027
8028DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8029 return Diags.Report(Loc, DiagID);
8030}
8031
8032/// \brief Retrieve the identifier table associated with the
8033/// preprocessor.
8034IdentifierTable &ASTReader::getIdentifierTable() {
8035 return PP.getIdentifierTable();
8036}
8037
8038/// \brief Record that the given ID maps to the given switch-case
8039/// statement.
8040void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008041 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008042 "Already have a SwitchCase with this ID");
8043 (*CurrSwitchCaseStmts)[ID] = SC;
8044}
8045
8046/// \brief Retrieve the switch-case statement with the given ID.
8047SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008048 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008049 return (*CurrSwitchCaseStmts)[ID];
8050}
8051
8052void ASTReader::ClearSwitchCaseIDs() {
8053 CurrSwitchCaseStmts->clear();
8054}
8055
8056void ASTReader::ReadComments() {
8057 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008058 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008059 serialization::ModuleFile *> >::iterator
8060 I = CommentsCursors.begin(),
8061 E = CommentsCursors.end();
8062 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008063 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008064 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008065 serialization::ModuleFile &F = *I->second;
8066 SavedStreamPosition SavedPosition(Cursor);
8067
8068 RecordData Record;
8069 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008070 llvm::BitstreamEntry Entry =
8071 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008072
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008073 switch (Entry.Kind) {
8074 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8075 case llvm::BitstreamEntry::Error:
8076 Error("malformed block record in AST file");
8077 return;
8078 case llvm::BitstreamEntry::EndBlock:
8079 goto NextCursor;
8080 case llvm::BitstreamEntry::Record:
8081 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008082 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008083 }
8084
8085 // Read a record.
8086 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008087 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008088 case COMMENTS_RAW_COMMENT: {
8089 unsigned Idx = 0;
8090 SourceRange SR = ReadSourceRange(F, Record, Idx);
8091 RawComment::CommentKind Kind =
8092 (RawComment::CommentKind) Record[Idx++];
8093 bool IsTrailingComment = Record[Idx++];
8094 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008095 Comments.push_back(new (Context) RawComment(
8096 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8097 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008098 break;
8099 }
8100 }
8101 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008102 NextCursor:
8103 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008104 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008105}
8106
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008107void ASTReader::getInputFiles(ModuleFile &F,
8108 SmallVectorImpl<serialization::InputFile> &Files) {
8109 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8110 unsigned ID = I+1;
8111 Files.push_back(getInputFile(F, ID));
8112 }
8113}
8114
Richard Smithcd45dbc2014-04-19 03:48:30 +00008115std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8116 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008117 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008118 return M->getFullModuleName();
8119
8120 // Otherwise, use the name of the top-level module the decl is within.
8121 if (ModuleFile *M = getOwningModuleFile(D))
8122 return M->ModuleName;
8123
8124 // Not from a module.
8125 return "";
8126}
8127
Guy Benyei11169dd2012-12-18 14:30:41 +00008128void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008129 while (!PendingIdentifierInfos.empty() ||
8130 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008131 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008132 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008133 // If any identifiers with corresponding top-level declarations have
8134 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008135 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8136 TopLevelDeclsMap;
8137 TopLevelDeclsMap TopLevelDecls;
8138
Guy Benyei11169dd2012-12-18 14:30:41 +00008139 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008140 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008141 SmallVector<uint32_t, 4> DeclIDs =
8142 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008143 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008144
8145 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008146 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008147
Richard Smith851072e2014-05-19 20:59:20 +00008148 // For each decl chain that we wanted to complete while deserializing, mark
8149 // it as "still needs to be completed".
8150 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8151 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8152 }
8153 PendingIncompleteDeclChains.clear();
8154
Guy Benyei11169dd2012-12-18 14:30:41 +00008155 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008156 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008157 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008158 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008159 }
8160 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008161 PendingDeclChains.clear();
8162
Douglas Gregor6168bd22013-02-18 15:53:43 +00008163 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008164 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8165 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008166 IdentifierInfo *II = TLD->first;
8167 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008168 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008169 }
8170 }
8171
Guy Benyei11169dd2012-12-18 14:30:41 +00008172 // Load any pending macro definitions.
8173 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008174 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8175 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8176 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8177 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008178 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008179 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008180 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008181 if (Info.M->Kind != MK_ImplicitModule &&
8182 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008183 resolvePendingMacro(II, Info);
8184 }
8185 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008186 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008187 ++IDIdx) {
8188 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008189 if (Info.M->Kind == MK_ImplicitModule ||
8190 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008191 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008192 }
8193 }
8194 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008195
8196 // Wire up the DeclContexts for Decls that we delayed setting until
8197 // recursive loading is completed.
8198 while (!PendingDeclContextInfos.empty()) {
8199 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8200 PendingDeclContextInfos.pop_front();
8201 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8202 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8203 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8204 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008205
Richard Smithd1c46742014-04-30 02:24:17 +00008206 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008207 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008208 auto Update = PendingUpdateRecords.pop_back_val();
8209 ReadingKindTracker ReadingKind(Read_Decl, *this);
8210 loadDeclUpdateRecords(Update.first, Update.second);
8211 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008212 }
Richard Smith8a639892015-01-24 01:07:20 +00008213
8214 // At this point, all update records for loaded decls are in place, so any
8215 // fake class definitions should have become real.
8216 assert(PendingFakeDefinitionData.empty() &&
8217 "faked up a class definition but never saw the real one");
8218
Guy Benyei11169dd2012-12-18 14:30:41 +00008219 // If we deserialized any C++ or Objective-C class definitions, any
8220 // Objective-C protocol definitions, or any redeclarable templates, make sure
8221 // that all redeclarations point to the definitions. Note that this can only
8222 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008223 for (Decl *D : PendingDefinitions) {
8224 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008225 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008226 // Make sure that the TagType points at the definition.
8227 const_cast<TagType*>(TagT)->decl = TD;
8228 }
Richard Smith8ce51082015-03-11 01:44:51 +00008229
Craig Topperc6914d02014-08-25 04:15:02 +00008230 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008231 for (auto *R = getMostRecentExistingDecl(RD); R;
8232 R = R->getPreviousDecl()) {
8233 assert((R == D) ==
8234 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008235 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008236 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008237 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008238 }
8239
8240 continue;
8241 }
Richard Smith8ce51082015-03-11 01:44:51 +00008242
Craig Topperc6914d02014-08-25 04:15:02 +00008243 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008244 // Make sure that the ObjCInterfaceType points at the definition.
8245 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8246 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008247
8248 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8249 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8250
Guy Benyei11169dd2012-12-18 14:30:41 +00008251 continue;
8252 }
Richard Smith8ce51082015-03-11 01:44:51 +00008253
Craig Topperc6914d02014-08-25 04:15:02 +00008254 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008255 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8256 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8257
Guy Benyei11169dd2012-12-18 14:30:41 +00008258 continue;
8259 }
Richard Smith8ce51082015-03-11 01:44:51 +00008260
Craig Topperc6914d02014-08-25 04:15:02 +00008261 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008262 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8263 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008264 }
8265 PendingDefinitions.clear();
8266
8267 // Load the bodies of any functions or methods we've encountered. We do
8268 // this now (delayed) so that we can be sure that the declaration chains
8269 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008270 // FIXME: There seems to be no point in delaying this, it does not depend
8271 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008272 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8273 PBEnd = PendingBodies.end();
8274 PB != PBEnd; ++PB) {
8275 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8276 // FIXME: Check for =delete/=default?
8277 // FIXME: Complain about ODR violations here?
8278 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8279 FD->setLazyBody(PB->second);
8280 continue;
8281 }
8282
8283 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8284 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8285 MD->setLazyBody(PB->second);
8286 }
8287 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008288
8289 // Do some cleanup.
8290 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8291 getContext().deduplicateMergedDefinitonsFor(ND);
8292 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008293}
8294
8295void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008296 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8297 return;
8298
Richard Smitha0ce9c42014-07-29 23:23:27 +00008299 // Trigger the import of the full definition of each class that had any
8300 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008301 // These updates may in turn find and diagnose some ODR failures, so take
8302 // ownership of the set first.
8303 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8304 PendingOdrMergeFailures.clear();
8305 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008306 Merge.first->buildLookup();
8307 Merge.first->decls_begin();
8308 Merge.first->bases_begin();
8309 Merge.first->vbases_begin();
8310 for (auto *RD : Merge.second) {
8311 RD->decls_begin();
8312 RD->bases_begin();
8313 RD->vbases_begin();
8314 }
8315 }
8316
8317 // For each declaration from a merged context, check that the canonical
8318 // definition of that context also contains a declaration of the same
8319 // entity.
8320 //
8321 // Caution: this loop does things that might invalidate iterators into
8322 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8323 while (!PendingOdrMergeChecks.empty()) {
8324 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8325
8326 // FIXME: Skip over implicit declarations for now. This matters for things
8327 // like implicitly-declared special member functions. This isn't entirely
8328 // correct; we can end up with multiple unmerged declarations of the same
8329 // implicit entity.
8330 if (D->isImplicit())
8331 continue;
8332
8333 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008334
8335 bool Found = false;
8336 const Decl *DCanon = D->getCanonicalDecl();
8337
Richard Smith01bdb7a2014-08-28 05:44:07 +00008338 for (auto RI : D->redecls()) {
8339 if (RI->getLexicalDeclContext() == CanonDef) {
8340 Found = true;
8341 break;
8342 }
8343 }
8344 if (Found)
8345 continue;
8346
Richard Smitha0ce9c42014-07-29 23:23:27 +00008347 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008348 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008349 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8350 !Found && I != E; ++I) {
8351 for (auto RI : (*I)->redecls()) {
8352 if (RI->getLexicalDeclContext() == CanonDef) {
8353 // This declaration is present in the canonical definition. If it's
8354 // in the same redecl chain, it's the one we're looking for.
8355 if (RI->getCanonicalDecl() == DCanon)
8356 Found = true;
8357 else
8358 Candidates.push_back(cast<NamedDecl>(RI));
8359 break;
8360 }
8361 }
8362 }
8363
8364 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008365 // The AST doesn't like TagDecls becoming invalid after they've been
8366 // completed. We only really need to mark FieldDecls as invalid here.
8367 if (!isa<TagDecl>(D))
8368 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008369
8370 // Ensure we don't accidentally recursively enter deserialization while
8371 // we're producing our diagnostic.
8372 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008373
8374 std::string CanonDefModule =
8375 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8376 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8377 << D << getOwningModuleNameForDiagnostic(D)
8378 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8379
8380 if (Candidates.empty())
8381 Diag(cast<Decl>(CanonDef)->getLocation(),
8382 diag::note_module_odr_violation_no_possible_decls) << D;
8383 else {
8384 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8385 Diag(Candidates[I]->getLocation(),
8386 diag::note_module_odr_violation_possible_decl)
8387 << Candidates[I];
8388 }
8389
8390 DiagnosedOdrMergeFailures.insert(CanonDef);
8391 }
8392 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008393
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008394 if (OdrMergeFailures.empty())
8395 return;
8396
8397 // Ensure we don't accidentally recursively enter deserialization while
8398 // we're producing our diagnostics.
8399 Deserializing RecursionGuard(this);
8400
Richard Smithcd45dbc2014-04-19 03:48:30 +00008401 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008402 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008403 // If we've already pointed out a specific problem with this class, don't
8404 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008405 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008406 continue;
8407
8408 bool Diagnosed = false;
8409 for (auto *RD : Merge.second) {
8410 // Multiple different declarations got merged together; tell the user
8411 // where they came from.
8412 if (Merge.first != RD) {
8413 // FIXME: Walk the definition, figure out what's different,
8414 // and diagnose that.
8415 if (!Diagnosed) {
8416 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8417 Diag(Merge.first->getLocation(),
8418 diag::err_module_odr_violation_different_definitions)
8419 << Merge.first << Module.empty() << Module;
8420 Diagnosed = true;
8421 }
8422
8423 Diag(RD->getLocation(),
8424 diag::note_module_odr_violation_different_definitions)
8425 << getOwningModuleNameForDiagnostic(RD);
8426 }
8427 }
8428
8429 if (!Diagnosed) {
8430 // All definitions are updates to the same declaration. This happens if a
8431 // module instantiates the declaration of a class template specialization
8432 // and two or more other modules instantiate its definition.
8433 //
8434 // FIXME: Indicate which modules had instantiations of this definition.
8435 // FIXME: How can this even happen?
8436 Diag(Merge.first->getLocation(),
8437 diag::err_module_odr_violation_different_instantiations)
8438 << Merge.first;
8439 }
8440 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008441}
8442
Richard Smithce18a182015-07-14 00:26:00 +00008443void ASTReader::StartedDeserializing() {
8444 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8445 ReadTimer->startTimer();
8446}
8447
Guy Benyei11169dd2012-12-18 14:30:41 +00008448void ASTReader::FinishedDeserializing() {
8449 assert(NumCurrentElementsDeserializing &&
8450 "FinishedDeserializing not paired with StartedDeserializing");
8451 if (NumCurrentElementsDeserializing == 1) {
8452 // We decrease NumCurrentElementsDeserializing only after pending actions
8453 // are finished, to avoid recursively re-calling finishPendingActions().
8454 finishPendingActions();
8455 }
8456 --NumCurrentElementsDeserializing;
8457
Richard Smitha0ce9c42014-07-29 23:23:27 +00008458 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008459 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008460 while (!PendingExceptionSpecUpdates.empty()) {
8461 auto Updates = std::move(PendingExceptionSpecUpdates);
8462 PendingExceptionSpecUpdates.clear();
8463 for (auto Update : Updates) {
8464 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8465 SemaObj->UpdateExceptionSpec(Update.second,
8466 FPT->getExtProtoInfo().ExceptionSpec);
8467 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008468 }
8469
Richard Smitha0ce9c42014-07-29 23:23:27 +00008470 diagnoseOdrViolations();
8471
Richard Smithce18a182015-07-14 00:26:00 +00008472 if (ReadTimer)
8473 ReadTimer->stopTimer();
8474
Richard Smith04d05b52014-03-23 00:27:18 +00008475 // We are not in recursive loading, so it's safe to pass the "interesting"
8476 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008477 if (Consumer)
8478 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008479 }
8480}
8481
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008482void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008483 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8484 // Remove any fake results before adding any real ones.
8485 auto It = PendingFakeLookupResults.find(II);
8486 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008487 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008488 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008489 // FIXME: this works around module+PCH performance issue.
8490 // Rather than erase the result from the map, which is O(n), just clear
8491 // the vector of NamedDecls.
8492 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008493 }
8494 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008495
8496 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8497 SemaObj->TUScope->AddDecl(D);
8498 } else if (SemaObj->TUScope) {
8499 // Adding the decl to IdResolver may have failed because it was already in
8500 // (even though it was not added in scope). If it is already in, make sure
8501 // it gets in the scope as well.
8502 if (std::find(SemaObj->IdResolver.begin(Name),
8503 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8504 SemaObj->TUScope->AddDecl(D);
8505 }
8506}
8507
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008508ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008509 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008510 StringRef isysroot, bool DisableValidation,
8511 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008512 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Richard Smithce18a182015-07-14 00:26:00 +00008513 bool UseGlobalIndex,
8514 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008515 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008516 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008517 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008518 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008519 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008520 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008521 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008522 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8523 AllowConfigurationMismatch(AllowConfigurationMismatch),
8524 ValidateSystemInputs(ValidateSystemInputs),
8525 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008526 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8527 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8528 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8529 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008530 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8531 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8532 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8533 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8534 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8535 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008536 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008537 SourceMgr.setExternalSLocEntrySource(this);
8538}
8539
8540ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008541 if (OwnsDeserializationListener)
8542 delete DeserializationListener;
8543
Guy Benyei11169dd2012-12-18 14:30:41 +00008544 for (DeclContextVisibleUpdatesPending::iterator
8545 I = PendingVisibleUpdates.begin(),
8546 E = PendingVisibleUpdates.end();
8547 I != E; ++I) {
8548 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8549 F = I->second.end();
8550 J != F; ++J)
8551 delete J->first;
8552 }
8553}