blob: ff771fd00a3b09ef2d9271f2d4ea3e884e5975f5 [file] [log] [blame]
Richard Smith9e2341d2015-03-23 03:25:59 +00001//===-- ASTReader.cpp - AST File Reader ----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
Adrian Prantlbb165fb2015-06-20 18:53:08 +000022#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000023#include "clang/AST/NestedNameSpecifier.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000026#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/SourceManagerInternals.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Basic/TargetOptions.h"
32#include "clang/Basic/Version.h"
33#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000034#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/HeaderSearchOptions.h"
37#include "clang/Lex/MacroInfo.h"
38#include "clang/Lex/PreprocessingRecord.h"
39#include "clang/Lex/Preprocessor.h"
40#include "clang/Lex/PreprocessorOptions.h"
41#include "clang/Sema/Scope.h"
42#include "clang/Sema/Sema.h"
43#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000044#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000045#include "clang/Serialization/ModuleManager.h"
46#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000047#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "llvm/ADT/StringExtras.h"
49#include "llvm/Bitcode/BitstreamReader.h"
50#include "llvm/Support/ErrorHandling.h"
51#include "llvm/Support/FileSystem.h"
52#include "llvm/Support/MemoryBuffer.h"
53#include "llvm/Support/Path.h"
54#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000055#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000056#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000057#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000058#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000059#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000060
61using namespace clang;
62using namespace clang::serialization;
63using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000064using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000065
Ben Langmuircb69b572014-03-07 06:40:32 +000066
67//===----------------------------------------------------------------------===//
68// ChainedASTReaderListener implementation
69//===----------------------------------------------------------------------===//
70
71bool
72ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
73 return First->ReadFullVersionInformation(FullVersion) ||
74 Second->ReadFullVersionInformation(FullVersion);
75}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000076void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
77 First->ReadModuleName(ModuleName);
78 Second->ReadModuleName(ModuleName);
79}
80void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
81 First->ReadModuleMapFile(ModuleMapPath);
82 Second->ReadModuleMapFile(ModuleMapPath);
83}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000084bool
85ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
86 bool Complain,
87 bool AllowCompatibleDifferences) {
88 return First->ReadLanguageOptions(LangOpts, Complain,
89 AllowCompatibleDifferences) ||
90 Second->ReadLanguageOptions(LangOpts, Complain,
91 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000092}
Chandler Carruth0d745bc2015-03-14 04:47:43 +000093bool ChainedASTReaderListener::ReadTargetOptions(
94 const TargetOptions &TargetOpts, bool Complain,
95 bool AllowCompatibleDifferences) {
96 return First->ReadTargetOptions(TargetOpts, Complain,
97 AllowCompatibleDifferences) ||
98 Second->ReadTargetOptions(TargetOpts, Complain,
99 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000100}
101bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000102 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000103 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
104 Second->ReadDiagnosticOptions(DiagOpts, Complain);
105}
106bool
107ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
108 bool Complain) {
109 return First->ReadFileSystemOptions(FSOpts, Complain) ||
110 Second->ReadFileSystemOptions(FSOpts, Complain);
111}
112
113bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000114 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
115 bool Complain) {
116 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
117 Complain) ||
118 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
119 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000120}
121bool ChainedASTReaderListener::ReadPreprocessorOptions(
122 const PreprocessorOptions &PPOpts, bool Complain,
123 std::string &SuggestedPredefines) {
124 return First->ReadPreprocessorOptions(PPOpts, Complain,
125 SuggestedPredefines) ||
126 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
127}
128void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
129 unsigned Value) {
130 First->ReadCounter(M, Value);
131 Second->ReadCounter(M, Value);
132}
133bool ChainedASTReaderListener::needsInputFileVisitation() {
134 return First->needsInputFileVisitation() ||
135 Second->needsInputFileVisitation();
136}
137bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
138 return First->needsSystemInputFileVisitation() ||
139 Second->needsSystemInputFileVisitation();
140}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000141void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
142 First->visitModuleFile(Filename);
143 Second->visitModuleFile(Filename);
144}
Ben Langmuircb69b572014-03-07 06:40:32 +0000145bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000146 bool isSystem,
147 bool isOverridden) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000148 bool Continue = false;
149 if (First->needsInputFileVisitation() &&
150 (!isSystem || First->needsSystemInputFileVisitation()))
151 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
152 if (Second->needsInputFileVisitation() &&
153 (!isSystem || Second->needsSystemInputFileVisitation()))
154 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
155 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000156}
157
Guy Benyei11169dd2012-12-18 14:30:41 +0000158//===----------------------------------------------------------------------===//
159// PCH validator implementation
160//===----------------------------------------------------------------------===//
161
162ASTReaderListener::~ASTReaderListener() {}
163
164/// \brief Compare the given set of language options against an existing set of
165/// language options.
166///
167/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000168/// \param AllowCompatibleDifferences If true, differences between compatible
169/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000170///
171/// \returns true if the languagae options mis-match, false otherwise.
172static bool checkLanguageOptions(const LangOptions &LangOpts,
173 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000174 DiagnosticsEngine *Diags,
175 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000176#define LANGOPT(Name, Bits, Default, Description) \
177 if (ExistingLangOpts.Name != LangOpts.Name) { \
178 if (Diags) \
179 Diags->Report(diag::err_pch_langopt_mismatch) \
180 << Description << LangOpts.Name << ExistingLangOpts.Name; \
181 return true; \
182 }
183
184#define VALUE_LANGOPT(Name, Bits, Default, Description) \
185 if (ExistingLangOpts.Name != LangOpts.Name) { \
186 if (Diags) \
187 Diags->Report(diag::err_pch_langopt_value_mismatch) \
188 << Description; \
189 return true; \
190 }
191
192#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
193 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
194 if (Diags) \
195 Diags->Report(diag::err_pch_langopt_value_mismatch) \
196 << Description; \
197 return true; \
198 }
199
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000200#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
201 if (!AllowCompatibleDifferences) \
202 LANGOPT(Name, Bits, Default, Description)
203
204#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
205 if (!AllowCompatibleDifferences) \
206 ENUM_LANGOPT(Name, Bits, Default, Description)
207
Guy Benyei11169dd2012-12-18 14:30:41 +0000208#define BENIGN_LANGOPT(Name, Bits, Default, Description)
209#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
210#include "clang/Basic/LangOptions.def"
211
Ben Langmuircd98cb72015-06-23 18:20:18 +0000212 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
213 if (Diags)
214 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
215 return true;
216 }
217
Guy Benyei11169dd2012-12-18 14:30:41 +0000218 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
219 if (Diags)
220 Diags->Report(diag::err_pch_langopt_value_mismatch)
221 << "target Objective-C runtime";
222 return true;
223 }
224
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000225 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
226 LangOpts.CommentOpts.BlockCommandNames) {
227 if (Diags)
228 Diags->Report(diag::err_pch_langopt_value_mismatch)
229 << "block command names";
230 return true;
231 }
232
Guy Benyei11169dd2012-12-18 14:30:41 +0000233 return false;
234}
235
236/// \brief Compare the given set of target options against an existing set of
237/// target options.
238///
239/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
240///
241/// \returns true if the target options mis-match, false otherwise.
242static bool checkTargetOptions(const TargetOptions &TargetOpts,
243 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000244 DiagnosticsEngine *Diags,
245 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000246#define CHECK_TARGET_OPT(Field, Name) \
247 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
248 if (Diags) \
249 Diags->Report(diag::err_pch_targetopt_mismatch) \
250 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
251 return true; \
252 }
253
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000254 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000255 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000256 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000257
258 // We can tolerate different CPUs in many cases, notably when one CPU
259 // supports a strict superset of another. When allowing compatible
260 // differences skip this check.
261 if (!AllowCompatibleDifferences)
262 CHECK_TARGET_OPT(CPU, "target CPU");
263
Guy Benyei11169dd2012-12-18 14:30:41 +0000264#undef CHECK_TARGET_OPT
265
266 // Compare feature sets.
267 SmallVector<StringRef, 4> ExistingFeatures(
268 ExistingTargetOpts.FeaturesAsWritten.begin(),
269 ExistingTargetOpts.FeaturesAsWritten.end());
270 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
271 TargetOpts.FeaturesAsWritten.end());
272 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
273 std::sort(ReadFeatures.begin(), ReadFeatures.end());
274
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000275 // We compute the set difference in both directions explicitly so that we can
276 // diagnose the differences differently.
277 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
278 std::set_difference(
279 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
280 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
281 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
282 ExistingFeatures.begin(), ExistingFeatures.end(),
283 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000284
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000285 // If we are allowing compatible differences and the read feature set is
286 // a strict subset of the existing feature set, there is nothing to diagnose.
287 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
288 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000289
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000290 if (Diags) {
291 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000292 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000293 << /* is-existing-feature */ false << Feature;
294 for (StringRef Feature : UnmatchedExistingFeatures)
295 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
296 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000297 }
298
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000299 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000300}
301
302bool
303PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000304 bool Complain,
305 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000306 const LangOptions &ExistingLangOpts = PP.getLangOpts();
307 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000308 Complain ? &Reader.Diags : nullptr,
309 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000310}
311
312bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000313 bool Complain,
314 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000315 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
316 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000317 Complain ? &Reader.Diags : nullptr,
318 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000319}
320
321namespace {
322 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
323 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000324 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
325 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000326}
327
Ben Langmuirb92de022014-04-29 16:25:26 +0000328static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
329 DiagnosticsEngine &Diags,
330 bool Complain) {
331 typedef DiagnosticsEngine::Level Level;
332
333 // Check current mappings for new -Werror mappings, and the stored mappings
334 // for cases that were explicitly mapped to *not* be errors that are now
335 // errors because of options like -Werror.
336 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
337
338 for (DiagnosticsEngine *MappingSource : MappingSources) {
339 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
340 diag::kind DiagID = DiagIDMappingPair.first;
341 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
342 if (CurLevel < DiagnosticsEngine::Error)
343 continue; // not significant
344 Level StoredLevel =
345 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
346 if (StoredLevel < DiagnosticsEngine::Error) {
347 if (Complain)
348 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
349 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
350 return true;
351 }
352 }
353 }
354
355 return false;
356}
357
Alp Tokerac4e8e52014-06-22 21:58:33 +0000358static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
359 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
360 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
361 return true;
362 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000363}
364
365static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
366 DiagnosticsEngine &Diags,
367 bool IsSystem, bool Complain) {
368 // Top-level options
369 if (IsSystem) {
370 if (Diags.getSuppressSystemWarnings())
371 return false;
372 // If -Wsystem-headers was not enabled before, be conservative
373 if (StoredDiags.getSuppressSystemWarnings()) {
374 if (Complain)
375 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
376 return true;
377 }
378 }
379
380 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
381 if (Complain)
382 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
383 return true;
384 }
385
386 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
387 !StoredDiags.getEnableAllWarnings()) {
388 if (Complain)
389 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
390 return true;
391 }
392
393 if (isExtHandlingFromDiagsError(Diags) &&
394 !isExtHandlingFromDiagsError(StoredDiags)) {
395 if (Complain)
396 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
397 return true;
398 }
399
400 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
401}
402
403bool PCHValidator::ReadDiagnosticOptions(
404 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
405 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
406 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
407 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000408 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000409 // This should never fail, because we would have processed these options
410 // before writing them to an ASTFile.
411 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
412
413 ModuleManager &ModuleMgr = Reader.getModuleManager();
414 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
415
416 // If the original import came from a file explicitly generated by the user,
417 // don't check the diagnostic mappings.
418 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000419 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000420 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
421 // the transitive closure of its imports, since unrelated modules cannot be
422 // imported until after this module finishes validation.
423 ModuleFile *TopImport = *ModuleMgr.rbegin();
424 while (!TopImport->ImportedBy.empty())
425 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000426 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000427 return false;
428
429 StringRef ModuleName = TopImport->ModuleName;
430 assert(!ModuleName.empty() && "diagnostic options read before module name");
431
432 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
433 assert(M && "missing module");
434
435 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
436 // contains the union of their flags.
437 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
438}
439
Guy Benyei11169dd2012-12-18 14:30:41 +0000440/// \brief Collect the macro definitions provided by the given preprocessor
441/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000442static void
443collectMacroDefinitions(const PreprocessorOptions &PPOpts,
444 MacroDefinitionsMap &Macros,
445 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000446 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
447 StringRef Macro = PPOpts.Macros[I].first;
448 bool IsUndef = PPOpts.Macros[I].second;
449
450 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
451 StringRef MacroName = MacroPair.first;
452 StringRef MacroBody = MacroPair.second;
453
454 // For an #undef'd macro, we only care about the name.
455 if (IsUndef) {
456 if (MacroNames && !Macros.count(MacroName))
457 MacroNames->push_back(MacroName);
458
459 Macros[MacroName] = std::make_pair("", true);
460 continue;
461 }
462
463 // For a #define'd macro, figure out the actual definition.
464 if (MacroName.size() == Macro.size())
465 MacroBody = "1";
466 else {
467 // Note: GCC drops anything following an end-of-line character.
468 StringRef::size_type End = MacroBody.find_first_of("\n\r");
469 MacroBody = MacroBody.substr(0, End);
470 }
471
472 if (MacroNames && !Macros.count(MacroName))
473 MacroNames->push_back(MacroName);
474 Macros[MacroName] = std::make_pair(MacroBody, false);
475 }
476}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000477
Guy Benyei11169dd2012-12-18 14:30:41 +0000478/// \brief Check the preprocessor options deserialized from the control block
479/// against the preprocessor options in an existing preprocessor.
480///
481/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
482static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
483 const PreprocessorOptions &ExistingPPOpts,
484 DiagnosticsEngine *Diags,
485 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000486 std::string &SuggestedPredefines,
487 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000488 // Check macro definitions.
489 MacroDefinitionsMap ASTFileMacros;
490 collectMacroDefinitions(PPOpts, ASTFileMacros);
491 MacroDefinitionsMap ExistingMacros;
492 SmallVector<StringRef, 4> ExistingMacroNames;
493 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
494
495 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
496 // Dig out the macro definition in the existing preprocessor options.
497 StringRef MacroName = ExistingMacroNames[I];
498 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
499
500 // Check whether we know anything about this macro name or not.
501 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
502 = ASTFileMacros.find(MacroName);
503 if (Known == ASTFileMacros.end()) {
504 // FIXME: Check whether this identifier was referenced anywhere in the
505 // AST file. If so, we should reject the AST file. Unfortunately, this
506 // information isn't in the control block. What shall we do about it?
507
508 if (Existing.second) {
509 SuggestedPredefines += "#undef ";
510 SuggestedPredefines += MacroName.str();
511 SuggestedPredefines += '\n';
512 } else {
513 SuggestedPredefines += "#define ";
514 SuggestedPredefines += MacroName.str();
515 SuggestedPredefines += ' ';
516 SuggestedPredefines += Existing.first.str();
517 SuggestedPredefines += '\n';
518 }
519 continue;
520 }
521
522 // If the macro was defined in one but undef'd in the other, we have a
523 // conflict.
524 if (Existing.second != Known->second.second) {
525 if (Diags) {
526 Diags->Report(diag::err_pch_macro_def_undef)
527 << MacroName << Known->second.second;
528 }
529 return true;
530 }
531
532 // If the macro was #undef'd in both, or if the macro bodies are identical,
533 // it's fine.
534 if (Existing.second || Existing.first == Known->second.first)
535 continue;
536
537 // The macro bodies differ; complain.
538 if (Diags) {
539 Diags->Report(diag::err_pch_macro_def_conflict)
540 << MacroName << Known->second.first << Existing.first;
541 }
542 return true;
543 }
544
545 // Check whether we're using predefines.
546 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
547 if (Diags) {
548 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
549 }
550 return true;
551 }
552
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000553 // Detailed record is important since it is used for the module cache hash.
554 if (LangOpts.Modules &&
555 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
556 if (Diags) {
557 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
558 }
559 return true;
560 }
561
Guy Benyei11169dd2012-12-18 14:30:41 +0000562 // Compute the #include and #include_macros lines we need.
563 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
564 StringRef File = ExistingPPOpts.Includes[I];
565 if (File == ExistingPPOpts.ImplicitPCHInclude)
566 continue;
567
568 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
569 != PPOpts.Includes.end())
570 continue;
571
572 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000573 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000574 SuggestedPredefines += "\"\n";
575 }
576
577 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
578 StringRef File = ExistingPPOpts.MacroIncludes[I];
579 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
580 File)
581 != PPOpts.MacroIncludes.end())
582 continue;
583
584 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000585 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000586 SuggestedPredefines += "\"\n##\n";
587 }
588
589 return false;
590}
591
592bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
593 bool Complain,
594 std::string &SuggestedPredefines) {
595 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
596
597 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000598 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000599 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000600 SuggestedPredefines,
601 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000602}
603
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000604/// Check the header search options deserialized from the control block
605/// against the header search options in an existing preprocessor.
606///
607/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
608static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
609 StringRef SpecificModuleCachePath,
610 StringRef ExistingModuleCachePath,
611 DiagnosticsEngine *Diags,
612 const LangOptions &LangOpts) {
613 if (LangOpts.Modules) {
614 if (SpecificModuleCachePath != ExistingModuleCachePath) {
615 if (Diags)
616 Diags->Report(diag::err_pch_modulecache_mismatch)
617 << SpecificModuleCachePath << ExistingModuleCachePath;
618 return true;
619 }
620 }
621
622 return false;
623}
624
625bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
626 StringRef SpecificModuleCachePath,
627 bool Complain) {
628 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
629 PP.getHeaderSearchInfo().getModuleCachePath(),
630 Complain ? &Reader.Diags : nullptr,
631 PP.getLangOpts());
632}
633
Guy Benyei11169dd2012-12-18 14:30:41 +0000634void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
635 PP.setCounterValue(Value);
636}
637
638//===----------------------------------------------------------------------===//
639// AST reader implementation
640//===----------------------------------------------------------------------===//
641
Nico Weber824285e2014-05-08 04:26:47 +0000642void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
643 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000644 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000645 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000646}
647
648
649
650unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
651 return serialization::ComputeHash(Sel);
652}
653
654
655std::pair<unsigned, unsigned>
656ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000657 using namespace llvm::support;
658 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
659 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000660 return std::make_pair(KeyLen, DataLen);
661}
662
663ASTSelectorLookupTrait::internal_key_type
664ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000665 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000666 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000667 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
668 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
669 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000670 if (N == 0)
671 return SelTable.getNullarySelector(FirstII);
672 else if (N == 1)
673 return SelTable.getUnarySelector(FirstII);
674
675 SmallVector<IdentifierInfo *, 16> Args;
676 Args.push_back(FirstII);
677 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000678 Args.push_back(Reader.getLocalIdentifier(
679 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000680
681 return SelTable.getSelector(N, Args.data());
682}
683
684ASTSelectorLookupTrait::data_type
685ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
686 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000687 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000688
689 data_type Result;
690
Justin Bogner57ba0b22014-03-28 22:03:24 +0000691 Result.ID = Reader.getGlobalSelectorID(
692 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000693 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
694 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
695 Result.InstanceBits = FullInstanceBits & 0x3;
696 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
697 Result.FactoryBits = FullFactoryBits & 0x3;
698 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
699 unsigned NumInstanceMethods = FullInstanceBits >> 3;
700 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000701
702 // Load instance methods
703 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000704 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
705 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000706 Result.Instance.push_back(Method);
707 }
708
709 // Load factory methods
710 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000711 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
712 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000713 Result.Factory.push_back(Method);
714 }
715
716 return Result;
717}
718
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000719unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
720 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000721}
722
723std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000724ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000725 using namespace llvm::support;
726 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
727 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000728 return std::make_pair(KeyLen, DataLen);
729}
730
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000731ASTIdentifierLookupTraitBase::internal_key_type
732ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000733 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000734 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000735}
736
Douglas Gregordcf25082013-02-11 18:16:18 +0000737/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000738static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
739 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000740 return II.hadMacroDefinition() ||
741 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000742 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000743 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000744 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
745 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000746}
747
Richard Smith76c2f2c2015-07-17 20:09:43 +0000748static bool readBit(unsigned &Bits) {
749 bool Value = Bits & 0x1;
750 Bits >>= 1;
751 return Value;
752}
753
Guy Benyei11169dd2012-12-18 14:30:41 +0000754IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
755 const unsigned char* d,
756 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000757 using namespace llvm::support;
758 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000759 bool IsInteresting = RawID & 0x01;
760
761 // Wipe out the "is interesting" bit.
762 RawID = RawID >> 1;
763
Richard Smith76c2f2c2015-07-17 20:09:43 +0000764 // Build the IdentifierInfo and link the identifier ID with it.
765 IdentifierInfo *II = KnownII;
766 if (!II) {
767 II = &Reader.getIdentifierTable().getOwn(k);
768 KnownII = II;
769 }
770 if (!II->isFromAST()) {
771 II->setIsFromAST();
Richard Smitha534a312015-07-21 23:54:07 +0000772 if (isInterestingIdentifier(Reader, *II, F.isModule()))
Richard Smith76c2f2c2015-07-17 20:09:43 +0000773 II->setChangedSinceDeserialization();
774 }
775 Reader.markIdentifierUpToDate(II);
776
Guy Benyei11169dd2012-12-18 14:30:41 +0000777 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
778 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000779 // For uninteresting identifiers, there's nothing else to do. Just notify
780 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000781 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000782 return II;
783 }
784
Justin Bogner57ba0b22014-03-28 22:03:24 +0000785 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
786 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000787 bool CPlusPlusOperatorKeyword = readBit(Bits);
788 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000789 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000790 bool Poisoned = readBit(Bits);
791 bool ExtensionToken = readBit(Bits);
792 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000793
794 assert(Bits == 0 && "Extra bits in the identifier?");
795 DataLen -= 8;
796
Guy Benyei11169dd2012-12-18 14:30:41 +0000797 // Set or check the various bits in the IdentifierInfo structure.
798 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000799 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000800 II->revertTokenIDToIdentifier();
801 if (!F.isModule())
802 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
803 else if (HasRevertedBuiltin && II->getBuiltinID()) {
804 II->revertBuiltin();
805 assert((II->hasRevertedBuiltin() ||
806 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
807 "Incorrect ObjC keyword or builtin ID");
808 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000809 assert(II->isExtensionToken() == ExtensionToken &&
810 "Incorrect extension token flag");
811 (void)ExtensionToken;
812 if (Poisoned)
813 II->setIsPoisoned(true);
814 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
815 "Incorrect C++ operator keyword flag");
816 (void)CPlusPlusOperatorKeyword;
817
818 // If this identifier is a macro, deserialize the macro
819 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000820 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000821 uint32_t MacroDirectivesOffset =
822 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000823 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000824
Richard Smithd7329392015-04-21 21:46:32 +0000825 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000826 }
827
828 Reader.SetIdentifierInfo(ID, II);
829
830 // Read all of the declarations visible at global scope with this
831 // name.
832 if (DataLen > 0) {
833 SmallVector<uint32_t, 4> DeclIDs;
834 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000835 DeclIDs.push_back(Reader.getGlobalDeclID(
836 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000837 Reader.SetGloballyVisibleDecls(II, DeclIDs);
838 }
839
840 return II;
841}
842
843unsigned
Richard Smith3b637412015-07-14 18:42:41 +0000844ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000845 llvm::FoldingSetNodeID ID;
846 ID.AddInteger(Key.Kind);
847
848 switch (Key.Kind) {
849 case DeclarationName::Identifier:
850 case DeclarationName::CXXLiteralOperatorName:
851 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
852 break;
853 case DeclarationName::ObjCZeroArgSelector:
854 case DeclarationName::ObjCOneArgSelector:
855 case DeclarationName::ObjCMultiArgSelector:
856 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
857 break;
858 case DeclarationName::CXXOperatorName:
859 ID.AddInteger((OverloadedOperatorKind)Key.Data);
860 break;
861 case DeclarationName::CXXConstructorName:
862 case DeclarationName::CXXDestructorName:
863 case DeclarationName::CXXConversionFunctionName:
864 case DeclarationName::CXXUsingDirective:
865 break;
866 }
867
868 return ID.ComputeHash();
869}
870
871ASTDeclContextNameLookupTrait::internal_key_type
872ASTDeclContextNameLookupTrait::GetInternalKey(
Richard Smith3b637412015-07-14 18:42:41 +0000873 const external_key_type& Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000874 DeclNameKey Key;
875 Key.Kind = Name.getNameKind();
876 switch (Name.getNameKind()) {
877 case DeclarationName::Identifier:
878 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
879 break;
880 case DeclarationName::ObjCZeroArgSelector:
881 case DeclarationName::ObjCOneArgSelector:
882 case DeclarationName::ObjCMultiArgSelector:
883 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
884 break;
885 case DeclarationName::CXXOperatorName:
886 Key.Data = Name.getCXXOverloadedOperator();
887 break;
888 case DeclarationName::CXXLiteralOperatorName:
889 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
890 break;
891 case DeclarationName::CXXConstructorName:
892 case DeclarationName::CXXDestructorName:
893 case DeclarationName::CXXConversionFunctionName:
894 case DeclarationName::CXXUsingDirective:
895 Key.Data = 0;
896 break;
897 }
898
899 return Key;
900}
901
902std::pair<unsigned, unsigned>
903ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000904 using namespace llvm::support;
905 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
906 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000907 return std::make_pair(KeyLen, DataLen);
908}
909
910ASTDeclContextNameLookupTrait::internal_key_type
911ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000912 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000913
914 DeclNameKey Key;
915 Key.Kind = (DeclarationName::NameKind)*d++;
916 switch (Key.Kind) {
917 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000918 Key.Data = (uint64_t)Reader.getLocalIdentifier(
919 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000920 break;
921 case DeclarationName::ObjCZeroArgSelector:
922 case DeclarationName::ObjCOneArgSelector:
923 case DeclarationName::ObjCMultiArgSelector:
924 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000925 (uint64_t)Reader.getLocalSelector(
926 F, endian::readNext<uint32_t, little, unaligned>(
927 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000928 break;
929 case DeclarationName::CXXOperatorName:
930 Key.Data = *d++; // OverloadedOperatorKind
931 break;
932 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000933 Key.Data = (uint64_t)Reader.getLocalIdentifier(
934 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000935 break;
936 case DeclarationName::CXXConstructorName:
937 case DeclarationName::CXXDestructorName:
938 case DeclarationName::CXXConversionFunctionName:
939 case DeclarationName::CXXUsingDirective:
940 Key.Data = 0;
941 break;
942 }
943
944 return Key;
945}
946
Richard Smithf02662d2015-07-30 03:17:16 +0000947ASTDeclContextNameLookupTrait::data_type
948ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
949 const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000950 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000951 using namespace llvm::support;
Richard Smithf02662d2015-07-30 03:17:16 +0000952 unsigned NumDecls = DataLen / 4;
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000953 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
954 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000955 return std::make_pair(Start, Start + NumDecls);
956}
957
Richard Smith0f4e2c42015-08-06 04:23:48 +0000958bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
959 BitstreamCursor &Cursor,
960 uint64_t Offset,
961 DeclContext *DC) {
962 assert(Offset != 0);
963
Guy Benyei11169dd2012-12-18 14:30:41 +0000964 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +0000965 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000966
Richard Smith0f4e2c42015-08-06 04:23:48 +0000967 RecordData Record;
968 StringRef Blob;
969 unsigned Code = Cursor.ReadCode();
970 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
971 if (RecCode != DECL_CONTEXT_LEXICAL) {
972 Error("Expected lexical block");
973 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000974 }
975
Richard Smith82f8fcd2015-08-06 22:07:25 +0000976 assert(!isa<TranslationUnitDecl>(DC) &&
977 "expected a TU_UPDATE_LEXICAL record for TU");
978 // FIXME: Once we remove RewriteDecl, assert that we didn't already have
979 // lexical decls for this context.
980 LexicalDecls[DC] = llvm::makeArrayRef(
981 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(Blob.data()),
982 Blob.size() / 4);
Richard Smith0f4e2c42015-08-06 04:23:48 +0000983 DC->setHasExternalLexicalStorage(true);
984 return false;
985}
Guy Benyei11169dd2012-12-18 14:30:41 +0000986
Richard Smith0f4e2c42015-08-06 04:23:48 +0000987bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
988 BitstreamCursor &Cursor,
989 uint64_t Offset,
990 DeclID ID) {
991 assert(Offset != 0);
992
993 SavedStreamPosition SavedPosition(Cursor);
994 Cursor.JumpToBit(Offset);
995
996 RecordData Record;
997 StringRef Blob;
998 unsigned Code = Cursor.ReadCode();
999 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1000 if (RecCode != DECL_CONTEXT_VISIBLE) {
1001 Error("Expected visible lookup table block");
1002 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001003 }
1004
Richard Smith0f4e2c42015-08-06 04:23:48 +00001005 // We can't safely determine the primary context yet, so delay attaching the
1006 // lookup table until we're done with recursive deserialization.
1007 unsigned BucketOffset = Record[0];
1008 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{
1009 &M, (const unsigned char *)Blob.data(), BucketOffset});
Guy Benyei11169dd2012-12-18 14:30:41 +00001010 return false;
1011}
1012
1013void ASTReader::Error(StringRef Msg) {
1014 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001015 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1016 Diag(diag::note_module_cache_path)
1017 << PP.getHeaderSearchInfo().getModuleCachePath();
1018 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001019}
1020
1021void ASTReader::Error(unsigned DiagID,
1022 StringRef Arg1, StringRef Arg2) {
1023 if (Diags.isDiagnosticInFlight())
1024 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1025 else
1026 Diag(DiagID) << Arg1 << Arg2;
1027}
1028
1029//===----------------------------------------------------------------------===//
1030// Source Manager Deserialization
1031//===----------------------------------------------------------------------===//
1032
1033/// \brief Read the line table in the source manager block.
1034/// \returns true if there was an error.
1035bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001036 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001037 unsigned Idx = 0;
1038 LineTableInfo &LineTable = SourceMgr.getLineTable();
1039
1040 // Parse the file names
1041 std::map<int, int> FileIDs;
1042 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1043 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001044 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001045 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1046 }
1047
1048 // Parse the line entries
1049 std::vector<LineEntry> Entries;
1050 while (Idx < Record.size()) {
1051 int FID = Record[Idx++];
1052 assert(FID >= 0 && "Serialized line entries for non-local file.");
1053 // Remap FileID from 1-based old view.
1054 FID += F.SLocEntryBaseID - 1;
1055
1056 // Extract the line entries
1057 unsigned NumEntries = Record[Idx++];
1058 assert(NumEntries && "Numentries is 00000");
1059 Entries.clear();
1060 Entries.reserve(NumEntries);
1061 for (unsigned I = 0; I != NumEntries; ++I) {
1062 unsigned FileOffset = Record[Idx++];
1063 unsigned LineNo = Record[Idx++];
1064 int FilenameID = FileIDs[Record[Idx++]];
1065 SrcMgr::CharacteristicKind FileKind
1066 = (SrcMgr::CharacteristicKind)Record[Idx++];
1067 unsigned IncludeOffset = Record[Idx++];
1068 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1069 FileKind, IncludeOffset));
1070 }
1071 LineTable.AddEntry(FileID::get(FID), Entries);
1072 }
1073
1074 return false;
1075}
1076
1077/// \brief Read a source manager block
1078bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1079 using namespace SrcMgr;
1080
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001081 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001082
1083 // Set the source-location entry cursor to the current position in
1084 // the stream. This cursor will be used to read the contents of the
1085 // source manager block initially, and then lazily read
1086 // source-location entries as needed.
1087 SLocEntryCursor = F.Stream;
1088
1089 // The stream itself is going to skip over the source manager block.
1090 if (F.Stream.SkipBlock()) {
1091 Error("malformed block record in AST file");
1092 return true;
1093 }
1094
1095 // Enter the source manager block.
1096 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1097 Error("malformed source manager block record in AST file");
1098 return true;
1099 }
1100
1101 RecordData Record;
1102 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001103 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1104
1105 switch (E.Kind) {
1106 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1107 case llvm::BitstreamEntry::Error:
1108 Error("malformed block record in AST file");
1109 return true;
1110 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001111 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001112 case llvm::BitstreamEntry::Record:
1113 // The interesting case.
1114 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001115 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001116
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001118 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001119 StringRef Blob;
1120 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001121 default: // Default behavior: ignore.
1122 break;
1123
1124 case SM_SLOC_FILE_ENTRY:
1125 case SM_SLOC_BUFFER_ENTRY:
1126 case SM_SLOC_EXPANSION_ENTRY:
1127 // Once we hit one of the source location entries, we're done.
1128 return false;
1129 }
1130 }
1131}
1132
1133/// \brief If a header file is not found at the path that we expect it to be
1134/// and the PCH file was moved from its original location, try to resolve the
1135/// file by assuming that header+PCH were moved together and the header is in
1136/// the same place relative to the PCH.
1137static std::string
1138resolveFileRelativeToOriginalDir(const std::string &Filename,
1139 const std::string &OriginalDir,
1140 const std::string &CurrDir) {
1141 assert(OriginalDir != CurrDir &&
1142 "No point trying to resolve the file if the PCH dir didn't change");
1143 using namespace llvm::sys;
1144 SmallString<128> filePath(Filename);
1145 fs::make_absolute(filePath);
1146 assert(path::is_absolute(OriginalDir));
1147 SmallString<128> currPCHPath(CurrDir);
1148
1149 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1150 fileDirE = path::end(path::parent_path(filePath));
1151 path::const_iterator origDirI = path::begin(OriginalDir),
1152 origDirE = path::end(OriginalDir);
1153 // Skip the common path components from filePath and OriginalDir.
1154 while (fileDirI != fileDirE && origDirI != origDirE &&
1155 *fileDirI == *origDirI) {
1156 ++fileDirI;
1157 ++origDirI;
1158 }
1159 for (; origDirI != origDirE; ++origDirI)
1160 path::append(currPCHPath, "..");
1161 path::append(currPCHPath, fileDirI, fileDirE);
1162 path::append(currPCHPath, path::filename(Filename));
1163 return currPCHPath.str();
1164}
1165
1166bool ASTReader::ReadSLocEntry(int ID) {
1167 if (ID == 0)
1168 return false;
1169
1170 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1171 Error("source location entry ID out-of-range for AST file");
1172 return true;
1173 }
1174
1175 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1176 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001177 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001178 unsigned BaseOffset = F->SLocEntryBaseOffset;
1179
1180 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001181 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1182 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001183 Error("incorrectly-formatted source location entry in AST file");
1184 return true;
1185 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001186
Guy Benyei11169dd2012-12-18 14:30:41 +00001187 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001188 StringRef Blob;
1189 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001190 default:
1191 Error("incorrectly-formatted source location entry in AST file");
1192 return true;
1193
1194 case SM_SLOC_FILE_ENTRY: {
1195 // We will detect whether a file changed and return 'Failure' for it, but
1196 // we will also try to fail gracefully by setting up the SLocEntry.
1197 unsigned InputID = Record[4];
1198 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001199 const FileEntry *File = IF.getFile();
1200 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001201
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001202 // Note that we only check if a File was returned. If it was out-of-date
1203 // we have complained but we will continue creating a FileID to recover
1204 // gracefully.
1205 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001206 return true;
1207
1208 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1209 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1210 // This is the module's main file.
1211 IncludeLoc = getImportLocation(F);
1212 }
1213 SrcMgr::CharacteristicKind
1214 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1215 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1216 ID, BaseOffset + Record[0]);
1217 SrcMgr::FileInfo &FileInfo =
1218 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1219 FileInfo.NumCreatedFIDs = Record[5];
1220 if (Record[3])
1221 FileInfo.setHasLineDirectives();
1222
1223 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1224 unsigned NumFileDecls = Record[7];
1225 if (NumFileDecls) {
1226 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1227 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1228 NumFileDecls));
1229 }
1230
1231 const SrcMgr::ContentCache *ContentCache
1232 = SourceMgr.getOrCreateContentCache(File,
1233 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1234 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1235 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1236 unsigned Code = SLocEntryCursor.ReadCode();
1237 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001238 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001239
1240 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1241 Error("AST record has invalid code");
1242 return true;
1243 }
1244
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001245 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001246 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001247 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001248 }
1249
1250 break;
1251 }
1252
1253 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001254 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001255 unsigned Offset = Record[0];
1256 SrcMgr::CharacteristicKind
1257 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1258 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001259 if (IncludeLoc.isInvalid() &&
1260 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001261 IncludeLoc = getImportLocation(F);
1262 }
1263 unsigned Code = SLocEntryCursor.ReadCode();
1264 Record.clear();
1265 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001266 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001267
1268 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1269 Error("AST record has invalid code");
1270 return true;
1271 }
1272
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001273 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1274 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001275 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001276 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001277 break;
1278 }
1279
1280 case SM_SLOC_EXPANSION_ENTRY: {
1281 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1282 SourceMgr.createExpansionLoc(SpellingLoc,
1283 ReadSourceLocation(*F, Record[2]),
1284 ReadSourceLocation(*F, Record[3]),
1285 Record[4],
1286 ID,
1287 BaseOffset + Record[0]);
1288 break;
1289 }
1290 }
1291
1292 return false;
1293}
1294
1295std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1296 if (ID == 0)
1297 return std::make_pair(SourceLocation(), "");
1298
1299 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1300 Error("source location entry ID out-of-range for AST file");
1301 return std::make_pair(SourceLocation(), "");
1302 }
1303
1304 // Find which module file this entry lands in.
1305 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001306 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001307 return std::make_pair(SourceLocation(), "");
1308
1309 // FIXME: Can we map this down to a particular submodule? That would be
1310 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001311 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001312}
1313
1314/// \brief Find the location where the module F is imported.
1315SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1316 if (F->ImportLoc.isValid())
1317 return F->ImportLoc;
1318
1319 // Otherwise we have a PCH. It's considered to be "imported" at the first
1320 // location of its includer.
1321 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001322 // Main file is the importer.
1323 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1324 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001325 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001326 return F->ImportedBy[0]->FirstLoc;
1327}
1328
1329/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1330/// specified cursor. Read the abbreviations that are at the top of the block
1331/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001332bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001333 if (Cursor.EnterSubBlock(BlockID)) {
1334 Error("malformed block record in AST file");
1335 return Failure;
1336 }
1337
1338 while (true) {
1339 uint64_t Offset = Cursor.GetCurrentBitNo();
1340 unsigned Code = Cursor.ReadCode();
1341
1342 // We expect all abbrevs to be at the start of the block.
1343 if (Code != llvm::bitc::DEFINE_ABBREV) {
1344 Cursor.JumpToBit(Offset);
1345 return false;
1346 }
1347 Cursor.ReadAbbrevRecord();
1348 }
1349}
1350
Richard Smithe40f2ba2013-08-07 21:41:30 +00001351Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001352 unsigned &Idx) {
1353 Token Tok;
1354 Tok.startToken();
1355 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1356 Tok.setLength(Record[Idx++]);
1357 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1358 Tok.setIdentifierInfo(II);
1359 Tok.setKind((tok::TokenKind)Record[Idx++]);
1360 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1361 return Tok;
1362}
1363
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001364MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001365 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001366
1367 // Keep track of where we are in the stream, then jump back there
1368 // after reading this macro.
1369 SavedStreamPosition SavedPosition(Stream);
1370
1371 Stream.JumpToBit(Offset);
1372 RecordData Record;
1373 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001374 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001375
Guy Benyei11169dd2012-12-18 14:30:41 +00001376 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001377 // Advance to the next record, but if we get to the end of the block, don't
1378 // pop it (removing all the abbreviations from the cursor) since we want to
1379 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001380 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001381 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1382
1383 switch (Entry.Kind) {
1384 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1385 case llvm::BitstreamEntry::Error:
1386 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001387 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001388 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001389 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001390 case llvm::BitstreamEntry::Record:
1391 // The interesting case.
1392 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001393 }
1394
1395 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001396 Record.clear();
1397 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001398 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001399 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001400 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001401 case PP_MACRO_DIRECTIVE_HISTORY:
1402 return Macro;
1403
Guy Benyei11169dd2012-12-18 14:30:41 +00001404 case PP_MACRO_OBJECT_LIKE:
1405 case PP_MACRO_FUNCTION_LIKE: {
1406 // If we already have a macro, that means that we've hit the end
1407 // of the definition of the macro we were looking for. We're
1408 // done.
1409 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001410 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001411
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001412 unsigned NextIndex = 1; // Skip identifier ID.
1413 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001414 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001415 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001416 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001418 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001419
Guy Benyei11169dd2012-12-18 14:30:41 +00001420 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1421 // Decode function-like macro info.
1422 bool isC99VarArgs = Record[NextIndex++];
1423 bool isGNUVarArgs = Record[NextIndex++];
1424 bool hasCommaPasting = Record[NextIndex++];
1425 MacroArgs.clear();
1426 unsigned NumArgs = Record[NextIndex++];
1427 for (unsigned i = 0; i != NumArgs; ++i)
1428 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1429
1430 // Install function-like macro info.
1431 MI->setIsFunctionLike();
1432 if (isC99VarArgs) MI->setIsC99Varargs();
1433 if (isGNUVarArgs) MI->setIsGNUVarargs();
1434 if (hasCommaPasting) MI->setHasCommaPasting();
1435 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1436 PP.getPreprocessorAllocator());
1437 }
1438
Guy Benyei11169dd2012-12-18 14:30:41 +00001439 // Remember that we saw this macro last so that we add the tokens that
1440 // form its body to it.
1441 Macro = MI;
1442
1443 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1444 Record[NextIndex]) {
1445 // We have a macro definition. Register the association
1446 PreprocessedEntityID
1447 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1448 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001449 PreprocessingRecord::PPEntityID PPID =
1450 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1451 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1452 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001453 if (PPDef)
1454 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001455 }
1456
1457 ++NumMacrosRead;
1458 break;
1459 }
1460
1461 case PP_TOKEN: {
1462 // If we see a TOKEN before a PP_MACRO_*, then the file is
1463 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001464 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001465
John McCallf413f5e2013-05-03 00:10:13 +00001466 unsigned Idx = 0;
1467 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001468 Macro->AddTokenToBody(Tok);
1469 break;
1470 }
1471 }
1472 }
1473}
1474
1475PreprocessedEntityID
1476ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1477 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1478 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1479 assert(I != M.PreprocessedEntityRemap.end()
1480 && "Invalid index into preprocessed entity index remap");
1481
1482 return LocalID + I->second;
1483}
1484
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001485unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1486 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001487}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001488
Guy Benyei11169dd2012-12-18 14:30:41 +00001489HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001490HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1491 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001492 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001493 return ikey;
1494}
Guy Benyei11169dd2012-12-18 14:30:41 +00001495
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001496bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1497 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001498 return false;
1499
Richard Smith7ed1bc92014-12-05 22:42:13 +00001500 if (llvm::sys::path::is_absolute(a.Filename) &&
1501 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001502 return true;
1503
Guy Benyei11169dd2012-12-18 14:30:41 +00001504 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001505 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001506 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1507 if (!Key.Imported)
1508 return FileMgr.getFile(Key.Filename);
1509
1510 std::string Resolved = Key.Filename;
1511 Reader.ResolveImportedPath(M, Resolved);
1512 return FileMgr.getFile(Resolved);
1513 };
1514
1515 const FileEntry *FEA = GetFile(a);
1516 const FileEntry *FEB = GetFile(b);
1517 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001518}
1519
1520std::pair<unsigned, unsigned>
1521HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001522 using namespace llvm::support;
1523 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001524 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001525 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001526}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001527
1528HeaderFileInfoTrait::internal_key_type
1529HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001530 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001531 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001532 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1533 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001534 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001535 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001536 return ikey;
1537}
1538
Guy Benyei11169dd2012-12-18 14:30:41 +00001539HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001540HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001541 unsigned DataLen) {
1542 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001543 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001544 HeaderFileInfo HFI;
1545 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001546 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1547 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001548 HFI.isImport = (Flags >> 5) & 0x01;
1549 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1550 HFI.DirInfo = (Flags >> 2) & 0x03;
1551 HFI.Resolved = (Flags >> 1) & 0x01;
1552 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001553 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1554 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1555 M, endian::readNext<uint32_t, little, unaligned>(d));
1556 if (unsigned FrameworkOffset =
1557 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001558 // The framework offset is 1 greater than the actual offset,
1559 // since 0 is used as an indicator for "no framework name".
1560 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1561 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1562 }
1563
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001564 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001565 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001566 if (LocalSMID) {
1567 // This header is part of a module. Associate it with the module to enable
1568 // implicit module import.
1569 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1570 Module *Mod = Reader.getSubmodule(GlobalSMID);
1571 HFI.isModuleHeader = true;
1572 FileManager &FileMgr = Reader.getFileManager();
1573 ModuleMap &ModMap =
1574 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001575 // FIXME: This information should be propagated through the
1576 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001577 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001578 std::string Filename = key.Filename;
1579 if (key.Imported)
1580 Reader.ResolveImportedPath(M, Filename);
1581 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001582 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001583 }
1584 }
1585
Guy Benyei11169dd2012-12-18 14:30:41 +00001586 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1587 (void)End;
1588
1589 // This HeaderFileInfo was externally loaded.
1590 HFI.External = true;
1591 return HFI;
1592}
1593
Richard Smithd7329392015-04-21 21:46:32 +00001594void ASTReader::addPendingMacro(IdentifierInfo *II,
1595 ModuleFile *M,
1596 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001597 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1598 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001599}
1600
1601void ASTReader::ReadDefinedMacros() {
1602 // Note that we are loading defined macros.
1603 Deserializing Macros(this);
1604
Pete Cooper57d3f142015-07-30 17:22:52 +00001605 for (auto &I : llvm::reverse(ModuleMgr)) {
1606 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001607
1608 // If there was no preprocessor block, skip this file.
1609 if (!MacroCursor.getBitStreamReader())
1610 continue;
1611
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001612 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001613 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001614
1615 RecordData Record;
1616 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001617 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1618
1619 switch (E.Kind) {
1620 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1621 case llvm::BitstreamEntry::Error:
1622 Error("malformed block record in AST file");
1623 return;
1624 case llvm::BitstreamEntry::EndBlock:
1625 goto NextCursor;
1626
1627 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001628 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001629 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001630 default: // Default behavior: ignore.
1631 break;
1632
1633 case PP_MACRO_OBJECT_LIKE:
1634 case PP_MACRO_FUNCTION_LIKE:
Pete Cooper57d3f142015-07-30 17:22:52 +00001635 getLocalIdentifier(*I, Record[0]);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001636 break;
1637
1638 case PP_TOKEN:
1639 // Ignore tokens.
1640 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001641 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001642 break;
1643 }
1644 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001645 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001646 }
1647}
1648
1649namespace {
1650 /// \brief Visitor class used to look up identifirs in an AST file.
1651 class IdentifierLookupVisitor {
1652 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001653 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001654 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001655 unsigned &NumIdentifierLookups;
1656 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001657 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001658
Guy Benyei11169dd2012-12-18 14:30:41 +00001659 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001660 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1661 unsigned &NumIdentifierLookups,
1662 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001663 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1664 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001665 NumIdentifierLookups(NumIdentifierLookups),
1666 NumIdentifierLookupHits(NumIdentifierLookupHits),
1667 Found()
1668 {
1669 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001670
1671 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001672 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001673 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001674 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001675
Guy Benyei11169dd2012-12-18 14:30:41 +00001676 ASTIdentifierLookupTable *IdTable
1677 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1678 if (!IdTable)
1679 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001680
1681 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001682 Found);
1683 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001684 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001685 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001686 if (Pos == IdTable->end())
1687 return false;
1688
1689 // Dereferencing the iterator has the effect of building the
1690 // IdentifierInfo node and populating it with the various
1691 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001692 ++NumIdentifierLookupHits;
1693 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001694 return true;
1695 }
1696
1697 // \brief Retrieve the identifier info found within the module
1698 // files.
1699 IdentifierInfo *getIdentifierInfo() const { return Found; }
1700 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001701}
Guy Benyei11169dd2012-12-18 14:30:41 +00001702
1703void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1704 // Note that we are loading an identifier.
1705 Deserializing AnIdentifier(this);
1706
1707 unsigned PriorGeneration = 0;
1708 if (getContext().getLangOpts().Modules)
1709 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001710
1711 // If there is a global index, look there first to determine which modules
1712 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001713 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001714 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001715 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001716 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1717 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001718 }
1719 }
1720
Douglas Gregor7211ac12013-01-25 23:32:03 +00001721 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001722 NumIdentifierLookups,
1723 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001724 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001725 markIdentifierUpToDate(&II);
1726}
1727
1728void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1729 if (!II)
1730 return;
1731
1732 II->setOutOfDate(false);
1733
1734 // Update the generation for this identifier.
1735 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001736 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001737}
1738
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001739void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1740 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001741 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001742
1743 BitstreamCursor &Cursor = M.MacroCursor;
1744 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001745 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001746
Richard Smith713369b2015-04-23 20:40:50 +00001747 struct ModuleMacroRecord {
1748 SubmoduleID SubModID;
1749 MacroInfo *MI;
1750 SmallVector<SubmoduleID, 8> Overrides;
1751 };
1752 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001753
Richard Smithd7329392015-04-21 21:46:32 +00001754 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1755 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1756 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001757 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001758 while (true) {
1759 llvm::BitstreamEntry Entry =
1760 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1761 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1762 Error("malformed block record in AST file");
1763 return;
1764 }
1765
1766 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001767 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001768 case PP_MACRO_DIRECTIVE_HISTORY:
1769 break;
1770
1771 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001772 ModuleMacros.push_back(ModuleMacroRecord());
1773 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001774 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1775 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001776 for (int I = 2, N = Record.size(); I != N; ++I)
1777 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001778 continue;
1779 }
1780
1781 default:
1782 Error("malformed block record in AST file");
1783 return;
1784 }
1785
1786 // We found the macro directive history; that's the last record
1787 // for this macro.
1788 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001789 }
1790
Richard Smithd7329392015-04-21 21:46:32 +00001791 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001792 {
1793 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001794 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001795 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001796 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001797 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001798 Module *Mod = getSubmodule(ModID);
1799 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001800 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001801 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001802 }
1803
1804 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001805 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001806 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001807 }
1808 }
1809
1810 // Don't read the directive history for a module; we don't have anywhere
1811 // to put it.
1812 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1813 return;
1814
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001815 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001816 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001817 unsigned Idx = 0, N = Record.size();
1818 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001819 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001820 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001821 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1822 switch (K) {
1823 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001824 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001825 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001826 break;
1827 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001828 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001829 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001830 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001831 }
1832 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001833 bool isPublic = Record[Idx++];
1834 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1835 break;
1836 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001837
1838 if (!Latest)
1839 Latest = MD;
1840 if (Earliest)
1841 Earliest->setPrevious(MD);
1842 Earliest = MD;
1843 }
1844
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001845 if (Latest)
1846 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001847}
1848
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001849ASTReader::InputFileInfo
1850ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001851 // Go find this input file.
1852 BitstreamCursor &Cursor = F.InputFilesCursor;
1853 SavedStreamPosition SavedPosition(Cursor);
1854 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1855
1856 unsigned Code = Cursor.ReadCode();
1857 RecordData Record;
1858 StringRef Blob;
1859
1860 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1861 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1862 "invalid record type for input file");
1863 (void)Result;
1864
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001865 std::string Filename;
1866 off_t StoredSize;
1867 time_t StoredTime;
1868 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001869
Ben Langmuir198c1682014-03-07 07:27:49 +00001870 assert(Record[0] == ID && "Bogus stored ID or offset");
1871 StoredSize = static_cast<off_t>(Record[1]);
1872 StoredTime = static_cast<time_t>(Record[2]);
1873 Overridden = static_cast<bool>(Record[3]);
1874 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001875 ResolveImportedPath(F, Filename);
1876
Hans Wennborg73945142014-03-14 17:45:06 +00001877 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1878 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001879}
1880
1881std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001882 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00001883}
1884
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001885InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001886 // If this ID is bogus, just return an empty input file.
1887 if (ID == 0 || ID > F.InputFilesLoaded.size())
1888 return InputFile();
1889
1890 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001891 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001892 return F.InputFilesLoaded[ID-1];
1893
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001894 if (F.InputFilesLoaded[ID-1].isNotFound())
1895 return InputFile();
1896
Guy Benyei11169dd2012-12-18 14:30:41 +00001897 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001898 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001899 SavedStreamPosition SavedPosition(Cursor);
1900 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1901
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001902 InputFileInfo FI = readInputFileInfo(F, ID);
1903 off_t StoredSize = FI.StoredSize;
1904 time_t StoredTime = FI.StoredTime;
1905 bool Overridden = FI.Overridden;
1906 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001907
Ben Langmuir198c1682014-03-07 07:27:49 +00001908 const FileEntry *File
1909 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1910 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1911
1912 // If we didn't find the file, resolve it relative to the
1913 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001914 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001915 F.OriginalDir != CurrentDir) {
1916 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1917 F.OriginalDir,
1918 CurrentDir);
1919 if (!Resolved.empty())
1920 File = FileMgr.getFile(Resolved);
1921 }
1922
1923 // For an overridden file, create a virtual file with the stored
1924 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001925 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001926 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1927 }
1928
Craig Toppera13603a2014-05-22 05:54:18 +00001929 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001930 if (Complain) {
1931 std::string ErrorStr = "could not find file '";
1932 ErrorStr += Filename;
1933 ErrorStr += "' referenced by AST file";
1934 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001935 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001936 // Record that we didn't find the file.
1937 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1938 return InputFile();
1939 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001940
Ben Langmuir198c1682014-03-07 07:27:49 +00001941 // Check if there was a request to override the contents of the file
1942 // that was part of the precompiled header. Overridding such a file
1943 // can lead to problems when lexing using the source locations from the
1944 // PCH.
1945 SourceManager &SM = getSourceManager();
1946 if (!Overridden && SM.isFileOverridden(File)) {
1947 if (Complain)
1948 Error(diag::err_fe_pch_file_overridden, Filename);
1949 // After emitting the diagnostic, recover by disabling the override so
1950 // that the original file will be used.
1951 SM.disableFileContentsOverride(File);
1952 // The FileEntry is a virtual file entry with the size of the contents
1953 // that would override the original contents. Set it to the original's
1954 // size/time.
1955 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1956 StoredSize, StoredTime);
1957 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001958
Ben Langmuir198c1682014-03-07 07:27:49 +00001959 bool IsOutOfDate = false;
1960
1961 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001962 if (!Overridden && //
1963 (StoredSize != File->getSize() ||
1964#if defined(LLVM_ON_WIN32)
1965 false
1966#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001967 // In our regression testing, the Windows file system seems to
1968 // have inconsistent modification times that sometimes
1969 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001970 //
1971 // This also happens in networked file systems, so disable this
1972 // check if validation is disabled or if we have an explicitly
1973 // built PCM file.
1974 //
1975 // FIXME: Should we also do this for PCH files? They could also
1976 // reasonably get shared across a network during a distributed build.
1977 (StoredTime != File->getModificationTime() && !DisableValidation &&
1978 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001979#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001980 )) {
1981 if (Complain) {
1982 // Build a list of the PCH imports that got us here (in reverse).
1983 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1984 while (ImportStack.back()->ImportedBy.size() > 0)
1985 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001986
Ben Langmuir198c1682014-03-07 07:27:49 +00001987 // The top-level PCH is stale.
1988 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1989 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00001990
Ben Langmuir198c1682014-03-07 07:27:49 +00001991 // Print the import stack.
1992 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1993 Diag(diag::note_pch_required_by)
1994 << Filename << ImportStack[0]->FileName;
1995 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00001996 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00001997 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00001998 }
1999
Ben Langmuir198c1682014-03-07 07:27:49 +00002000 if (!Diags.isDiagnosticInFlight())
2001 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002002 }
2003
Ben Langmuir198c1682014-03-07 07:27:49 +00002004 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002005 }
2006
Ben Langmuir198c1682014-03-07 07:27:49 +00002007 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2008
2009 // Note that we've loaded this input file.
2010 F.InputFilesLoaded[ID-1] = IF;
2011 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002012}
2013
Richard Smith7ed1bc92014-12-05 22:42:13 +00002014/// \brief If we are loading a relocatable PCH or module file, and the filename
2015/// is not an absolute path, add the system or module root to the beginning of
2016/// the file name.
2017void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2018 // Resolve relative to the base directory, if we have one.
2019 if (!M.BaseDirectory.empty())
2020 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002021}
2022
Richard Smith7ed1bc92014-12-05 22:42:13 +00002023void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002024 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2025 return;
2026
Richard Smith7ed1bc92014-12-05 22:42:13 +00002027 SmallString<128> Buffer;
2028 llvm::sys::path::append(Buffer, Prefix, Filename);
2029 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002030}
2031
2032ASTReader::ASTReadResult
2033ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002034 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002035 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002036 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002037 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002038
2039 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2040 Error("malformed block record in AST file");
2041 return Failure;
2042 }
2043
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002044 // Should we allow the configuration of the module file to differ from the
2045 // configuration of the current translation unit in a compatible way?
2046 //
2047 // FIXME: Allow this for files explicitly specified with -include-pch too.
2048 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2049
Guy Benyei11169dd2012-12-18 14:30:41 +00002050 // Read all of the records and blocks in the control block.
2051 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002052 unsigned NumInputs = 0;
2053 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002054 while (1) {
2055 llvm::BitstreamEntry Entry = Stream.advance();
2056
2057 switch (Entry.Kind) {
2058 case llvm::BitstreamEntry::Error:
2059 Error("malformed block record in AST file");
2060 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002061 case llvm::BitstreamEntry::EndBlock: {
2062 // Validate input files.
2063 const HeaderSearchOptions &HSOpts =
2064 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002065
Richard Smitha1825302014-10-23 22:18:29 +00002066 // All user input files reside at the index range [0, NumUserInputs), and
2067 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002068 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002069 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002070
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002071 // If we are reading a module, we will create a verification timestamp,
2072 // so we verify all input files. Otherwise, verify only user input
2073 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002074
2075 unsigned N = NumUserInputs;
2076 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002077 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002078 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002079 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002080 N = NumInputs;
2081
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002082 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002083 InputFile IF = getInputFile(F, I+1, Complain);
2084 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002085 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002086 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002087 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002088
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002089 if (Listener)
2090 Listener->visitModuleFile(F.FileName);
2091
Ben Langmuircb69b572014-03-07 06:40:32 +00002092 if (Listener && Listener->needsInputFileVisitation()) {
2093 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2094 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002095 for (unsigned I = 0; I < N; ++I) {
2096 bool IsSystem = I >= NumUserInputs;
2097 InputFileInfo FI = readInputFileInfo(F, I+1);
2098 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2099 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002100 }
2101
Guy Benyei11169dd2012-12-18 14:30:41 +00002102 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002103 }
2104
Chris Lattnere7b154b2013-01-19 21:39:22 +00002105 case llvm::BitstreamEntry::SubBlock:
2106 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002107 case INPUT_FILES_BLOCK_ID:
2108 F.InputFilesCursor = Stream;
2109 if (Stream.SkipBlock() || // Skip with the main cursor
2110 // Read the abbreviations
2111 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2112 Error("malformed block record in AST file");
2113 return Failure;
2114 }
2115 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002116
Guy Benyei11169dd2012-12-18 14:30:41 +00002117 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002118 if (Stream.SkipBlock()) {
2119 Error("malformed block record in AST file");
2120 return Failure;
2121 }
2122 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002123 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002124
2125 case llvm::BitstreamEntry::Record:
2126 // The interesting case.
2127 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002128 }
2129
2130 // Read and process a record.
2131 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002132 StringRef Blob;
2133 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002134 case METADATA: {
2135 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2136 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002137 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2138 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002139 return VersionMismatch;
2140 }
2141
2142 bool hasErrors = Record[5];
2143 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2144 Diag(diag::err_pch_with_compiler_errors);
2145 return HadErrors;
2146 }
2147
2148 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002149 // Relative paths in a relocatable PCH are relative to our sysroot.
2150 if (F.RelocatablePCH)
2151 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002152
2153 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002154 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002155 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2156 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002157 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002158 return VersionMismatch;
2159 }
2160 break;
2161 }
2162
Ben Langmuir487ea142014-10-23 18:05:36 +00002163 case SIGNATURE:
2164 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2165 F.Signature = Record[0];
2166 break;
2167
Guy Benyei11169dd2012-12-18 14:30:41 +00002168 case IMPORTS: {
2169 // Load each of the imported PCH files.
2170 unsigned Idx = 0, N = Record.size();
2171 while (Idx < N) {
2172 // Read information about the AST file.
2173 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2174 // The import location will be the local one for now; we will adjust
2175 // all import locations of module imports after the global source
2176 // location info are setup.
2177 SourceLocation ImportLoc =
2178 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002179 off_t StoredSize = (off_t)Record[Idx++];
2180 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002181 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002182 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002183
2184 // Load the AST file.
2185 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002186 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002187 ClientLoadCapabilities)) {
2188 case Failure: return Failure;
2189 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002190 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002191 case OutOfDate: return OutOfDate;
2192 case VersionMismatch: return VersionMismatch;
2193 case ConfigurationMismatch: return ConfigurationMismatch;
2194 case HadErrors: return HadErrors;
2195 case Success: break;
2196 }
2197 }
2198 break;
2199 }
2200
Richard Smith7f330cd2015-03-18 01:42:29 +00002201 case KNOWN_MODULE_FILES:
2202 break;
2203
Guy Benyei11169dd2012-12-18 14:30:41 +00002204 case LANGUAGE_OPTIONS: {
2205 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002206 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002207 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002208 ParseLanguageOptions(Record, Complain, *Listener,
2209 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002210 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002211 return ConfigurationMismatch;
2212 break;
2213 }
2214
2215 case TARGET_OPTIONS: {
2216 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2217 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002218 ParseTargetOptions(Record, Complain, *Listener,
2219 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002220 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002221 return ConfigurationMismatch;
2222 break;
2223 }
2224
2225 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002226 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002227 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002228 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002229 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002230 !DisableValidation)
2231 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002232 break;
2233 }
2234
2235 case FILE_SYSTEM_OPTIONS: {
2236 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2237 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002238 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002239 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002240 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002241 return ConfigurationMismatch;
2242 break;
2243 }
2244
2245 case HEADER_SEARCH_OPTIONS: {
2246 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2247 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002248 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002249 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002250 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002251 return ConfigurationMismatch;
2252 break;
2253 }
2254
2255 case PREPROCESSOR_OPTIONS: {
2256 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2257 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002258 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002259 ParsePreprocessorOptions(Record, Complain, *Listener,
2260 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002261 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002262 return ConfigurationMismatch;
2263 break;
2264 }
2265
2266 case ORIGINAL_FILE:
2267 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002268 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002269 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002270 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002271 break;
2272
2273 case ORIGINAL_FILE_ID:
2274 F.OriginalSourceFileID = FileID::get(Record[0]);
2275 break;
2276
2277 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002278 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002279 break;
2280
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002281 case MODULE_NAME:
2282 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002283 if (Listener)
2284 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002285 break;
2286
Richard Smith223d3f22014-12-06 03:21:08 +00002287 case MODULE_DIRECTORY: {
2288 assert(!F.ModuleName.empty() &&
2289 "MODULE_DIRECTORY found before MODULE_NAME");
2290 // If we've already loaded a module map file covering this module, we may
2291 // have a better path for it (relative to the current build).
2292 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2293 if (M && M->Directory) {
2294 // If we're implicitly loading a module, the base directory can't
2295 // change between the build and use.
2296 if (F.Kind != MK_ExplicitModule) {
2297 const DirectoryEntry *BuildDir =
2298 PP.getFileManager().getDirectory(Blob);
2299 if (!BuildDir || BuildDir != M->Directory) {
2300 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2301 Diag(diag::err_imported_module_relocated)
2302 << F.ModuleName << Blob << M->Directory->getName();
2303 return OutOfDate;
2304 }
2305 }
2306 F.BaseDirectory = M->Directory->getName();
2307 } else {
2308 F.BaseDirectory = Blob;
2309 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002310 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002311 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002312
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002313 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002314 if (ASTReadResult Result =
2315 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2316 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002317 break;
2318
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002319 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002320 NumInputs = Record[0];
2321 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002322 F.InputFileOffsets =
2323 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002324 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002325 break;
2326 }
2327 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002328}
2329
Ben Langmuir2c9af442014-04-10 17:57:43 +00002330ASTReader::ASTReadResult
2331ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002332 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002333
2334 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2335 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002336 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002337 }
2338
2339 // Read all of the records and blocks for the AST file.
2340 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002341 while (1) {
2342 llvm::BitstreamEntry Entry = Stream.advance();
2343
2344 switch (Entry.Kind) {
2345 case llvm::BitstreamEntry::Error:
2346 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002347 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002348 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002349 // Outside of C++, we do not store a lookup map for the translation unit.
2350 // Instead, mark it as needing a lookup map to be built if this module
2351 // contains any declarations lexically within it (which it always does!).
2352 // This usually has no cost, since we very rarely need the lookup map for
2353 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002354 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002355 if (DC->hasExternalLexicalStorage() &&
2356 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002357 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002358
Ben Langmuir2c9af442014-04-10 17:57:43 +00002359 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002360 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002361 case llvm::BitstreamEntry::SubBlock:
2362 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002363 case DECLTYPES_BLOCK_ID:
2364 // We lazily load the decls block, but we want to set up the
2365 // DeclsCursor cursor to point into it. Clone our current bitcode
2366 // cursor to it, enter the block and read the abbrevs in that block.
2367 // With the main cursor, we just skip over it.
2368 F.DeclsCursor = Stream;
2369 if (Stream.SkipBlock() || // Skip with the main cursor.
2370 // Read the abbrevs.
2371 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2372 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002373 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002374 }
2375 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002376
Guy Benyei11169dd2012-12-18 14:30:41 +00002377 case PREPROCESSOR_BLOCK_ID:
2378 F.MacroCursor = Stream;
2379 if (!PP.getExternalSource())
2380 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002381
Guy Benyei11169dd2012-12-18 14:30:41 +00002382 if (Stream.SkipBlock() ||
2383 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2384 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002385 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002386 }
2387 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2388 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002389
Guy Benyei11169dd2012-12-18 14:30:41 +00002390 case PREPROCESSOR_DETAIL_BLOCK_ID:
2391 F.PreprocessorDetailCursor = Stream;
2392 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002393 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002394 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002395 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002396 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002397 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002398 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002399 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2400
Guy Benyei11169dd2012-12-18 14:30:41 +00002401 if (!PP.getPreprocessingRecord())
2402 PP.createPreprocessingRecord();
2403 if (!PP.getPreprocessingRecord()->getExternalSource())
2404 PP.getPreprocessingRecord()->SetExternalSource(*this);
2405 break;
2406
2407 case SOURCE_MANAGER_BLOCK_ID:
2408 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002409 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002411
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002413 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2414 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002415 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002416
Guy Benyei11169dd2012-12-18 14:30:41 +00002417 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002418 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002419 if (Stream.SkipBlock() ||
2420 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2421 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002422 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002423 }
2424 CommentsCursors.push_back(std::make_pair(C, &F));
2425 break;
2426 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002427
Guy Benyei11169dd2012-12-18 14:30:41 +00002428 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002429 if (Stream.SkipBlock()) {
2430 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002431 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002432 }
2433 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 }
2435 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002436
2437 case llvm::BitstreamEntry::Record:
2438 // The interesting case.
2439 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002440 }
2441
2442 // Read and process a record.
2443 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002444 StringRef Blob;
2445 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002446 default: // Default behavior: ignore.
2447 break;
2448
2449 case TYPE_OFFSET: {
2450 if (F.LocalNumTypes != 0) {
2451 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002452 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002454 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 F.LocalNumTypes = Record[0];
2456 unsigned LocalBaseTypeIndex = Record[1];
2457 F.BaseTypeIndex = getTotalNumTypes();
2458
2459 if (F.LocalNumTypes > 0) {
2460 // Introduce the global -> local mapping for types within this module.
2461 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2462
2463 // Introduce the local -> global mapping for types within this module.
2464 F.TypeRemap.insertOrReplace(
2465 std::make_pair(LocalBaseTypeIndex,
2466 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002467
2468 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 }
2470 break;
2471 }
2472
2473 case DECL_OFFSET: {
2474 if (F.LocalNumDecls != 0) {
2475 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002476 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002477 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002478 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002479 F.LocalNumDecls = Record[0];
2480 unsigned LocalBaseDeclID = Record[1];
2481 F.BaseDeclID = getTotalNumDecls();
2482
2483 if (F.LocalNumDecls > 0) {
2484 // Introduce the global -> local mapping for declarations within this
2485 // module.
2486 GlobalDeclMap.insert(
2487 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2488
2489 // Introduce the local -> global mapping for declarations within this
2490 // module.
2491 F.DeclRemap.insertOrReplace(
2492 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2493
2494 // Introduce the global -> local mapping for declarations within this
2495 // module.
2496 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002497
Ben Langmuir52ca6782014-10-20 16:27:32 +00002498 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2499 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002500 break;
2501 }
2502
2503 case TU_UPDATE_LEXICAL: {
2504 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002505 LexicalContents Contents(
2506 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2507 Blob.data()),
2508 static_cast<unsigned int>(Blob.size() / 4));
2509 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002510 TU->setHasExternalLexicalStorage(true);
2511 break;
2512 }
2513
2514 case UPDATE_VISIBLE: {
2515 unsigned Idx = 0;
2516 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002517 auto *Data = (const unsigned char*)Blob.data();
2518 unsigned BucketOffset = Record[Idx++];
2519 PendingVisibleUpdates[ID].push_back(
2520 PendingVisibleUpdate{&F, Data, BucketOffset});
2521 // If we've already loaded the decl, perform the updates when we finish
2522 // loading this block.
2523 if (Decl *D = GetExistingDecl(ID))
2524 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 break;
2526 }
2527
2528 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002529 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002530 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002531 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2532 (const unsigned char *)F.IdentifierTableData + Record[0],
2533 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2534 (const unsigned char *)F.IdentifierTableData,
2535 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002536
2537 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2538 }
2539 break;
2540
2541 case IDENTIFIER_OFFSET: {
2542 if (F.LocalNumIdentifiers != 0) {
2543 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002544 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002545 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002546 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 F.LocalNumIdentifiers = Record[0];
2548 unsigned LocalBaseIdentifierID = Record[1];
2549 F.BaseIdentifierID = getTotalNumIdentifiers();
2550
2551 if (F.LocalNumIdentifiers > 0) {
2552 // Introduce the global -> local mapping for identifiers within this
2553 // module.
2554 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2555 &F));
2556
2557 // Introduce the local -> global mapping for identifiers within this
2558 // module.
2559 F.IdentifierRemap.insertOrReplace(
2560 std::make_pair(LocalBaseIdentifierID,
2561 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002562
Ben Langmuir52ca6782014-10-20 16:27:32 +00002563 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2564 + F.LocalNumIdentifiers);
2565 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 break;
2567 }
2568
Richard Smith33e0f7e2015-07-22 02:08:40 +00002569 case INTERESTING_IDENTIFIERS:
2570 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2571 break;
2572
Ben Langmuir332aafe2014-01-31 01:06:56 +00002573 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002574 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2575 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002577 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 break;
2579
2580 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002581 if (SpecialTypes.empty()) {
2582 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2583 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2584 break;
2585 }
2586
2587 if (SpecialTypes.size() != Record.size()) {
2588 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002589 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002590 }
2591
2592 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2593 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2594 if (!SpecialTypes[I])
2595 SpecialTypes[I] = ID;
2596 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2597 // merge step?
2598 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 break;
2600
2601 case STATISTICS:
2602 TotalNumStatements += Record[0];
2603 TotalNumMacros += Record[1];
2604 TotalLexicalDeclContexts += Record[2];
2605 TotalVisibleDeclContexts += Record[3];
2606 break;
2607
2608 case UNUSED_FILESCOPED_DECLS:
2609 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2610 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2611 break;
2612
2613 case DELEGATING_CTORS:
2614 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2615 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2616 break;
2617
2618 case WEAK_UNDECLARED_IDENTIFIERS:
2619 if (Record.size() % 4 != 0) {
2620 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002621 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 }
2623
2624 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2625 // files. This isn't the way to do it :)
2626 WeakUndeclaredIdentifiers.clear();
2627
2628 // Translate the weak, undeclared identifiers into global IDs.
2629 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2630 WeakUndeclaredIdentifiers.push_back(
2631 getGlobalIdentifierID(F, Record[I++]));
2632 WeakUndeclaredIdentifiers.push_back(
2633 getGlobalIdentifierID(F, Record[I++]));
2634 WeakUndeclaredIdentifiers.push_back(
2635 ReadSourceLocation(F, Record, I).getRawEncoding());
2636 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2637 }
2638 break;
2639
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002641 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 F.LocalNumSelectors = Record[0];
2643 unsigned LocalBaseSelectorID = Record[1];
2644 F.BaseSelectorID = getTotalNumSelectors();
2645
2646 if (F.LocalNumSelectors > 0) {
2647 // Introduce the global -> local mapping for selectors within this
2648 // module.
2649 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2650
2651 // Introduce the local -> global mapping for selectors within this
2652 // module.
2653 F.SelectorRemap.insertOrReplace(
2654 std::make_pair(LocalBaseSelectorID,
2655 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002656
2657 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002658 }
2659 break;
2660 }
2661
2662 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002663 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002664 if (Record[0])
2665 F.SelectorLookupTable
2666 = ASTSelectorLookupTable::Create(
2667 F.SelectorLookupTableData + Record[0],
2668 F.SelectorLookupTableData,
2669 ASTSelectorLookupTrait(*this, F));
2670 TotalNumMethodPoolEntries += Record[1];
2671 break;
2672
2673 case REFERENCED_SELECTOR_POOL:
2674 if (!Record.empty()) {
2675 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2676 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2677 Record[Idx++]));
2678 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2679 getRawEncoding());
2680 }
2681 }
2682 break;
2683
2684 case PP_COUNTER_VALUE:
2685 if (!Record.empty() && Listener)
2686 Listener->ReadCounter(F, Record[0]);
2687 break;
2688
2689 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002690 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 F.NumFileSortedDecls = Record[0];
2692 break;
2693
2694 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002695 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 F.LocalNumSLocEntries = Record[0];
2697 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002698 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002699 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002700 SLocSpaceSize);
2701 // Make our entry in the range map. BaseID is negative and growing, so
2702 // we invert it. Because we invert it, though, we need the other end of
2703 // the range.
2704 unsigned RangeStart =
2705 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2706 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2707 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2708
2709 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2710 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2711 GlobalSLocOffsetMap.insert(
2712 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2713 - SLocSpaceSize,&F));
2714
2715 // Initialize the remapping table.
2716 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002717 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002718 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002719 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002720 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2721
2722 TotalNumSLocEntries += F.LocalNumSLocEntries;
2723 break;
2724 }
2725
2726 case MODULE_OFFSET_MAP: {
2727 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002728 const unsigned char *Data = (const unsigned char*)Blob.data();
2729 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002730
2731 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2732 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2733 F.SLocRemap.insert(std::make_pair(0U, 0));
2734 F.SLocRemap.insert(std::make_pair(2U, 1));
2735 }
2736
Guy Benyei11169dd2012-12-18 14:30:41 +00002737 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002738 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2739 RemapBuilder;
2740 RemapBuilder SLocRemap(F.SLocRemap);
2741 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2742 RemapBuilder MacroRemap(F.MacroRemap);
2743 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2744 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2745 RemapBuilder SelectorRemap(F.SelectorRemap);
2746 RemapBuilder DeclRemap(F.DeclRemap);
2747 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002748
2749 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002750 using namespace llvm::support;
2751 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002752 StringRef Name = StringRef((const char*)Data, Len);
2753 Data += Len;
2754 ModuleFile *OM = ModuleMgr.lookup(Name);
2755 if (!OM) {
2756 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002757 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 }
2759
Justin Bogner57ba0b22014-03-28 22:03:24 +00002760 uint32_t SLocOffset =
2761 endian::readNext<uint32_t, little, unaligned>(Data);
2762 uint32_t IdentifierIDOffset =
2763 endian::readNext<uint32_t, little, unaligned>(Data);
2764 uint32_t MacroIDOffset =
2765 endian::readNext<uint32_t, little, unaligned>(Data);
2766 uint32_t PreprocessedEntityIDOffset =
2767 endian::readNext<uint32_t, little, unaligned>(Data);
2768 uint32_t SubmoduleIDOffset =
2769 endian::readNext<uint32_t, little, unaligned>(Data);
2770 uint32_t SelectorIDOffset =
2771 endian::readNext<uint32_t, little, unaligned>(Data);
2772 uint32_t DeclIDOffset =
2773 endian::readNext<uint32_t, little, unaligned>(Data);
2774 uint32_t TypeIndexOffset =
2775 endian::readNext<uint32_t, little, unaligned>(Data);
2776
Ben Langmuir785180e2014-10-20 16:27:30 +00002777 uint32_t None = std::numeric_limits<uint32_t>::max();
2778
2779 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2780 RemapBuilder &Remap) {
2781 if (Offset != None)
2782 Remap.insert(std::make_pair(Offset,
2783 static_cast<int>(BaseOffset - Offset)));
2784 };
2785 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2786 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2787 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2788 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2789 PreprocessedEntityRemap);
2790 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2791 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2792 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2793 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002794
2795 // Global -> local mappings.
2796 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2797 }
2798 break;
2799 }
2800
2801 case SOURCE_MANAGER_LINE_TABLE:
2802 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002803 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002804 break;
2805
2806 case SOURCE_LOCATION_PRELOADS: {
2807 // Need to transform from the local view (1-based IDs) to the global view,
2808 // which is based off F.SLocEntryBaseID.
2809 if (!F.PreloadSLocEntries.empty()) {
2810 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002811 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002812 }
2813
2814 F.PreloadSLocEntries.swap(Record);
2815 break;
2816 }
2817
2818 case EXT_VECTOR_DECLS:
2819 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2820 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2821 break;
2822
2823 case VTABLE_USES:
2824 if (Record.size() % 3 != 0) {
2825 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002826 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002827 }
2828
2829 // Later tables overwrite earlier ones.
2830 // FIXME: Modules will have some trouble with this. This is clearly not
2831 // the right way to do this.
2832 VTableUses.clear();
2833
2834 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2835 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2836 VTableUses.push_back(
2837 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2838 VTableUses.push_back(Record[Idx++]);
2839 }
2840 break;
2841
Guy Benyei11169dd2012-12-18 14:30:41 +00002842 case PENDING_IMPLICIT_INSTANTIATIONS:
2843 if (PendingInstantiations.size() % 2 != 0) {
2844 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002845 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002846 }
2847
2848 if (Record.size() % 2 != 0) {
2849 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002850 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002851 }
2852
2853 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2854 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2855 PendingInstantiations.push_back(
2856 ReadSourceLocation(F, Record, I).getRawEncoding());
2857 }
2858 break;
2859
2860 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002861 if (Record.size() != 2) {
2862 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002863 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002864 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002865 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2866 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2867 break;
2868
2869 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002870 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2871 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2872 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002873
2874 unsigned LocalBasePreprocessedEntityID = Record[0];
2875
2876 unsigned StartingID;
2877 if (!PP.getPreprocessingRecord())
2878 PP.createPreprocessingRecord();
2879 if (!PP.getPreprocessingRecord()->getExternalSource())
2880 PP.getPreprocessingRecord()->SetExternalSource(*this);
2881 StartingID
2882 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002883 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002884 F.BasePreprocessedEntityID = StartingID;
2885
2886 if (F.NumPreprocessedEntities > 0) {
2887 // Introduce the global -> local mapping for preprocessed entities in
2888 // this module.
2889 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2890
2891 // Introduce the local -> global mapping for preprocessed entities in
2892 // this module.
2893 F.PreprocessedEntityRemap.insertOrReplace(
2894 std::make_pair(LocalBasePreprocessedEntityID,
2895 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2896 }
2897
2898 break;
2899 }
2900
2901 case DECL_UPDATE_OFFSETS: {
2902 if (Record.size() % 2 != 0) {
2903 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002904 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002905 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002906 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2907 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2908 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2909
2910 // If we've already loaded the decl, perform the updates when we finish
2911 // loading this block.
2912 if (Decl *D = GetExistingDecl(ID))
2913 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2914 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002915 break;
2916 }
2917
2918 case DECL_REPLACEMENTS: {
2919 if (Record.size() % 3 != 0) {
2920 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002921 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002922 }
2923 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2924 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2925 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2926 break;
2927 }
2928
2929 case OBJC_CATEGORIES_MAP: {
2930 if (F.LocalNumObjCCategoriesInMap != 0) {
2931 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002932 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 }
2934
2935 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002936 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002937 break;
2938 }
2939
2940 case OBJC_CATEGORIES:
2941 F.ObjCCategories.swap(Record);
2942 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00002943
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 case CXX_BASE_SPECIFIER_OFFSETS: {
2945 if (F.LocalNumCXXBaseSpecifiers != 0) {
2946 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002947 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002948 }
Richard Smithc2bb8182015-03-24 06:36:48 +00002949
Guy Benyei11169dd2012-12-18 14:30:41 +00002950 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002951 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00002952 break;
2953 }
2954
2955 case CXX_CTOR_INITIALIZERS_OFFSETS: {
2956 if (F.LocalNumCXXCtorInitializers != 0) {
2957 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2958 return Failure;
2959 }
2960
2961 F.LocalNumCXXCtorInitializers = Record[0];
2962 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002963 break;
2964 }
2965
2966 case DIAG_PRAGMA_MAPPINGS:
2967 if (F.PragmaDiagMappings.empty())
2968 F.PragmaDiagMappings.swap(Record);
2969 else
2970 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2971 Record.begin(), Record.end());
2972 break;
2973
2974 case CUDA_SPECIAL_DECL_REFS:
2975 // Later tables overwrite earlier ones.
2976 // FIXME: Modules will have trouble with this.
2977 CUDASpecialDeclRefs.clear();
2978 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2979 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2980 break;
2981
2982 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002983 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002984 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002985 if (Record[0]) {
2986 F.HeaderFileInfoTable
2987 = HeaderFileInfoLookupTable::Create(
2988 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2989 (const unsigned char *)F.HeaderFileInfoTableData,
2990 HeaderFileInfoTrait(*this, F,
2991 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002992 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002993
2994 PP.getHeaderSearchInfo().SetExternalSource(this);
2995 if (!PP.getHeaderSearchInfo().getExternalLookup())
2996 PP.getHeaderSearchInfo().SetExternalLookup(this);
2997 }
2998 break;
2999 }
3000
3001 case FP_PRAGMA_OPTIONS:
3002 // Later tables overwrite earlier ones.
3003 FPPragmaOptions.swap(Record);
3004 break;
3005
3006 case OPENCL_EXTENSIONS:
3007 // Later tables overwrite earlier ones.
3008 OpenCLExtensions.swap(Record);
3009 break;
3010
3011 case TENTATIVE_DEFINITIONS:
3012 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3013 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3014 break;
3015
3016 case KNOWN_NAMESPACES:
3017 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3018 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3019 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003020
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003021 case UNDEFINED_BUT_USED:
3022 if (UndefinedButUsed.size() % 2 != 0) {
3023 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003024 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003025 }
3026
3027 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003028 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003029 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003030 }
3031 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003032 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3033 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003034 ReadSourceLocation(F, Record, I).getRawEncoding());
3035 }
3036 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003037 case DELETE_EXPRS_TO_ANALYZE:
3038 for (unsigned I = 0, N = Record.size(); I != N;) {
3039 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3040 const uint64_t Count = Record[I++];
3041 DelayedDeleteExprs.push_back(Count);
3042 for (uint64_t C = 0; C < Count; ++C) {
3043 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3044 bool IsArrayForm = Record[I++] == 1;
3045 DelayedDeleteExprs.push_back(IsArrayForm);
3046 }
3047 }
3048 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003049
Guy Benyei11169dd2012-12-18 14:30:41 +00003050 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003051 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003052 // If we aren't loading a module (which has its own exports), make
3053 // all of the imported modules visible.
3054 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003055 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3056 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3057 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3058 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003059 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003060 }
3061 }
3062 break;
3063 }
3064
3065 case LOCAL_REDECLARATIONS: {
3066 F.RedeclarationChains.swap(Record);
3067 break;
3068 }
3069
3070 case LOCAL_REDECLARATIONS_MAP: {
3071 if (F.LocalNumRedeclarationsInMap != 0) {
3072 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003073 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003074 }
3075
3076 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003077 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003078 break;
3079 }
3080
Guy Benyei11169dd2012-12-18 14:30:41 +00003081 case MACRO_OFFSET: {
3082 if (F.LocalNumMacros != 0) {
3083 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003084 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003085 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003086 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003087 F.LocalNumMacros = Record[0];
3088 unsigned LocalBaseMacroID = Record[1];
3089 F.BaseMacroID = getTotalNumMacros();
3090
3091 if (F.LocalNumMacros > 0) {
3092 // Introduce the global -> local mapping for macros within this module.
3093 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3094
3095 // Introduce the local -> global mapping for macros within this module.
3096 F.MacroRemap.insertOrReplace(
3097 std::make_pair(LocalBaseMacroID,
3098 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003099
3100 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003101 }
3102 break;
3103 }
3104
Richard Smithe40f2ba2013-08-07 21:41:30 +00003105 case LATE_PARSED_TEMPLATE: {
3106 LateParsedTemplates.append(Record.begin(), Record.end());
3107 break;
3108 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003109
3110 case OPTIMIZE_PRAGMA_OPTIONS:
3111 if (Record.size() != 1) {
3112 Error("invalid pragma optimize record");
3113 return Failure;
3114 }
3115 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3116 break;
Nico Weber72889432014-09-06 01:25:55 +00003117
3118 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3119 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3120 UnusedLocalTypedefNameCandidates.push_back(
3121 getGlobalDeclID(F, Record[I]));
3122 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003123 }
3124 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003125}
3126
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003127ASTReader::ASTReadResult
3128ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3129 const ModuleFile *ImportedBy,
3130 unsigned ClientLoadCapabilities) {
3131 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003132 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003133
Richard Smithe842a472014-10-22 02:05:46 +00003134 if (F.Kind == MK_ExplicitModule) {
3135 // For an explicitly-loaded module, we don't care whether the original
3136 // module map file exists or matches.
3137 return Success;
3138 }
3139
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003140 // Try to resolve ModuleName in the current header search context and
3141 // verify that it is found in the same module map file as we saved. If the
3142 // top-level AST file is a main file, skip this check because there is no
3143 // usable header search context.
3144 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003145 "MODULE_NAME should come before MODULE_MAP_FILE");
3146 if (F.Kind == MK_ImplicitModule &&
3147 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3148 // An implicitly-loaded module file should have its module listed in some
3149 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003150 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003151 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3152 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3153 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003154 assert(ImportedBy && "top-level import should be verified");
3155 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003156 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3157 << ImportedBy->FileName
3158 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003159 return Missing;
3160 }
3161
Richard Smithe842a472014-10-22 02:05:46 +00003162 assert(M->Name == F.ModuleName && "found module with different name");
3163
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003164 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003165 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003166 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3167 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003168 assert(ImportedBy && "top-level import should be verified");
3169 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3170 Diag(diag::err_imported_module_modmap_changed)
3171 << F.ModuleName << ImportedBy->FileName
3172 << ModMap->getName() << F.ModuleMapPath;
3173 return OutOfDate;
3174 }
3175
3176 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3177 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3178 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003179 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003180 const FileEntry *F =
3181 FileMgr.getFile(Filename, false, false);
3182 if (F == nullptr) {
3183 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3184 Error("could not find file '" + Filename +"' referenced by AST file");
3185 return OutOfDate;
3186 }
3187 AdditionalStoredMaps.insert(F);
3188 }
3189
3190 // Check any additional module map files (e.g. module.private.modulemap)
3191 // that are not in the pcm.
3192 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3193 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3194 // Remove files that match
3195 // Note: SmallPtrSet::erase is really remove
3196 if (!AdditionalStoredMaps.erase(ModMap)) {
3197 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3198 Diag(diag::err_module_different_modmap)
3199 << F.ModuleName << /*new*/0 << ModMap->getName();
3200 return OutOfDate;
3201 }
3202 }
3203 }
3204
3205 // Check any additional module map files that are in the pcm, but not
3206 // found in header search. Cases that match are already removed.
3207 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3208 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3209 Diag(diag::err_module_different_modmap)
3210 << F.ModuleName << /*not new*/1 << ModMap->getName();
3211 return OutOfDate;
3212 }
3213 }
3214
3215 if (Listener)
3216 Listener->ReadModuleMapFile(F.ModuleMapPath);
3217 return Success;
3218}
3219
3220
Douglas Gregorc1489562013-02-12 23:36:21 +00003221/// \brief Move the given method to the back of the global list of methods.
3222static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3223 // Find the entry for this selector in the method pool.
3224 Sema::GlobalMethodPool::iterator Known
3225 = S.MethodPool.find(Method->getSelector());
3226 if (Known == S.MethodPool.end())
3227 return;
3228
3229 // Retrieve the appropriate method list.
3230 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3231 : Known->second.second;
3232 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003233 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003234 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003235 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003236 Found = true;
3237 } else {
3238 // Keep searching.
3239 continue;
3240 }
3241 }
3242
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003243 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003244 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003245 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003246 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003247 }
3248}
3249
Richard Smithde711422015-04-23 21:20:19 +00003250void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003251 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003252 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003253 bool wasHidden = D->Hidden;
3254 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003255
Richard Smith49f906a2014-03-01 00:08:04 +00003256 if (wasHidden && SemaObj) {
3257 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3258 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003259 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003260 }
3261 }
3262}
3263
Richard Smith49f906a2014-03-01 00:08:04 +00003264void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003265 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003266 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003267 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003268 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003269 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003270 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003271 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003272
3273 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003274 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003275 // there is nothing more to do.
3276 continue;
3277 }
Richard Smith49f906a2014-03-01 00:08:04 +00003278
Guy Benyei11169dd2012-12-18 14:30:41 +00003279 if (!Mod->isAvailable()) {
3280 // Modules that aren't available cannot be made visible.
3281 continue;
3282 }
3283
3284 // Update the module's name visibility.
3285 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003286
Guy Benyei11169dd2012-12-18 14:30:41 +00003287 // If we've already deserialized any names from this module,
3288 // mark them as visible.
3289 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3290 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003291 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003292 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003293 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003294 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3295 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003296 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003297
Guy Benyei11169dd2012-12-18 14:30:41 +00003298 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003299 SmallVector<Module *, 16> Exports;
3300 Mod->getExportedModules(Exports);
3301 for (SmallVectorImpl<Module *>::iterator
3302 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3303 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003304 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003305 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003306 }
3307 }
3308}
3309
Douglas Gregore060e572013-01-25 01:03:03 +00003310bool ASTReader::loadGlobalIndex() {
3311 if (GlobalIndex)
3312 return false;
3313
3314 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3315 !Context.getLangOpts().Modules)
3316 return true;
3317
3318 // Try to load the global index.
3319 TriedLoadingGlobalIndex = true;
3320 StringRef ModuleCachePath
3321 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3322 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003323 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003324 if (!Result.first)
3325 return true;
3326
3327 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003328 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003329 return false;
3330}
3331
3332bool ASTReader::isGlobalIndexUnavailable() const {
3333 return Context.getLangOpts().Modules && UseGlobalIndex &&
3334 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3335}
3336
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003337static void updateModuleTimestamp(ModuleFile &MF) {
3338 // Overwrite the timestamp file contents so that file's mtime changes.
3339 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003340 std::error_code EC;
3341 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3342 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003343 return;
3344 OS << "Timestamp file\n";
3345}
3346
Guy Benyei11169dd2012-12-18 14:30:41 +00003347ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3348 ModuleKind Type,
3349 SourceLocation ImportLoc,
3350 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003351 llvm::SaveAndRestore<SourceLocation>
3352 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3353
Richard Smithd1c46742014-04-30 02:24:17 +00003354 // Defer any pending actions until we get to the end of reading the AST file.
3355 Deserializing AnASTFile(this);
3356
Guy Benyei11169dd2012-12-18 14:30:41 +00003357 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003358 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003359
3360 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003361 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003362 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003363 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003364 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003365 ClientLoadCapabilities)) {
3366 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003367 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003368 case OutOfDate:
3369 case VersionMismatch:
3370 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003371 case HadErrors: {
3372 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3373 for (const ImportedModule &IM : Loaded)
3374 LoadedSet.insert(IM.Mod);
3375
Douglas Gregor7029ce12013-03-19 00:28:20 +00003376 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003377 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003378 Context.getLangOpts().Modules
3379 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003380 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003381
3382 // If we find that any modules are unusable, the global index is going
3383 // to be out-of-date. Just remove it.
3384 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003385 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003386 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003387 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003388 case Success:
3389 break;
3390 }
3391
3392 // Here comes stuff that we only do once the entire chain is loaded.
3393
3394 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003395 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3396 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003397 M != MEnd; ++M) {
3398 ModuleFile &F = *M->Mod;
3399
3400 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003401 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3402 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003403
3404 // Once read, set the ModuleFile bit base offset and update the size in
3405 // bits of all files we've seen.
3406 F.GlobalBitOffset = TotalModulesSizeInBits;
3407 TotalModulesSizeInBits += F.SizeInBits;
3408 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3409
3410 // Preload SLocEntries.
3411 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3412 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3413 // Load it through the SourceManager and don't call ReadSLocEntry()
3414 // directly because the entry may have already been loaded in which case
3415 // calling ReadSLocEntry() directly would trigger an assertion in
3416 // SourceManager.
3417 SourceMgr.getLoadedSLocEntryByID(Index);
3418 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003419
3420 // Preload all the pending interesting identifiers by marking them out of
3421 // date.
3422 for (auto Offset : F.PreloadIdentifierOffsets) {
3423 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3424 F.IdentifierTableData + Offset);
3425
3426 ASTIdentifierLookupTrait Trait(*this, F);
3427 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3428 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3429 PP.getIdentifierTable().getOwn(Key).setOutOfDate(true);
3430 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003431 }
3432
Douglas Gregor603cd862013-03-22 18:50:14 +00003433 // Setup the import locations and notify the module manager that we've
3434 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003435 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3436 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003437 M != MEnd; ++M) {
3438 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003439
3440 ModuleMgr.moduleFileAccepted(&F);
3441
3442 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003443 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003444 if (!M->ImportedBy)
3445 F.ImportLoc = M->ImportLoc;
3446 else
3447 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3448 M->ImportLoc.getRawEncoding());
3449 }
3450
Richard Smith33e0f7e2015-07-22 02:08:40 +00003451 if (!Context.getLangOpts().CPlusPlus ||
3452 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3453 // Mark all of the identifiers in the identifier table as being out of date,
3454 // so that various accessors know to check the loaded modules when the
3455 // identifier is used.
3456 //
3457 // For C++ modules, we don't need information on many identifiers (just
3458 // those that provide macros or are poisoned), so we mark all of
3459 // the interesting ones via PreloadIdentifierOffsets.
3460 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3461 IdEnd = PP.getIdentifierTable().end();
3462 Id != IdEnd; ++Id)
3463 Id->second->setOutOfDate(true);
3464 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003465
3466 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003467 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3468 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003469 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3470 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003471
3472 switch (Unresolved.Kind) {
3473 case UnresolvedModuleRef::Conflict:
3474 if (ResolvedMod) {
3475 Module::Conflict Conflict;
3476 Conflict.Other = ResolvedMod;
3477 Conflict.Message = Unresolved.String.str();
3478 Unresolved.Mod->Conflicts.push_back(Conflict);
3479 }
3480 continue;
3481
3482 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003483 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003484 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003485 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003486
Douglas Gregorfb912652013-03-20 21:10:35 +00003487 case UnresolvedModuleRef::Export:
3488 if (ResolvedMod || Unresolved.IsWildcard)
3489 Unresolved.Mod->Exports.push_back(
3490 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3491 continue;
3492 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003493 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003494 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003495
3496 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3497 // Might be unnecessary as use declarations are only used to build the
3498 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003499
3500 InitializeContext();
3501
Richard Smith3d8e97e2013-10-18 06:54:39 +00003502 if (SemaObj)
3503 UpdateSema();
3504
Guy Benyei11169dd2012-12-18 14:30:41 +00003505 if (DeserializationListener)
3506 DeserializationListener->ReaderInitialized(this);
3507
3508 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3509 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3510 PrimaryModule.OriginalSourceFileID
3511 = FileID::get(PrimaryModule.SLocEntryBaseID
3512 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3513
3514 // If this AST file is a precompiled preamble, then set the
3515 // preamble file ID of the source manager to the file source file
3516 // from which the preamble was built.
3517 if (Type == MK_Preamble) {
3518 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3519 } else if (Type == MK_MainFile) {
3520 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3521 }
3522 }
3523
3524 // For any Objective-C class definitions we have already loaded, make sure
3525 // that we load any additional categories.
3526 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3527 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3528 ObjCClassesLoaded[I],
3529 PreviousGeneration);
3530 }
Douglas Gregore060e572013-01-25 01:03:03 +00003531
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003532 if (PP.getHeaderSearchInfo()
3533 .getHeaderSearchOpts()
3534 .ModulesValidateOncePerBuildSession) {
3535 // Now we are certain that the module and all modules it depends on are
3536 // up to date. Create or update timestamp files for modules that are
3537 // located in the module cache (not for PCH files that could be anywhere
3538 // in the filesystem).
3539 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3540 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003541 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003542 updateModuleTimestamp(*M.Mod);
3543 }
3544 }
3545 }
3546
Guy Benyei11169dd2012-12-18 14:30:41 +00003547 return Success;
3548}
3549
Ben Langmuir487ea142014-10-23 18:05:36 +00003550static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3551
Ben Langmuir70a1b812015-03-24 04:43:52 +00003552/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3553static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3554 return Stream.Read(8) == 'C' &&
3555 Stream.Read(8) == 'P' &&
3556 Stream.Read(8) == 'C' &&
3557 Stream.Read(8) == 'H';
3558}
3559
Guy Benyei11169dd2012-12-18 14:30:41 +00003560ASTReader::ASTReadResult
3561ASTReader::ReadASTCore(StringRef FileName,
3562 ModuleKind Type,
3563 SourceLocation ImportLoc,
3564 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003565 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003566 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003567 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003568 unsigned ClientLoadCapabilities) {
3569 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003570 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003571 ModuleManager::AddModuleResult AddResult
3572 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003573 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003574 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003575 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003576
Douglas Gregor7029ce12013-03-19 00:28:20 +00003577 switch (AddResult) {
3578 case ModuleManager::AlreadyLoaded:
3579 return Success;
3580
3581 case ModuleManager::NewlyLoaded:
3582 // Load module file below.
3583 break;
3584
3585 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003586 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003587 // it.
3588 if (ClientLoadCapabilities & ARR_Missing)
3589 return Missing;
3590
3591 // Otherwise, return an error.
3592 {
3593 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3594 + ErrorStr;
3595 Error(Msg);
3596 }
3597 return Failure;
3598
3599 case ModuleManager::OutOfDate:
3600 // We couldn't load the module file because it is out-of-date. If the
3601 // client can handle out-of-date, return it.
3602 if (ClientLoadCapabilities & ARR_OutOfDate)
3603 return OutOfDate;
3604
3605 // Otherwise, return an error.
3606 {
3607 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3608 + ErrorStr;
3609 Error(Msg);
3610 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003611 return Failure;
3612 }
3613
Douglas Gregor7029ce12013-03-19 00:28:20 +00003614 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003615
3616 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3617 // module?
3618 if (FileName != "-") {
3619 CurrentDir = llvm::sys::path::parent_path(FileName);
3620 if (CurrentDir.empty()) CurrentDir = ".";
3621 }
3622
3623 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003624 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003625 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003626 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003627 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3628
Guy Benyei11169dd2012-12-18 14:30:41 +00003629 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003630 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003631 Diag(diag::err_not_a_pch_file) << FileName;
3632 return Failure;
3633 }
3634
3635 // This is used for compatibility with older PCH formats.
3636 bool HaveReadControlBlock = false;
3637
Chris Lattnerefa77172013-01-20 00:00:22 +00003638 while (1) {
3639 llvm::BitstreamEntry Entry = Stream.advance();
3640
3641 switch (Entry.Kind) {
3642 case llvm::BitstreamEntry::Error:
3643 case llvm::BitstreamEntry::EndBlock:
3644 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003645 Error("invalid record at top-level of AST file");
3646 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003647
3648 case llvm::BitstreamEntry::SubBlock:
3649 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003650 }
3651
Guy Benyei11169dd2012-12-18 14:30:41 +00003652 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003653 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003654 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3655 if (Stream.ReadBlockInfoBlock()) {
3656 Error("malformed BlockInfoBlock in AST file");
3657 return Failure;
3658 }
3659 break;
3660 case CONTROL_BLOCK_ID:
3661 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003662 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003663 case Success:
3664 break;
3665
3666 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003667 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003668 case OutOfDate: return OutOfDate;
3669 case VersionMismatch: return VersionMismatch;
3670 case ConfigurationMismatch: return ConfigurationMismatch;
3671 case HadErrors: return HadErrors;
3672 }
3673 break;
3674 case AST_BLOCK_ID:
3675 if (!HaveReadControlBlock) {
3676 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003677 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003678 return VersionMismatch;
3679 }
3680
3681 // Record that we've loaded this module.
3682 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3683 return Success;
3684
3685 default:
3686 if (Stream.SkipBlock()) {
3687 Error("malformed block record in AST file");
3688 return Failure;
3689 }
3690 break;
3691 }
3692 }
3693
3694 return Success;
3695}
3696
Richard Smitha7e2cc62015-05-01 01:53:09 +00003697void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003698 // If there's a listener, notify them that we "read" the translation unit.
3699 if (DeserializationListener)
3700 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3701 Context.getTranslationUnitDecl());
3702
Guy Benyei11169dd2012-12-18 14:30:41 +00003703 // FIXME: Find a better way to deal with collisions between these
3704 // built-in types. Right now, we just ignore the problem.
3705
3706 // Load the special types.
3707 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3708 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3709 if (!Context.CFConstantStringTypeDecl)
3710 Context.setCFConstantStringType(GetType(String));
3711 }
3712
3713 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3714 QualType FileType = GetType(File);
3715 if (FileType.isNull()) {
3716 Error("FILE type is NULL");
3717 return;
3718 }
3719
3720 if (!Context.FILEDecl) {
3721 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3722 Context.setFILEDecl(Typedef->getDecl());
3723 else {
3724 const TagType *Tag = FileType->getAs<TagType>();
3725 if (!Tag) {
3726 Error("Invalid FILE type in AST file");
3727 return;
3728 }
3729 Context.setFILEDecl(Tag->getDecl());
3730 }
3731 }
3732 }
3733
3734 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3735 QualType Jmp_bufType = GetType(Jmp_buf);
3736 if (Jmp_bufType.isNull()) {
3737 Error("jmp_buf type is NULL");
3738 return;
3739 }
3740
3741 if (!Context.jmp_bufDecl) {
3742 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3743 Context.setjmp_bufDecl(Typedef->getDecl());
3744 else {
3745 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3746 if (!Tag) {
3747 Error("Invalid jmp_buf type in AST file");
3748 return;
3749 }
3750 Context.setjmp_bufDecl(Tag->getDecl());
3751 }
3752 }
3753 }
3754
3755 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3756 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3757 if (Sigjmp_bufType.isNull()) {
3758 Error("sigjmp_buf type is NULL");
3759 return;
3760 }
3761
3762 if (!Context.sigjmp_bufDecl) {
3763 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3764 Context.setsigjmp_bufDecl(Typedef->getDecl());
3765 else {
3766 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3767 assert(Tag && "Invalid sigjmp_buf type in AST file");
3768 Context.setsigjmp_bufDecl(Tag->getDecl());
3769 }
3770 }
3771 }
3772
3773 if (unsigned ObjCIdRedef
3774 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3775 if (Context.ObjCIdRedefinitionType.isNull())
3776 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3777 }
3778
3779 if (unsigned ObjCClassRedef
3780 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3781 if (Context.ObjCClassRedefinitionType.isNull())
3782 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3783 }
3784
3785 if (unsigned ObjCSelRedef
3786 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3787 if (Context.ObjCSelRedefinitionType.isNull())
3788 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3789 }
3790
3791 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3792 QualType Ucontext_tType = GetType(Ucontext_t);
3793 if (Ucontext_tType.isNull()) {
3794 Error("ucontext_t type is NULL");
3795 return;
3796 }
3797
3798 if (!Context.ucontext_tDecl) {
3799 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3800 Context.setucontext_tDecl(Typedef->getDecl());
3801 else {
3802 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3803 assert(Tag && "Invalid ucontext_t type in AST file");
3804 Context.setucontext_tDecl(Tag->getDecl());
3805 }
3806 }
3807 }
3808 }
3809
3810 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3811
3812 // If there were any CUDA special declarations, deserialize them.
3813 if (!CUDASpecialDeclRefs.empty()) {
3814 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3815 Context.setcudaConfigureCallDecl(
3816 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3817 }
Richard Smith56be7542014-03-21 00:33:59 +00003818
Guy Benyei11169dd2012-12-18 14:30:41 +00003819 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003820 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003821 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003822 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003823 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003824 /*ImportLoc=*/Import.ImportLoc);
3825 PP.makeModuleVisible(Imported, Import.ImportLoc);
3826 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003827 }
3828 ImportedModules.clear();
3829}
3830
3831void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003832 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003833}
3834
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003835/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3836/// cursor into the start of the given block ID, returning false on success and
3837/// true on failure.
3838static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003839 while (1) {
3840 llvm::BitstreamEntry Entry = Cursor.advance();
3841 switch (Entry.Kind) {
3842 case llvm::BitstreamEntry::Error:
3843 case llvm::BitstreamEntry::EndBlock:
3844 return true;
3845
3846 case llvm::BitstreamEntry::Record:
3847 // Ignore top-level records.
3848 Cursor.skipRecord(Entry.ID);
3849 break;
3850
3851 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003852 if (Entry.ID == BlockID) {
3853 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003854 return true;
3855 // Found it!
3856 return false;
3857 }
3858
3859 if (Cursor.SkipBlock())
3860 return true;
3861 }
3862 }
3863}
3864
Ben Langmuir70a1b812015-03-24 04:43:52 +00003865/// \brief Reads and return the signature record from \p StreamFile's control
3866/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003867static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3868 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003869 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003870 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003871
3872 // Scan for the CONTROL_BLOCK_ID block.
3873 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3874 return 0;
3875
3876 // Scan for SIGNATURE inside the control block.
3877 ASTReader::RecordData Record;
3878 while (1) {
3879 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3880 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3881 Entry.Kind != llvm::BitstreamEntry::Record)
3882 return 0;
3883
3884 Record.clear();
3885 StringRef Blob;
3886 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3887 return Record[0];
3888 }
3889}
3890
Guy Benyei11169dd2012-12-18 14:30:41 +00003891/// \brief Retrieve the name of the original source file name
3892/// directly from the AST file, without actually loading the AST
3893/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003894std::string ASTReader::getOriginalSourceFile(
3895 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003896 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003897 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00003898 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00003899 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00003900 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3901 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00003902 return std::string();
3903 }
3904
3905 // Initialize the stream
3906 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003907 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003908 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003909
3910 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003911 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003912 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3913 return std::string();
3914 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003915
Chris Lattnere7b154b2013-01-19 21:39:22 +00003916 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003917 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003918 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3919 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003920 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003921
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003922 // Scan for ORIGINAL_FILE inside the control block.
3923 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003924 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003925 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003926 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3927 return std::string();
3928
3929 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3930 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3931 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003932 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003933
Guy Benyei11169dd2012-12-18 14:30:41 +00003934 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003935 StringRef Blob;
3936 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3937 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003938 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003939}
3940
3941namespace {
3942 class SimplePCHValidator : public ASTReaderListener {
3943 const LangOptions &ExistingLangOpts;
3944 const TargetOptions &ExistingTargetOpts;
3945 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003946 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00003947 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003948
Guy Benyei11169dd2012-12-18 14:30:41 +00003949 public:
3950 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3951 const TargetOptions &ExistingTargetOpts,
3952 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003953 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00003954 FileManager &FileMgr)
3955 : ExistingLangOpts(ExistingLangOpts),
3956 ExistingTargetOpts(ExistingTargetOpts),
3957 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003958 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00003959 FileMgr(FileMgr)
3960 {
3961 }
3962
Richard Smith1e2cf0d2014-10-31 02:28:58 +00003963 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
3964 bool AllowCompatibleDifferences) override {
3965 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
3966 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003967 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00003968 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
3969 bool AllowCompatibleDifferences) override {
3970 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
3971 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003972 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003973 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
3974 StringRef SpecificModuleCachePath,
3975 bool Complain) override {
3976 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
3977 ExistingModuleCachePath,
3978 nullptr, ExistingLangOpts);
3979 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003980 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3981 bool Complain,
3982 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00003983 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003984 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003985 }
3986 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003987}
Guy Benyei11169dd2012-12-18 14:30:41 +00003988
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003989bool ASTReader::readASTFileControlBlock(
3990 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003991 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003992 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003993 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00003994 // FIXME: This allows use of the VFS; we do not allow use of the
3995 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00003996 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00003997 if (!Buffer) {
3998 return true;
3999 }
4000
4001 // Initialize the stream
4002 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004003 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004004 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004005
4006 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004007 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004008 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004009
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004010 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004011 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004012 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004013
4014 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004015 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004016 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004017 BitstreamCursor InputFilesCursor;
4018 if (NeedsInputFiles) {
4019 InputFilesCursor = Stream;
4020 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4021 return true;
4022
4023 // Read the abbreviations
4024 while (true) {
4025 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4026 unsigned Code = InputFilesCursor.ReadCode();
4027
4028 // We expect all abbrevs to be at the start of the block.
4029 if (Code != llvm::bitc::DEFINE_ABBREV) {
4030 InputFilesCursor.JumpToBit(Offset);
4031 break;
4032 }
4033 InputFilesCursor.ReadAbbrevRecord();
4034 }
4035 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004036
4037 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004038 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004039 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004040 while (1) {
4041 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4042 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4043 return false;
4044
4045 if (Entry.Kind != llvm::BitstreamEntry::Record)
4046 return true;
4047
Guy Benyei11169dd2012-12-18 14:30:41 +00004048 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004049 StringRef Blob;
4050 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004051 switch ((ControlRecordTypes)RecCode) {
4052 case METADATA: {
4053 if (Record[0] != VERSION_MAJOR)
4054 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004055
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004056 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004057 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004058
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004059 break;
4060 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004061 case MODULE_NAME:
4062 Listener.ReadModuleName(Blob);
4063 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004064 case MODULE_DIRECTORY:
4065 ModuleDir = Blob;
4066 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004067 case MODULE_MAP_FILE: {
4068 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004069 auto Path = ReadString(Record, Idx);
4070 ResolveImportedPath(Path, ModuleDir);
4071 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004072 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004073 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004074 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004075 if (ParseLanguageOptions(Record, false, Listener,
4076 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004077 return true;
4078 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004079
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004080 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004081 if (ParseTargetOptions(Record, false, Listener,
4082 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004083 return true;
4084 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004085
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004086 case DIAGNOSTIC_OPTIONS:
4087 if (ParseDiagnosticOptions(Record, false, Listener))
4088 return true;
4089 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004090
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004091 case FILE_SYSTEM_OPTIONS:
4092 if (ParseFileSystemOptions(Record, false, Listener))
4093 return true;
4094 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004095
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004096 case HEADER_SEARCH_OPTIONS:
4097 if (ParseHeaderSearchOptions(Record, false, Listener))
4098 return true;
4099 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004100
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004101 case PREPROCESSOR_OPTIONS: {
4102 std::string IgnoredSuggestedPredefines;
4103 if (ParsePreprocessorOptions(Record, false, Listener,
4104 IgnoredSuggestedPredefines))
4105 return true;
4106 break;
4107 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004108
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004109 case INPUT_FILE_OFFSETS: {
4110 if (!NeedsInputFiles)
4111 break;
4112
4113 unsigned NumInputFiles = Record[0];
4114 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004115 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004116 for (unsigned I = 0; I != NumInputFiles; ++I) {
4117 // Go find this input file.
4118 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004119
4120 if (isSystemFile && !NeedsSystemInputFiles)
4121 break; // the rest are system input files
4122
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004123 BitstreamCursor &Cursor = InputFilesCursor;
4124 SavedStreamPosition SavedPosition(Cursor);
4125 Cursor.JumpToBit(InputFileOffs[I]);
4126
4127 unsigned Code = Cursor.ReadCode();
4128 RecordData Record;
4129 StringRef Blob;
4130 bool shouldContinue = false;
4131 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4132 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004133 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004134 std::string Filename = Blob;
4135 ResolveImportedPath(Filename, ModuleDir);
4136 shouldContinue =
4137 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004138 break;
4139 }
4140 if (!shouldContinue)
4141 break;
4142 }
4143 break;
4144 }
4145
Richard Smithd4b230b2014-10-27 23:01:16 +00004146 case IMPORTS: {
4147 if (!NeedsImports)
4148 break;
4149
4150 unsigned Idx = 0, N = Record.size();
4151 while (Idx < N) {
4152 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004153 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004154 std::string Filename = ReadString(Record, Idx);
4155 ResolveImportedPath(Filename, ModuleDir);
4156 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004157 }
4158 break;
4159 }
4160
Richard Smith7f330cd2015-03-18 01:42:29 +00004161 case KNOWN_MODULE_FILES: {
4162 // Known-but-not-technically-used module files are treated as imports.
4163 if (!NeedsImports)
4164 break;
4165
4166 unsigned Idx = 0, N = Record.size();
4167 while (Idx < N) {
4168 std::string Filename = ReadString(Record, Idx);
4169 ResolveImportedPath(Filename, ModuleDir);
4170 Listener.visitImport(Filename);
4171 }
4172 break;
4173 }
4174
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004175 default:
4176 // No other validation to perform.
4177 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004178 }
4179 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004180}
4181
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004182bool ASTReader::isAcceptableASTFile(
4183 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004184 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004185 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4186 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004187 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4188 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004189 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004190 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004191}
4192
Ben Langmuir2c9af442014-04-10 17:57:43 +00004193ASTReader::ASTReadResult
4194ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004195 // Enter the submodule block.
4196 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4197 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004198 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004199 }
4200
4201 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4202 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004203 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004204 RecordData Record;
4205 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004206 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4207
4208 switch (Entry.Kind) {
4209 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4210 case llvm::BitstreamEntry::Error:
4211 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004212 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004213 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004214 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004215 case llvm::BitstreamEntry::Record:
4216 // The interesting case.
4217 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004218 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004219
Guy Benyei11169dd2012-12-18 14:30:41 +00004220 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004221 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004222 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004223 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4224
4225 if ((Kind == SUBMODULE_METADATA) != First) {
4226 Error("submodule metadata record should be at beginning of block");
4227 return Failure;
4228 }
4229 First = false;
4230
4231 // Submodule information is only valid if we have a current module.
4232 // FIXME: Should we error on these cases?
4233 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4234 Kind != SUBMODULE_DEFINITION)
4235 continue;
4236
4237 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004238 default: // Default behavior: ignore.
4239 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004240
Richard Smith03478d92014-10-23 22:12:14 +00004241 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004242 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004243 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004244 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004245 }
Richard Smith03478d92014-10-23 22:12:14 +00004246
Chris Lattner0e6c9402013-01-20 02:38:54 +00004247 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004248 unsigned Idx = 0;
4249 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4250 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4251 bool IsFramework = Record[Idx++];
4252 bool IsExplicit = Record[Idx++];
4253 bool IsSystem = Record[Idx++];
4254 bool IsExternC = Record[Idx++];
4255 bool InferSubmodules = Record[Idx++];
4256 bool InferExplicitSubmodules = Record[Idx++];
4257 bool InferExportWildcard = Record[Idx++];
4258 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004259
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004260 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004261 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004262 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004263
Guy Benyei11169dd2012-12-18 14:30:41 +00004264 // Retrieve this (sub)module from the module map, creating it if
4265 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004266 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004267 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004268
4269 // FIXME: set the definition loc for CurrentModule, or call
4270 // ModMap.setInferredModuleAllowedBy()
4271
Guy Benyei11169dd2012-12-18 14:30:41 +00004272 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4273 if (GlobalIndex >= SubmodulesLoaded.size() ||
4274 SubmodulesLoaded[GlobalIndex]) {
4275 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004276 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004277 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004278
Douglas Gregor7029ce12013-03-19 00:28:20 +00004279 if (!ParentModule) {
4280 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4281 if (CurFile != F.File) {
4282 if (!Diags.isDiagnosticInFlight()) {
4283 Diag(diag::err_module_file_conflict)
4284 << CurrentModule->getTopLevelModuleName()
4285 << CurFile->getName()
4286 << F.File->getName();
4287 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004288 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004289 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004290 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004291
4292 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004293 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004294
Adrian Prantl15bcf702015-06-30 17:39:43 +00004295 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 CurrentModule->IsFromModuleFile = true;
4297 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004298 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004299 CurrentModule->InferSubmodules = InferSubmodules;
4300 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4301 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004302 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 if (DeserializationListener)
4304 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4305
4306 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004307
Douglas Gregorfb912652013-03-20 21:10:35 +00004308 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004309 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004310 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004311 CurrentModule->UnresolvedConflicts.clear();
4312 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004313 break;
4314 }
4315
4316 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004317 std::string Filename = Blob;
4318 ResolveImportedPath(F, Filename);
4319 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004320 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004321 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4322 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004323 // This can be a spurious difference caused by changing the VFS to
4324 // point to a different copy of the file, and it is too late to
4325 // to rebuild safely.
4326 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4327 // after input file validation only real problems would remain and we
4328 // could just error. For now, assume it's okay.
4329 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004330 }
4331 }
4332 break;
4333 }
4334
Richard Smith202210b2014-10-24 20:23:01 +00004335 case SUBMODULE_HEADER:
4336 case SUBMODULE_EXCLUDED_HEADER:
4337 case SUBMODULE_PRIVATE_HEADER:
4338 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004339 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4340 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004341 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004342
Richard Smith202210b2014-10-24 20:23:01 +00004343 case SUBMODULE_TEXTUAL_HEADER:
4344 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4345 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4346 // them here.
4347 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004348
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004350 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004351 break;
4352 }
4353
4354 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004355 std::string Dirname = Blob;
4356 ResolveImportedPath(F, Dirname);
4357 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004358 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004359 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4360 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004361 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4362 Error("mismatched umbrella directories in submodule");
4363 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004364 }
4365 }
4366 break;
4367 }
4368
4369 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004370 F.BaseSubmoduleID = getTotalNumSubmodules();
4371 F.LocalNumSubmodules = Record[0];
4372 unsigned LocalBaseSubmoduleID = Record[1];
4373 if (F.LocalNumSubmodules > 0) {
4374 // Introduce the global -> local mapping for submodules within this
4375 // module.
4376 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4377
4378 // Introduce the local -> global mapping for submodules within this
4379 // module.
4380 F.SubmoduleRemap.insertOrReplace(
4381 std::make_pair(LocalBaseSubmoduleID,
4382 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004383
Ben Langmuir52ca6782014-10-20 16:27:32 +00004384 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4385 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004386 break;
4387 }
4388
4389 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004390 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004391 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004392 Unresolved.File = &F;
4393 Unresolved.Mod = CurrentModule;
4394 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004395 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004396 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004397 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004398 }
4399 break;
4400 }
4401
4402 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004403 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004404 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004405 Unresolved.File = &F;
4406 Unresolved.Mod = CurrentModule;
4407 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004408 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004409 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004410 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004411 }
4412
4413 // Once we've loaded the set of exports, there's no reason to keep
4414 // the parsed, unresolved exports around.
4415 CurrentModule->UnresolvedExports.clear();
4416 break;
4417 }
4418 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004419 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004420 Context.getTargetInfo());
4421 break;
4422 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004423
4424 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004425 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004426 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004427 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004428
4429 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004430 CurrentModule->ConfigMacros.push_back(Blob.str());
4431 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004432
4433 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004434 UnresolvedModuleRef Unresolved;
4435 Unresolved.File = &F;
4436 Unresolved.Mod = CurrentModule;
4437 Unresolved.ID = Record[0];
4438 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4439 Unresolved.IsWildcard = false;
4440 Unresolved.String = Blob;
4441 UnresolvedModuleRefs.push_back(Unresolved);
4442 break;
4443 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004444 }
4445 }
4446}
4447
4448/// \brief Parse the record that corresponds to a LangOptions data
4449/// structure.
4450///
4451/// This routine parses the language options from the AST file and then gives
4452/// them to the AST listener if one is set.
4453///
4454/// \returns true if the listener deems the file unacceptable, false otherwise.
4455bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4456 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004457 ASTReaderListener &Listener,
4458 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004459 LangOptions LangOpts;
4460 unsigned Idx = 0;
4461#define LANGOPT(Name, Bits, Default, Description) \
4462 LangOpts.Name = Record[Idx++];
4463#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4464 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4465#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004466#define SANITIZER(NAME, ID) \
4467 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004468#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004469
Ben Langmuircd98cb72015-06-23 18:20:18 +00004470 for (unsigned N = Record[Idx++]; N; --N)
4471 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4472
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4474 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4475 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004476
Ben Langmuird4a667a2015-06-23 18:20:23 +00004477 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004478
4479 // Comment options.
4480 for (unsigned N = Record[Idx++]; N; --N) {
4481 LangOpts.CommentOpts.BlockCommandNames.push_back(
4482 ReadString(Record, Idx));
4483 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004484 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004485
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004486 return Listener.ReadLanguageOptions(LangOpts, Complain,
4487 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004488}
4489
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004490bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4491 ASTReaderListener &Listener,
4492 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004493 unsigned Idx = 0;
4494 TargetOptions TargetOpts;
4495 TargetOpts.Triple = ReadString(Record, Idx);
4496 TargetOpts.CPU = ReadString(Record, Idx);
4497 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004498 for (unsigned N = Record[Idx++]; N; --N) {
4499 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4500 }
4501 for (unsigned N = Record[Idx++]; N; --N) {
4502 TargetOpts.Features.push_back(ReadString(Record, Idx));
4503 }
4504
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004505 return Listener.ReadTargetOptions(TargetOpts, Complain,
4506 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004507}
4508
4509bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4510 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004511 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004512 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004513#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004514#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004515 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004516#include "clang/Basic/DiagnosticOptions.def"
4517
Richard Smith3be1cb22014-08-07 00:24:21 +00004518 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004519 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004520 for (unsigned N = Record[Idx++]; N; --N)
4521 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004522
4523 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4524}
4525
4526bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4527 ASTReaderListener &Listener) {
4528 FileSystemOptions FSOpts;
4529 unsigned Idx = 0;
4530 FSOpts.WorkingDir = ReadString(Record, Idx);
4531 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4532}
4533
4534bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4535 bool Complain,
4536 ASTReaderListener &Listener) {
4537 HeaderSearchOptions HSOpts;
4538 unsigned Idx = 0;
4539 HSOpts.Sysroot = ReadString(Record, Idx);
4540
4541 // Include entries.
4542 for (unsigned N = Record[Idx++]; N; --N) {
4543 std::string Path = ReadString(Record, Idx);
4544 frontend::IncludeDirGroup Group
4545 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004546 bool IsFramework = Record[Idx++];
4547 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004548 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4549 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 }
4551
4552 // System header prefixes.
4553 for (unsigned N = Record[Idx++]; N; --N) {
4554 std::string Prefix = ReadString(Record, Idx);
4555 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004556 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 }
4558
4559 HSOpts.ResourceDir = ReadString(Record, Idx);
4560 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004561 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004562 HSOpts.DisableModuleHash = Record[Idx++];
4563 HSOpts.UseBuiltinIncludes = Record[Idx++];
4564 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4565 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4566 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004567 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004568
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004569 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4570 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004571}
4572
4573bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4574 bool Complain,
4575 ASTReaderListener &Listener,
4576 std::string &SuggestedPredefines) {
4577 PreprocessorOptions PPOpts;
4578 unsigned Idx = 0;
4579
4580 // Macro definitions/undefs
4581 for (unsigned N = Record[Idx++]; N; --N) {
4582 std::string Macro = ReadString(Record, Idx);
4583 bool IsUndef = Record[Idx++];
4584 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4585 }
4586
4587 // Includes
4588 for (unsigned N = Record[Idx++]; N; --N) {
4589 PPOpts.Includes.push_back(ReadString(Record, Idx));
4590 }
4591
4592 // Macro Includes
4593 for (unsigned N = Record[Idx++]; N; --N) {
4594 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4595 }
4596
4597 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004598 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004599 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4600 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4601 PPOpts.ObjCXXARCStandardLibrary =
4602 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4603 SuggestedPredefines.clear();
4604 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4605 SuggestedPredefines);
4606}
4607
4608std::pair<ModuleFile *, unsigned>
4609ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4610 GlobalPreprocessedEntityMapType::iterator
4611 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4612 assert(I != GlobalPreprocessedEntityMap.end() &&
4613 "Corrupted global preprocessed entity map");
4614 ModuleFile *M = I->second;
4615 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4616 return std::make_pair(M, LocalIndex);
4617}
4618
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004619llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004620ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4621 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4622 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4623 Mod.NumPreprocessedEntities);
4624
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004625 return llvm::make_range(PreprocessingRecord::iterator(),
4626 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004627}
4628
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004629llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004630ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004631 return llvm::make_range(
4632 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4633 ModuleDeclIterator(this, &Mod,
4634 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004635}
4636
4637PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4638 PreprocessedEntityID PPID = Index+1;
4639 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4640 ModuleFile &M = *PPInfo.first;
4641 unsigned LocalIndex = PPInfo.second;
4642 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4643
Guy Benyei11169dd2012-12-18 14:30:41 +00004644 if (!PP.getPreprocessingRecord()) {
4645 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004646 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004647 }
4648
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004649 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4650 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4651
4652 llvm::BitstreamEntry Entry =
4653 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4654 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004655 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004656
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 // Read the record.
4658 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4659 ReadSourceLocation(M, PPOffs.End));
4660 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004661 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004662 RecordData Record;
4663 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004664 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4665 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004666 switch (RecType) {
4667 case PPD_MACRO_EXPANSION: {
4668 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004669 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004670 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004671 if (isBuiltin)
4672 Name = getLocalIdentifier(M, Record[1]);
4673 else {
Richard Smith66a81862015-05-04 02:25:31 +00004674 PreprocessedEntityID GlobalID =
4675 getGlobalPreprocessedEntityID(M, Record[1]);
4676 Def = cast<MacroDefinitionRecord>(
4677 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004678 }
4679
4680 MacroExpansion *ME;
4681 if (isBuiltin)
4682 ME = new (PPRec) MacroExpansion(Name, Range);
4683 else
4684 ME = new (PPRec) MacroExpansion(Def, Range);
4685
4686 return ME;
4687 }
4688
4689 case PPD_MACRO_DEFINITION: {
4690 // Decode the identifier info and then check again; if the macro is
4691 // still defined and associated with the identifier,
4692 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004693 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004694
4695 if (DeserializationListener)
4696 DeserializationListener->MacroDefinitionRead(PPID, MD);
4697
4698 return MD;
4699 }
4700
4701 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004702 const char *FullFileNameStart = Blob.data() + Record[0];
4703 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004704 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004705 if (!FullFileName.empty())
4706 File = PP.getFileManager().getFile(FullFileName);
4707
4708 // FIXME: Stable encoding
4709 InclusionDirective::InclusionKind Kind
4710 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4711 InclusionDirective *ID
4712 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004713 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004714 Record[1], Record[3],
4715 File,
4716 Range);
4717 return ID;
4718 }
4719 }
4720
4721 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4722}
4723
4724/// \brief \arg SLocMapI points at a chunk of a module that contains no
4725/// preprocessed entities or the entities it contains are not the ones we are
4726/// looking for. Find the next module that contains entities and return the ID
4727/// of the first entry.
4728PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4729 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4730 ++SLocMapI;
4731 for (GlobalSLocOffsetMapType::const_iterator
4732 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4733 ModuleFile &M = *SLocMapI->second;
4734 if (M.NumPreprocessedEntities)
4735 return M.BasePreprocessedEntityID;
4736 }
4737
4738 return getTotalNumPreprocessedEntities();
4739}
4740
4741namespace {
4742
4743template <unsigned PPEntityOffset::*PPLoc>
4744struct PPEntityComp {
4745 const ASTReader &Reader;
4746 ModuleFile &M;
4747
4748 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4749
4750 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4751 SourceLocation LHS = getLoc(L);
4752 SourceLocation RHS = getLoc(R);
4753 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4754 }
4755
4756 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4757 SourceLocation LHS = getLoc(L);
4758 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4759 }
4760
4761 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4762 SourceLocation RHS = getLoc(R);
4763 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4764 }
4765
4766 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4767 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4768 }
4769};
4770
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004771}
Guy Benyei11169dd2012-12-18 14:30:41 +00004772
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004773PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4774 bool EndsAfter) const {
4775 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004776 return getTotalNumPreprocessedEntities();
4777
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004778 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4779 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004780 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4781 "Corrupted global sloc offset map");
4782
4783 if (SLocMapI->second->NumPreprocessedEntities == 0)
4784 return findNextPreprocessedEntity(SLocMapI);
4785
4786 ModuleFile &M = *SLocMapI->second;
4787 typedef const PPEntityOffset *pp_iterator;
4788 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4789 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4790
4791 size_t Count = M.NumPreprocessedEntities;
4792 size_t Half;
4793 pp_iterator First = pp_begin;
4794 pp_iterator PPI;
4795
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004796 if (EndsAfter) {
4797 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4798 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4799 } else {
4800 // Do a binary search manually instead of using std::lower_bound because
4801 // The end locations of entities may be unordered (when a macro expansion
4802 // is inside another macro argument), but for this case it is not important
4803 // whether we get the first macro expansion or its containing macro.
4804 while (Count > 0) {
4805 Half = Count / 2;
4806 PPI = First;
4807 std::advance(PPI, Half);
4808 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4809 Loc)) {
4810 First = PPI;
4811 ++First;
4812 Count = Count - Half - 1;
4813 } else
4814 Count = Half;
4815 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004816 }
4817
4818 if (PPI == pp_end)
4819 return findNextPreprocessedEntity(SLocMapI);
4820
4821 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4822}
4823
Guy Benyei11169dd2012-12-18 14:30:41 +00004824/// \brief Returns a pair of [Begin, End) indices of preallocated
4825/// preprocessed entities that \arg Range encompasses.
4826std::pair<unsigned, unsigned>
4827 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4828 if (Range.isInvalid())
4829 return std::make_pair(0,0);
4830 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4831
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004832 PreprocessedEntityID BeginID =
4833 findPreprocessedEntity(Range.getBegin(), false);
4834 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004835 return std::make_pair(BeginID, EndID);
4836}
4837
4838/// \brief Optionally returns true or false if the preallocated preprocessed
4839/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004840Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004841 FileID FID) {
4842 if (FID.isInvalid())
4843 return false;
4844
4845 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4846 ModuleFile &M = *PPInfo.first;
4847 unsigned LocalIndex = PPInfo.second;
4848 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4849
4850 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4851 if (Loc.isInvalid())
4852 return false;
4853
4854 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4855 return true;
4856 else
4857 return false;
4858}
4859
4860namespace {
4861 /// \brief Visitor used to search for information about a header file.
4862 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004863 const FileEntry *FE;
4864
David Blaikie05785d12013-02-20 22:23:23 +00004865 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004866
4867 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004868 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4869 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004870
4871 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004872 HeaderFileInfoLookupTable *Table
4873 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4874 if (!Table)
4875 return false;
4876
4877 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00004878 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004879 if (Pos == Table->end())
4880 return false;
4881
Richard Smithbdf2d932015-07-30 03:37:16 +00004882 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00004883 return true;
4884 }
4885
David Blaikie05785d12013-02-20 22:23:23 +00004886 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004887 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004888}
Guy Benyei11169dd2012-12-18 14:30:41 +00004889
4890HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004891 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004892 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004893 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004894 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004895
4896 return HeaderFileInfo();
4897}
4898
4899void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4900 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004901 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004902 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4903 ModuleFile &F = *(*I);
4904 unsigned Idx = 0;
4905 DiagStates.clear();
4906 assert(!Diag.DiagStates.empty());
4907 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4908 while (Idx < F.PragmaDiagMappings.size()) {
4909 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4910 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4911 if (DiagStateID != 0) {
4912 Diag.DiagStatePoints.push_back(
4913 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4914 FullSourceLoc(Loc, SourceMgr)));
4915 continue;
4916 }
4917
4918 assert(DiagStateID == 0);
4919 // A new DiagState was created here.
4920 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4921 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4922 DiagStates.push_back(NewState);
4923 Diag.DiagStatePoints.push_back(
4924 DiagnosticsEngine::DiagStatePoint(NewState,
4925 FullSourceLoc(Loc, SourceMgr)));
4926 while (1) {
4927 assert(Idx < F.PragmaDiagMappings.size() &&
4928 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4929 if (Idx >= F.PragmaDiagMappings.size()) {
4930 break; // Something is messed up but at least avoid infinite loop in
4931 // release build.
4932 }
4933 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4934 if (DiagID == (unsigned)-1) {
4935 break; // no more diag/map pairs for this location.
4936 }
Alp Tokerc726c362014-06-10 09:31:37 +00004937 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4938 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4939 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00004940 }
4941 }
4942 }
4943}
4944
4945/// \brief Get the correct cursor and offset for loading a type.
4946ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4947 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4948 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4949 ModuleFile *M = I->second;
4950 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4951}
4952
4953/// \brief Read and return the type with the given index..
4954///
4955/// The index is the type ID, shifted and minus the number of predefs. This
4956/// routine actually reads the record corresponding to the type at the given
4957/// location. It is a helper routine for GetType, which deals with reading type
4958/// IDs.
4959QualType ASTReader::readTypeRecord(unsigned Index) {
4960 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004961 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004962
4963 // Keep track of where we are in the stream, then jump back there
4964 // after reading this type.
4965 SavedStreamPosition SavedPosition(DeclsCursor);
4966
4967 ReadingKindTracker ReadingKind(Read_Type, *this);
4968
4969 // Note that we are loading a type record.
4970 Deserializing AType(this);
4971
4972 unsigned Idx = 0;
4973 DeclsCursor.JumpToBit(Loc.Offset);
4974 RecordData Record;
4975 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004976 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004977 case TYPE_EXT_QUAL: {
4978 if (Record.size() != 2) {
4979 Error("Incorrect encoding of extended qualifier type");
4980 return QualType();
4981 }
4982 QualType Base = readType(*Loc.F, Record, Idx);
4983 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4984 return Context.getQualifiedType(Base, Quals);
4985 }
4986
4987 case TYPE_COMPLEX: {
4988 if (Record.size() != 1) {
4989 Error("Incorrect encoding of complex type");
4990 return QualType();
4991 }
4992 QualType ElemType = readType(*Loc.F, Record, Idx);
4993 return Context.getComplexType(ElemType);
4994 }
4995
4996 case TYPE_POINTER: {
4997 if (Record.size() != 1) {
4998 Error("Incorrect encoding of pointer type");
4999 return QualType();
5000 }
5001 QualType PointeeType = readType(*Loc.F, Record, Idx);
5002 return Context.getPointerType(PointeeType);
5003 }
5004
Reid Kleckner8a365022013-06-24 17:51:48 +00005005 case TYPE_DECAYED: {
5006 if (Record.size() != 1) {
5007 Error("Incorrect encoding of decayed type");
5008 return QualType();
5009 }
5010 QualType OriginalType = readType(*Loc.F, Record, Idx);
5011 QualType DT = Context.getAdjustedParameterType(OriginalType);
5012 if (!isa<DecayedType>(DT))
5013 Error("Decayed type does not decay");
5014 return DT;
5015 }
5016
Reid Kleckner0503a872013-12-05 01:23:43 +00005017 case TYPE_ADJUSTED: {
5018 if (Record.size() != 2) {
5019 Error("Incorrect encoding of adjusted type");
5020 return QualType();
5021 }
5022 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5023 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5024 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5025 }
5026
Guy Benyei11169dd2012-12-18 14:30:41 +00005027 case TYPE_BLOCK_POINTER: {
5028 if (Record.size() != 1) {
5029 Error("Incorrect encoding of block pointer type");
5030 return QualType();
5031 }
5032 QualType PointeeType = readType(*Loc.F, Record, Idx);
5033 return Context.getBlockPointerType(PointeeType);
5034 }
5035
5036 case TYPE_LVALUE_REFERENCE: {
5037 if (Record.size() != 2) {
5038 Error("Incorrect encoding of lvalue reference type");
5039 return QualType();
5040 }
5041 QualType PointeeType = readType(*Loc.F, Record, Idx);
5042 return Context.getLValueReferenceType(PointeeType, Record[1]);
5043 }
5044
5045 case TYPE_RVALUE_REFERENCE: {
5046 if (Record.size() != 1) {
5047 Error("Incorrect encoding of rvalue reference type");
5048 return QualType();
5049 }
5050 QualType PointeeType = readType(*Loc.F, Record, Idx);
5051 return Context.getRValueReferenceType(PointeeType);
5052 }
5053
5054 case TYPE_MEMBER_POINTER: {
5055 if (Record.size() != 2) {
5056 Error("Incorrect encoding of member pointer type");
5057 return QualType();
5058 }
5059 QualType PointeeType = readType(*Loc.F, Record, Idx);
5060 QualType ClassType = readType(*Loc.F, Record, Idx);
5061 if (PointeeType.isNull() || ClassType.isNull())
5062 return QualType();
5063
5064 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5065 }
5066
5067 case TYPE_CONSTANT_ARRAY: {
5068 QualType ElementType = readType(*Loc.F, Record, Idx);
5069 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5070 unsigned IndexTypeQuals = Record[2];
5071 unsigned Idx = 3;
5072 llvm::APInt Size = ReadAPInt(Record, Idx);
5073 return Context.getConstantArrayType(ElementType, Size,
5074 ASM, IndexTypeQuals);
5075 }
5076
5077 case TYPE_INCOMPLETE_ARRAY: {
5078 QualType ElementType = readType(*Loc.F, Record, Idx);
5079 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5080 unsigned IndexTypeQuals = Record[2];
5081 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5082 }
5083
5084 case TYPE_VARIABLE_ARRAY: {
5085 QualType ElementType = readType(*Loc.F, Record, Idx);
5086 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5087 unsigned IndexTypeQuals = Record[2];
5088 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5089 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5090 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5091 ASM, IndexTypeQuals,
5092 SourceRange(LBLoc, RBLoc));
5093 }
5094
5095 case TYPE_VECTOR: {
5096 if (Record.size() != 3) {
5097 Error("incorrect encoding of vector type in AST file");
5098 return QualType();
5099 }
5100
5101 QualType ElementType = readType(*Loc.F, Record, Idx);
5102 unsigned NumElements = Record[1];
5103 unsigned VecKind = Record[2];
5104 return Context.getVectorType(ElementType, NumElements,
5105 (VectorType::VectorKind)VecKind);
5106 }
5107
5108 case TYPE_EXT_VECTOR: {
5109 if (Record.size() != 3) {
5110 Error("incorrect encoding of extended vector type in AST file");
5111 return QualType();
5112 }
5113
5114 QualType ElementType = readType(*Loc.F, Record, Idx);
5115 unsigned NumElements = Record[1];
5116 return Context.getExtVectorType(ElementType, NumElements);
5117 }
5118
5119 case TYPE_FUNCTION_NO_PROTO: {
5120 if (Record.size() != 6) {
5121 Error("incorrect encoding of no-proto function type");
5122 return QualType();
5123 }
5124 QualType ResultType = readType(*Loc.F, Record, Idx);
5125 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5126 (CallingConv)Record[4], Record[5]);
5127 return Context.getFunctionNoProtoType(ResultType, Info);
5128 }
5129
5130 case TYPE_FUNCTION_PROTO: {
5131 QualType ResultType = readType(*Loc.F, Record, Idx);
5132
5133 FunctionProtoType::ExtProtoInfo EPI;
5134 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5135 /*hasregparm*/ Record[2],
5136 /*regparm*/ Record[3],
5137 static_cast<CallingConv>(Record[4]),
5138 /*produces*/ Record[5]);
5139
5140 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005141
5142 EPI.Variadic = Record[Idx++];
5143 EPI.HasTrailingReturn = Record[Idx++];
5144 EPI.TypeQuals = Record[Idx++];
5145 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005146 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005147 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005148
5149 unsigned NumParams = Record[Idx++];
5150 SmallVector<QualType, 16> ParamTypes;
5151 for (unsigned I = 0; I != NumParams; ++I)
5152 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5153
Jordan Rose5c382722013-03-08 21:51:21 +00005154 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 }
5156
5157 case TYPE_UNRESOLVED_USING: {
5158 unsigned Idx = 0;
5159 return Context.getTypeDeclType(
5160 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5161 }
5162
5163 case TYPE_TYPEDEF: {
5164 if (Record.size() != 2) {
5165 Error("incorrect encoding of typedef type");
5166 return QualType();
5167 }
5168 unsigned Idx = 0;
5169 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5170 QualType Canonical = readType(*Loc.F, Record, Idx);
5171 if (!Canonical.isNull())
5172 Canonical = Context.getCanonicalType(Canonical);
5173 return Context.getTypedefType(Decl, Canonical);
5174 }
5175
5176 case TYPE_TYPEOF_EXPR:
5177 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5178
5179 case TYPE_TYPEOF: {
5180 if (Record.size() != 1) {
5181 Error("incorrect encoding of typeof(type) in AST file");
5182 return QualType();
5183 }
5184 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5185 return Context.getTypeOfType(UnderlyingType);
5186 }
5187
5188 case TYPE_DECLTYPE: {
5189 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5190 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5191 }
5192
5193 case TYPE_UNARY_TRANSFORM: {
5194 QualType BaseType = readType(*Loc.F, Record, Idx);
5195 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5196 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5197 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5198 }
5199
Richard Smith74aeef52013-04-26 16:15:35 +00005200 case TYPE_AUTO: {
5201 QualType Deduced = readType(*Loc.F, Record, Idx);
5202 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005203 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005204 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005205 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005206
5207 case TYPE_RECORD: {
5208 if (Record.size() != 2) {
5209 Error("incorrect encoding of record type");
5210 return QualType();
5211 }
5212 unsigned Idx = 0;
5213 bool IsDependent = Record[Idx++];
5214 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5215 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5216 QualType T = Context.getRecordType(RD);
5217 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5218 return T;
5219 }
5220
5221 case TYPE_ENUM: {
5222 if (Record.size() != 2) {
5223 Error("incorrect encoding of enum type");
5224 return QualType();
5225 }
5226 unsigned Idx = 0;
5227 bool IsDependent = Record[Idx++];
5228 QualType T
5229 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5230 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5231 return T;
5232 }
5233
5234 case TYPE_ATTRIBUTED: {
5235 if (Record.size() != 3) {
5236 Error("incorrect encoding of attributed type");
5237 return QualType();
5238 }
5239 QualType modifiedType = readType(*Loc.F, Record, Idx);
5240 QualType equivalentType = readType(*Loc.F, Record, Idx);
5241 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5242 return Context.getAttributedType(kind, modifiedType, equivalentType);
5243 }
5244
5245 case TYPE_PAREN: {
5246 if (Record.size() != 1) {
5247 Error("incorrect encoding of paren type");
5248 return QualType();
5249 }
5250 QualType InnerType = readType(*Loc.F, Record, Idx);
5251 return Context.getParenType(InnerType);
5252 }
5253
5254 case TYPE_PACK_EXPANSION: {
5255 if (Record.size() != 2) {
5256 Error("incorrect encoding of pack expansion type");
5257 return QualType();
5258 }
5259 QualType Pattern = readType(*Loc.F, Record, Idx);
5260 if (Pattern.isNull())
5261 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005262 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005263 if (Record[1])
5264 NumExpansions = Record[1] - 1;
5265 return Context.getPackExpansionType(Pattern, NumExpansions);
5266 }
5267
5268 case TYPE_ELABORATED: {
5269 unsigned Idx = 0;
5270 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5271 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5272 QualType NamedType = readType(*Loc.F, Record, Idx);
5273 return Context.getElaboratedType(Keyword, NNS, NamedType);
5274 }
5275
5276 case TYPE_OBJC_INTERFACE: {
5277 unsigned Idx = 0;
5278 ObjCInterfaceDecl *ItfD
5279 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5280 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5281 }
5282
5283 case TYPE_OBJC_OBJECT: {
5284 unsigned Idx = 0;
5285 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005286 unsigned NumTypeArgs = Record[Idx++];
5287 SmallVector<QualType, 4> TypeArgs;
5288 for (unsigned I = 0; I != NumTypeArgs; ++I)
5289 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 unsigned NumProtos = Record[Idx++];
5291 SmallVector<ObjCProtocolDecl*, 4> Protos;
5292 for (unsigned I = 0; I != NumProtos; ++I)
5293 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005294 bool IsKindOf = Record[Idx++];
5295 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005296 }
5297
5298 case TYPE_OBJC_OBJECT_POINTER: {
5299 unsigned Idx = 0;
5300 QualType Pointee = readType(*Loc.F, Record, Idx);
5301 return Context.getObjCObjectPointerType(Pointee);
5302 }
5303
5304 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5305 unsigned Idx = 0;
5306 QualType Parm = readType(*Loc.F, Record, Idx);
5307 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005308 return Context.getSubstTemplateTypeParmType(
5309 cast<TemplateTypeParmType>(Parm),
5310 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005311 }
5312
5313 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5314 unsigned Idx = 0;
5315 QualType Parm = readType(*Loc.F, Record, Idx);
5316 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5317 return Context.getSubstTemplateTypeParmPackType(
5318 cast<TemplateTypeParmType>(Parm),
5319 ArgPack);
5320 }
5321
5322 case TYPE_INJECTED_CLASS_NAME: {
5323 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5324 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5325 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5326 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005327 const Type *T = nullptr;
5328 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5329 if (const Type *Existing = DI->getTypeForDecl()) {
5330 T = Existing;
5331 break;
5332 }
5333 }
5334 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005335 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005336 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5337 DI->setTypeForDecl(T);
5338 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005339 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005340 }
5341
5342 case TYPE_TEMPLATE_TYPE_PARM: {
5343 unsigned Idx = 0;
5344 unsigned Depth = Record[Idx++];
5345 unsigned Index = Record[Idx++];
5346 bool Pack = Record[Idx++];
5347 TemplateTypeParmDecl *D
5348 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5349 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5350 }
5351
5352 case TYPE_DEPENDENT_NAME: {
5353 unsigned Idx = 0;
5354 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5355 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005356 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005357 QualType Canon = readType(*Loc.F, Record, Idx);
5358 if (!Canon.isNull())
5359 Canon = Context.getCanonicalType(Canon);
5360 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5361 }
5362
5363 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5364 unsigned Idx = 0;
5365 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5366 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005367 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005368 unsigned NumArgs = Record[Idx++];
5369 SmallVector<TemplateArgument, 8> Args;
5370 Args.reserve(NumArgs);
5371 while (NumArgs--)
5372 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5373 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5374 Args.size(), Args.data());
5375 }
5376
5377 case TYPE_DEPENDENT_SIZED_ARRAY: {
5378 unsigned Idx = 0;
5379
5380 // ArrayType
5381 QualType ElementType = readType(*Loc.F, Record, Idx);
5382 ArrayType::ArraySizeModifier ASM
5383 = (ArrayType::ArraySizeModifier)Record[Idx++];
5384 unsigned IndexTypeQuals = Record[Idx++];
5385
5386 // DependentSizedArrayType
5387 Expr *NumElts = ReadExpr(*Loc.F);
5388 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5389
5390 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5391 IndexTypeQuals, Brackets);
5392 }
5393
5394 case TYPE_TEMPLATE_SPECIALIZATION: {
5395 unsigned Idx = 0;
5396 bool IsDependent = Record[Idx++];
5397 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5398 SmallVector<TemplateArgument, 8> Args;
5399 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5400 QualType Underlying = readType(*Loc.F, Record, Idx);
5401 QualType T;
5402 if (Underlying.isNull())
5403 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5404 Args.size());
5405 else
5406 T = Context.getTemplateSpecializationType(Name, Args.data(),
5407 Args.size(), Underlying);
5408 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5409 return T;
5410 }
5411
5412 case TYPE_ATOMIC: {
5413 if (Record.size() != 1) {
5414 Error("Incorrect encoding of atomic type");
5415 return QualType();
5416 }
5417 QualType ValueType = readType(*Loc.F, Record, Idx);
5418 return Context.getAtomicType(ValueType);
5419 }
5420 }
5421 llvm_unreachable("Invalid TypeCode!");
5422}
5423
Richard Smith564417a2014-03-20 21:47:22 +00005424void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5425 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005426 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005427 const RecordData &Record, unsigned &Idx) {
5428 ExceptionSpecificationType EST =
5429 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005430 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005431 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005432 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005433 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005434 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005435 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005436 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005437 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005438 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5439 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005440 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005441 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005442 }
5443}
5444
Guy Benyei11169dd2012-12-18 14:30:41 +00005445class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5446 ASTReader &Reader;
5447 ModuleFile &F;
5448 const ASTReader::RecordData &Record;
5449 unsigned &Idx;
5450
5451 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5452 unsigned &I) {
5453 return Reader.ReadSourceLocation(F, R, I);
5454 }
5455
5456 template<typename T>
5457 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5458 return Reader.ReadDeclAs<T>(F, Record, Idx);
5459 }
5460
5461public:
5462 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5463 const ASTReader::RecordData &Record, unsigned &Idx)
5464 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5465 { }
5466
5467 // We want compile-time assurance that we've enumerated all of
5468 // these, so unfortunately we have to declare them first, then
5469 // define them out-of-line.
5470#define ABSTRACT_TYPELOC(CLASS, PARENT)
5471#define TYPELOC(CLASS, PARENT) \
5472 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5473#include "clang/AST/TypeLocNodes.def"
5474
5475 void VisitFunctionTypeLoc(FunctionTypeLoc);
5476 void VisitArrayTypeLoc(ArrayTypeLoc);
5477};
5478
5479void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5480 // nothing to do
5481}
5482void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5483 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5484 if (TL.needsExtraLocalData()) {
5485 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5486 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5487 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5488 TL.setModeAttr(Record[Idx++]);
5489 }
5490}
5491void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5492 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5493}
5494void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5495 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5496}
Reid Kleckner8a365022013-06-24 17:51:48 +00005497void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5498 // nothing to do
5499}
Reid Kleckner0503a872013-12-05 01:23:43 +00005500void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5501 // nothing to do
5502}
Guy Benyei11169dd2012-12-18 14:30:41 +00005503void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5504 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5505}
5506void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5507 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5508}
5509void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5510 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5511}
5512void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5513 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5514 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5515}
5516void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5517 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5518 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5519 if (Record[Idx++])
5520 TL.setSizeExpr(Reader.ReadExpr(F));
5521 else
Craig Toppera13603a2014-05-22 05:54:18 +00005522 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005523}
5524void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5525 VisitArrayTypeLoc(TL);
5526}
5527void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5528 VisitArrayTypeLoc(TL);
5529}
5530void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5531 VisitArrayTypeLoc(TL);
5532}
5533void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5534 DependentSizedArrayTypeLoc TL) {
5535 VisitArrayTypeLoc(TL);
5536}
5537void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5538 DependentSizedExtVectorTypeLoc TL) {
5539 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5540}
5541void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5542 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5543}
5544void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5545 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5546}
5547void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5548 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5549 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5550 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5551 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005552 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5553 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005554 }
5555}
5556void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5557 VisitFunctionTypeLoc(TL);
5558}
5559void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5560 VisitFunctionTypeLoc(TL);
5561}
5562void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5563 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5564}
5565void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5566 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5567}
5568void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5569 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5570 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5571 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5572}
5573void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5574 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5575 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5576 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5577 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5578}
5579void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5580 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5581}
5582void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5583 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5584 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5585 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5586 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5587}
5588void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5589 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5590}
5591void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5592 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5593}
5594void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5595 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5596}
5597void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5598 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5599 if (TL.hasAttrOperand()) {
5600 SourceRange range;
5601 range.setBegin(ReadSourceLocation(Record, Idx));
5602 range.setEnd(ReadSourceLocation(Record, Idx));
5603 TL.setAttrOperandParensRange(range);
5604 }
5605 if (TL.hasAttrExprOperand()) {
5606 if (Record[Idx++])
5607 TL.setAttrExprOperand(Reader.ReadExpr(F));
5608 else
Craig Toppera13603a2014-05-22 05:54:18 +00005609 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005610 } else if (TL.hasAttrEnumOperand())
5611 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5612}
5613void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5614 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5615}
5616void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5617 SubstTemplateTypeParmTypeLoc TL) {
5618 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5619}
5620void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5621 SubstTemplateTypeParmPackTypeLoc TL) {
5622 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5623}
5624void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5625 TemplateSpecializationTypeLoc TL) {
5626 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5627 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5628 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5629 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5630 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5631 TL.setArgLocInfo(i,
5632 Reader.GetTemplateArgumentLocInfo(F,
5633 TL.getTypePtr()->getArg(i).getKind(),
5634 Record, Idx));
5635}
5636void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5637 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5638 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5639}
5640void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5641 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5642 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5643}
5644void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5645 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5646}
5647void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5648 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5649 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5650 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5651}
5652void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5653 DependentTemplateSpecializationTypeLoc TL) {
5654 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5655 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5656 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5657 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5658 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5659 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5660 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5661 TL.setArgLocInfo(I,
5662 Reader.GetTemplateArgumentLocInfo(F,
5663 TL.getTypePtr()->getArg(I).getKind(),
5664 Record, Idx));
5665}
5666void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5667 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5668}
5669void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5670 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5671}
5672void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5673 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005674 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5675 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5676 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5677 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5678 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5679 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005680 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5681 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5682}
5683void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5684 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5685}
5686void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5687 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5688 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5689 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5690}
5691
5692TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5693 const RecordData &Record,
5694 unsigned &Idx) {
5695 QualType InfoTy = readType(F, Record, Idx);
5696 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005697 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005698
5699 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5700 TypeLocReader TLR(*this, F, Record, Idx);
5701 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5702 TLR.Visit(TL);
5703 return TInfo;
5704}
5705
5706QualType ASTReader::GetType(TypeID ID) {
5707 unsigned FastQuals = ID & Qualifiers::FastMask;
5708 unsigned Index = ID >> Qualifiers::FastWidth;
5709
5710 if (Index < NUM_PREDEF_TYPE_IDS) {
5711 QualType T;
5712 switch ((PredefinedTypeIDs)Index) {
5713 case PREDEF_TYPE_NULL_ID: return QualType();
5714 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5715 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5716
5717 case PREDEF_TYPE_CHAR_U_ID:
5718 case PREDEF_TYPE_CHAR_S_ID:
5719 // FIXME: Check that the signedness of CharTy is correct!
5720 T = Context.CharTy;
5721 break;
5722
5723 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5724 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5725 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5726 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5727 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5728 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5729 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5730 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5731 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5732 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5733 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5734 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5735 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5736 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5737 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5738 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5739 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5740 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5741 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5742 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5743 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5744 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5745 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5746 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5747 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5748 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5749 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5750 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005751 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5752 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5753 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5754 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5755 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5756 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005757 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005758 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005759 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5760
5761 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5762 T = Context.getAutoRRefDeductType();
5763 break;
5764
5765 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5766 T = Context.ARCUnbridgedCastTy;
5767 break;
5768
Guy Benyei11169dd2012-12-18 14:30:41 +00005769 case PREDEF_TYPE_BUILTIN_FN:
5770 T = Context.BuiltinFnTy;
5771 break;
5772 }
5773
5774 assert(!T.isNull() && "Unknown predefined type");
5775 return T.withFastQualifiers(FastQuals);
5776 }
5777
5778 Index -= NUM_PREDEF_TYPE_IDS;
5779 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5780 if (TypesLoaded[Index].isNull()) {
5781 TypesLoaded[Index] = readTypeRecord(Index);
5782 if (TypesLoaded[Index].isNull())
5783 return QualType();
5784
5785 TypesLoaded[Index]->setFromAST();
5786 if (DeserializationListener)
5787 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5788 TypesLoaded[Index]);
5789 }
5790
5791 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5792}
5793
5794QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5795 return GetType(getGlobalTypeID(F, LocalID));
5796}
5797
5798serialization::TypeID
5799ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5800 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5801 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5802
5803 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5804 return LocalID;
5805
5806 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5807 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5808 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5809
5810 unsigned GlobalIndex = LocalIndex + I->second;
5811 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5812}
5813
5814TemplateArgumentLocInfo
5815ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5816 TemplateArgument::ArgKind Kind,
5817 const RecordData &Record,
5818 unsigned &Index) {
5819 switch (Kind) {
5820 case TemplateArgument::Expression:
5821 return ReadExpr(F);
5822 case TemplateArgument::Type:
5823 return GetTypeSourceInfo(F, Record, Index);
5824 case TemplateArgument::Template: {
5825 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5826 Index);
5827 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5828 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5829 SourceLocation());
5830 }
5831 case TemplateArgument::TemplateExpansion: {
5832 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5833 Index);
5834 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5835 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5836 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5837 EllipsisLoc);
5838 }
5839 case TemplateArgument::Null:
5840 case TemplateArgument::Integral:
5841 case TemplateArgument::Declaration:
5842 case TemplateArgument::NullPtr:
5843 case TemplateArgument::Pack:
5844 // FIXME: Is this right?
5845 return TemplateArgumentLocInfo();
5846 }
5847 llvm_unreachable("unexpected template argument loc");
5848}
5849
5850TemplateArgumentLoc
5851ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5852 const RecordData &Record, unsigned &Index) {
5853 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5854
5855 if (Arg.getKind() == TemplateArgument::Expression) {
5856 if (Record[Index++]) // bool InfoHasSameExpr.
5857 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5858 }
5859 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5860 Record, Index));
5861}
5862
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005863const ASTTemplateArgumentListInfo*
5864ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5865 const RecordData &Record,
5866 unsigned &Index) {
5867 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5868 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5869 unsigned NumArgsAsWritten = Record[Index++];
5870 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5871 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5872 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5873 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5874}
5875
Guy Benyei11169dd2012-12-18 14:30:41 +00005876Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5877 return GetDecl(ID);
5878}
5879
Richard Smith50895422015-01-31 03:04:55 +00005880template<typename TemplateSpecializationDecl>
5881static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5882 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5883 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5884}
5885
Richard Smith053f6c62014-05-16 23:01:30 +00005886void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005887 if (NumCurrentElementsDeserializing) {
5888 // We arrange to not care about the complete redeclaration chain while we're
5889 // deserializing. Just remember that the AST has marked this one as complete
5890 // but that it's not actually complete yet, so we know we still need to
5891 // complete it later.
5892 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5893 return;
5894 }
5895
Richard Smith053f6c62014-05-16 23:01:30 +00005896 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5897
Richard Smith053f6c62014-05-16 23:01:30 +00005898 // If this is a named declaration, complete it by looking it up
5899 // within its context.
5900 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005901 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005902 // all mergeable entities within it.
5903 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5904 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5905 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00005906 if (!getContext().getLangOpts().CPlusPlus &&
5907 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00005908 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00005909 // the identifier instead. (For C++ modules, we don't store decls
5910 // in the serialized identifier table, so we do the lookup in the TU.)
5911 auto *II = Name.getAsIdentifierInfo();
5912 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00005913 if (II->isOutOfDate())
5914 updateOutOfDateIdentifier(*II);
5915 } else
5916 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005917 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00005918 // Find all declarations of this kind from the relevant context.
5919 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
5920 auto *DC = cast<DeclContext>(DCDecl);
5921 SmallVector<Decl*, 8> Decls;
5922 FindExternalLexicalDecls(
5923 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
5924 }
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
Richard Smith9b88a4c2015-07-27 05:40:23 +00006086 case PREDEF_DECL_VA_LIST_TAG:
6087 return Context.getVaListTagDecl();
6088
Richard Smithf19e1272015-03-07 00:04:49 +00006089 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6090 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006091 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006092 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006093}
6094
Richard Smithcd45dbc2014-04-19 03:48:30 +00006095Decl *ASTReader::GetExistingDecl(DeclID ID) {
6096 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006097 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6098 if (D) {
6099 // Track that we have merged the declaration with ID \p ID into the
6100 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006101 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006102 if (Merged.empty())
6103 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006104 }
Richard Smithfe620d22015-03-05 23:24:12 +00006105 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006106 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006107
Guy Benyei11169dd2012-12-18 14:30:41 +00006108 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6109
6110 if (Index >= DeclsLoaded.size()) {
6111 assert(0 && "declaration ID out-of-range for AST file");
6112 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006113 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006114 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006115
6116 return DeclsLoaded[Index];
6117}
6118
6119Decl *ASTReader::GetDecl(DeclID ID) {
6120 if (ID < NUM_PREDEF_DECL_IDS)
6121 return GetExistingDecl(ID);
6122
6123 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6124
6125 if (Index >= DeclsLoaded.size()) {
6126 assert(0 && "declaration ID out-of-range for AST file");
6127 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006128 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006129 }
6130
Guy Benyei11169dd2012-12-18 14:30:41 +00006131 if (!DeclsLoaded[Index]) {
6132 ReadDeclRecord(ID);
6133 if (DeserializationListener)
6134 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6135 }
6136
6137 return DeclsLoaded[Index];
6138}
6139
6140DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6141 DeclID GlobalID) {
6142 if (GlobalID < NUM_PREDEF_DECL_IDS)
6143 return GlobalID;
6144
6145 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6146 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6147 ModuleFile *Owner = I->second;
6148
6149 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6150 = M.GlobalToLocalDeclIDs.find(Owner);
6151 if (Pos == M.GlobalToLocalDeclIDs.end())
6152 return 0;
6153
6154 return GlobalID - Owner->BaseDeclID + Pos->second;
6155}
6156
6157serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6158 const RecordData &Record,
6159 unsigned &Idx) {
6160 if (Idx >= Record.size()) {
6161 Error("Corrupted AST file");
6162 return 0;
6163 }
6164
6165 return getGlobalDeclID(F, Record[Idx++]);
6166}
6167
6168/// \brief Resolve the offset of a statement into a statement.
6169///
6170/// This operation will read a new statement from the external
6171/// source each time it is called, and is meant to be used via a
6172/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6173Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6174 // Switch case IDs are per Decl.
6175 ClearSwitchCaseIDs();
6176
6177 // Offset here is a global offset across the entire chain.
6178 RecordLocation Loc = getLocalBitOffset(Offset);
6179 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6180 return ReadStmtFromStream(*Loc.F);
6181}
6182
Richard Smith3cb15722015-08-05 22:41:45 +00006183void ASTReader::FindExternalLexicalDecls(
6184 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6185 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006186 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6187
Richard Smith9ccdd932015-08-06 22:14:12 +00006188 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006189 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6190 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6191 auto K = (Decl::Kind)+LexicalDecls[I];
6192 if (!IsKindWeWant(K))
6193 continue;
6194
6195 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6196
6197 // Don't add predefined declarations to the lexical context more
6198 // than once.
6199 if (ID < NUM_PREDEF_DECL_IDS) {
6200 if (PredefsVisited[ID])
6201 continue;
6202
6203 PredefsVisited[ID] = true;
6204 }
6205
6206 if (Decl *D = GetLocalDecl(*M, ID)) {
6207 if (!DC->isDeclInLexicalTraversal(D))
6208 Decls.push_back(D);
6209 }
6210 }
6211 };
6212
6213 if (isa<TranslationUnitDecl>(DC)) {
6214 for (auto Lexical : TULexicalDecls)
6215 Visit(Lexical.first, Lexical.second);
6216 } else {
6217 auto I = LexicalDecls.find(DC);
6218 if (I != LexicalDecls.end())
6219 Visit(getOwningModuleFile(cast<Decl>(DC)), I->second);
6220 }
6221
Guy Benyei11169dd2012-12-18 14:30:41 +00006222 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006223}
6224
6225namespace {
6226
6227class DeclIDComp {
6228 ASTReader &Reader;
6229 ModuleFile &Mod;
6230
6231public:
6232 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6233
6234 bool operator()(LocalDeclID L, LocalDeclID R) const {
6235 SourceLocation LHS = getLocation(L);
6236 SourceLocation RHS = getLocation(R);
6237 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6238 }
6239
6240 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6241 SourceLocation RHS = getLocation(R);
6242 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6243 }
6244
6245 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6246 SourceLocation LHS = getLocation(L);
6247 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6248 }
6249
6250 SourceLocation getLocation(LocalDeclID ID) const {
6251 return Reader.getSourceManager().getFileLoc(
6252 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6253 }
6254};
6255
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006256}
Guy Benyei11169dd2012-12-18 14:30:41 +00006257
6258void ASTReader::FindFileRegionDecls(FileID File,
6259 unsigned Offset, unsigned Length,
6260 SmallVectorImpl<Decl *> &Decls) {
6261 SourceManager &SM = getSourceManager();
6262
6263 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6264 if (I == FileDeclIDs.end())
6265 return;
6266
6267 FileDeclsInfo &DInfo = I->second;
6268 if (DInfo.Decls.empty())
6269 return;
6270
6271 SourceLocation
6272 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6273 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6274
6275 DeclIDComp DIDComp(*this, *DInfo.Mod);
6276 ArrayRef<serialization::LocalDeclID>::iterator
6277 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6278 BeginLoc, DIDComp);
6279 if (BeginIt != DInfo.Decls.begin())
6280 --BeginIt;
6281
6282 // If we are pointing at a top-level decl inside an objc container, we need
6283 // to backtrack until we find it otherwise we will fail to report that the
6284 // region overlaps with an objc container.
6285 while (BeginIt != DInfo.Decls.begin() &&
6286 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6287 ->isTopLevelDeclInObjCContainer())
6288 --BeginIt;
6289
6290 ArrayRef<serialization::LocalDeclID>::iterator
6291 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6292 EndLoc, DIDComp);
6293 if (EndIt != DInfo.Decls.end())
6294 ++EndIt;
6295
6296 for (ArrayRef<serialization::LocalDeclID>::iterator
6297 DIt = BeginIt; DIt != EndIt; ++DIt)
6298 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6299}
6300
Richard Smith3b637412015-07-14 18:42:41 +00006301/// \brief Retrieve the "definitive" module file for the definition of the
6302/// given declaration context, if there is one.
6303///
6304/// The "definitive" module file is the only place where we need to look to
6305/// find information about the declarations within the given declaration
6306/// context. For example, C++ and Objective-C classes, C structs/unions, and
6307/// Objective-C protocols, categories, and extensions are all defined in a
6308/// single place in the source code, so they have definitive module files
6309/// associated with them. C++ namespaces, on the other hand, can have
6310/// definitions in multiple different module files.
6311///
6312/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6313/// NDEBUG checking.
6314static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6315 ASTReader &Reader) {
6316 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6317 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6318
6319 return nullptr;
6320}
6321
Guy Benyei11169dd2012-12-18 14:30:41 +00006322namespace {
6323 /// \brief ModuleFile visitor used to perform name lookup into a
6324 /// declaration context.
6325 class DeclContextNameLookupVisitor {
6326 ASTReader &Reader;
Richard Smithf13c68d2015-08-06 21:05:21 +00006327 const DeclContext *Context;
Guy Benyei11169dd2012-12-18 14:30:41 +00006328 DeclarationName Name;
Richard Smith3b637412015-07-14 18:42:41 +00006329 ASTDeclContextNameLookupTrait::DeclNameKey NameKey;
6330 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00006331 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006332 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006333
6334 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006335 DeclContextNameLookupVisitor(ASTReader &Reader,
Richard Smithf13c68d2015-08-06 21:05:21 +00006336 const DeclContext *Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00006337 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006338 SmallVectorImpl<NamedDecl *> &Decls,
6339 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
Richard Smithf13c68d2015-08-06 21:05:21 +00006340 : Reader(Reader), Context(Context), Name(Name),
Richard Smith3b637412015-07-14 18:42:41 +00006341 NameKey(ASTDeclContextNameLookupTrait::GetInternalKey(Name)),
6342 NameHash(ASTDeclContextNameLookupTrait::ComputeHash(NameKey)),
6343 Decls(Decls), DeclSet(DeclSet) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006344
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006345 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006346 // Check whether we have any visible declaration information for
6347 // this context in this module.
Richard Smithf13c68d2015-08-06 21:05:21 +00006348 auto Info = M.DeclContextInfos.find(Context);
6349 if (Info == M.DeclContextInfos.end() || !Info->second.NameLookupTableData)
Guy Benyei11169dd2012-12-18 14:30:41 +00006350 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006351
Guy Benyei11169dd2012-12-18 14:30:41 +00006352 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006353 ASTDeclContextNameLookupTable *LookupTable =
Richard Smithf13c68d2015-08-06 21:05:21 +00006354 Info->second.NameLookupTableData;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006355 ASTDeclContextNameLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00006356 LookupTable->find_hashed(NameKey, NameHash);
Guy Benyei11169dd2012-12-18 14:30:41 +00006357 if (Pos == LookupTable->end())
6358 return false;
6359
6360 bool FoundAnything = false;
6361 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6362 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006363 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006364 if (!ND)
6365 continue;
6366
Richard Smithbdf2d932015-07-30 03:37:16 +00006367 if (ND->getDeclName() != Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006368 // A name might be null because the decl's redeclarable part is
6369 // currently read before reading its name. The lookup is triggered by
6370 // building that decl (likely indirectly), and so it is later in the
6371 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006372 // FIXME: This should not happen; deserializing declarations should
6373 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006374 continue;
6375 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006376
Guy Benyei11169dd2012-12-18 14:30:41 +00006377 // Record this declaration.
6378 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006379 if (DeclSet.insert(ND).second)
6380 Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006381 }
6382
6383 return FoundAnything;
6384 }
6385 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006386}
Guy Benyei11169dd2012-12-18 14:30:41 +00006387
Richard Smith9ce12e32013-02-07 03:30:24 +00006388bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006389ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6390 DeclarationName Name) {
6391 assert(DC->hasExternalVisibleStorage() &&
6392 "DeclContext has no visible decls in storage");
6393 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006394 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006395
Richard Smith8c913ec2014-08-14 02:21:01 +00006396 Deserializing LookupResults(this);
6397
Guy Benyei11169dd2012-12-18 14:30:41 +00006398 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006399 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006400
Richard Smithf13c68d2015-08-06 21:05:21 +00006401 DeclContextNameLookupVisitor Visitor(*this, DC, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006402
Richard Smithf13c68d2015-08-06 21:05:21 +00006403 // If we can definitively determine which module file to look into,
6404 // only look there. Otherwise, look in all module files.
6405 if (ModuleFile *Definitive = getDefinitiveModuleFileFor(DC, *this))
6406 Visitor(*Definitive);
6407 else
6408 ModuleMgr.visit(Visitor);
Richard Smithcd45dbc2014-04-19 03:48:30 +00006409
Guy Benyei11169dd2012-12-18 14:30:41 +00006410 ++NumVisibleDeclContextsRead;
6411 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006412 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006413}
6414
6415namespace {
6416 /// \brief ModuleFile visitor used to retrieve all visible names in a
6417 /// declaration context.
6418 class DeclContextAllNamesVisitor {
6419 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006420 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006421 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006422 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006423 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006424
6425 public:
6426 DeclContextAllNamesVisitor(ASTReader &Reader,
6427 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006428 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006429 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006430
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006431 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006432 // Check whether we have any visible declaration information for
6433 // this context in this module.
6434 ModuleFile::DeclContextInfosMap::iterator Info;
6435 bool FoundInfo = false;
Richard Smithbdf2d932015-07-30 03:37:16 +00006436 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
6437 Info = M.DeclContextInfos.find(Contexts[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006438 if (Info != M.DeclContextInfos.end() &&
6439 Info->second.NameLookupTableData) {
6440 FoundInfo = true;
6441 break;
6442 }
6443 }
6444
6445 if (!FoundInfo)
6446 return false;
6447
Richard Smith52e3fba2014-03-11 07:17:35 +00006448 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006449 Info->second.NameLookupTableData;
6450 bool FoundAnything = false;
6451 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006452 I = LookupTable->data_begin(), E = LookupTable->data_end();
6453 I != E;
6454 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006455 ASTDeclContextNameLookupTrait::data_type Data = *I;
6456 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006457 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006458 if (!ND)
6459 continue;
6460
6461 // Record this declaration.
6462 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006463 if (DeclSet.insert(ND).second)
6464 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006465 }
6466 }
6467
Richard Smithbdf2d932015-07-30 03:37:16 +00006468 return FoundAnything && !VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006469 }
6470 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006471}
Guy Benyei11169dd2012-12-18 14:30:41 +00006472
6473void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6474 if (!DC->hasExternalVisibleStorage())
6475 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006476 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006477
6478 // Compute the declaration contexts we need to look into. Multiple such
6479 // declaration contexts occur when two declaration contexts from disjoint
6480 // modules get merged, e.g., when two namespaces with the same name are
6481 // independently defined in separate modules.
6482 SmallVector<const DeclContext *, 2> Contexts;
6483 Contexts.push_back(DC);
6484
6485 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006486 KeyDeclsMap::iterator Key =
6487 KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6488 if (Key != KeyDecls.end()) {
6489 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6490 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006491 }
6492 }
6493
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006494 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6495 /*VisitAll=*/DC->isFileContext());
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006496 ModuleMgr.visit(Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006497 ++NumVisibleDeclContextsRead;
6498
Craig Topper79be4cd2013-07-05 04:33:53 +00006499 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006500 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6501 }
6502 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6503}
6504
6505/// \brief Under non-PCH compilation the consumer receives the objc methods
6506/// before receiving the implementation, and codegen depends on this.
6507/// We simulate this by deserializing and passing to consumer the methods of the
6508/// implementation before passing the deserialized implementation decl.
6509static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6510 ASTConsumer *Consumer) {
6511 assert(ImplD && Consumer);
6512
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006513 for (auto *I : ImplD->methods())
6514 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006515
6516 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6517}
6518
6519void ASTReader::PassInterestingDeclsToConsumer() {
6520 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006521
6522 if (PassingDeclsToConsumer)
6523 return;
6524
6525 // Guard variable to avoid recursively redoing the process of passing
6526 // decls to consumer.
6527 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6528 true);
6529
Richard Smith9e2341d2015-03-23 03:25:59 +00006530 // Ensure that we've loaded all potentially-interesting declarations
6531 // that need to be eagerly loaded.
6532 for (auto ID : EagerlyDeserializedDecls)
6533 GetDecl(ID);
6534 EagerlyDeserializedDecls.clear();
6535
Guy Benyei11169dd2012-12-18 14:30:41 +00006536 while (!InterestingDecls.empty()) {
6537 Decl *D = InterestingDecls.front();
6538 InterestingDecls.pop_front();
6539
6540 PassInterestingDeclToConsumer(D);
6541 }
6542}
6543
6544void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6545 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6546 PassObjCImplDeclToConsumer(ImplD, Consumer);
6547 else
6548 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6549}
6550
6551void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6552 this->Consumer = Consumer;
6553
Richard Smith9e2341d2015-03-23 03:25:59 +00006554 if (Consumer)
6555 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006556
6557 if (DeserializationListener)
6558 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006559}
6560
6561void ASTReader::PrintStats() {
6562 std::fprintf(stderr, "*** AST File Statistics:\n");
6563
6564 unsigned NumTypesLoaded
6565 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6566 QualType());
6567 unsigned NumDeclsLoaded
6568 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006569 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006570 unsigned NumIdentifiersLoaded
6571 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6572 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006573 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006574 unsigned NumMacrosLoaded
6575 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6576 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006577 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006578 unsigned NumSelectorsLoaded
6579 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6580 SelectorsLoaded.end(),
6581 Selector());
6582
6583 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6584 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6585 NumSLocEntriesRead, TotalNumSLocEntries,
6586 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6587 if (!TypesLoaded.empty())
6588 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6589 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6590 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6591 if (!DeclsLoaded.empty())
6592 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6593 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6594 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6595 if (!IdentifiersLoaded.empty())
6596 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6597 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6598 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6599 if (!MacrosLoaded.empty())
6600 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6601 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6602 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6603 if (!SelectorsLoaded.empty())
6604 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6605 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6606 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6607 if (TotalNumStatements)
6608 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6609 NumStatementsRead, TotalNumStatements,
6610 ((float)NumStatementsRead/TotalNumStatements * 100));
6611 if (TotalNumMacros)
6612 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6613 NumMacrosRead, TotalNumMacros,
6614 ((float)NumMacrosRead/TotalNumMacros * 100));
6615 if (TotalLexicalDeclContexts)
6616 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6617 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6618 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6619 * 100));
6620 if (TotalVisibleDeclContexts)
6621 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6622 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6623 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6624 * 100));
6625 if (TotalNumMethodPoolEntries) {
6626 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6627 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6628 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6629 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006630 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006631 if (NumMethodPoolLookups) {
6632 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6633 NumMethodPoolHits, NumMethodPoolLookups,
6634 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6635 }
6636 if (NumMethodPoolTableLookups) {
6637 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6638 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6639 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6640 * 100.0));
6641 }
6642
Douglas Gregor00a50f72013-01-25 00:38:33 +00006643 if (NumIdentifierLookupHits) {
6644 std::fprintf(stderr,
6645 " %u / %u identifier table lookups succeeded (%f%%)\n",
6646 NumIdentifierLookupHits, NumIdentifierLookups,
6647 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6648 }
6649
Douglas Gregore060e572013-01-25 01:03:03 +00006650 if (GlobalIndex) {
6651 std::fprintf(stderr, "\n");
6652 GlobalIndex->printStats();
6653 }
6654
Guy Benyei11169dd2012-12-18 14:30:41 +00006655 std::fprintf(stderr, "\n");
6656 dump();
6657 std::fprintf(stderr, "\n");
6658}
6659
6660template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6661static void
6662dumpModuleIDMap(StringRef Name,
6663 const ContinuousRangeMap<Key, ModuleFile *,
6664 InitialCapacity> &Map) {
6665 if (Map.begin() == Map.end())
6666 return;
6667
6668 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6669 llvm::errs() << Name << ":\n";
6670 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6671 I != IEnd; ++I) {
6672 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6673 << "\n";
6674 }
6675}
6676
6677void ASTReader::dump() {
6678 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6679 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6680 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6681 dumpModuleIDMap("Global type map", GlobalTypeMap);
6682 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6683 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6684 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6685 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6686 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6687 dumpModuleIDMap("Global preprocessed entity map",
6688 GlobalPreprocessedEntityMap);
6689
6690 llvm::errs() << "\n*** PCH/Modules Loaded:";
6691 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6692 MEnd = ModuleMgr.end();
6693 M != MEnd; ++M)
6694 (*M)->dump();
6695}
6696
6697/// Return the amount of memory used by memory buffers, breaking down
6698/// by heap-backed versus mmap'ed memory.
6699void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6700 for (ModuleConstIterator I = ModuleMgr.begin(),
6701 E = ModuleMgr.end(); I != E; ++I) {
6702 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6703 size_t bytes = buf->getBufferSize();
6704 switch (buf->getBufferKind()) {
6705 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6706 sizes.malloc_bytes += bytes;
6707 break;
6708 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6709 sizes.mmap_bytes += bytes;
6710 break;
6711 }
6712 }
6713 }
6714}
6715
6716void ASTReader::InitializeSema(Sema &S) {
6717 SemaObj = &S;
6718 S.addExternalSource(this);
6719
6720 // Makes sure any declarations that were deserialized "too early"
6721 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006722 for (uint64_t ID : PreloadedDeclIDs) {
6723 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6724 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006725 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006726 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006727
Richard Smith3d8e97e2013-10-18 06:54:39 +00006728 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006729 if (!FPPragmaOptions.empty()) {
6730 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6731 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6732 }
6733
Richard Smith3d8e97e2013-10-18 06:54:39 +00006734 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006735 if (!OpenCLExtensions.empty()) {
6736 unsigned I = 0;
6737#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6738#include "clang/Basic/OpenCLExtensions.def"
6739
6740 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6741 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006742
6743 UpdateSema();
6744}
6745
6746void ASTReader::UpdateSema() {
6747 assert(SemaObj && "no Sema to update");
6748
6749 // Load the offsets of the declarations that Sema references.
6750 // They will be lazily deserialized when needed.
6751 if (!SemaDeclRefs.empty()) {
6752 assert(SemaDeclRefs.size() % 2 == 0);
6753 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6754 if (!SemaObj->StdNamespace)
6755 SemaObj->StdNamespace = SemaDeclRefs[I];
6756 if (!SemaObj->StdBadAlloc)
6757 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6758 }
6759 SemaDeclRefs.clear();
6760 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006761
6762 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6763 // encountered the pragma in the source.
6764 if(OptimizeOffPragmaLocation.isValid())
6765 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006766}
6767
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006768IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006769 // Note that we are loading an identifier.
6770 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006771
Douglas Gregor7211ac12013-01-25 23:32:03 +00006772 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006773 NumIdentifierLookups,
6774 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006775
6776 // We don't need to do identifier table lookups in C++ modules (we preload
6777 // all interesting declarations, and don't need to use the scope for name
6778 // lookups). Perform the lookup in PCH files, though, since we don't build
6779 // a complete initial identifier table if we're carrying on from a PCH.
6780 if (Context.getLangOpts().CPlusPlus) {
6781 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006782 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006783 break;
6784 } else {
6785 // If there is a global index, look there first to determine which modules
6786 // provably do not have any results for this identifier.
6787 GlobalModuleIndex::HitSet Hits;
6788 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6789 if (!loadGlobalIndex()) {
6790 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6791 HitsPtr = &Hits;
6792 }
6793 }
6794
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006795 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006796 }
6797
Guy Benyei11169dd2012-12-18 14:30:41 +00006798 IdentifierInfo *II = Visitor.getIdentifierInfo();
6799 markIdentifierUpToDate(II);
6800 return II;
6801}
6802
6803namespace clang {
6804 /// \brief An identifier-lookup iterator that enumerates all of the
6805 /// identifiers stored within a set of AST files.
6806 class ASTIdentifierIterator : public IdentifierIterator {
6807 /// \brief The AST reader whose identifiers are being enumerated.
6808 const ASTReader &Reader;
6809
6810 /// \brief The current index into the chain of AST files stored in
6811 /// the AST reader.
6812 unsigned Index;
6813
6814 /// \brief The current position within the identifier lookup table
6815 /// of the current AST file.
6816 ASTIdentifierLookupTable::key_iterator Current;
6817
6818 /// \brief The end position within the identifier lookup table of
6819 /// the current AST file.
6820 ASTIdentifierLookupTable::key_iterator End;
6821
6822 public:
6823 explicit ASTIdentifierIterator(const ASTReader &Reader);
6824
Craig Topper3e89dfe2014-03-13 02:13:41 +00006825 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006826 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006827}
Guy Benyei11169dd2012-12-18 14:30:41 +00006828
6829ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6830 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6831 ASTIdentifierLookupTable *IdTable
6832 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6833 Current = IdTable->key_begin();
6834 End = IdTable->key_end();
6835}
6836
6837StringRef ASTIdentifierIterator::Next() {
6838 while (Current == End) {
6839 // If we have exhausted all of our AST files, we're done.
6840 if (Index == 0)
6841 return StringRef();
6842
6843 --Index;
6844 ASTIdentifierLookupTable *IdTable
6845 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6846 IdentifierLookupTable;
6847 Current = IdTable->key_begin();
6848 End = IdTable->key_end();
6849 }
6850
6851 // We have any identifiers remaining in the current AST file; return
6852 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006853 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006854 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006855 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006856}
6857
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006858IdentifierIterator *ASTReader::getIdentifiers() {
6859 if (!loadGlobalIndex())
6860 return GlobalIndex->createIdentifierIterator();
6861
Guy Benyei11169dd2012-12-18 14:30:41 +00006862 return new ASTIdentifierIterator(*this);
6863}
6864
6865namespace clang { namespace serialization {
6866 class ReadMethodPoolVisitor {
6867 ASTReader &Reader;
6868 Selector Sel;
6869 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006870 unsigned InstanceBits;
6871 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006872 bool InstanceHasMoreThanOneDecl;
6873 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006874 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6875 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006876
6877 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006878 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006879 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006880 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006881 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6882 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006883
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006884 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006885 if (!M.SelectorLookupTable)
6886 return false;
6887
6888 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00006889 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00006890 return true;
6891
Richard Smithbdf2d932015-07-30 03:37:16 +00006892 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006893 ASTSelectorLookupTable *PoolTable
6894 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00006895 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00006896 if (Pos == PoolTable->end())
6897 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006898
Richard Smithbdf2d932015-07-30 03:37:16 +00006899 ++Reader.NumMethodPoolTableHits;
6900 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006901 // FIXME: Not quite happy with the statistics here. We probably should
6902 // disable this tracking when called via LoadSelector.
6903 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00006904 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006905 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00006906 if (Reader.DeserializationListener)
6907 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006908
Richard Smithbdf2d932015-07-30 03:37:16 +00006909 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6910 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6911 InstanceBits = Data.InstanceBits;
6912 FactoryBits = Data.FactoryBits;
6913 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6914 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006915 return true;
6916 }
6917
6918 /// \brief Retrieve the instance methods found by this visitor.
6919 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6920 return InstanceMethods;
6921 }
6922
6923 /// \brief Retrieve the instance methods found by this visitor.
6924 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6925 return FactoryMethods;
6926 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006927
6928 unsigned getInstanceBits() const { return InstanceBits; }
6929 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006930 bool instanceHasMoreThanOneDecl() const {
6931 return InstanceHasMoreThanOneDecl;
6932 }
6933 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006934 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006935} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00006936
6937/// \brief Add the given set of methods to the method list.
6938static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6939 ObjCMethodList &List) {
6940 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6941 S.addMethodToGlobalList(&List, Methods[I]);
6942 }
6943}
6944
6945void ASTReader::ReadMethodPool(Selector Sel) {
6946 // Get the selector generation and update it to the current generation.
6947 unsigned &Generation = SelectorGeneration[Sel];
6948 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00006949 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00006950
6951 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006952 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006953 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006954 ModuleMgr.visit(Visitor);
6955
Guy Benyei11169dd2012-12-18 14:30:41 +00006956 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006957 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006958 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006959
6960 ++NumMethodPoolHits;
6961
Guy Benyei11169dd2012-12-18 14:30:41 +00006962 if (!getSema())
6963 return;
6964
6965 Sema &S = *getSema();
6966 Sema::GlobalMethodPool::iterator Pos
6967 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00006968
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006969 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00006970 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006971 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00006972 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00006973
6974 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
6975 // when building a module we keep every method individually and may need to
6976 // update hasMoreThanOneDecl as we add the methods.
6977 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6978 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00006979}
6980
6981void ASTReader::ReadKnownNamespaces(
6982 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6983 Namespaces.clear();
6984
6985 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6986 if (NamespaceDecl *Namespace
6987 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6988 Namespaces.push_back(Namespace);
6989 }
6990}
6991
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006992void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00006993 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006994 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6995 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00006996 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006997 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00006998 Undefined.insert(std::make_pair(D, Loc));
6999 }
7000}
Nick Lewycky8334af82013-01-26 00:35:08 +00007001
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007002void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7003 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7004 Exprs) {
7005 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7006 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7007 uint64_t Count = DelayedDeleteExprs[Idx++];
7008 for (uint64_t C = 0; C < Count; ++C) {
7009 SourceLocation DeleteLoc =
7010 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7011 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7012 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7013 }
7014 }
7015}
7016
Guy Benyei11169dd2012-12-18 14:30:41 +00007017void ASTReader::ReadTentativeDefinitions(
7018 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7019 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7020 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7021 if (Var)
7022 TentativeDefs.push_back(Var);
7023 }
7024 TentativeDefinitions.clear();
7025}
7026
7027void ASTReader::ReadUnusedFileScopedDecls(
7028 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7029 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7030 DeclaratorDecl *D
7031 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7032 if (D)
7033 Decls.push_back(D);
7034 }
7035 UnusedFileScopedDecls.clear();
7036}
7037
7038void ASTReader::ReadDelegatingConstructors(
7039 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7040 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7041 CXXConstructorDecl *D
7042 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7043 if (D)
7044 Decls.push_back(D);
7045 }
7046 DelegatingCtorDecls.clear();
7047}
7048
7049void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7050 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7051 TypedefNameDecl *D
7052 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7053 if (D)
7054 Decls.push_back(D);
7055 }
7056 ExtVectorDecls.clear();
7057}
7058
Nico Weber72889432014-09-06 01:25:55 +00007059void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7060 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7061 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7062 ++I) {
7063 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7064 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7065 if (D)
7066 Decls.insert(D);
7067 }
7068 UnusedLocalTypedefNameCandidates.clear();
7069}
7070
Guy Benyei11169dd2012-12-18 14:30:41 +00007071void ASTReader::ReadReferencedSelectors(
7072 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7073 if (ReferencedSelectorsData.empty())
7074 return;
7075
7076 // If there are @selector references added them to its pool. This is for
7077 // implementation of -Wselector.
7078 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7079 unsigned I = 0;
7080 while (I < DataSize) {
7081 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7082 SourceLocation SelLoc
7083 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7084 Sels.push_back(std::make_pair(Sel, SelLoc));
7085 }
7086 ReferencedSelectorsData.clear();
7087}
7088
7089void ASTReader::ReadWeakUndeclaredIdentifiers(
7090 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7091 if (WeakUndeclaredIdentifiers.empty())
7092 return;
7093
7094 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7095 IdentifierInfo *WeakId
7096 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7097 IdentifierInfo *AliasId
7098 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7099 SourceLocation Loc
7100 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7101 bool Used = WeakUndeclaredIdentifiers[I++];
7102 WeakInfo WI(AliasId, Loc);
7103 WI.setUsed(Used);
7104 WeakIDs.push_back(std::make_pair(WeakId, WI));
7105 }
7106 WeakUndeclaredIdentifiers.clear();
7107}
7108
7109void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7110 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7111 ExternalVTableUse VT;
7112 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7113 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7114 VT.DefinitionRequired = VTableUses[Idx++];
7115 VTables.push_back(VT);
7116 }
7117
7118 VTableUses.clear();
7119}
7120
7121void ASTReader::ReadPendingInstantiations(
7122 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7123 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7124 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7125 SourceLocation Loc
7126 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7127
7128 Pending.push_back(std::make_pair(D, Loc));
7129 }
7130 PendingInstantiations.clear();
7131}
7132
Richard Smithe40f2ba2013-08-07 21:41:30 +00007133void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007134 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007135 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7136 /* In loop */) {
7137 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7138
7139 LateParsedTemplate *LT = new LateParsedTemplate;
7140 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7141
7142 ModuleFile *F = getOwningModuleFile(LT->D);
7143 assert(F && "No module");
7144
7145 unsigned TokN = LateParsedTemplates[Idx++];
7146 LT->Toks.reserve(TokN);
7147 for (unsigned T = 0; T < TokN; ++T)
7148 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7149
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007150 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007151 }
7152
7153 LateParsedTemplates.clear();
7154}
7155
Guy Benyei11169dd2012-12-18 14:30:41 +00007156void ASTReader::LoadSelector(Selector Sel) {
7157 // It would be complicated to avoid reading the methods anyway. So don't.
7158 ReadMethodPool(Sel);
7159}
7160
7161void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7162 assert(ID && "Non-zero identifier ID required");
7163 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7164 IdentifiersLoaded[ID - 1] = II;
7165 if (DeserializationListener)
7166 DeserializationListener->IdentifierRead(ID, II);
7167}
7168
7169/// \brief Set the globally-visible declarations associated with the given
7170/// identifier.
7171///
7172/// If the AST reader is currently in a state where the given declaration IDs
7173/// cannot safely be resolved, they are queued until it is safe to resolve
7174/// them.
7175///
7176/// \param II an IdentifierInfo that refers to one or more globally-visible
7177/// declarations.
7178///
7179/// \param DeclIDs the set of declaration IDs with the name @p II that are
7180/// visible at global scope.
7181///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007182/// \param Decls if non-null, this vector will be populated with the set of
7183/// deserialized declarations. These declarations will not be pushed into
7184/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007185void
7186ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7187 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007188 SmallVectorImpl<Decl *> *Decls) {
7189 if (NumCurrentElementsDeserializing && !Decls) {
7190 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007191 return;
7192 }
7193
7194 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007195 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007196 // Queue this declaration so that it will be added to the
7197 // translation unit scope and identifier's declaration chain
7198 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007199 PreloadedDeclIDs.push_back(DeclIDs[I]);
7200 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007201 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007202
7203 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7204
7205 // If we're simply supposed to record the declarations, do so now.
7206 if (Decls) {
7207 Decls->push_back(D);
7208 continue;
7209 }
7210
7211 // Introduce this declaration into the translation-unit scope
7212 // and add it to the declaration chain for this identifier, so
7213 // that (unqualified) name lookup will find it.
7214 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007215 }
7216}
7217
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007218IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007219 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007220 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007221
7222 if (IdentifiersLoaded.empty()) {
7223 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007224 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007225 }
7226
7227 ID -= 1;
7228 if (!IdentifiersLoaded[ID]) {
7229 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7230 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7231 ModuleFile *M = I->second;
7232 unsigned Index = ID - M->BaseIdentifierID;
7233 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7234
7235 // All of the strings in the AST file are preceded by a 16-bit length.
7236 // Extract that 16-bit length to avoid having to execute strlen().
7237 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7238 // unsigned integers. This is important to avoid integer overflow when
7239 // we cast them to 'unsigned'.
7240 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7241 unsigned StrLen = (((unsigned) StrLenPtr[0])
7242 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007243 IdentifiersLoaded[ID]
7244 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007245 if (DeserializationListener)
7246 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7247 }
7248
7249 return IdentifiersLoaded[ID];
7250}
7251
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007252IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7253 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007254}
7255
7256IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7257 if (LocalID < NUM_PREDEF_IDENT_IDS)
7258 return LocalID;
7259
7260 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7261 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7262 assert(I != M.IdentifierRemap.end()
7263 && "Invalid index into identifier index remap");
7264
7265 return LocalID + I->second;
7266}
7267
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007268MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007269 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007270 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007271
7272 if (MacrosLoaded.empty()) {
7273 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007274 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007275 }
7276
7277 ID -= NUM_PREDEF_MACRO_IDS;
7278 if (!MacrosLoaded[ID]) {
7279 GlobalMacroMapType::iterator I
7280 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7281 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7282 ModuleFile *M = I->second;
7283 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007284 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7285
7286 if (DeserializationListener)
7287 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7288 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007289 }
7290
7291 return MacrosLoaded[ID];
7292}
7293
7294MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7295 if (LocalID < NUM_PREDEF_MACRO_IDS)
7296 return LocalID;
7297
7298 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7299 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7300 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7301
7302 return LocalID + I->second;
7303}
7304
7305serialization::SubmoduleID
7306ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7307 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7308 return LocalID;
7309
7310 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7311 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7312 assert(I != M.SubmoduleRemap.end()
7313 && "Invalid index into submodule index remap");
7314
7315 return LocalID + I->second;
7316}
7317
7318Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7319 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7320 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007321 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007322 }
7323
7324 if (GlobalID > SubmodulesLoaded.size()) {
7325 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007326 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007327 }
7328
7329 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7330}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007331
7332Module *ASTReader::getModule(unsigned ID) {
7333 return getSubmodule(ID);
7334}
7335
Adrian Prantl15bcf702015-06-30 17:39:43 +00007336ExternalASTSource::ASTSourceDescriptor
7337ASTReader::getSourceDescriptor(const Module &M) {
7338 StringRef Dir, Filename;
7339 if (M.Directory)
7340 Dir = M.Directory->getName();
7341 if (auto *File = M.getASTFile())
7342 Filename = File->getName();
7343 return ASTReader::ASTSourceDescriptor{
7344 M.getFullModuleName(), Dir, Filename,
7345 M.Signature
7346 };
7347}
7348
7349llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7350ASTReader::getSourceDescriptor(unsigned ID) {
7351 if (const Module *M = getSubmodule(ID))
7352 return getSourceDescriptor(*M);
7353
7354 // If there is only a single PCH, return it instead.
7355 // Chained PCH are not suported.
7356 if (ModuleMgr.size() == 1) {
7357 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7358 return ASTReader::ASTSourceDescriptor{
7359 MF.OriginalSourceFileName, MF.OriginalDir,
7360 MF.FileName,
7361 MF.Signature
7362 };
7363 }
7364 return None;
7365}
7366
Guy Benyei11169dd2012-12-18 14:30:41 +00007367Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7368 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7369}
7370
7371Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7372 if (ID == 0)
7373 return Selector();
7374
7375 if (ID > SelectorsLoaded.size()) {
7376 Error("selector ID out of range in AST file");
7377 return Selector();
7378 }
7379
Craig Toppera13603a2014-05-22 05:54:18 +00007380 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007381 // Load this selector from the selector table.
7382 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7383 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7384 ModuleFile &M = *I->second;
7385 ASTSelectorLookupTrait Trait(*this, M);
7386 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7387 SelectorsLoaded[ID - 1] =
7388 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7389 if (DeserializationListener)
7390 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7391 }
7392
7393 return SelectorsLoaded[ID - 1];
7394}
7395
7396Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7397 return DecodeSelector(ID);
7398}
7399
7400uint32_t ASTReader::GetNumExternalSelectors() {
7401 // ID 0 (the null selector) is considered an external selector.
7402 return getTotalNumSelectors() + 1;
7403}
7404
7405serialization::SelectorID
7406ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7407 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7408 return LocalID;
7409
7410 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7411 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7412 assert(I != M.SelectorRemap.end()
7413 && "Invalid index into selector index remap");
7414
7415 return LocalID + I->second;
7416}
7417
7418DeclarationName
7419ASTReader::ReadDeclarationName(ModuleFile &F,
7420 const RecordData &Record, unsigned &Idx) {
7421 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7422 switch (Kind) {
7423 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007424 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007425
7426 case DeclarationName::ObjCZeroArgSelector:
7427 case DeclarationName::ObjCOneArgSelector:
7428 case DeclarationName::ObjCMultiArgSelector:
7429 return DeclarationName(ReadSelector(F, Record, Idx));
7430
7431 case DeclarationName::CXXConstructorName:
7432 return Context.DeclarationNames.getCXXConstructorName(
7433 Context.getCanonicalType(readType(F, Record, Idx)));
7434
7435 case DeclarationName::CXXDestructorName:
7436 return Context.DeclarationNames.getCXXDestructorName(
7437 Context.getCanonicalType(readType(F, Record, Idx)));
7438
7439 case DeclarationName::CXXConversionFunctionName:
7440 return Context.DeclarationNames.getCXXConversionFunctionName(
7441 Context.getCanonicalType(readType(F, Record, Idx)));
7442
7443 case DeclarationName::CXXOperatorName:
7444 return Context.DeclarationNames.getCXXOperatorName(
7445 (OverloadedOperatorKind)Record[Idx++]);
7446
7447 case DeclarationName::CXXLiteralOperatorName:
7448 return Context.DeclarationNames.getCXXLiteralOperatorName(
7449 GetIdentifierInfo(F, Record, Idx));
7450
7451 case DeclarationName::CXXUsingDirective:
7452 return DeclarationName::getUsingDirectiveName();
7453 }
7454
7455 llvm_unreachable("Invalid NameKind!");
7456}
7457
7458void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7459 DeclarationNameLoc &DNLoc,
7460 DeclarationName Name,
7461 const RecordData &Record, unsigned &Idx) {
7462 switch (Name.getNameKind()) {
7463 case DeclarationName::CXXConstructorName:
7464 case DeclarationName::CXXDestructorName:
7465 case DeclarationName::CXXConversionFunctionName:
7466 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7467 break;
7468
7469 case DeclarationName::CXXOperatorName:
7470 DNLoc.CXXOperatorName.BeginOpNameLoc
7471 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7472 DNLoc.CXXOperatorName.EndOpNameLoc
7473 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7474 break;
7475
7476 case DeclarationName::CXXLiteralOperatorName:
7477 DNLoc.CXXLiteralOperatorName.OpNameLoc
7478 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7479 break;
7480
7481 case DeclarationName::Identifier:
7482 case DeclarationName::ObjCZeroArgSelector:
7483 case DeclarationName::ObjCOneArgSelector:
7484 case DeclarationName::ObjCMultiArgSelector:
7485 case DeclarationName::CXXUsingDirective:
7486 break;
7487 }
7488}
7489
7490void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7491 DeclarationNameInfo &NameInfo,
7492 const RecordData &Record, unsigned &Idx) {
7493 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7494 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7495 DeclarationNameLoc DNLoc;
7496 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7497 NameInfo.setInfo(DNLoc);
7498}
7499
7500void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7501 const RecordData &Record, unsigned &Idx) {
7502 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7503 unsigned NumTPLists = Record[Idx++];
7504 Info.NumTemplParamLists = NumTPLists;
7505 if (NumTPLists) {
7506 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7507 for (unsigned i=0; i != NumTPLists; ++i)
7508 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7509 }
7510}
7511
7512TemplateName
7513ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7514 unsigned &Idx) {
7515 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7516 switch (Kind) {
7517 case TemplateName::Template:
7518 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7519
7520 case TemplateName::OverloadedTemplate: {
7521 unsigned size = Record[Idx++];
7522 UnresolvedSet<8> Decls;
7523 while (size--)
7524 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7525
7526 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7527 }
7528
7529 case TemplateName::QualifiedTemplate: {
7530 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7531 bool hasTemplKeyword = Record[Idx++];
7532 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7533 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7534 }
7535
7536 case TemplateName::DependentTemplate: {
7537 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7538 if (Record[Idx++]) // isIdentifier
7539 return Context.getDependentTemplateName(NNS,
7540 GetIdentifierInfo(F, Record,
7541 Idx));
7542 return Context.getDependentTemplateName(NNS,
7543 (OverloadedOperatorKind)Record[Idx++]);
7544 }
7545
7546 case TemplateName::SubstTemplateTemplateParm: {
7547 TemplateTemplateParmDecl *param
7548 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7549 if (!param) return TemplateName();
7550 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7551 return Context.getSubstTemplateTemplateParm(param, replacement);
7552 }
7553
7554 case TemplateName::SubstTemplateTemplateParmPack: {
7555 TemplateTemplateParmDecl *Param
7556 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7557 if (!Param)
7558 return TemplateName();
7559
7560 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7561 if (ArgPack.getKind() != TemplateArgument::Pack)
7562 return TemplateName();
7563
7564 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7565 }
7566 }
7567
7568 llvm_unreachable("Unhandled template name kind!");
7569}
7570
Richard Smith2bb3c342015-08-09 01:05:31 +00007571TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7572 const RecordData &Record,
7573 unsigned &Idx,
7574 bool Canonicalize) {
7575 if (Canonicalize) {
7576 // The caller wants a canonical template argument. Sometimes the AST only
7577 // wants template arguments in canonical form (particularly as the template
7578 // argument lists of template specializations) so ensure we preserve that
7579 // canonical form across serialization.
7580 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7581 return Context.getCanonicalTemplateArgument(Arg);
7582 }
7583
Guy Benyei11169dd2012-12-18 14:30:41 +00007584 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7585 switch (Kind) {
7586 case TemplateArgument::Null:
7587 return TemplateArgument();
7588 case TemplateArgument::Type:
7589 return TemplateArgument(readType(F, Record, Idx));
7590 case TemplateArgument::Declaration: {
7591 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007592 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007593 }
7594 case TemplateArgument::NullPtr:
7595 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7596 case TemplateArgument::Integral: {
7597 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7598 QualType T = readType(F, Record, Idx);
7599 return TemplateArgument(Context, Value, T);
7600 }
7601 case TemplateArgument::Template:
7602 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7603 case TemplateArgument::TemplateExpansion: {
7604 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007605 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007606 if (unsigned NumExpansions = Record[Idx++])
7607 NumTemplateExpansions = NumExpansions - 1;
7608 return TemplateArgument(Name, NumTemplateExpansions);
7609 }
7610 case TemplateArgument::Expression:
7611 return TemplateArgument(ReadExpr(F));
7612 case TemplateArgument::Pack: {
7613 unsigned NumArgs = Record[Idx++];
7614 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7615 for (unsigned I = 0; I != NumArgs; ++I)
7616 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007617 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007618 }
7619 }
7620
7621 llvm_unreachable("Unhandled template argument kind!");
7622}
7623
7624TemplateParameterList *
7625ASTReader::ReadTemplateParameterList(ModuleFile &F,
7626 const RecordData &Record, unsigned &Idx) {
7627 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7628 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7629 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7630
7631 unsigned NumParams = Record[Idx++];
7632 SmallVector<NamedDecl *, 16> Params;
7633 Params.reserve(NumParams);
7634 while (NumParams--)
7635 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7636
7637 TemplateParameterList* TemplateParams =
7638 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7639 Params.data(), Params.size(), RAngleLoc);
7640 return TemplateParams;
7641}
7642
7643void
7644ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007645ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007646 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007647 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007648 unsigned NumTemplateArgs = Record[Idx++];
7649 TemplArgs.reserve(NumTemplateArgs);
7650 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007651 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007652}
7653
7654/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007655void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007656 const RecordData &Record, unsigned &Idx) {
7657 unsigned NumDecls = Record[Idx++];
7658 Set.reserve(Context, NumDecls);
7659 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007660 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007661 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007662 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007663 }
7664}
7665
7666CXXBaseSpecifier
7667ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7668 const RecordData &Record, unsigned &Idx) {
7669 bool isVirtual = static_cast<bool>(Record[Idx++]);
7670 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7671 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7672 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7673 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7674 SourceRange Range = ReadSourceRange(F, Record, Idx);
7675 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7676 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7677 EllipsisLoc);
7678 Result.setInheritConstructors(inheritConstructors);
7679 return Result;
7680}
7681
Richard Smithc2bb8182015-03-24 06:36:48 +00007682CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007683ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7684 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007685 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007686 assert(NumInitializers && "wrote ctor initializers but have no inits");
7687 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7688 for (unsigned i = 0; i != NumInitializers; ++i) {
7689 TypeSourceInfo *TInfo = nullptr;
7690 bool IsBaseVirtual = false;
7691 FieldDecl *Member = nullptr;
7692 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007693
Richard Smithc2bb8182015-03-24 06:36:48 +00007694 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7695 switch (Type) {
7696 case CTOR_INITIALIZER_BASE:
7697 TInfo = GetTypeSourceInfo(F, Record, Idx);
7698 IsBaseVirtual = Record[Idx++];
7699 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007700
Richard Smithc2bb8182015-03-24 06:36:48 +00007701 case CTOR_INITIALIZER_DELEGATING:
7702 TInfo = GetTypeSourceInfo(F, Record, Idx);
7703 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007704
Richard Smithc2bb8182015-03-24 06:36:48 +00007705 case CTOR_INITIALIZER_MEMBER:
7706 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7707 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007708
Richard Smithc2bb8182015-03-24 06:36:48 +00007709 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7710 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7711 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007712 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007713
7714 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7715 Expr *Init = ReadExpr(F);
7716 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7717 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7718 bool IsWritten = Record[Idx++];
7719 unsigned SourceOrderOrNumArrayIndices;
7720 SmallVector<VarDecl *, 8> Indices;
7721 if (IsWritten) {
7722 SourceOrderOrNumArrayIndices = Record[Idx++];
7723 } else {
7724 SourceOrderOrNumArrayIndices = Record[Idx++];
7725 Indices.reserve(SourceOrderOrNumArrayIndices);
7726 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7727 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7728 }
7729
7730 CXXCtorInitializer *BOMInit;
7731 if (Type == CTOR_INITIALIZER_BASE) {
7732 BOMInit = new (Context)
7733 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7734 RParenLoc, MemberOrEllipsisLoc);
7735 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7736 BOMInit = new (Context)
7737 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7738 } else if (IsWritten) {
7739 if (Member)
7740 BOMInit = new (Context) CXXCtorInitializer(
7741 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7742 else
7743 BOMInit = new (Context)
7744 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7745 LParenLoc, Init, RParenLoc);
7746 } else {
7747 if (IndirectMember) {
7748 assert(Indices.empty() && "Indirect field improperly initialized");
7749 BOMInit = new (Context)
7750 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7751 LParenLoc, Init, RParenLoc);
7752 } else {
7753 BOMInit = CXXCtorInitializer::Create(
7754 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7755 Indices.data(), Indices.size());
7756 }
7757 }
7758
7759 if (IsWritten)
7760 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7761 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007762 }
7763
Richard Smithc2bb8182015-03-24 06:36:48 +00007764 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007765}
7766
7767NestedNameSpecifier *
7768ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7769 const RecordData &Record, unsigned &Idx) {
7770 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007771 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007772 for (unsigned I = 0; I != N; ++I) {
7773 NestedNameSpecifier::SpecifierKind Kind
7774 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7775 switch (Kind) {
7776 case NestedNameSpecifier::Identifier: {
7777 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7778 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7779 break;
7780 }
7781
7782 case NestedNameSpecifier::Namespace: {
7783 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7784 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7785 break;
7786 }
7787
7788 case NestedNameSpecifier::NamespaceAlias: {
7789 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7790 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7791 break;
7792 }
7793
7794 case NestedNameSpecifier::TypeSpec:
7795 case NestedNameSpecifier::TypeSpecWithTemplate: {
7796 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7797 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007798 return nullptr;
7799
Guy Benyei11169dd2012-12-18 14:30:41 +00007800 bool Template = Record[Idx++];
7801 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7802 break;
7803 }
7804
7805 case NestedNameSpecifier::Global: {
7806 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7807 // No associated value, and there can't be a prefix.
7808 break;
7809 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007810
7811 case NestedNameSpecifier::Super: {
7812 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7813 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7814 break;
7815 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007816 }
7817 Prev = NNS;
7818 }
7819 return NNS;
7820}
7821
7822NestedNameSpecifierLoc
7823ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7824 unsigned &Idx) {
7825 unsigned N = Record[Idx++];
7826 NestedNameSpecifierLocBuilder Builder;
7827 for (unsigned I = 0; I != N; ++I) {
7828 NestedNameSpecifier::SpecifierKind Kind
7829 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7830 switch (Kind) {
7831 case NestedNameSpecifier::Identifier: {
7832 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7833 SourceRange Range = ReadSourceRange(F, Record, Idx);
7834 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7835 break;
7836 }
7837
7838 case NestedNameSpecifier::Namespace: {
7839 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7840 SourceRange Range = ReadSourceRange(F, Record, Idx);
7841 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7842 break;
7843 }
7844
7845 case NestedNameSpecifier::NamespaceAlias: {
7846 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7847 SourceRange Range = ReadSourceRange(F, Record, Idx);
7848 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7849 break;
7850 }
7851
7852 case NestedNameSpecifier::TypeSpec:
7853 case NestedNameSpecifier::TypeSpecWithTemplate: {
7854 bool Template = Record[Idx++];
7855 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7856 if (!T)
7857 return NestedNameSpecifierLoc();
7858 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7859
7860 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7861 Builder.Extend(Context,
7862 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7863 T->getTypeLoc(), ColonColonLoc);
7864 break;
7865 }
7866
7867 case NestedNameSpecifier::Global: {
7868 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7869 Builder.MakeGlobal(Context, ColonColonLoc);
7870 break;
7871 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007872
7873 case NestedNameSpecifier::Super: {
7874 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7875 SourceRange Range = ReadSourceRange(F, Record, Idx);
7876 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7877 break;
7878 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007879 }
7880 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007881
Guy Benyei11169dd2012-12-18 14:30:41 +00007882 return Builder.getWithLocInContext(Context);
7883}
7884
7885SourceRange
7886ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7887 unsigned &Idx) {
7888 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7889 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7890 return SourceRange(beg, end);
7891}
7892
7893/// \brief Read an integral value
7894llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7895 unsigned BitWidth = Record[Idx++];
7896 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7897 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7898 Idx += NumWords;
7899 return Result;
7900}
7901
7902/// \brief Read a signed integral value
7903llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7904 bool isUnsigned = Record[Idx++];
7905 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7906}
7907
7908/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007909llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7910 const llvm::fltSemantics &Sem,
7911 unsigned &Idx) {
7912 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007913}
7914
7915// \brief Read a string
7916std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7917 unsigned Len = Record[Idx++];
7918 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7919 Idx += Len;
7920 return Result;
7921}
7922
Richard Smith7ed1bc92014-12-05 22:42:13 +00007923std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7924 unsigned &Idx) {
7925 std::string Filename = ReadString(Record, Idx);
7926 ResolveImportedPath(F, Filename);
7927 return Filename;
7928}
7929
Guy Benyei11169dd2012-12-18 14:30:41 +00007930VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7931 unsigned &Idx) {
7932 unsigned Major = Record[Idx++];
7933 unsigned Minor = Record[Idx++];
7934 unsigned Subminor = Record[Idx++];
7935 if (Minor == 0)
7936 return VersionTuple(Major);
7937 if (Subminor == 0)
7938 return VersionTuple(Major, Minor - 1);
7939 return VersionTuple(Major, Minor - 1, Subminor - 1);
7940}
7941
7942CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7943 const RecordData &Record,
7944 unsigned &Idx) {
7945 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7946 return CXXTemporary::Create(Context, Decl);
7947}
7948
7949DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007950 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007951}
7952
7953DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7954 return Diags.Report(Loc, DiagID);
7955}
7956
7957/// \brief Retrieve the identifier table associated with the
7958/// preprocessor.
7959IdentifierTable &ASTReader::getIdentifierTable() {
7960 return PP.getIdentifierTable();
7961}
7962
7963/// \brief Record that the given ID maps to the given switch-case
7964/// statement.
7965void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007966 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007967 "Already have a SwitchCase with this ID");
7968 (*CurrSwitchCaseStmts)[ID] = SC;
7969}
7970
7971/// \brief Retrieve the switch-case statement with the given ID.
7972SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007973 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00007974 return (*CurrSwitchCaseStmts)[ID];
7975}
7976
7977void ASTReader::ClearSwitchCaseIDs() {
7978 CurrSwitchCaseStmts->clear();
7979}
7980
7981void ASTReader::ReadComments() {
7982 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007983 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007984 serialization::ModuleFile *> >::iterator
7985 I = CommentsCursors.begin(),
7986 E = CommentsCursors.end();
7987 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007988 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007989 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007990 serialization::ModuleFile &F = *I->second;
7991 SavedStreamPosition SavedPosition(Cursor);
7992
7993 RecordData Record;
7994 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007995 llvm::BitstreamEntry Entry =
7996 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007997
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007998 switch (Entry.Kind) {
7999 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8000 case llvm::BitstreamEntry::Error:
8001 Error("malformed block record in AST file");
8002 return;
8003 case llvm::BitstreamEntry::EndBlock:
8004 goto NextCursor;
8005 case llvm::BitstreamEntry::Record:
8006 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008007 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008008 }
8009
8010 // Read a record.
8011 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008012 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008013 case COMMENTS_RAW_COMMENT: {
8014 unsigned Idx = 0;
8015 SourceRange SR = ReadSourceRange(F, Record, Idx);
8016 RawComment::CommentKind Kind =
8017 (RawComment::CommentKind) Record[Idx++];
8018 bool IsTrailingComment = Record[Idx++];
8019 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008020 Comments.push_back(new (Context) RawComment(
8021 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8022 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008023 break;
8024 }
8025 }
8026 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008027 NextCursor:
8028 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008029 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008030}
8031
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008032void ASTReader::getInputFiles(ModuleFile &F,
8033 SmallVectorImpl<serialization::InputFile> &Files) {
8034 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8035 unsigned ID = I+1;
8036 Files.push_back(getInputFile(F, ID));
8037 }
8038}
8039
Richard Smithcd45dbc2014-04-19 03:48:30 +00008040std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8041 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008042 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008043 return M->getFullModuleName();
8044
8045 // Otherwise, use the name of the top-level module the decl is within.
8046 if (ModuleFile *M = getOwningModuleFile(D))
8047 return M->ModuleName;
8048
8049 // Not from a module.
8050 return "";
8051}
8052
Guy Benyei11169dd2012-12-18 14:30:41 +00008053void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008054 while (!PendingIdentifierInfos.empty() ||
8055 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008056 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008057 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008058 // If any identifiers with corresponding top-level declarations have
8059 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008060 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8061 TopLevelDeclsMap;
8062 TopLevelDeclsMap TopLevelDecls;
8063
Guy Benyei11169dd2012-12-18 14:30:41 +00008064 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008065 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008066 SmallVector<uint32_t, 4> DeclIDs =
8067 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008068 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008069
8070 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008071 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008072
Richard Smith851072e2014-05-19 20:59:20 +00008073 // For each decl chain that we wanted to complete while deserializing, mark
8074 // it as "still needs to be completed".
8075 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8076 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8077 }
8078 PendingIncompleteDeclChains.clear();
8079
Guy Benyei11169dd2012-12-18 14:30:41 +00008080 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008081 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008082 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008083 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008084 }
8085 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008086 PendingDeclChains.clear();
8087
Richard Smith9b88a4c2015-07-27 05:40:23 +00008088 assert(RedeclsDeserialized.empty() && "some redecls not wired up");
8089
Douglas Gregor6168bd22013-02-18 15:53:43 +00008090 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008091 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8092 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008093 IdentifierInfo *II = TLD->first;
8094 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008095 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008096 }
8097 }
8098
Guy Benyei11169dd2012-12-18 14:30:41 +00008099 // Load any pending macro definitions.
8100 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008101 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8102 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8103 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8104 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008105 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008106 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008107 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008108 if (Info.M->Kind != MK_ImplicitModule &&
8109 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008110 resolvePendingMacro(II, Info);
8111 }
8112 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008113 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008114 ++IDIdx) {
8115 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008116 if (Info.M->Kind == MK_ImplicitModule ||
8117 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008118 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008119 }
8120 }
8121 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008122
8123 // Wire up the DeclContexts for Decls that we delayed setting until
8124 // recursive loading is completed.
8125 while (!PendingDeclContextInfos.empty()) {
8126 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8127 PendingDeclContextInfos.pop_front();
8128 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8129 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8130 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8131 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008132
Richard Smithd1c46742014-04-30 02:24:17 +00008133 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008134 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008135 auto Update = PendingUpdateRecords.pop_back_val();
8136 ReadingKindTracker ReadingKind(Read_Decl, *this);
8137 loadDeclUpdateRecords(Update.first, Update.second);
8138 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008139 }
Richard Smith8a639892015-01-24 01:07:20 +00008140
8141 // At this point, all update records for loaded decls are in place, so any
8142 // fake class definitions should have become real.
8143 assert(PendingFakeDefinitionData.empty() &&
8144 "faked up a class definition but never saw the real one");
8145
Guy Benyei11169dd2012-12-18 14:30:41 +00008146 // If we deserialized any C++ or Objective-C class definitions, any
8147 // Objective-C protocol definitions, or any redeclarable templates, make sure
8148 // that all redeclarations point to the definitions. Note that this can only
8149 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008150 for (Decl *D : PendingDefinitions) {
8151 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008152 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008153 // Make sure that the TagType points at the definition.
8154 const_cast<TagType*>(TagT)->decl = TD;
8155 }
Richard Smith8ce51082015-03-11 01:44:51 +00008156
Craig Topperc6914d02014-08-25 04:15:02 +00008157 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008158 for (auto *R = getMostRecentExistingDecl(RD); R;
8159 R = R->getPreviousDecl()) {
8160 assert((R == D) ==
8161 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008162 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008163 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008164 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008165 }
8166
8167 continue;
8168 }
Richard Smith8ce51082015-03-11 01:44:51 +00008169
Craig Topperc6914d02014-08-25 04:15:02 +00008170 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008171 // Make sure that the ObjCInterfaceType points at the definition.
8172 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8173 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008174
8175 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8176 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8177
Guy Benyei11169dd2012-12-18 14:30:41 +00008178 continue;
8179 }
Richard Smith8ce51082015-03-11 01:44:51 +00008180
Craig Topperc6914d02014-08-25 04:15:02 +00008181 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008182 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8183 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8184
Guy Benyei11169dd2012-12-18 14:30:41 +00008185 continue;
8186 }
Richard Smith8ce51082015-03-11 01:44:51 +00008187
Craig Topperc6914d02014-08-25 04:15:02 +00008188 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008189 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8190 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008191 }
8192 PendingDefinitions.clear();
8193
8194 // Load the bodies of any functions or methods we've encountered. We do
8195 // this now (delayed) so that we can be sure that the declaration chains
8196 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008197 // FIXME: There seems to be no point in delaying this, it does not depend
8198 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008199 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8200 PBEnd = PendingBodies.end();
8201 PB != PBEnd; ++PB) {
8202 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8203 // FIXME: Check for =delete/=default?
8204 // FIXME: Complain about ODR violations here?
8205 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8206 FD->setLazyBody(PB->second);
8207 continue;
8208 }
8209
8210 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8211 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8212 MD->setLazyBody(PB->second);
8213 }
8214 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008215
8216 // Do some cleanup.
8217 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8218 getContext().deduplicateMergedDefinitonsFor(ND);
8219 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008220}
8221
8222void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008223 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8224 return;
8225
Richard Smitha0ce9c42014-07-29 23:23:27 +00008226 // Trigger the import of the full definition of each class that had any
8227 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008228 // These updates may in turn find and diagnose some ODR failures, so take
8229 // ownership of the set first.
8230 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8231 PendingOdrMergeFailures.clear();
8232 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008233 Merge.first->buildLookup();
8234 Merge.first->decls_begin();
8235 Merge.first->bases_begin();
8236 Merge.first->vbases_begin();
8237 for (auto *RD : Merge.second) {
8238 RD->decls_begin();
8239 RD->bases_begin();
8240 RD->vbases_begin();
8241 }
8242 }
8243
8244 // For each declaration from a merged context, check that the canonical
8245 // definition of that context also contains a declaration of the same
8246 // entity.
8247 //
8248 // Caution: this loop does things that might invalidate iterators into
8249 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8250 while (!PendingOdrMergeChecks.empty()) {
8251 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8252
8253 // FIXME: Skip over implicit declarations for now. This matters for things
8254 // like implicitly-declared special member functions. This isn't entirely
8255 // correct; we can end up with multiple unmerged declarations of the same
8256 // implicit entity.
8257 if (D->isImplicit())
8258 continue;
8259
8260 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008261
8262 bool Found = false;
8263 const Decl *DCanon = D->getCanonicalDecl();
8264
Richard Smith01bdb7a2014-08-28 05:44:07 +00008265 for (auto RI : D->redecls()) {
8266 if (RI->getLexicalDeclContext() == CanonDef) {
8267 Found = true;
8268 break;
8269 }
8270 }
8271 if (Found)
8272 continue;
8273
Richard Smith0f4e2c42015-08-06 04:23:48 +00008274 // Quick check failed, time to do the slow thing. Note, we can't just
8275 // look up the name of D in CanonDef here, because the member that is
8276 // in CanonDef might not be found by name lookup (it might have been
8277 // replaced by a more recent declaration in the lookup table), and we
8278 // can't necessarily find it in the redeclaration chain because it might
8279 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008280 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008281 for (auto *CanonMember : CanonDef->decls()) {
8282 if (CanonMember->getCanonicalDecl() == DCanon) {
8283 // This can happen if the declaration is merely mergeable and not
8284 // actually redeclarable (we looked for redeclarations earlier).
8285 //
8286 // FIXME: We should be able to detect this more efficiently, without
8287 // pulling in all of the members of CanonDef.
8288 Found = true;
8289 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008290 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008291 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8292 if (ND->getDeclName() == D->getDeclName())
8293 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008294 }
8295
8296 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008297 // The AST doesn't like TagDecls becoming invalid after they've been
8298 // completed. We only really need to mark FieldDecls as invalid here.
8299 if (!isa<TagDecl>(D))
8300 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008301
8302 // Ensure we don't accidentally recursively enter deserialization while
8303 // we're producing our diagnostic.
8304 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008305
8306 std::string CanonDefModule =
8307 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8308 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8309 << D << getOwningModuleNameForDiagnostic(D)
8310 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8311
8312 if (Candidates.empty())
8313 Diag(cast<Decl>(CanonDef)->getLocation(),
8314 diag::note_module_odr_violation_no_possible_decls) << D;
8315 else {
8316 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8317 Diag(Candidates[I]->getLocation(),
8318 diag::note_module_odr_violation_possible_decl)
8319 << Candidates[I];
8320 }
8321
8322 DiagnosedOdrMergeFailures.insert(CanonDef);
8323 }
8324 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008325
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008326 if (OdrMergeFailures.empty())
8327 return;
8328
8329 // Ensure we don't accidentally recursively enter deserialization while
8330 // we're producing our diagnostics.
8331 Deserializing RecursionGuard(this);
8332
Richard Smithcd45dbc2014-04-19 03:48:30 +00008333 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008334 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008335 // If we've already pointed out a specific problem with this class, don't
8336 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008337 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008338 continue;
8339
8340 bool Diagnosed = false;
8341 for (auto *RD : Merge.second) {
8342 // Multiple different declarations got merged together; tell the user
8343 // where they came from.
8344 if (Merge.first != RD) {
8345 // FIXME: Walk the definition, figure out what's different,
8346 // and diagnose that.
8347 if (!Diagnosed) {
8348 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8349 Diag(Merge.first->getLocation(),
8350 diag::err_module_odr_violation_different_definitions)
8351 << Merge.first << Module.empty() << Module;
8352 Diagnosed = true;
8353 }
8354
8355 Diag(RD->getLocation(),
8356 diag::note_module_odr_violation_different_definitions)
8357 << getOwningModuleNameForDiagnostic(RD);
8358 }
8359 }
8360
8361 if (!Diagnosed) {
8362 // All definitions are updates to the same declaration. This happens if a
8363 // module instantiates the declaration of a class template specialization
8364 // and two or more other modules instantiate its definition.
8365 //
8366 // FIXME: Indicate which modules had instantiations of this definition.
8367 // FIXME: How can this even happen?
8368 Diag(Merge.first->getLocation(),
8369 diag::err_module_odr_violation_different_instantiations)
8370 << Merge.first;
8371 }
8372 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008373}
8374
Richard Smithce18a182015-07-14 00:26:00 +00008375void ASTReader::StartedDeserializing() {
8376 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8377 ReadTimer->startTimer();
8378}
8379
Guy Benyei11169dd2012-12-18 14:30:41 +00008380void ASTReader::FinishedDeserializing() {
8381 assert(NumCurrentElementsDeserializing &&
8382 "FinishedDeserializing not paired with StartedDeserializing");
8383 if (NumCurrentElementsDeserializing == 1) {
8384 // We decrease NumCurrentElementsDeserializing only after pending actions
8385 // are finished, to avoid recursively re-calling finishPendingActions().
8386 finishPendingActions();
8387 }
8388 --NumCurrentElementsDeserializing;
8389
Richard Smitha0ce9c42014-07-29 23:23:27 +00008390 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008391 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008392 while (!PendingExceptionSpecUpdates.empty()) {
8393 auto Updates = std::move(PendingExceptionSpecUpdates);
8394 PendingExceptionSpecUpdates.clear();
8395 for (auto Update : Updates) {
8396 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8397 SemaObj->UpdateExceptionSpec(Update.second,
8398 FPT->getExtProtoInfo().ExceptionSpec);
8399 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008400 }
8401
Richard Smithce18a182015-07-14 00:26:00 +00008402 if (ReadTimer)
8403 ReadTimer->stopTimer();
8404
Richard Smith0f4e2c42015-08-06 04:23:48 +00008405 diagnoseOdrViolations();
8406
Richard Smith04d05b52014-03-23 00:27:18 +00008407 // We are not in recursive loading, so it's safe to pass the "interesting"
8408 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008409 if (Consumer)
8410 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008411 }
8412}
8413
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008414void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008415 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8416 // Remove any fake results before adding any real ones.
8417 auto It = PendingFakeLookupResults.find(II);
8418 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008419 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008420 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008421 // FIXME: this works around module+PCH performance issue.
8422 // Rather than erase the result from the map, which is O(n), just clear
8423 // the vector of NamedDecls.
8424 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008425 }
8426 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008427
8428 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8429 SemaObj->TUScope->AddDecl(D);
8430 } else if (SemaObj->TUScope) {
8431 // Adding the decl to IdResolver may have failed because it was already in
8432 // (even though it was not added in scope). If it is already in, make sure
8433 // it gets in the scope as well.
8434 if (std::find(SemaObj->IdResolver.begin(Name),
8435 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8436 SemaObj->TUScope->AddDecl(D);
8437 }
8438}
8439
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008440ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008441 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008442 StringRef isysroot, bool DisableValidation,
8443 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008444 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Richard Smithce18a182015-07-14 00:26:00 +00008445 bool UseGlobalIndex,
8446 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008447 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008448 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008449 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008450 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008451 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008452 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008453 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008454 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8455 AllowConfigurationMismatch(AllowConfigurationMismatch),
8456 ValidateSystemInputs(ValidateSystemInputs),
8457 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008458 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8459 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8460 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8461 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008462 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8463 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8464 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8465 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8466 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8467 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008468 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008469 SourceMgr.setExternalSLocEntrySource(this);
8470}
8471
8472ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008473 if (OwnsDeserializationListener)
8474 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008475}