blob: bf3f830e795a6e0a9259e0a10f18004169b8a324 [file] [log] [blame]
Richard Smith9e2341d2015-03-23 03:25:59 +00001//===-- ASTReader.cpp - AST File Reader ----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
Adrian Prantlbb165fb2015-06-20 18:53:08 +000022#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000023#include "clang/AST/NestedNameSpecifier.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000026#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/SourceManagerInternals.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Basic/TargetOptions.h"
32#include "clang/Basic/Version.h"
33#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000034#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/HeaderSearchOptions.h"
37#include "clang/Lex/MacroInfo.h"
38#include "clang/Lex/PreprocessingRecord.h"
39#include "clang/Lex/Preprocessor.h"
40#include "clang/Lex/PreprocessorOptions.h"
41#include "clang/Sema/Scope.h"
42#include "clang/Sema/Sema.h"
43#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000044#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000045#include "clang/Serialization/ModuleManager.h"
46#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000047#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "llvm/ADT/StringExtras.h"
49#include "llvm/Bitcode/BitstreamReader.h"
50#include "llvm/Support/ErrorHandling.h"
51#include "llvm/Support/FileSystem.h"
52#include "llvm/Support/MemoryBuffer.h"
53#include "llvm/Support/Path.h"
54#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000055#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000056#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000057#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000058#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000059#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000060
61using namespace clang;
62using namespace clang::serialization;
63using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000064using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000065
Ben Langmuircb69b572014-03-07 06:40:32 +000066
67//===----------------------------------------------------------------------===//
68// ChainedASTReaderListener implementation
69//===----------------------------------------------------------------------===//
70
71bool
72ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
73 return First->ReadFullVersionInformation(FullVersion) ||
74 Second->ReadFullVersionInformation(FullVersion);
75}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000076void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
77 First->ReadModuleName(ModuleName);
78 Second->ReadModuleName(ModuleName);
79}
80void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
81 First->ReadModuleMapFile(ModuleMapPath);
82 Second->ReadModuleMapFile(ModuleMapPath);
83}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000084bool
85ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
86 bool Complain,
87 bool AllowCompatibleDifferences) {
88 return First->ReadLanguageOptions(LangOpts, Complain,
89 AllowCompatibleDifferences) ||
90 Second->ReadLanguageOptions(LangOpts, Complain,
91 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000092}
Chandler Carruth0d745bc2015-03-14 04:47:43 +000093bool ChainedASTReaderListener::ReadTargetOptions(
94 const TargetOptions &TargetOpts, bool Complain,
95 bool AllowCompatibleDifferences) {
96 return First->ReadTargetOptions(TargetOpts, Complain,
97 AllowCompatibleDifferences) ||
98 Second->ReadTargetOptions(TargetOpts, Complain,
99 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000100}
101bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000102 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000103 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
104 Second->ReadDiagnosticOptions(DiagOpts, Complain);
105}
106bool
107ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
108 bool Complain) {
109 return First->ReadFileSystemOptions(FSOpts, Complain) ||
110 Second->ReadFileSystemOptions(FSOpts, Complain);
111}
112
113bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000114 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
115 bool Complain) {
116 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
117 Complain) ||
118 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
119 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000120}
121bool ChainedASTReaderListener::ReadPreprocessorOptions(
122 const PreprocessorOptions &PPOpts, bool Complain,
123 std::string &SuggestedPredefines) {
124 return First->ReadPreprocessorOptions(PPOpts, Complain,
125 SuggestedPredefines) ||
126 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
127}
128void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
129 unsigned Value) {
130 First->ReadCounter(M, Value);
131 Second->ReadCounter(M, Value);
132}
133bool ChainedASTReaderListener::needsInputFileVisitation() {
134 return First->needsInputFileVisitation() ||
135 Second->needsInputFileVisitation();
136}
137bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
138 return First->needsSystemInputFileVisitation() ||
139 Second->needsSystemInputFileVisitation();
140}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000141void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
142 First->visitModuleFile(Filename);
143 Second->visitModuleFile(Filename);
144}
Ben Langmuircb69b572014-03-07 06:40:32 +0000145bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000146 bool isSystem,
147 bool isOverridden) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000148 bool Continue = false;
149 if (First->needsInputFileVisitation() &&
150 (!isSystem || First->needsSystemInputFileVisitation()))
151 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
152 if (Second->needsInputFileVisitation() &&
153 (!isSystem || Second->needsSystemInputFileVisitation()))
154 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
155 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000156}
157
Guy Benyei11169dd2012-12-18 14:30:41 +0000158//===----------------------------------------------------------------------===//
159// PCH validator implementation
160//===----------------------------------------------------------------------===//
161
162ASTReaderListener::~ASTReaderListener() {}
163
164/// \brief Compare the given set of language options against an existing set of
165/// language options.
166///
167/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000168/// \param AllowCompatibleDifferences If true, differences between compatible
169/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000170///
171/// \returns true if the languagae options mis-match, false otherwise.
172static bool checkLanguageOptions(const LangOptions &LangOpts,
173 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000174 DiagnosticsEngine *Diags,
175 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000176#define LANGOPT(Name, Bits, Default, Description) \
177 if (ExistingLangOpts.Name != LangOpts.Name) { \
178 if (Diags) \
179 Diags->Report(diag::err_pch_langopt_mismatch) \
180 << Description << LangOpts.Name << ExistingLangOpts.Name; \
181 return true; \
182 }
183
184#define VALUE_LANGOPT(Name, Bits, Default, Description) \
185 if (ExistingLangOpts.Name != LangOpts.Name) { \
186 if (Diags) \
187 Diags->Report(diag::err_pch_langopt_value_mismatch) \
188 << Description; \
189 return true; \
190 }
191
192#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
193 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
194 if (Diags) \
195 Diags->Report(diag::err_pch_langopt_value_mismatch) \
196 << Description; \
197 return true; \
198 }
199
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000200#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
201 if (!AllowCompatibleDifferences) \
202 LANGOPT(Name, Bits, Default, Description)
203
204#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
205 if (!AllowCompatibleDifferences) \
206 ENUM_LANGOPT(Name, Bits, Default, Description)
207
Guy Benyei11169dd2012-12-18 14:30:41 +0000208#define BENIGN_LANGOPT(Name, Bits, Default, Description)
209#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
210#include "clang/Basic/LangOptions.def"
211
Ben Langmuircd98cb72015-06-23 18:20:18 +0000212 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
213 if (Diags)
214 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
215 return true;
216 }
217
Guy Benyei11169dd2012-12-18 14:30:41 +0000218 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
219 if (Diags)
220 Diags->Report(diag::err_pch_langopt_value_mismatch)
221 << "target Objective-C runtime";
222 return true;
223 }
224
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000225 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
226 LangOpts.CommentOpts.BlockCommandNames) {
227 if (Diags)
228 Diags->Report(diag::err_pch_langopt_value_mismatch)
229 << "block command names";
230 return true;
231 }
232
Guy Benyei11169dd2012-12-18 14:30:41 +0000233 return false;
234}
235
236/// \brief Compare the given set of target options against an existing set of
237/// target options.
238///
239/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
240///
241/// \returns true if the target options mis-match, false otherwise.
242static bool checkTargetOptions(const TargetOptions &TargetOpts,
243 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000244 DiagnosticsEngine *Diags,
245 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000246#define CHECK_TARGET_OPT(Field, Name) \
247 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
248 if (Diags) \
249 Diags->Report(diag::err_pch_targetopt_mismatch) \
250 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
251 return true; \
252 }
253
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000254 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000255 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000256 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000257
258 // We can tolerate different CPUs in many cases, notably when one CPU
259 // supports a strict superset of another. When allowing compatible
260 // differences skip this check.
261 if (!AllowCompatibleDifferences)
262 CHECK_TARGET_OPT(CPU, "target CPU");
263
Guy Benyei11169dd2012-12-18 14:30:41 +0000264#undef CHECK_TARGET_OPT
265
266 // Compare feature sets.
267 SmallVector<StringRef, 4> ExistingFeatures(
268 ExistingTargetOpts.FeaturesAsWritten.begin(),
269 ExistingTargetOpts.FeaturesAsWritten.end());
270 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
271 TargetOpts.FeaturesAsWritten.end());
272 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
273 std::sort(ReadFeatures.begin(), ReadFeatures.end());
274
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000275 // We compute the set difference in both directions explicitly so that we can
276 // diagnose the differences differently.
277 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
278 std::set_difference(
279 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
280 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
281 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
282 ExistingFeatures.begin(), ExistingFeatures.end(),
283 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000284
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000285 // If we are allowing compatible differences and the read feature set is
286 // a strict subset of the existing feature set, there is nothing to diagnose.
287 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
288 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000289
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000290 if (Diags) {
291 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000292 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000293 << /* is-existing-feature */ false << Feature;
294 for (StringRef Feature : UnmatchedExistingFeatures)
295 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
296 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000297 }
298
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000299 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000300}
301
302bool
303PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000304 bool Complain,
305 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000306 const LangOptions &ExistingLangOpts = PP.getLangOpts();
307 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000308 Complain ? &Reader.Diags : nullptr,
309 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000310}
311
312bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000313 bool Complain,
314 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000315 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
316 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000317 Complain ? &Reader.Diags : nullptr,
318 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000319}
320
321namespace {
322 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
323 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000324 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
325 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000326}
327
Ben Langmuirb92de022014-04-29 16:25:26 +0000328static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
329 DiagnosticsEngine &Diags,
330 bool Complain) {
331 typedef DiagnosticsEngine::Level Level;
332
333 // Check current mappings for new -Werror mappings, and the stored mappings
334 // for cases that were explicitly mapped to *not* be errors that are now
335 // errors because of options like -Werror.
336 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
337
338 for (DiagnosticsEngine *MappingSource : MappingSources) {
339 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
340 diag::kind DiagID = DiagIDMappingPair.first;
341 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
342 if (CurLevel < DiagnosticsEngine::Error)
343 continue; // not significant
344 Level StoredLevel =
345 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
346 if (StoredLevel < DiagnosticsEngine::Error) {
347 if (Complain)
348 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
349 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
350 return true;
351 }
352 }
353 }
354
355 return false;
356}
357
Alp Tokerac4e8e52014-06-22 21:58:33 +0000358static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
359 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
360 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
361 return true;
362 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000363}
364
365static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
366 DiagnosticsEngine &Diags,
367 bool IsSystem, bool Complain) {
368 // Top-level options
369 if (IsSystem) {
370 if (Diags.getSuppressSystemWarnings())
371 return false;
372 // If -Wsystem-headers was not enabled before, be conservative
373 if (StoredDiags.getSuppressSystemWarnings()) {
374 if (Complain)
375 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
376 return true;
377 }
378 }
379
380 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
381 if (Complain)
382 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
383 return true;
384 }
385
386 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
387 !StoredDiags.getEnableAllWarnings()) {
388 if (Complain)
389 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
390 return true;
391 }
392
393 if (isExtHandlingFromDiagsError(Diags) &&
394 !isExtHandlingFromDiagsError(StoredDiags)) {
395 if (Complain)
396 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
397 return true;
398 }
399
400 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
401}
402
403bool PCHValidator::ReadDiagnosticOptions(
404 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
405 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
406 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
407 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000408 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000409 // This should never fail, because we would have processed these options
410 // before writing them to an ASTFile.
411 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
412
413 ModuleManager &ModuleMgr = Reader.getModuleManager();
414 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
415
416 // If the original import came from a file explicitly generated by the user,
417 // don't check the diagnostic mappings.
418 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000419 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000420 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
421 // the transitive closure of its imports, since unrelated modules cannot be
422 // imported until after this module finishes validation.
423 ModuleFile *TopImport = *ModuleMgr.rbegin();
424 while (!TopImport->ImportedBy.empty())
425 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000426 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000427 return false;
428
429 StringRef ModuleName = TopImport->ModuleName;
430 assert(!ModuleName.empty() && "diagnostic options read before module name");
431
432 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
433 assert(M && "missing module");
434
435 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
436 // contains the union of their flags.
437 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
438}
439
Guy Benyei11169dd2012-12-18 14:30:41 +0000440/// \brief Collect the macro definitions provided by the given preprocessor
441/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000442static void
443collectMacroDefinitions(const PreprocessorOptions &PPOpts,
444 MacroDefinitionsMap &Macros,
445 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000446 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
447 StringRef Macro = PPOpts.Macros[I].first;
448 bool IsUndef = PPOpts.Macros[I].second;
449
450 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
451 StringRef MacroName = MacroPair.first;
452 StringRef MacroBody = MacroPair.second;
453
454 // For an #undef'd macro, we only care about the name.
455 if (IsUndef) {
456 if (MacroNames && !Macros.count(MacroName))
457 MacroNames->push_back(MacroName);
458
459 Macros[MacroName] = std::make_pair("", true);
460 continue;
461 }
462
463 // For a #define'd macro, figure out the actual definition.
464 if (MacroName.size() == Macro.size())
465 MacroBody = "1";
466 else {
467 // Note: GCC drops anything following an end-of-line character.
468 StringRef::size_type End = MacroBody.find_first_of("\n\r");
469 MacroBody = MacroBody.substr(0, End);
470 }
471
472 if (MacroNames && !Macros.count(MacroName))
473 MacroNames->push_back(MacroName);
474 Macros[MacroName] = std::make_pair(MacroBody, false);
475 }
476}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000477
Guy Benyei11169dd2012-12-18 14:30:41 +0000478/// \brief Check the preprocessor options deserialized from the control block
479/// against the preprocessor options in an existing preprocessor.
480///
481/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
482static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
483 const PreprocessorOptions &ExistingPPOpts,
484 DiagnosticsEngine *Diags,
485 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000486 std::string &SuggestedPredefines,
487 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000488 // Check macro definitions.
489 MacroDefinitionsMap ASTFileMacros;
490 collectMacroDefinitions(PPOpts, ASTFileMacros);
491 MacroDefinitionsMap ExistingMacros;
492 SmallVector<StringRef, 4> ExistingMacroNames;
493 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
494
495 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
496 // Dig out the macro definition in the existing preprocessor options.
497 StringRef MacroName = ExistingMacroNames[I];
498 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
499
500 // Check whether we know anything about this macro name or not.
501 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
502 = ASTFileMacros.find(MacroName);
503 if (Known == ASTFileMacros.end()) {
504 // FIXME: Check whether this identifier was referenced anywhere in the
505 // AST file. If so, we should reject the AST file. Unfortunately, this
506 // information isn't in the control block. What shall we do about it?
507
508 if (Existing.second) {
509 SuggestedPredefines += "#undef ";
510 SuggestedPredefines += MacroName.str();
511 SuggestedPredefines += '\n';
512 } else {
513 SuggestedPredefines += "#define ";
514 SuggestedPredefines += MacroName.str();
515 SuggestedPredefines += ' ';
516 SuggestedPredefines += Existing.first.str();
517 SuggestedPredefines += '\n';
518 }
519 continue;
520 }
521
522 // If the macro was defined in one but undef'd in the other, we have a
523 // conflict.
524 if (Existing.second != Known->second.second) {
525 if (Diags) {
526 Diags->Report(diag::err_pch_macro_def_undef)
527 << MacroName << Known->second.second;
528 }
529 return true;
530 }
531
532 // If the macro was #undef'd in both, or if the macro bodies are identical,
533 // it's fine.
534 if (Existing.second || Existing.first == Known->second.first)
535 continue;
536
537 // The macro bodies differ; complain.
538 if (Diags) {
539 Diags->Report(diag::err_pch_macro_def_conflict)
540 << MacroName << Known->second.first << Existing.first;
541 }
542 return true;
543 }
544
545 // Check whether we're using predefines.
546 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
547 if (Diags) {
548 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
549 }
550 return true;
551 }
552
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000553 // Detailed record is important since it is used for the module cache hash.
554 if (LangOpts.Modules &&
555 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
556 if (Diags) {
557 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
558 }
559 return true;
560 }
561
Guy Benyei11169dd2012-12-18 14:30:41 +0000562 // Compute the #include and #include_macros lines we need.
563 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
564 StringRef File = ExistingPPOpts.Includes[I];
565 if (File == ExistingPPOpts.ImplicitPCHInclude)
566 continue;
567
568 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
569 != PPOpts.Includes.end())
570 continue;
571
572 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000573 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000574 SuggestedPredefines += "\"\n";
575 }
576
577 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
578 StringRef File = ExistingPPOpts.MacroIncludes[I];
579 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
580 File)
581 != PPOpts.MacroIncludes.end())
582 continue;
583
584 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000585 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000586 SuggestedPredefines += "\"\n##\n";
587 }
588
589 return false;
590}
591
592bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
593 bool Complain,
594 std::string &SuggestedPredefines) {
595 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
596
597 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000598 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000599 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000600 SuggestedPredefines,
601 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000602}
603
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000604/// Check the header search options deserialized from the control block
605/// against the header search options in an existing preprocessor.
606///
607/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
608static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
609 StringRef SpecificModuleCachePath,
610 StringRef ExistingModuleCachePath,
611 DiagnosticsEngine *Diags,
612 const LangOptions &LangOpts) {
613 if (LangOpts.Modules) {
614 if (SpecificModuleCachePath != ExistingModuleCachePath) {
615 if (Diags)
616 Diags->Report(diag::err_pch_modulecache_mismatch)
617 << SpecificModuleCachePath << ExistingModuleCachePath;
618 return true;
619 }
620 }
621
622 return false;
623}
624
625bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
626 StringRef SpecificModuleCachePath,
627 bool Complain) {
628 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
629 PP.getHeaderSearchInfo().getModuleCachePath(),
630 Complain ? &Reader.Diags : nullptr,
631 PP.getLangOpts());
632}
633
Guy Benyei11169dd2012-12-18 14:30:41 +0000634void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
635 PP.setCounterValue(Value);
636}
637
638//===----------------------------------------------------------------------===//
639// AST reader implementation
640//===----------------------------------------------------------------------===//
641
Nico Weber824285e2014-05-08 04:26:47 +0000642void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
643 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000644 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000645 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000646}
647
648
649
650unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
651 return serialization::ComputeHash(Sel);
652}
653
654
655std::pair<unsigned, unsigned>
656ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000657 using namespace llvm::support;
658 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
659 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000660 return std::make_pair(KeyLen, DataLen);
661}
662
663ASTSelectorLookupTrait::internal_key_type
664ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000665 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000666 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000667 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
668 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
669 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000670 if (N == 0)
671 return SelTable.getNullarySelector(FirstII);
672 else if (N == 1)
673 return SelTable.getUnarySelector(FirstII);
674
675 SmallVector<IdentifierInfo *, 16> Args;
676 Args.push_back(FirstII);
677 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000678 Args.push_back(Reader.getLocalIdentifier(
679 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000680
681 return SelTable.getSelector(N, Args.data());
682}
683
684ASTSelectorLookupTrait::data_type
685ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
686 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000687 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000688
689 data_type Result;
690
Justin Bogner57ba0b22014-03-28 22:03:24 +0000691 Result.ID = Reader.getGlobalSelectorID(
692 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000693 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
694 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
695 Result.InstanceBits = FullInstanceBits & 0x3;
696 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
697 Result.FactoryBits = FullFactoryBits & 0x3;
698 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
699 unsigned NumInstanceMethods = FullInstanceBits >> 3;
700 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000701
702 // Load instance methods
703 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000704 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
705 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000706 Result.Instance.push_back(Method);
707 }
708
709 // Load factory methods
710 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000711 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
712 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000713 Result.Factory.push_back(Method);
714 }
715
716 return Result;
717}
718
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000719unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
720 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000721}
722
723std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000724ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000725 using namespace llvm::support;
726 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
727 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000728 return std::make_pair(KeyLen, DataLen);
729}
730
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000731ASTIdentifierLookupTraitBase::internal_key_type
732ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000733 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000734 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000735}
736
Douglas Gregordcf25082013-02-11 18:16:18 +0000737/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000738static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
739 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000740 return II.hadMacroDefinition() ||
741 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000742 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000743 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000744 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
745 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000746}
747
Richard Smith76c2f2c2015-07-17 20:09:43 +0000748static bool readBit(unsigned &Bits) {
749 bool Value = Bits & 0x1;
750 Bits >>= 1;
751 return Value;
752}
753
Guy Benyei11169dd2012-12-18 14:30:41 +0000754IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
755 const unsigned char* d,
756 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000757 using namespace llvm::support;
758 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000759 bool IsInteresting = RawID & 0x01;
760
761 // Wipe out the "is interesting" bit.
762 RawID = RawID >> 1;
763
Richard Smith76c2f2c2015-07-17 20:09:43 +0000764 // Build the IdentifierInfo and link the identifier ID with it.
765 IdentifierInfo *II = KnownII;
766 if (!II) {
767 II = &Reader.getIdentifierTable().getOwn(k);
768 KnownII = II;
769 }
770 if (!II->isFromAST()) {
771 II->setIsFromAST();
Richard Smitha534a312015-07-21 23:54:07 +0000772 if (isInterestingIdentifier(Reader, *II, F.isModule()))
Richard Smith76c2f2c2015-07-17 20:09:43 +0000773 II->setChangedSinceDeserialization();
774 }
775 Reader.markIdentifierUpToDate(II);
776
Guy Benyei11169dd2012-12-18 14:30:41 +0000777 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
778 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000779 // For uninteresting identifiers, there's nothing else to do. Just notify
780 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000781 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000782 return II;
783 }
784
Justin Bogner57ba0b22014-03-28 22:03:24 +0000785 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
786 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000787 bool CPlusPlusOperatorKeyword = readBit(Bits);
788 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000789 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000790 bool Poisoned = readBit(Bits);
791 bool ExtensionToken = readBit(Bits);
792 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000793
794 assert(Bits == 0 && "Extra bits in the identifier?");
795 DataLen -= 8;
796
Guy Benyei11169dd2012-12-18 14:30:41 +0000797 // Set or check the various bits in the IdentifierInfo structure.
798 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000799 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000800 II->revertTokenIDToIdentifier();
801 if (!F.isModule())
802 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
803 else if (HasRevertedBuiltin && II->getBuiltinID()) {
804 II->revertBuiltin();
805 assert((II->hasRevertedBuiltin() ||
806 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
807 "Incorrect ObjC keyword or builtin ID");
808 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000809 assert(II->isExtensionToken() == ExtensionToken &&
810 "Incorrect extension token flag");
811 (void)ExtensionToken;
812 if (Poisoned)
813 II->setIsPoisoned(true);
814 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
815 "Incorrect C++ operator keyword flag");
816 (void)CPlusPlusOperatorKeyword;
817
818 // If this identifier is a macro, deserialize the macro
819 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000820 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000821 uint32_t MacroDirectivesOffset =
822 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000823 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000824
Richard Smithd7329392015-04-21 21:46:32 +0000825 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000826 }
827
828 Reader.SetIdentifierInfo(ID, II);
829
830 // Read all of the declarations visible at global scope with this
831 // name.
832 if (DataLen > 0) {
833 SmallVector<uint32_t, 4> DeclIDs;
834 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000835 DeclIDs.push_back(Reader.getGlobalDeclID(
836 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000837 Reader.SetGloballyVisibleDecls(II, DeclIDs);
838 }
839
840 return II;
841}
842
843unsigned
Richard Smith3b637412015-07-14 18:42:41 +0000844ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000845 llvm::FoldingSetNodeID ID;
846 ID.AddInteger(Key.Kind);
847
848 switch (Key.Kind) {
849 case DeclarationName::Identifier:
850 case DeclarationName::CXXLiteralOperatorName:
851 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
852 break;
853 case DeclarationName::ObjCZeroArgSelector:
854 case DeclarationName::ObjCOneArgSelector:
855 case DeclarationName::ObjCMultiArgSelector:
856 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
857 break;
858 case DeclarationName::CXXOperatorName:
859 ID.AddInteger((OverloadedOperatorKind)Key.Data);
860 break;
861 case DeclarationName::CXXConstructorName:
862 case DeclarationName::CXXDestructorName:
863 case DeclarationName::CXXConversionFunctionName:
864 case DeclarationName::CXXUsingDirective:
865 break;
866 }
867
868 return ID.ComputeHash();
869}
870
871ASTDeclContextNameLookupTrait::internal_key_type
872ASTDeclContextNameLookupTrait::GetInternalKey(
Richard Smith3b637412015-07-14 18:42:41 +0000873 const external_key_type& Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000874 DeclNameKey Key;
875 Key.Kind = Name.getNameKind();
876 switch (Name.getNameKind()) {
877 case DeclarationName::Identifier:
878 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
879 break;
880 case DeclarationName::ObjCZeroArgSelector:
881 case DeclarationName::ObjCOneArgSelector:
882 case DeclarationName::ObjCMultiArgSelector:
883 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
884 break;
885 case DeclarationName::CXXOperatorName:
886 Key.Data = Name.getCXXOverloadedOperator();
887 break;
888 case DeclarationName::CXXLiteralOperatorName:
889 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
890 break;
891 case DeclarationName::CXXConstructorName:
892 case DeclarationName::CXXDestructorName:
893 case DeclarationName::CXXConversionFunctionName:
894 case DeclarationName::CXXUsingDirective:
895 Key.Data = 0;
896 break;
897 }
898
899 return Key;
900}
901
902std::pair<unsigned, unsigned>
903ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000904 using namespace llvm::support;
905 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
906 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000907 return std::make_pair(KeyLen, DataLen);
908}
909
910ASTDeclContextNameLookupTrait::internal_key_type
911ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000912 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000913
914 DeclNameKey Key;
915 Key.Kind = (DeclarationName::NameKind)*d++;
916 switch (Key.Kind) {
917 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000918 Key.Data = (uint64_t)Reader.getLocalIdentifier(
919 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000920 break;
921 case DeclarationName::ObjCZeroArgSelector:
922 case DeclarationName::ObjCOneArgSelector:
923 case DeclarationName::ObjCMultiArgSelector:
924 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000925 (uint64_t)Reader.getLocalSelector(
926 F, endian::readNext<uint32_t, little, unaligned>(
927 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000928 break;
929 case DeclarationName::CXXOperatorName:
930 Key.Data = *d++; // OverloadedOperatorKind
931 break;
932 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000933 Key.Data = (uint64_t)Reader.getLocalIdentifier(
934 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000935 break;
936 case DeclarationName::CXXConstructorName:
937 case DeclarationName::CXXDestructorName:
938 case DeclarationName::CXXConversionFunctionName:
939 case DeclarationName::CXXUsingDirective:
940 Key.Data = 0;
941 break;
942 }
943
944 return Key;
945}
946
Richard Smithf02662d2015-07-30 03:17:16 +0000947ASTDeclContextNameLookupTrait::data_type
948ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
949 const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000950 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000951 using namespace llvm::support;
Richard Smithf02662d2015-07-30 03:17:16 +0000952 unsigned NumDecls = DataLen / 4;
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000953 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
954 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000955 return std::make_pair(Start, Start + NumDecls);
956}
957
958bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000959 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000960 const std::pair<uint64_t, uint64_t> &Offsets,
961 DeclContextInfo &Info) {
962 SavedStreamPosition SavedPosition(Cursor);
963 // First the lexical decls.
964 if (Offsets.first != 0) {
965 Cursor.JumpToBit(Offsets.first);
966
967 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000968 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000969 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000970 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000971 if (RecCode != DECL_CONTEXT_LEXICAL) {
972 Error("Expected lexical block");
973 return true;
974 }
975
Richard Smith787c0e42015-07-23 00:53:59 +0000976 Info.LexicalDecls = llvm::makeArrayRef(
977 reinterpret_cast<const KindDeclIDPair *>(Blob.data()),
978 Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +0000979 }
980
981 // Now the lookup table.
982 if (Offsets.second != 0) {
983 Cursor.JumpToBit(Offsets.second);
984
985 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000986 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000987 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000988 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000989 if (RecCode != DECL_CONTEXT_VISIBLE) {
990 Error("Expected visible lookup table block");
991 return true;
992 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000993 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
994 (const unsigned char *)Blob.data() + Record[0],
995 (const unsigned char *)Blob.data() + sizeof(uint32_t),
996 (const unsigned char *)Blob.data(),
997 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000998 }
999
1000 return false;
1001}
1002
1003void ASTReader::Error(StringRef Msg) {
1004 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001005 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1006 Diag(diag::note_module_cache_path)
1007 << PP.getHeaderSearchInfo().getModuleCachePath();
1008 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001009}
1010
1011void ASTReader::Error(unsigned DiagID,
1012 StringRef Arg1, StringRef Arg2) {
1013 if (Diags.isDiagnosticInFlight())
1014 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1015 else
1016 Diag(DiagID) << Arg1 << Arg2;
1017}
1018
1019//===----------------------------------------------------------------------===//
1020// Source Manager Deserialization
1021//===----------------------------------------------------------------------===//
1022
1023/// \brief Read the line table in the source manager block.
1024/// \returns true if there was an error.
1025bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001026 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 unsigned Idx = 0;
1028 LineTableInfo &LineTable = SourceMgr.getLineTable();
1029
1030 // Parse the file names
1031 std::map<int, int> FileIDs;
1032 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1033 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001034 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001035 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1036 }
1037
1038 // Parse the line entries
1039 std::vector<LineEntry> Entries;
1040 while (Idx < Record.size()) {
1041 int FID = Record[Idx++];
1042 assert(FID >= 0 && "Serialized line entries for non-local file.");
1043 // Remap FileID from 1-based old view.
1044 FID += F.SLocEntryBaseID - 1;
1045
1046 // Extract the line entries
1047 unsigned NumEntries = Record[Idx++];
1048 assert(NumEntries && "Numentries is 00000");
1049 Entries.clear();
1050 Entries.reserve(NumEntries);
1051 for (unsigned I = 0; I != NumEntries; ++I) {
1052 unsigned FileOffset = Record[Idx++];
1053 unsigned LineNo = Record[Idx++];
1054 int FilenameID = FileIDs[Record[Idx++]];
1055 SrcMgr::CharacteristicKind FileKind
1056 = (SrcMgr::CharacteristicKind)Record[Idx++];
1057 unsigned IncludeOffset = Record[Idx++];
1058 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1059 FileKind, IncludeOffset));
1060 }
1061 LineTable.AddEntry(FileID::get(FID), Entries);
1062 }
1063
1064 return false;
1065}
1066
1067/// \brief Read a source manager block
1068bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1069 using namespace SrcMgr;
1070
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001071 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001072
1073 // Set the source-location entry cursor to the current position in
1074 // the stream. This cursor will be used to read the contents of the
1075 // source manager block initially, and then lazily read
1076 // source-location entries as needed.
1077 SLocEntryCursor = F.Stream;
1078
1079 // The stream itself is going to skip over the source manager block.
1080 if (F.Stream.SkipBlock()) {
1081 Error("malformed block record in AST file");
1082 return true;
1083 }
1084
1085 // Enter the source manager block.
1086 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1087 Error("malformed source manager block record in AST file");
1088 return true;
1089 }
1090
1091 RecordData Record;
1092 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001093 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1094
1095 switch (E.Kind) {
1096 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1097 case llvm::BitstreamEntry::Error:
1098 Error("malformed block record in AST file");
1099 return true;
1100 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001101 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001102 case llvm::BitstreamEntry::Record:
1103 // The interesting case.
1104 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001105 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001106
Guy Benyei11169dd2012-12-18 14:30:41 +00001107 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001108 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001109 StringRef Blob;
1110 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001111 default: // Default behavior: ignore.
1112 break;
1113
1114 case SM_SLOC_FILE_ENTRY:
1115 case SM_SLOC_BUFFER_ENTRY:
1116 case SM_SLOC_EXPANSION_ENTRY:
1117 // Once we hit one of the source location entries, we're done.
1118 return false;
1119 }
1120 }
1121}
1122
1123/// \brief If a header file is not found at the path that we expect it to be
1124/// and the PCH file was moved from its original location, try to resolve the
1125/// file by assuming that header+PCH were moved together and the header is in
1126/// the same place relative to the PCH.
1127static std::string
1128resolveFileRelativeToOriginalDir(const std::string &Filename,
1129 const std::string &OriginalDir,
1130 const std::string &CurrDir) {
1131 assert(OriginalDir != CurrDir &&
1132 "No point trying to resolve the file if the PCH dir didn't change");
1133 using namespace llvm::sys;
1134 SmallString<128> filePath(Filename);
1135 fs::make_absolute(filePath);
1136 assert(path::is_absolute(OriginalDir));
1137 SmallString<128> currPCHPath(CurrDir);
1138
1139 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1140 fileDirE = path::end(path::parent_path(filePath));
1141 path::const_iterator origDirI = path::begin(OriginalDir),
1142 origDirE = path::end(OriginalDir);
1143 // Skip the common path components from filePath and OriginalDir.
1144 while (fileDirI != fileDirE && origDirI != origDirE &&
1145 *fileDirI == *origDirI) {
1146 ++fileDirI;
1147 ++origDirI;
1148 }
1149 for (; origDirI != origDirE; ++origDirI)
1150 path::append(currPCHPath, "..");
1151 path::append(currPCHPath, fileDirI, fileDirE);
1152 path::append(currPCHPath, path::filename(Filename));
1153 return currPCHPath.str();
1154}
1155
1156bool ASTReader::ReadSLocEntry(int ID) {
1157 if (ID == 0)
1158 return false;
1159
1160 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1161 Error("source location entry ID out-of-range for AST file");
1162 return true;
1163 }
1164
1165 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1166 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001167 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001168 unsigned BaseOffset = F->SLocEntryBaseOffset;
1169
1170 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001171 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1172 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001173 Error("incorrectly-formatted source location entry in AST file");
1174 return true;
1175 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001176
Guy Benyei11169dd2012-12-18 14:30:41 +00001177 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001178 StringRef Blob;
1179 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001180 default:
1181 Error("incorrectly-formatted source location entry in AST file");
1182 return true;
1183
1184 case SM_SLOC_FILE_ENTRY: {
1185 // We will detect whether a file changed and return 'Failure' for it, but
1186 // we will also try to fail gracefully by setting up the SLocEntry.
1187 unsigned InputID = Record[4];
1188 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001189 const FileEntry *File = IF.getFile();
1190 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001191
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001192 // Note that we only check if a File was returned. If it was out-of-date
1193 // we have complained but we will continue creating a FileID to recover
1194 // gracefully.
1195 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001196 return true;
1197
1198 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1199 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1200 // This is the module's main file.
1201 IncludeLoc = getImportLocation(F);
1202 }
1203 SrcMgr::CharacteristicKind
1204 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1205 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1206 ID, BaseOffset + Record[0]);
1207 SrcMgr::FileInfo &FileInfo =
1208 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1209 FileInfo.NumCreatedFIDs = Record[5];
1210 if (Record[3])
1211 FileInfo.setHasLineDirectives();
1212
1213 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1214 unsigned NumFileDecls = Record[7];
1215 if (NumFileDecls) {
1216 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1217 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1218 NumFileDecls));
1219 }
1220
1221 const SrcMgr::ContentCache *ContentCache
1222 = SourceMgr.getOrCreateContentCache(File,
1223 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1224 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1225 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1226 unsigned Code = SLocEntryCursor.ReadCode();
1227 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001228 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001229
1230 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1231 Error("AST record has invalid code");
1232 return true;
1233 }
1234
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001235 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001236 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001237 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001238 }
1239
1240 break;
1241 }
1242
1243 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001244 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001245 unsigned Offset = Record[0];
1246 SrcMgr::CharacteristicKind
1247 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1248 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001249 if (IncludeLoc.isInvalid() &&
1250 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001251 IncludeLoc = getImportLocation(F);
1252 }
1253 unsigned Code = SLocEntryCursor.ReadCode();
1254 Record.clear();
1255 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001256 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001257
1258 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1259 Error("AST record has invalid code");
1260 return true;
1261 }
1262
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001263 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1264 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001265 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001266 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001267 break;
1268 }
1269
1270 case SM_SLOC_EXPANSION_ENTRY: {
1271 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1272 SourceMgr.createExpansionLoc(SpellingLoc,
1273 ReadSourceLocation(*F, Record[2]),
1274 ReadSourceLocation(*F, Record[3]),
1275 Record[4],
1276 ID,
1277 BaseOffset + Record[0]);
1278 break;
1279 }
1280 }
1281
1282 return false;
1283}
1284
1285std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1286 if (ID == 0)
1287 return std::make_pair(SourceLocation(), "");
1288
1289 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1290 Error("source location entry ID out-of-range for AST file");
1291 return std::make_pair(SourceLocation(), "");
1292 }
1293
1294 // Find which module file this entry lands in.
1295 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001296 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001297 return std::make_pair(SourceLocation(), "");
1298
1299 // FIXME: Can we map this down to a particular submodule? That would be
1300 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001301 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001302}
1303
1304/// \brief Find the location where the module F is imported.
1305SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1306 if (F->ImportLoc.isValid())
1307 return F->ImportLoc;
1308
1309 // Otherwise we have a PCH. It's considered to be "imported" at the first
1310 // location of its includer.
1311 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001312 // Main file is the importer.
1313 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1314 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001315 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001316 return F->ImportedBy[0]->FirstLoc;
1317}
1318
1319/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1320/// specified cursor. Read the abbreviations that are at the top of the block
1321/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001322bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001323 if (Cursor.EnterSubBlock(BlockID)) {
1324 Error("malformed block record in AST file");
1325 return Failure;
1326 }
1327
1328 while (true) {
1329 uint64_t Offset = Cursor.GetCurrentBitNo();
1330 unsigned Code = Cursor.ReadCode();
1331
1332 // We expect all abbrevs to be at the start of the block.
1333 if (Code != llvm::bitc::DEFINE_ABBREV) {
1334 Cursor.JumpToBit(Offset);
1335 return false;
1336 }
1337 Cursor.ReadAbbrevRecord();
1338 }
1339}
1340
Richard Smithe40f2ba2013-08-07 21:41:30 +00001341Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001342 unsigned &Idx) {
1343 Token Tok;
1344 Tok.startToken();
1345 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1346 Tok.setLength(Record[Idx++]);
1347 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1348 Tok.setIdentifierInfo(II);
1349 Tok.setKind((tok::TokenKind)Record[Idx++]);
1350 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1351 return Tok;
1352}
1353
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001354MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001355 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001356
1357 // Keep track of where we are in the stream, then jump back there
1358 // after reading this macro.
1359 SavedStreamPosition SavedPosition(Stream);
1360
1361 Stream.JumpToBit(Offset);
1362 RecordData Record;
1363 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001364 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001365
Guy Benyei11169dd2012-12-18 14:30:41 +00001366 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001367 // Advance to the next record, but if we get to the end of the block, don't
1368 // pop it (removing all the abbreviations from the cursor) since we want to
1369 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001370 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001371 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1372
1373 switch (Entry.Kind) {
1374 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1375 case llvm::BitstreamEntry::Error:
1376 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001377 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001378 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001379 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001380 case llvm::BitstreamEntry::Record:
1381 // The interesting case.
1382 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001383 }
1384
1385 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001386 Record.clear();
1387 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001388 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001389 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001390 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001391 case PP_MACRO_DIRECTIVE_HISTORY:
1392 return Macro;
1393
Guy Benyei11169dd2012-12-18 14:30:41 +00001394 case PP_MACRO_OBJECT_LIKE:
1395 case PP_MACRO_FUNCTION_LIKE: {
1396 // If we already have a macro, that means that we've hit the end
1397 // of the definition of the macro we were looking for. We're
1398 // done.
1399 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001400 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001401
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001402 unsigned NextIndex = 1; // Skip identifier ID.
1403 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001404 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001405 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001406 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001407 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001408 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001409
Guy Benyei11169dd2012-12-18 14:30:41 +00001410 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1411 // Decode function-like macro info.
1412 bool isC99VarArgs = Record[NextIndex++];
1413 bool isGNUVarArgs = Record[NextIndex++];
1414 bool hasCommaPasting = Record[NextIndex++];
1415 MacroArgs.clear();
1416 unsigned NumArgs = Record[NextIndex++];
1417 for (unsigned i = 0; i != NumArgs; ++i)
1418 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1419
1420 // Install function-like macro info.
1421 MI->setIsFunctionLike();
1422 if (isC99VarArgs) MI->setIsC99Varargs();
1423 if (isGNUVarArgs) MI->setIsGNUVarargs();
1424 if (hasCommaPasting) MI->setHasCommaPasting();
1425 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1426 PP.getPreprocessorAllocator());
1427 }
1428
Guy Benyei11169dd2012-12-18 14:30:41 +00001429 // Remember that we saw this macro last so that we add the tokens that
1430 // form its body to it.
1431 Macro = MI;
1432
1433 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1434 Record[NextIndex]) {
1435 // We have a macro definition. Register the association
1436 PreprocessedEntityID
1437 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1438 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001439 PreprocessingRecord::PPEntityID PPID =
1440 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1441 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1442 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001443 if (PPDef)
1444 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001445 }
1446
1447 ++NumMacrosRead;
1448 break;
1449 }
1450
1451 case PP_TOKEN: {
1452 // If we see a TOKEN before a PP_MACRO_*, then the file is
1453 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001454 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001455
John McCallf413f5e2013-05-03 00:10:13 +00001456 unsigned Idx = 0;
1457 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001458 Macro->AddTokenToBody(Tok);
1459 break;
1460 }
1461 }
1462 }
1463}
1464
1465PreprocessedEntityID
1466ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1467 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1468 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1469 assert(I != M.PreprocessedEntityRemap.end()
1470 && "Invalid index into preprocessed entity index remap");
1471
1472 return LocalID + I->second;
1473}
1474
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001475unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1476 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001477}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001478
Guy Benyei11169dd2012-12-18 14:30:41 +00001479HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001480HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1481 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001482 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001483 return ikey;
1484}
Guy Benyei11169dd2012-12-18 14:30:41 +00001485
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001486bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1487 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001488 return false;
1489
Richard Smith7ed1bc92014-12-05 22:42:13 +00001490 if (llvm::sys::path::is_absolute(a.Filename) &&
1491 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001492 return true;
1493
Guy Benyei11169dd2012-12-18 14:30:41 +00001494 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001495 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001496 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1497 if (!Key.Imported)
1498 return FileMgr.getFile(Key.Filename);
1499
1500 std::string Resolved = Key.Filename;
1501 Reader.ResolveImportedPath(M, Resolved);
1502 return FileMgr.getFile(Resolved);
1503 };
1504
1505 const FileEntry *FEA = GetFile(a);
1506 const FileEntry *FEB = GetFile(b);
1507 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001508}
1509
1510std::pair<unsigned, unsigned>
1511HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001512 using namespace llvm::support;
1513 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001514 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001515 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001516}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001517
1518HeaderFileInfoTrait::internal_key_type
1519HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001520 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001521 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001522 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1523 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001524 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001525 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001526 return ikey;
1527}
1528
Guy Benyei11169dd2012-12-18 14:30:41 +00001529HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001530HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001531 unsigned DataLen) {
1532 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001533 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001534 HeaderFileInfo HFI;
1535 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001536 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1537 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001538 HFI.isImport = (Flags >> 5) & 0x01;
1539 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1540 HFI.DirInfo = (Flags >> 2) & 0x03;
1541 HFI.Resolved = (Flags >> 1) & 0x01;
1542 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001543 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1544 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1545 M, endian::readNext<uint32_t, little, unaligned>(d));
1546 if (unsigned FrameworkOffset =
1547 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001548 // The framework offset is 1 greater than the actual offset,
1549 // since 0 is used as an indicator for "no framework name".
1550 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1551 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1552 }
1553
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001554 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001555 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001556 if (LocalSMID) {
1557 // This header is part of a module. Associate it with the module to enable
1558 // implicit module import.
1559 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1560 Module *Mod = Reader.getSubmodule(GlobalSMID);
1561 HFI.isModuleHeader = true;
1562 FileManager &FileMgr = Reader.getFileManager();
1563 ModuleMap &ModMap =
1564 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001565 // FIXME: This information should be propagated through the
1566 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001567 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001568 std::string Filename = key.Filename;
1569 if (key.Imported)
1570 Reader.ResolveImportedPath(M, Filename);
1571 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001572 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001573 }
1574 }
1575
Guy Benyei11169dd2012-12-18 14:30:41 +00001576 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1577 (void)End;
1578
1579 // This HeaderFileInfo was externally loaded.
1580 HFI.External = true;
1581 return HFI;
1582}
1583
Richard Smithd7329392015-04-21 21:46:32 +00001584void ASTReader::addPendingMacro(IdentifierInfo *II,
1585 ModuleFile *M,
1586 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001587 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1588 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001589}
1590
1591void ASTReader::ReadDefinedMacros() {
1592 // Note that we are loading defined macros.
1593 Deserializing Macros(this);
1594
Pete Cooper57d3f142015-07-30 17:22:52 +00001595 for (auto &I : llvm::reverse(ModuleMgr)) {
1596 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001597
1598 // If there was no preprocessor block, skip this file.
1599 if (!MacroCursor.getBitStreamReader())
1600 continue;
1601
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001602 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001603 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001604
1605 RecordData Record;
1606 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001607 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1608
1609 switch (E.Kind) {
1610 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1611 case llvm::BitstreamEntry::Error:
1612 Error("malformed block record in AST file");
1613 return;
1614 case llvm::BitstreamEntry::EndBlock:
1615 goto NextCursor;
1616
1617 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001618 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001619 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001620 default: // Default behavior: ignore.
1621 break;
1622
1623 case PP_MACRO_OBJECT_LIKE:
1624 case PP_MACRO_FUNCTION_LIKE:
Pete Cooper57d3f142015-07-30 17:22:52 +00001625 getLocalIdentifier(*I, Record[0]);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001626 break;
1627
1628 case PP_TOKEN:
1629 // Ignore tokens.
1630 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001631 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001632 break;
1633 }
1634 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001635 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001636 }
1637}
1638
1639namespace {
1640 /// \brief Visitor class used to look up identifirs in an AST file.
1641 class IdentifierLookupVisitor {
1642 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001643 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001644 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001645 unsigned &NumIdentifierLookups;
1646 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001647 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001648
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001650 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1651 unsigned &NumIdentifierLookups,
1652 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001653 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1654 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001655 NumIdentifierLookups(NumIdentifierLookups),
1656 NumIdentifierLookupHits(NumIdentifierLookupHits),
1657 Found()
1658 {
1659 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001660
1661 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001662 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001663 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001664 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001665
Guy Benyei11169dd2012-12-18 14:30:41 +00001666 ASTIdentifierLookupTable *IdTable
1667 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1668 if (!IdTable)
1669 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001670
1671 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001672 Found);
1673 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001674 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001675 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001676 if (Pos == IdTable->end())
1677 return false;
1678
1679 // Dereferencing the iterator has the effect of building the
1680 // IdentifierInfo node and populating it with the various
1681 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001682 ++NumIdentifierLookupHits;
1683 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001684 return true;
1685 }
1686
1687 // \brief Retrieve the identifier info found within the module
1688 // files.
1689 IdentifierInfo *getIdentifierInfo() const { return Found; }
1690 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001691}
Guy Benyei11169dd2012-12-18 14:30:41 +00001692
1693void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1694 // Note that we are loading an identifier.
1695 Deserializing AnIdentifier(this);
1696
1697 unsigned PriorGeneration = 0;
1698 if (getContext().getLangOpts().Modules)
1699 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001700
1701 // If there is a global index, look there first to determine which modules
1702 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001703 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001704 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001705 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001706 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1707 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001708 }
1709 }
1710
Douglas Gregor7211ac12013-01-25 23:32:03 +00001711 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001712 NumIdentifierLookups,
1713 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001714 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001715 markIdentifierUpToDate(&II);
1716}
1717
1718void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1719 if (!II)
1720 return;
1721
1722 II->setOutOfDate(false);
1723
1724 // Update the generation for this identifier.
1725 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001726 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001727}
1728
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001729void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1730 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001731 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001732
1733 BitstreamCursor &Cursor = M.MacroCursor;
1734 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001735 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001736
Richard Smith713369b2015-04-23 20:40:50 +00001737 struct ModuleMacroRecord {
1738 SubmoduleID SubModID;
1739 MacroInfo *MI;
1740 SmallVector<SubmoduleID, 8> Overrides;
1741 };
1742 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001743
Richard Smithd7329392015-04-21 21:46:32 +00001744 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1745 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1746 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001747 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001748 while (true) {
1749 llvm::BitstreamEntry Entry =
1750 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1751 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1752 Error("malformed block record in AST file");
1753 return;
1754 }
1755
1756 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001757 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001758 case PP_MACRO_DIRECTIVE_HISTORY:
1759 break;
1760
1761 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001762 ModuleMacros.push_back(ModuleMacroRecord());
1763 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001764 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1765 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001766 for (int I = 2, N = Record.size(); I != N; ++I)
1767 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001768 continue;
1769 }
1770
1771 default:
1772 Error("malformed block record in AST file");
1773 return;
1774 }
1775
1776 // We found the macro directive history; that's the last record
1777 // for this macro.
1778 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001779 }
1780
Richard Smithd7329392015-04-21 21:46:32 +00001781 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001782 {
1783 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001784 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001785 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001786 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001787 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001788 Module *Mod = getSubmodule(ModID);
1789 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001790 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001791 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001792 }
1793
1794 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001795 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001796 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001797 }
1798 }
1799
1800 // Don't read the directive history for a module; we don't have anywhere
1801 // to put it.
1802 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1803 return;
1804
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001805 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001806 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001807 unsigned Idx = 0, N = Record.size();
1808 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001809 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001810 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001811 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1812 switch (K) {
1813 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001814 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001815 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001816 break;
1817 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001818 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001819 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001820 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001821 }
1822 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001823 bool isPublic = Record[Idx++];
1824 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1825 break;
1826 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001827
1828 if (!Latest)
1829 Latest = MD;
1830 if (Earliest)
1831 Earliest->setPrevious(MD);
1832 Earliest = MD;
1833 }
1834
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001835 if (Latest)
1836 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001837}
1838
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001839ASTReader::InputFileInfo
1840ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001841 // Go find this input file.
1842 BitstreamCursor &Cursor = F.InputFilesCursor;
1843 SavedStreamPosition SavedPosition(Cursor);
1844 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1845
1846 unsigned Code = Cursor.ReadCode();
1847 RecordData Record;
1848 StringRef Blob;
1849
1850 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1851 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1852 "invalid record type for input file");
1853 (void)Result;
1854
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001855 std::string Filename;
1856 off_t StoredSize;
1857 time_t StoredTime;
1858 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001859
Ben Langmuir198c1682014-03-07 07:27:49 +00001860 assert(Record[0] == ID && "Bogus stored ID or offset");
1861 StoredSize = static_cast<off_t>(Record[1]);
1862 StoredTime = static_cast<time_t>(Record[2]);
1863 Overridden = static_cast<bool>(Record[3]);
1864 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001865 ResolveImportedPath(F, Filename);
1866
Hans Wennborg73945142014-03-14 17:45:06 +00001867 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1868 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001869}
1870
1871std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001872 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00001873}
1874
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001875InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001876 // If this ID is bogus, just return an empty input file.
1877 if (ID == 0 || ID > F.InputFilesLoaded.size())
1878 return InputFile();
1879
1880 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001881 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001882 return F.InputFilesLoaded[ID-1];
1883
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001884 if (F.InputFilesLoaded[ID-1].isNotFound())
1885 return InputFile();
1886
Guy Benyei11169dd2012-12-18 14:30:41 +00001887 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001888 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001889 SavedStreamPosition SavedPosition(Cursor);
1890 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1891
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001892 InputFileInfo FI = readInputFileInfo(F, ID);
1893 off_t StoredSize = FI.StoredSize;
1894 time_t StoredTime = FI.StoredTime;
1895 bool Overridden = FI.Overridden;
1896 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001897
Ben Langmuir198c1682014-03-07 07:27:49 +00001898 const FileEntry *File
1899 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1900 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1901
1902 // If we didn't find the file, resolve it relative to the
1903 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001904 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001905 F.OriginalDir != CurrentDir) {
1906 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1907 F.OriginalDir,
1908 CurrentDir);
1909 if (!Resolved.empty())
1910 File = FileMgr.getFile(Resolved);
1911 }
1912
1913 // For an overridden file, create a virtual file with the stored
1914 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001915 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001916 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1917 }
1918
Craig Toppera13603a2014-05-22 05:54:18 +00001919 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001920 if (Complain) {
1921 std::string ErrorStr = "could not find file '";
1922 ErrorStr += Filename;
1923 ErrorStr += "' referenced by AST file";
1924 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001925 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001926 // Record that we didn't find the file.
1927 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1928 return InputFile();
1929 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001930
Ben Langmuir198c1682014-03-07 07:27:49 +00001931 // Check if there was a request to override the contents of the file
1932 // that was part of the precompiled header. Overridding such a file
1933 // can lead to problems when lexing using the source locations from the
1934 // PCH.
1935 SourceManager &SM = getSourceManager();
1936 if (!Overridden && SM.isFileOverridden(File)) {
1937 if (Complain)
1938 Error(diag::err_fe_pch_file_overridden, Filename);
1939 // After emitting the diagnostic, recover by disabling the override so
1940 // that the original file will be used.
1941 SM.disableFileContentsOverride(File);
1942 // The FileEntry is a virtual file entry with the size of the contents
1943 // that would override the original contents. Set it to the original's
1944 // size/time.
1945 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1946 StoredSize, StoredTime);
1947 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001948
Ben Langmuir198c1682014-03-07 07:27:49 +00001949 bool IsOutOfDate = false;
1950
1951 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001952 if (!Overridden && //
1953 (StoredSize != File->getSize() ||
1954#if defined(LLVM_ON_WIN32)
1955 false
1956#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001957 // In our regression testing, the Windows file system seems to
1958 // have inconsistent modification times that sometimes
1959 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001960 //
1961 // This also happens in networked file systems, so disable this
1962 // check if validation is disabled or if we have an explicitly
1963 // built PCM file.
1964 //
1965 // FIXME: Should we also do this for PCH files? They could also
1966 // reasonably get shared across a network during a distributed build.
1967 (StoredTime != File->getModificationTime() && !DisableValidation &&
1968 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001969#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001970 )) {
1971 if (Complain) {
1972 // Build a list of the PCH imports that got us here (in reverse).
1973 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1974 while (ImportStack.back()->ImportedBy.size() > 0)
1975 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001976
Ben Langmuir198c1682014-03-07 07:27:49 +00001977 // The top-level PCH is stale.
1978 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1979 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00001980
Ben Langmuir198c1682014-03-07 07:27:49 +00001981 // Print the import stack.
1982 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1983 Diag(diag::note_pch_required_by)
1984 << Filename << ImportStack[0]->FileName;
1985 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00001986 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00001987 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00001988 }
1989
Ben Langmuir198c1682014-03-07 07:27:49 +00001990 if (!Diags.isDiagnosticInFlight())
1991 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00001992 }
1993
Ben Langmuir198c1682014-03-07 07:27:49 +00001994 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001995 }
1996
Ben Langmuir198c1682014-03-07 07:27:49 +00001997 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
1998
1999 // Note that we've loaded this input file.
2000 F.InputFilesLoaded[ID-1] = IF;
2001 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002002}
2003
Richard Smith7ed1bc92014-12-05 22:42:13 +00002004/// \brief If we are loading a relocatable PCH or module file, and the filename
2005/// is not an absolute path, add the system or module root to the beginning of
2006/// the file name.
2007void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2008 // Resolve relative to the base directory, if we have one.
2009 if (!M.BaseDirectory.empty())
2010 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002011}
2012
Richard Smith7ed1bc92014-12-05 22:42:13 +00002013void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002014 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2015 return;
2016
Richard Smith7ed1bc92014-12-05 22:42:13 +00002017 SmallString<128> Buffer;
2018 llvm::sys::path::append(Buffer, Prefix, Filename);
2019 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002020}
2021
2022ASTReader::ASTReadResult
2023ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002024 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002025 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002026 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002027 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002028
2029 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2030 Error("malformed block record in AST file");
2031 return Failure;
2032 }
2033
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002034 // Should we allow the configuration of the module file to differ from the
2035 // configuration of the current translation unit in a compatible way?
2036 //
2037 // FIXME: Allow this for files explicitly specified with -include-pch too.
2038 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2039
Guy Benyei11169dd2012-12-18 14:30:41 +00002040 // Read all of the records and blocks in the control block.
2041 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002042 unsigned NumInputs = 0;
2043 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002044 while (1) {
2045 llvm::BitstreamEntry Entry = Stream.advance();
2046
2047 switch (Entry.Kind) {
2048 case llvm::BitstreamEntry::Error:
2049 Error("malformed block record in AST file");
2050 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002051 case llvm::BitstreamEntry::EndBlock: {
2052 // Validate input files.
2053 const HeaderSearchOptions &HSOpts =
2054 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002055
Richard Smitha1825302014-10-23 22:18:29 +00002056 // All user input files reside at the index range [0, NumUserInputs), and
2057 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002058 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002059 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002060
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002061 // If we are reading a module, we will create a verification timestamp,
2062 // so we verify all input files. Otherwise, verify only user input
2063 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002064
2065 unsigned N = NumUserInputs;
2066 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002067 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002068 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002069 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002070 N = NumInputs;
2071
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002072 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002073 InputFile IF = getInputFile(F, I+1, Complain);
2074 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002075 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002076 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002077 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002078
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002079 if (Listener)
2080 Listener->visitModuleFile(F.FileName);
2081
Ben Langmuircb69b572014-03-07 06:40:32 +00002082 if (Listener && Listener->needsInputFileVisitation()) {
2083 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2084 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002085 for (unsigned I = 0; I < N; ++I) {
2086 bool IsSystem = I >= NumUserInputs;
2087 InputFileInfo FI = readInputFileInfo(F, I+1);
2088 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2089 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002090 }
2091
Guy Benyei11169dd2012-12-18 14:30:41 +00002092 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002093 }
2094
Chris Lattnere7b154b2013-01-19 21:39:22 +00002095 case llvm::BitstreamEntry::SubBlock:
2096 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002097 case INPUT_FILES_BLOCK_ID:
2098 F.InputFilesCursor = Stream;
2099 if (Stream.SkipBlock() || // Skip with the main cursor
2100 // Read the abbreviations
2101 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2102 Error("malformed block record in AST file");
2103 return Failure;
2104 }
2105 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002106
Guy Benyei11169dd2012-12-18 14:30:41 +00002107 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002108 if (Stream.SkipBlock()) {
2109 Error("malformed block record in AST file");
2110 return Failure;
2111 }
2112 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002113 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002114
2115 case llvm::BitstreamEntry::Record:
2116 // The interesting case.
2117 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002118 }
2119
2120 // Read and process a record.
2121 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002122 StringRef Blob;
2123 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002124 case METADATA: {
2125 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2126 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002127 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2128 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002129 return VersionMismatch;
2130 }
2131
2132 bool hasErrors = Record[5];
2133 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2134 Diag(diag::err_pch_with_compiler_errors);
2135 return HadErrors;
2136 }
2137
2138 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002139 // Relative paths in a relocatable PCH are relative to our sysroot.
2140 if (F.RelocatablePCH)
2141 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002142
2143 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002144 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002145 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2146 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002147 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002148 return VersionMismatch;
2149 }
2150 break;
2151 }
2152
Ben Langmuir487ea142014-10-23 18:05:36 +00002153 case SIGNATURE:
2154 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2155 F.Signature = Record[0];
2156 break;
2157
Guy Benyei11169dd2012-12-18 14:30:41 +00002158 case IMPORTS: {
2159 // Load each of the imported PCH files.
2160 unsigned Idx = 0, N = Record.size();
2161 while (Idx < N) {
2162 // Read information about the AST file.
2163 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2164 // The import location will be the local one for now; we will adjust
2165 // all import locations of module imports after the global source
2166 // location info are setup.
2167 SourceLocation ImportLoc =
2168 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002169 off_t StoredSize = (off_t)Record[Idx++];
2170 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002171 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002172 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002173
2174 // Load the AST file.
2175 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002176 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002177 ClientLoadCapabilities)) {
2178 case Failure: return Failure;
2179 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002180 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002181 case OutOfDate: return OutOfDate;
2182 case VersionMismatch: return VersionMismatch;
2183 case ConfigurationMismatch: return ConfigurationMismatch;
2184 case HadErrors: return HadErrors;
2185 case Success: break;
2186 }
2187 }
2188 break;
2189 }
2190
Richard Smith7f330cd2015-03-18 01:42:29 +00002191 case KNOWN_MODULE_FILES:
2192 break;
2193
Guy Benyei11169dd2012-12-18 14:30:41 +00002194 case LANGUAGE_OPTIONS: {
2195 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002196 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002197 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002198 ParseLanguageOptions(Record, Complain, *Listener,
2199 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002200 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002201 return ConfigurationMismatch;
2202 break;
2203 }
2204
2205 case TARGET_OPTIONS: {
2206 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2207 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002208 ParseTargetOptions(Record, Complain, *Listener,
2209 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002210 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002211 return ConfigurationMismatch;
2212 break;
2213 }
2214
2215 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002216 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002217 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002218 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002219 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002220 !DisableValidation)
2221 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002222 break;
2223 }
2224
2225 case FILE_SYSTEM_OPTIONS: {
2226 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2227 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002228 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002229 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002230 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002231 return ConfigurationMismatch;
2232 break;
2233 }
2234
2235 case HEADER_SEARCH_OPTIONS: {
2236 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2237 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002238 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002239 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002240 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002241 return ConfigurationMismatch;
2242 break;
2243 }
2244
2245 case PREPROCESSOR_OPTIONS: {
2246 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2247 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002248 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002249 ParsePreprocessorOptions(Record, Complain, *Listener,
2250 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002251 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002252 return ConfigurationMismatch;
2253 break;
2254 }
2255
2256 case ORIGINAL_FILE:
2257 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002258 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002259 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002260 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002261 break;
2262
2263 case ORIGINAL_FILE_ID:
2264 F.OriginalSourceFileID = FileID::get(Record[0]);
2265 break;
2266
2267 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002268 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002269 break;
2270
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002271 case MODULE_NAME:
2272 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002273 if (Listener)
2274 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002275 break;
2276
Richard Smith223d3f22014-12-06 03:21:08 +00002277 case MODULE_DIRECTORY: {
2278 assert(!F.ModuleName.empty() &&
2279 "MODULE_DIRECTORY found before MODULE_NAME");
2280 // If we've already loaded a module map file covering this module, we may
2281 // have a better path for it (relative to the current build).
2282 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2283 if (M && M->Directory) {
2284 // If we're implicitly loading a module, the base directory can't
2285 // change between the build and use.
2286 if (F.Kind != MK_ExplicitModule) {
2287 const DirectoryEntry *BuildDir =
2288 PP.getFileManager().getDirectory(Blob);
2289 if (!BuildDir || BuildDir != M->Directory) {
2290 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2291 Diag(diag::err_imported_module_relocated)
2292 << F.ModuleName << Blob << M->Directory->getName();
2293 return OutOfDate;
2294 }
2295 }
2296 F.BaseDirectory = M->Directory->getName();
2297 } else {
2298 F.BaseDirectory = Blob;
2299 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002300 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002301 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002302
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002303 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002304 if (ASTReadResult Result =
2305 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2306 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002307 break;
2308
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002309 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002310 NumInputs = Record[0];
2311 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002312 F.InputFileOffsets =
2313 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002314 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002315 break;
2316 }
2317 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002318}
2319
Ben Langmuir2c9af442014-04-10 17:57:43 +00002320ASTReader::ASTReadResult
2321ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002322 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002323
2324 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2325 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002326 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002327 }
2328
2329 // Read all of the records and blocks for the AST file.
2330 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002331 while (1) {
2332 llvm::BitstreamEntry Entry = Stream.advance();
2333
2334 switch (Entry.Kind) {
2335 case llvm::BitstreamEntry::Error:
2336 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002337 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002338 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002339 // Outside of C++, we do not store a lookup map for the translation unit.
2340 // Instead, mark it as needing a lookup map to be built if this module
2341 // contains any declarations lexically within it (which it always does!).
2342 // This usually has no cost, since we very rarely need the lookup map for
2343 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002344 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002345 if (DC->hasExternalLexicalStorage() &&
2346 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002347 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002348
Ben Langmuir2c9af442014-04-10 17:57:43 +00002349 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002350 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002351 case llvm::BitstreamEntry::SubBlock:
2352 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 case DECLTYPES_BLOCK_ID:
2354 // We lazily load the decls block, but we want to set up the
2355 // DeclsCursor cursor to point into it. Clone our current bitcode
2356 // cursor to it, enter the block and read the abbrevs in that block.
2357 // With the main cursor, we just skip over it.
2358 F.DeclsCursor = Stream;
2359 if (Stream.SkipBlock() || // Skip with the main cursor.
2360 // Read the abbrevs.
2361 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2362 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002363 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002364 }
2365 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002366
Guy Benyei11169dd2012-12-18 14:30:41 +00002367 case PREPROCESSOR_BLOCK_ID:
2368 F.MacroCursor = Stream;
2369 if (!PP.getExternalSource())
2370 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002371
Guy Benyei11169dd2012-12-18 14:30:41 +00002372 if (Stream.SkipBlock() ||
2373 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2374 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002375 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002376 }
2377 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2378 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002379
Guy Benyei11169dd2012-12-18 14:30:41 +00002380 case PREPROCESSOR_DETAIL_BLOCK_ID:
2381 F.PreprocessorDetailCursor = Stream;
2382 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002383 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002385 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002386 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002387 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002388 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002389 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2390
Guy Benyei11169dd2012-12-18 14:30:41 +00002391 if (!PP.getPreprocessingRecord())
2392 PP.createPreprocessingRecord();
2393 if (!PP.getPreprocessingRecord()->getExternalSource())
2394 PP.getPreprocessingRecord()->SetExternalSource(*this);
2395 break;
2396
2397 case SOURCE_MANAGER_BLOCK_ID:
2398 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002399 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002400 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002401
Guy Benyei11169dd2012-12-18 14:30:41 +00002402 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002403 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2404 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002406
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002408 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002409 if (Stream.SkipBlock() ||
2410 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2411 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002412 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002413 }
2414 CommentsCursors.push_back(std::make_pair(C, &F));
2415 break;
2416 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002417
Guy Benyei11169dd2012-12-18 14:30:41 +00002418 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002419 if (Stream.SkipBlock()) {
2420 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002421 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002422 }
2423 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 }
2425 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002426
2427 case llvm::BitstreamEntry::Record:
2428 // The interesting case.
2429 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002430 }
2431
2432 // Read and process a record.
2433 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002434 StringRef Blob;
2435 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002436 default: // Default behavior: ignore.
2437 break;
2438
2439 case TYPE_OFFSET: {
2440 if (F.LocalNumTypes != 0) {
2441 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002442 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002443 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002444 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002445 F.LocalNumTypes = Record[0];
2446 unsigned LocalBaseTypeIndex = Record[1];
2447 F.BaseTypeIndex = getTotalNumTypes();
2448
2449 if (F.LocalNumTypes > 0) {
2450 // Introduce the global -> local mapping for types within this module.
2451 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2452
2453 // Introduce the local -> global mapping for types within this module.
2454 F.TypeRemap.insertOrReplace(
2455 std::make_pair(LocalBaseTypeIndex,
2456 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002457
2458 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002459 }
2460 break;
2461 }
2462
2463 case DECL_OFFSET: {
2464 if (F.LocalNumDecls != 0) {
2465 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002466 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002467 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002468 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 F.LocalNumDecls = Record[0];
2470 unsigned LocalBaseDeclID = Record[1];
2471 F.BaseDeclID = getTotalNumDecls();
2472
2473 if (F.LocalNumDecls > 0) {
2474 // Introduce the global -> local mapping for declarations within this
2475 // module.
2476 GlobalDeclMap.insert(
2477 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2478
2479 // Introduce the local -> global mapping for declarations within this
2480 // module.
2481 F.DeclRemap.insertOrReplace(
2482 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2483
2484 // Introduce the global -> local mapping for declarations within this
2485 // module.
2486 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002487
Ben Langmuir52ca6782014-10-20 16:27:32 +00002488 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2489 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 break;
2491 }
2492
2493 case TU_UPDATE_LEXICAL: {
2494 DeclContext *TU = Context.getTranslationUnitDecl();
2495 DeclContextInfo &Info = F.DeclContextInfos[TU];
Richard Smith787c0e42015-07-23 00:53:59 +00002496 Info.LexicalDecls = llvm::makeArrayRef(
2497 reinterpret_cast<const KindDeclIDPair *>(Blob.data()),
2498 static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 TU->setHasExternalLexicalStorage(true);
2500 break;
2501 }
2502
2503 case UPDATE_VISIBLE: {
2504 unsigned Idx = 0;
2505 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2506 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002507 ASTDeclContextNameLookupTable::Create(
2508 (const unsigned char *)Blob.data() + Record[Idx++],
2509 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2510 (const unsigned char *)Blob.data(),
2511 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002512 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002513 auto *DC = cast<DeclContext>(D);
2514 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002515 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2516 delete LookupTable;
2517 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 } else
2519 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2520 break;
2521 }
2522
2523 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002524 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002526 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2527 (const unsigned char *)F.IdentifierTableData + Record[0],
2528 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2529 (const unsigned char *)F.IdentifierTableData,
2530 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002531
2532 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2533 }
2534 break;
2535
2536 case IDENTIFIER_OFFSET: {
2537 if (F.LocalNumIdentifiers != 0) {
2538 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002539 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002540 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002541 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 F.LocalNumIdentifiers = Record[0];
2543 unsigned LocalBaseIdentifierID = Record[1];
2544 F.BaseIdentifierID = getTotalNumIdentifiers();
2545
2546 if (F.LocalNumIdentifiers > 0) {
2547 // Introduce the global -> local mapping for identifiers within this
2548 // module.
2549 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2550 &F));
2551
2552 // Introduce the local -> global mapping for identifiers within this
2553 // module.
2554 F.IdentifierRemap.insertOrReplace(
2555 std::make_pair(LocalBaseIdentifierID,
2556 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002557
Ben Langmuir52ca6782014-10-20 16:27:32 +00002558 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2559 + F.LocalNumIdentifiers);
2560 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 break;
2562 }
2563
Richard Smith33e0f7e2015-07-22 02:08:40 +00002564 case INTERESTING_IDENTIFIERS:
2565 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2566 break;
2567
Ben Langmuir332aafe2014-01-31 01:06:56 +00002568 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002569 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2570 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002572 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 break;
2574
2575 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002576 if (SpecialTypes.empty()) {
2577 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2578 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2579 break;
2580 }
2581
2582 if (SpecialTypes.size() != Record.size()) {
2583 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002584 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002585 }
2586
2587 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2588 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2589 if (!SpecialTypes[I])
2590 SpecialTypes[I] = ID;
2591 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2592 // merge step?
2593 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 break;
2595
2596 case STATISTICS:
2597 TotalNumStatements += Record[0];
2598 TotalNumMacros += Record[1];
2599 TotalLexicalDeclContexts += Record[2];
2600 TotalVisibleDeclContexts += Record[3];
2601 break;
2602
2603 case UNUSED_FILESCOPED_DECLS:
2604 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2605 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2606 break;
2607
2608 case DELEGATING_CTORS:
2609 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2610 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2611 break;
2612
2613 case WEAK_UNDECLARED_IDENTIFIERS:
2614 if (Record.size() % 4 != 0) {
2615 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002616 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002617 }
2618
2619 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2620 // files. This isn't the way to do it :)
2621 WeakUndeclaredIdentifiers.clear();
2622
2623 // Translate the weak, undeclared identifiers into global IDs.
2624 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2625 WeakUndeclaredIdentifiers.push_back(
2626 getGlobalIdentifierID(F, Record[I++]));
2627 WeakUndeclaredIdentifiers.push_back(
2628 getGlobalIdentifierID(F, Record[I++]));
2629 WeakUndeclaredIdentifiers.push_back(
2630 ReadSourceLocation(F, Record, I).getRawEncoding());
2631 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2632 }
2633 break;
2634
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002636 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 F.LocalNumSelectors = Record[0];
2638 unsigned LocalBaseSelectorID = Record[1];
2639 F.BaseSelectorID = getTotalNumSelectors();
2640
2641 if (F.LocalNumSelectors > 0) {
2642 // Introduce the global -> local mapping for selectors within this
2643 // module.
2644 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2645
2646 // Introduce the local -> global mapping for selectors within this
2647 // module.
2648 F.SelectorRemap.insertOrReplace(
2649 std::make_pair(LocalBaseSelectorID,
2650 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002651
2652 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 }
2654 break;
2655 }
2656
2657 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002658 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002659 if (Record[0])
2660 F.SelectorLookupTable
2661 = ASTSelectorLookupTable::Create(
2662 F.SelectorLookupTableData + Record[0],
2663 F.SelectorLookupTableData,
2664 ASTSelectorLookupTrait(*this, F));
2665 TotalNumMethodPoolEntries += Record[1];
2666 break;
2667
2668 case REFERENCED_SELECTOR_POOL:
2669 if (!Record.empty()) {
2670 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2671 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2672 Record[Idx++]));
2673 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2674 getRawEncoding());
2675 }
2676 }
2677 break;
2678
2679 case PP_COUNTER_VALUE:
2680 if (!Record.empty() && Listener)
2681 Listener->ReadCounter(F, Record[0]);
2682 break;
2683
2684 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002685 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 F.NumFileSortedDecls = Record[0];
2687 break;
2688
2689 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002690 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 F.LocalNumSLocEntries = Record[0];
2692 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002693 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002694 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002695 SLocSpaceSize);
2696 // Make our entry in the range map. BaseID is negative and growing, so
2697 // we invert it. Because we invert it, though, we need the other end of
2698 // the range.
2699 unsigned RangeStart =
2700 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2701 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2702 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2703
2704 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2705 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2706 GlobalSLocOffsetMap.insert(
2707 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2708 - SLocSpaceSize,&F));
2709
2710 // Initialize the remapping table.
2711 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002712 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002714 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2716
2717 TotalNumSLocEntries += F.LocalNumSLocEntries;
2718 break;
2719 }
2720
2721 case MODULE_OFFSET_MAP: {
2722 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002723 const unsigned char *Data = (const unsigned char*)Blob.data();
2724 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002725
2726 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2727 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2728 F.SLocRemap.insert(std::make_pair(0U, 0));
2729 F.SLocRemap.insert(std::make_pair(2U, 1));
2730 }
2731
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002733 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2734 RemapBuilder;
2735 RemapBuilder SLocRemap(F.SLocRemap);
2736 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2737 RemapBuilder MacroRemap(F.MacroRemap);
2738 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2739 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2740 RemapBuilder SelectorRemap(F.SelectorRemap);
2741 RemapBuilder DeclRemap(F.DeclRemap);
2742 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002743
2744 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002745 using namespace llvm::support;
2746 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 StringRef Name = StringRef((const char*)Data, Len);
2748 Data += Len;
2749 ModuleFile *OM = ModuleMgr.lookup(Name);
2750 if (!OM) {
2751 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002752 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002753 }
2754
Justin Bogner57ba0b22014-03-28 22:03:24 +00002755 uint32_t SLocOffset =
2756 endian::readNext<uint32_t, little, unaligned>(Data);
2757 uint32_t IdentifierIDOffset =
2758 endian::readNext<uint32_t, little, unaligned>(Data);
2759 uint32_t MacroIDOffset =
2760 endian::readNext<uint32_t, little, unaligned>(Data);
2761 uint32_t PreprocessedEntityIDOffset =
2762 endian::readNext<uint32_t, little, unaligned>(Data);
2763 uint32_t SubmoduleIDOffset =
2764 endian::readNext<uint32_t, little, unaligned>(Data);
2765 uint32_t SelectorIDOffset =
2766 endian::readNext<uint32_t, little, unaligned>(Data);
2767 uint32_t DeclIDOffset =
2768 endian::readNext<uint32_t, little, unaligned>(Data);
2769 uint32_t TypeIndexOffset =
2770 endian::readNext<uint32_t, little, unaligned>(Data);
2771
Ben Langmuir785180e2014-10-20 16:27:30 +00002772 uint32_t None = std::numeric_limits<uint32_t>::max();
2773
2774 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2775 RemapBuilder &Remap) {
2776 if (Offset != None)
2777 Remap.insert(std::make_pair(Offset,
2778 static_cast<int>(BaseOffset - Offset)));
2779 };
2780 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2781 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2782 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2783 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2784 PreprocessedEntityRemap);
2785 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2786 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2787 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2788 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002789
2790 // Global -> local mappings.
2791 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2792 }
2793 break;
2794 }
2795
2796 case SOURCE_MANAGER_LINE_TABLE:
2797 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002798 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002799 break;
2800
2801 case SOURCE_LOCATION_PRELOADS: {
2802 // Need to transform from the local view (1-based IDs) to the global view,
2803 // which is based off F.SLocEntryBaseID.
2804 if (!F.PreloadSLocEntries.empty()) {
2805 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002806 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002807 }
2808
2809 F.PreloadSLocEntries.swap(Record);
2810 break;
2811 }
2812
2813 case EXT_VECTOR_DECLS:
2814 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2815 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2816 break;
2817
2818 case VTABLE_USES:
2819 if (Record.size() % 3 != 0) {
2820 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002821 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002822 }
2823
2824 // Later tables overwrite earlier ones.
2825 // FIXME: Modules will have some trouble with this. This is clearly not
2826 // the right way to do this.
2827 VTableUses.clear();
2828
2829 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2830 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2831 VTableUses.push_back(
2832 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2833 VTableUses.push_back(Record[Idx++]);
2834 }
2835 break;
2836
Guy Benyei11169dd2012-12-18 14:30:41 +00002837 case PENDING_IMPLICIT_INSTANTIATIONS:
2838 if (PendingInstantiations.size() % 2 != 0) {
2839 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002840 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002841 }
2842
2843 if (Record.size() % 2 != 0) {
2844 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002845 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002846 }
2847
2848 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2849 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2850 PendingInstantiations.push_back(
2851 ReadSourceLocation(F, Record, I).getRawEncoding());
2852 }
2853 break;
2854
2855 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002856 if (Record.size() != 2) {
2857 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002858 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002859 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2861 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2862 break;
2863
2864 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002865 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2866 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2867 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002868
2869 unsigned LocalBasePreprocessedEntityID = Record[0];
2870
2871 unsigned StartingID;
2872 if (!PP.getPreprocessingRecord())
2873 PP.createPreprocessingRecord();
2874 if (!PP.getPreprocessingRecord()->getExternalSource())
2875 PP.getPreprocessingRecord()->SetExternalSource(*this);
2876 StartingID
2877 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002878 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002879 F.BasePreprocessedEntityID = StartingID;
2880
2881 if (F.NumPreprocessedEntities > 0) {
2882 // Introduce the global -> local mapping for preprocessed entities in
2883 // this module.
2884 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2885
2886 // Introduce the local -> global mapping for preprocessed entities in
2887 // this module.
2888 F.PreprocessedEntityRemap.insertOrReplace(
2889 std::make_pair(LocalBasePreprocessedEntityID,
2890 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2891 }
2892
2893 break;
2894 }
2895
2896 case DECL_UPDATE_OFFSETS: {
2897 if (Record.size() % 2 != 0) {
2898 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002899 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002900 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002901 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2902 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2903 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2904
2905 // If we've already loaded the decl, perform the updates when we finish
2906 // loading this block.
2907 if (Decl *D = GetExistingDecl(ID))
2908 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2909 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002910 break;
2911 }
2912
2913 case DECL_REPLACEMENTS: {
2914 if (Record.size() % 3 != 0) {
2915 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002916 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002917 }
2918 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2919 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2920 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2921 break;
2922 }
2923
2924 case OBJC_CATEGORIES_MAP: {
2925 if (F.LocalNumObjCCategoriesInMap != 0) {
2926 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002927 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002928 }
2929
2930 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002931 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002932 break;
2933 }
2934
2935 case OBJC_CATEGORIES:
2936 F.ObjCCategories.swap(Record);
2937 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00002938
Guy Benyei11169dd2012-12-18 14:30:41 +00002939 case CXX_BASE_SPECIFIER_OFFSETS: {
2940 if (F.LocalNumCXXBaseSpecifiers != 0) {
2941 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002942 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002943 }
Richard Smithc2bb8182015-03-24 06:36:48 +00002944
Guy Benyei11169dd2012-12-18 14:30:41 +00002945 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002946 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00002947 break;
2948 }
2949
2950 case CXX_CTOR_INITIALIZERS_OFFSETS: {
2951 if (F.LocalNumCXXCtorInitializers != 0) {
2952 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2953 return Failure;
2954 }
2955
2956 F.LocalNumCXXCtorInitializers = Record[0];
2957 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002958 break;
2959 }
2960
2961 case DIAG_PRAGMA_MAPPINGS:
2962 if (F.PragmaDiagMappings.empty())
2963 F.PragmaDiagMappings.swap(Record);
2964 else
2965 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2966 Record.begin(), Record.end());
2967 break;
2968
2969 case CUDA_SPECIAL_DECL_REFS:
2970 // Later tables overwrite earlier ones.
2971 // FIXME: Modules will have trouble with this.
2972 CUDASpecialDeclRefs.clear();
2973 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2974 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2975 break;
2976
2977 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002978 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002979 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002980 if (Record[0]) {
2981 F.HeaderFileInfoTable
2982 = HeaderFileInfoLookupTable::Create(
2983 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2984 (const unsigned char *)F.HeaderFileInfoTableData,
2985 HeaderFileInfoTrait(*this, F,
2986 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002987 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002988
2989 PP.getHeaderSearchInfo().SetExternalSource(this);
2990 if (!PP.getHeaderSearchInfo().getExternalLookup())
2991 PP.getHeaderSearchInfo().SetExternalLookup(this);
2992 }
2993 break;
2994 }
2995
2996 case FP_PRAGMA_OPTIONS:
2997 // Later tables overwrite earlier ones.
2998 FPPragmaOptions.swap(Record);
2999 break;
3000
3001 case OPENCL_EXTENSIONS:
3002 // Later tables overwrite earlier ones.
3003 OpenCLExtensions.swap(Record);
3004 break;
3005
3006 case TENTATIVE_DEFINITIONS:
3007 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3008 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3009 break;
3010
3011 case KNOWN_NAMESPACES:
3012 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3013 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3014 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003015
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003016 case UNDEFINED_BUT_USED:
3017 if (UndefinedButUsed.size() % 2 != 0) {
3018 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003019 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003020 }
3021
3022 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003023 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003024 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003025 }
3026 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003027 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3028 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003029 ReadSourceLocation(F, Record, I).getRawEncoding());
3030 }
3031 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003032 case DELETE_EXPRS_TO_ANALYZE:
3033 for (unsigned I = 0, N = Record.size(); I != N;) {
3034 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3035 const uint64_t Count = Record[I++];
3036 DelayedDeleteExprs.push_back(Count);
3037 for (uint64_t C = 0; C < Count; ++C) {
3038 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3039 bool IsArrayForm = Record[I++] == 1;
3040 DelayedDeleteExprs.push_back(IsArrayForm);
3041 }
3042 }
3043 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003044
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003046 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003047 // If we aren't loading a module (which has its own exports), make
3048 // all of the imported modules visible.
3049 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003050 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3051 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3052 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3053 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003054 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003055 }
3056 }
3057 break;
3058 }
3059
3060 case LOCAL_REDECLARATIONS: {
3061 F.RedeclarationChains.swap(Record);
3062 break;
3063 }
3064
3065 case LOCAL_REDECLARATIONS_MAP: {
3066 if (F.LocalNumRedeclarationsInMap != 0) {
3067 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003068 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003069 }
3070
3071 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003072 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003073 break;
3074 }
3075
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 case MACRO_OFFSET: {
3077 if (F.LocalNumMacros != 0) {
3078 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003079 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003080 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003081 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003082 F.LocalNumMacros = Record[0];
3083 unsigned LocalBaseMacroID = Record[1];
3084 F.BaseMacroID = getTotalNumMacros();
3085
3086 if (F.LocalNumMacros > 0) {
3087 // Introduce the global -> local mapping for macros within this module.
3088 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3089
3090 // Introduce the local -> global mapping for macros within this module.
3091 F.MacroRemap.insertOrReplace(
3092 std::make_pair(LocalBaseMacroID,
3093 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003094
3095 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003096 }
3097 break;
3098 }
3099
Richard Smithe40f2ba2013-08-07 21:41:30 +00003100 case LATE_PARSED_TEMPLATE: {
3101 LateParsedTemplates.append(Record.begin(), Record.end());
3102 break;
3103 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003104
3105 case OPTIMIZE_PRAGMA_OPTIONS:
3106 if (Record.size() != 1) {
3107 Error("invalid pragma optimize record");
3108 return Failure;
3109 }
3110 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3111 break;
Nico Weber72889432014-09-06 01:25:55 +00003112
3113 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3114 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3115 UnusedLocalTypedefNameCandidates.push_back(
3116 getGlobalDeclID(F, Record[I]));
3117 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003118 }
3119 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003120}
3121
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003122ASTReader::ASTReadResult
3123ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3124 const ModuleFile *ImportedBy,
3125 unsigned ClientLoadCapabilities) {
3126 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003127 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003128
Richard Smithe842a472014-10-22 02:05:46 +00003129 if (F.Kind == MK_ExplicitModule) {
3130 // For an explicitly-loaded module, we don't care whether the original
3131 // module map file exists or matches.
3132 return Success;
3133 }
3134
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003135 // Try to resolve ModuleName in the current header search context and
3136 // verify that it is found in the same module map file as we saved. If the
3137 // top-level AST file is a main file, skip this check because there is no
3138 // usable header search context.
3139 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003140 "MODULE_NAME should come before MODULE_MAP_FILE");
3141 if (F.Kind == MK_ImplicitModule &&
3142 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3143 // An implicitly-loaded module file should have its module listed in some
3144 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003145 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003146 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3147 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3148 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003149 assert(ImportedBy && "top-level import should be verified");
3150 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003151 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3152 << ImportedBy->FileName
3153 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003154 return Missing;
3155 }
3156
Richard Smithe842a472014-10-22 02:05:46 +00003157 assert(M->Name == F.ModuleName && "found module with different name");
3158
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003159 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003160 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003161 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3162 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003163 assert(ImportedBy && "top-level import should be verified");
3164 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3165 Diag(diag::err_imported_module_modmap_changed)
3166 << F.ModuleName << ImportedBy->FileName
3167 << ModMap->getName() << F.ModuleMapPath;
3168 return OutOfDate;
3169 }
3170
3171 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3172 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3173 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003174 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003175 const FileEntry *F =
3176 FileMgr.getFile(Filename, false, false);
3177 if (F == nullptr) {
3178 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3179 Error("could not find file '" + Filename +"' referenced by AST file");
3180 return OutOfDate;
3181 }
3182 AdditionalStoredMaps.insert(F);
3183 }
3184
3185 // Check any additional module map files (e.g. module.private.modulemap)
3186 // that are not in the pcm.
3187 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3188 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3189 // Remove files that match
3190 // Note: SmallPtrSet::erase is really remove
3191 if (!AdditionalStoredMaps.erase(ModMap)) {
3192 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3193 Diag(diag::err_module_different_modmap)
3194 << F.ModuleName << /*new*/0 << ModMap->getName();
3195 return OutOfDate;
3196 }
3197 }
3198 }
3199
3200 // Check any additional module map files that are in the pcm, but not
3201 // found in header search. Cases that match are already removed.
3202 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3203 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3204 Diag(diag::err_module_different_modmap)
3205 << F.ModuleName << /*not new*/1 << ModMap->getName();
3206 return OutOfDate;
3207 }
3208 }
3209
3210 if (Listener)
3211 Listener->ReadModuleMapFile(F.ModuleMapPath);
3212 return Success;
3213}
3214
3215
Douglas Gregorc1489562013-02-12 23:36:21 +00003216/// \brief Move the given method to the back of the global list of methods.
3217static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3218 // Find the entry for this selector in the method pool.
3219 Sema::GlobalMethodPool::iterator Known
3220 = S.MethodPool.find(Method->getSelector());
3221 if (Known == S.MethodPool.end())
3222 return;
3223
3224 // Retrieve the appropriate method list.
3225 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3226 : Known->second.second;
3227 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003228 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003229 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003230 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003231 Found = true;
3232 } else {
3233 // Keep searching.
3234 continue;
3235 }
3236 }
3237
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003238 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003239 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003240 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003241 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003242 }
3243}
3244
Richard Smithde711422015-04-23 21:20:19 +00003245void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003246 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003247 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003248 bool wasHidden = D->Hidden;
3249 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003250
Richard Smith49f906a2014-03-01 00:08:04 +00003251 if (wasHidden && SemaObj) {
3252 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3253 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003254 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003255 }
3256 }
3257}
3258
Richard Smith49f906a2014-03-01 00:08:04 +00003259void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003260 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003261 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003262 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003263 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003264 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003265 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003266 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003267
3268 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003269 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003270 // there is nothing more to do.
3271 continue;
3272 }
Richard Smith49f906a2014-03-01 00:08:04 +00003273
Guy Benyei11169dd2012-12-18 14:30:41 +00003274 if (!Mod->isAvailable()) {
3275 // Modules that aren't available cannot be made visible.
3276 continue;
3277 }
3278
3279 // Update the module's name visibility.
3280 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003281
Guy Benyei11169dd2012-12-18 14:30:41 +00003282 // If we've already deserialized any names from this module,
3283 // mark them as visible.
3284 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3285 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003286 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003287 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003288 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003289 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3290 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003291 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003292
Guy Benyei11169dd2012-12-18 14:30:41 +00003293 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003294 SmallVector<Module *, 16> Exports;
3295 Mod->getExportedModules(Exports);
3296 for (SmallVectorImpl<Module *>::iterator
3297 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3298 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003299 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003300 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003301 }
3302 }
3303}
3304
Douglas Gregore060e572013-01-25 01:03:03 +00003305bool ASTReader::loadGlobalIndex() {
3306 if (GlobalIndex)
3307 return false;
3308
3309 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3310 !Context.getLangOpts().Modules)
3311 return true;
3312
3313 // Try to load the global index.
3314 TriedLoadingGlobalIndex = true;
3315 StringRef ModuleCachePath
3316 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3317 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003318 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003319 if (!Result.first)
3320 return true;
3321
3322 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003323 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003324 return false;
3325}
3326
3327bool ASTReader::isGlobalIndexUnavailable() const {
3328 return Context.getLangOpts().Modules && UseGlobalIndex &&
3329 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3330}
3331
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003332static void updateModuleTimestamp(ModuleFile &MF) {
3333 // Overwrite the timestamp file contents so that file's mtime changes.
3334 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003335 std::error_code EC;
3336 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3337 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003338 return;
3339 OS << "Timestamp file\n";
3340}
3341
Guy Benyei11169dd2012-12-18 14:30:41 +00003342ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3343 ModuleKind Type,
3344 SourceLocation ImportLoc,
3345 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003346 llvm::SaveAndRestore<SourceLocation>
3347 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3348
Richard Smithd1c46742014-04-30 02:24:17 +00003349 // Defer any pending actions until we get to the end of reading the AST file.
3350 Deserializing AnASTFile(this);
3351
Guy Benyei11169dd2012-12-18 14:30:41 +00003352 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003353 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003354
3355 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003356 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003357 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003358 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003359 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003360 ClientLoadCapabilities)) {
3361 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003362 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003363 case OutOfDate:
3364 case VersionMismatch:
3365 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003366 case HadErrors: {
3367 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3368 for (const ImportedModule &IM : Loaded)
3369 LoadedSet.insert(IM.Mod);
3370
Douglas Gregor7029ce12013-03-19 00:28:20 +00003371 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003372 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003373 Context.getLangOpts().Modules
3374 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003375 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003376
3377 // If we find that any modules are unusable, the global index is going
3378 // to be out-of-date. Just remove it.
3379 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003380 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003381 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003382 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003383 case Success:
3384 break;
3385 }
3386
3387 // Here comes stuff that we only do once the entire chain is loaded.
3388
3389 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003390 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3391 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003392 M != MEnd; ++M) {
3393 ModuleFile &F = *M->Mod;
3394
3395 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003396 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3397 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003398
3399 // Once read, set the ModuleFile bit base offset and update the size in
3400 // bits of all files we've seen.
3401 F.GlobalBitOffset = TotalModulesSizeInBits;
3402 TotalModulesSizeInBits += F.SizeInBits;
3403 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3404
3405 // Preload SLocEntries.
3406 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3407 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3408 // Load it through the SourceManager and don't call ReadSLocEntry()
3409 // directly because the entry may have already been loaded in which case
3410 // calling ReadSLocEntry() directly would trigger an assertion in
3411 // SourceManager.
3412 SourceMgr.getLoadedSLocEntryByID(Index);
3413 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003414
3415 // Preload all the pending interesting identifiers by marking them out of
3416 // date.
3417 for (auto Offset : F.PreloadIdentifierOffsets) {
3418 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3419 F.IdentifierTableData + Offset);
3420
3421 ASTIdentifierLookupTrait Trait(*this, F);
3422 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3423 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3424 PP.getIdentifierTable().getOwn(Key).setOutOfDate(true);
3425 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003426 }
3427
Douglas Gregor603cd862013-03-22 18:50:14 +00003428 // Setup the import locations and notify the module manager that we've
3429 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003430 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3431 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003432 M != MEnd; ++M) {
3433 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003434
3435 ModuleMgr.moduleFileAccepted(&F);
3436
3437 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003438 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003439 if (!M->ImportedBy)
3440 F.ImportLoc = M->ImportLoc;
3441 else
3442 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3443 M->ImportLoc.getRawEncoding());
3444 }
3445
Richard Smith33e0f7e2015-07-22 02:08:40 +00003446 if (!Context.getLangOpts().CPlusPlus ||
3447 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3448 // Mark all of the identifiers in the identifier table as being out of date,
3449 // so that various accessors know to check the loaded modules when the
3450 // identifier is used.
3451 //
3452 // For C++ modules, we don't need information on many identifiers (just
3453 // those that provide macros or are poisoned), so we mark all of
3454 // the interesting ones via PreloadIdentifierOffsets.
3455 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3456 IdEnd = PP.getIdentifierTable().end();
3457 Id != IdEnd; ++Id)
3458 Id->second->setOutOfDate(true);
3459 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003460
3461 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003462 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3463 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003464 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3465 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003466
3467 switch (Unresolved.Kind) {
3468 case UnresolvedModuleRef::Conflict:
3469 if (ResolvedMod) {
3470 Module::Conflict Conflict;
3471 Conflict.Other = ResolvedMod;
3472 Conflict.Message = Unresolved.String.str();
3473 Unresolved.Mod->Conflicts.push_back(Conflict);
3474 }
3475 continue;
3476
3477 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003478 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003479 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003480 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003481
Douglas Gregorfb912652013-03-20 21:10:35 +00003482 case UnresolvedModuleRef::Export:
3483 if (ResolvedMod || Unresolved.IsWildcard)
3484 Unresolved.Mod->Exports.push_back(
3485 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3486 continue;
3487 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003488 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003489 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003490
3491 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3492 // Might be unnecessary as use declarations are only used to build the
3493 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003494
3495 InitializeContext();
3496
Richard Smith3d8e97e2013-10-18 06:54:39 +00003497 if (SemaObj)
3498 UpdateSema();
3499
Guy Benyei11169dd2012-12-18 14:30:41 +00003500 if (DeserializationListener)
3501 DeserializationListener->ReaderInitialized(this);
3502
3503 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3504 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3505 PrimaryModule.OriginalSourceFileID
3506 = FileID::get(PrimaryModule.SLocEntryBaseID
3507 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3508
3509 // If this AST file is a precompiled preamble, then set the
3510 // preamble file ID of the source manager to the file source file
3511 // from which the preamble was built.
3512 if (Type == MK_Preamble) {
3513 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3514 } else if (Type == MK_MainFile) {
3515 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3516 }
3517 }
3518
3519 // For any Objective-C class definitions we have already loaded, make sure
3520 // that we load any additional categories.
3521 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3522 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3523 ObjCClassesLoaded[I],
3524 PreviousGeneration);
3525 }
Douglas Gregore060e572013-01-25 01:03:03 +00003526
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003527 if (PP.getHeaderSearchInfo()
3528 .getHeaderSearchOpts()
3529 .ModulesValidateOncePerBuildSession) {
3530 // Now we are certain that the module and all modules it depends on are
3531 // up to date. Create or update timestamp files for modules that are
3532 // located in the module cache (not for PCH files that could be anywhere
3533 // in the filesystem).
3534 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3535 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003536 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003537 updateModuleTimestamp(*M.Mod);
3538 }
3539 }
3540 }
3541
Guy Benyei11169dd2012-12-18 14:30:41 +00003542 return Success;
3543}
3544
Ben Langmuir487ea142014-10-23 18:05:36 +00003545static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3546
Ben Langmuir70a1b812015-03-24 04:43:52 +00003547/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3548static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3549 return Stream.Read(8) == 'C' &&
3550 Stream.Read(8) == 'P' &&
3551 Stream.Read(8) == 'C' &&
3552 Stream.Read(8) == 'H';
3553}
3554
Guy Benyei11169dd2012-12-18 14:30:41 +00003555ASTReader::ASTReadResult
3556ASTReader::ReadASTCore(StringRef FileName,
3557 ModuleKind Type,
3558 SourceLocation ImportLoc,
3559 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003560 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003561 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003562 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003563 unsigned ClientLoadCapabilities) {
3564 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003565 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003566 ModuleManager::AddModuleResult AddResult
3567 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003568 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003569 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003570 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003571
Douglas Gregor7029ce12013-03-19 00:28:20 +00003572 switch (AddResult) {
3573 case ModuleManager::AlreadyLoaded:
3574 return Success;
3575
3576 case ModuleManager::NewlyLoaded:
3577 // Load module file below.
3578 break;
3579
3580 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003581 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003582 // it.
3583 if (ClientLoadCapabilities & ARR_Missing)
3584 return Missing;
3585
3586 // Otherwise, return an error.
3587 {
3588 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3589 + ErrorStr;
3590 Error(Msg);
3591 }
3592 return Failure;
3593
3594 case ModuleManager::OutOfDate:
3595 // We couldn't load the module file because it is out-of-date. If the
3596 // client can handle out-of-date, return it.
3597 if (ClientLoadCapabilities & ARR_OutOfDate)
3598 return OutOfDate;
3599
3600 // Otherwise, return an error.
3601 {
3602 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3603 + ErrorStr;
3604 Error(Msg);
3605 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003606 return Failure;
3607 }
3608
Douglas Gregor7029ce12013-03-19 00:28:20 +00003609 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003610
3611 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3612 // module?
3613 if (FileName != "-") {
3614 CurrentDir = llvm::sys::path::parent_path(FileName);
3615 if (CurrentDir.empty()) CurrentDir = ".";
3616 }
3617
3618 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003619 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003620 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003621 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003622 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3623
Guy Benyei11169dd2012-12-18 14:30:41 +00003624 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003625 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003626 Diag(diag::err_not_a_pch_file) << FileName;
3627 return Failure;
3628 }
3629
3630 // This is used for compatibility with older PCH formats.
3631 bool HaveReadControlBlock = false;
3632
Chris Lattnerefa77172013-01-20 00:00:22 +00003633 while (1) {
3634 llvm::BitstreamEntry Entry = Stream.advance();
3635
3636 switch (Entry.Kind) {
3637 case llvm::BitstreamEntry::Error:
3638 case llvm::BitstreamEntry::EndBlock:
3639 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003640 Error("invalid record at top-level of AST file");
3641 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003642
3643 case llvm::BitstreamEntry::SubBlock:
3644 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003645 }
3646
Guy Benyei11169dd2012-12-18 14:30:41 +00003647 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003648 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003649 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3650 if (Stream.ReadBlockInfoBlock()) {
3651 Error("malformed BlockInfoBlock in AST file");
3652 return Failure;
3653 }
3654 break;
3655 case CONTROL_BLOCK_ID:
3656 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003657 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003658 case Success:
3659 break;
3660
3661 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003662 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003663 case OutOfDate: return OutOfDate;
3664 case VersionMismatch: return VersionMismatch;
3665 case ConfigurationMismatch: return ConfigurationMismatch;
3666 case HadErrors: return HadErrors;
3667 }
3668 break;
3669 case AST_BLOCK_ID:
3670 if (!HaveReadControlBlock) {
3671 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003672 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003673 return VersionMismatch;
3674 }
3675
3676 // Record that we've loaded this module.
3677 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3678 return Success;
3679
3680 default:
3681 if (Stream.SkipBlock()) {
3682 Error("malformed block record in AST file");
3683 return Failure;
3684 }
3685 break;
3686 }
3687 }
3688
3689 return Success;
3690}
3691
Richard Smitha7e2cc62015-05-01 01:53:09 +00003692void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003693 // If there's a listener, notify them that we "read" the translation unit.
3694 if (DeserializationListener)
3695 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3696 Context.getTranslationUnitDecl());
3697
Guy Benyei11169dd2012-12-18 14:30:41 +00003698 // FIXME: Find a better way to deal with collisions between these
3699 // built-in types. Right now, we just ignore the problem.
3700
3701 // Load the special types.
3702 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3703 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3704 if (!Context.CFConstantStringTypeDecl)
3705 Context.setCFConstantStringType(GetType(String));
3706 }
3707
3708 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3709 QualType FileType = GetType(File);
3710 if (FileType.isNull()) {
3711 Error("FILE type is NULL");
3712 return;
3713 }
3714
3715 if (!Context.FILEDecl) {
3716 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3717 Context.setFILEDecl(Typedef->getDecl());
3718 else {
3719 const TagType *Tag = FileType->getAs<TagType>();
3720 if (!Tag) {
3721 Error("Invalid FILE type in AST file");
3722 return;
3723 }
3724 Context.setFILEDecl(Tag->getDecl());
3725 }
3726 }
3727 }
3728
3729 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3730 QualType Jmp_bufType = GetType(Jmp_buf);
3731 if (Jmp_bufType.isNull()) {
3732 Error("jmp_buf type is NULL");
3733 return;
3734 }
3735
3736 if (!Context.jmp_bufDecl) {
3737 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3738 Context.setjmp_bufDecl(Typedef->getDecl());
3739 else {
3740 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3741 if (!Tag) {
3742 Error("Invalid jmp_buf type in AST file");
3743 return;
3744 }
3745 Context.setjmp_bufDecl(Tag->getDecl());
3746 }
3747 }
3748 }
3749
3750 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3751 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3752 if (Sigjmp_bufType.isNull()) {
3753 Error("sigjmp_buf type is NULL");
3754 return;
3755 }
3756
3757 if (!Context.sigjmp_bufDecl) {
3758 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3759 Context.setsigjmp_bufDecl(Typedef->getDecl());
3760 else {
3761 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3762 assert(Tag && "Invalid sigjmp_buf type in AST file");
3763 Context.setsigjmp_bufDecl(Tag->getDecl());
3764 }
3765 }
3766 }
3767
3768 if (unsigned ObjCIdRedef
3769 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3770 if (Context.ObjCIdRedefinitionType.isNull())
3771 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3772 }
3773
3774 if (unsigned ObjCClassRedef
3775 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3776 if (Context.ObjCClassRedefinitionType.isNull())
3777 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3778 }
3779
3780 if (unsigned ObjCSelRedef
3781 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3782 if (Context.ObjCSelRedefinitionType.isNull())
3783 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3784 }
3785
3786 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3787 QualType Ucontext_tType = GetType(Ucontext_t);
3788 if (Ucontext_tType.isNull()) {
3789 Error("ucontext_t type is NULL");
3790 return;
3791 }
3792
3793 if (!Context.ucontext_tDecl) {
3794 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3795 Context.setucontext_tDecl(Typedef->getDecl());
3796 else {
3797 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3798 assert(Tag && "Invalid ucontext_t type in AST file");
3799 Context.setucontext_tDecl(Tag->getDecl());
3800 }
3801 }
3802 }
3803 }
3804
3805 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3806
3807 // If there were any CUDA special declarations, deserialize them.
3808 if (!CUDASpecialDeclRefs.empty()) {
3809 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3810 Context.setcudaConfigureCallDecl(
3811 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3812 }
Richard Smith56be7542014-03-21 00:33:59 +00003813
Guy Benyei11169dd2012-12-18 14:30:41 +00003814 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003815 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003816 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003817 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003818 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003819 /*ImportLoc=*/Import.ImportLoc);
3820 PP.makeModuleVisible(Imported, Import.ImportLoc);
3821 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003822 }
3823 ImportedModules.clear();
3824}
3825
3826void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003827 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003828}
3829
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003830/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3831/// cursor into the start of the given block ID, returning false on success and
3832/// true on failure.
3833static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003834 while (1) {
3835 llvm::BitstreamEntry Entry = Cursor.advance();
3836 switch (Entry.Kind) {
3837 case llvm::BitstreamEntry::Error:
3838 case llvm::BitstreamEntry::EndBlock:
3839 return true;
3840
3841 case llvm::BitstreamEntry::Record:
3842 // Ignore top-level records.
3843 Cursor.skipRecord(Entry.ID);
3844 break;
3845
3846 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003847 if (Entry.ID == BlockID) {
3848 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003849 return true;
3850 // Found it!
3851 return false;
3852 }
3853
3854 if (Cursor.SkipBlock())
3855 return true;
3856 }
3857 }
3858}
3859
Ben Langmuir70a1b812015-03-24 04:43:52 +00003860/// \brief Reads and return the signature record from \p StreamFile's control
3861/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003862static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3863 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003864 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003865 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003866
3867 // Scan for the CONTROL_BLOCK_ID block.
3868 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3869 return 0;
3870
3871 // Scan for SIGNATURE inside the control block.
3872 ASTReader::RecordData Record;
3873 while (1) {
3874 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3875 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3876 Entry.Kind != llvm::BitstreamEntry::Record)
3877 return 0;
3878
3879 Record.clear();
3880 StringRef Blob;
3881 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3882 return Record[0];
3883 }
3884}
3885
Guy Benyei11169dd2012-12-18 14:30:41 +00003886/// \brief Retrieve the name of the original source file name
3887/// directly from the AST file, without actually loading the AST
3888/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003889std::string ASTReader::getOriginalSourceFile(
3890 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003891 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003892 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00003893 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00003894 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00003895 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3896 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00003897 return std::string();
3898 }
3899
3900 // Initialize the stream
3901 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003902 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003903 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003904
3905 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003906 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003907 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3908 return std::string();
3909 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003910
Chris Lattnere7b154b2013-01-19 21:39:22 +00003911 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003912 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003913 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3914 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003915 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003916
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003917 // Scan for ORIGINAL_FILE inside the control block.
3918 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003919 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003920 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003921 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3922 return std::string();
3923
3924 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3925 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3926 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003927 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003928
Guy Benyei11169dd2012-12-18 14:30:41 +00003929 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003930 StringRef Blob;
3931 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3932 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003933 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003934}
3935
3936namespace {
3937 class SimplePCHValidator : public ASTReaderListener {
3938 const LangOptions &ExistingLangOpts;
3939 const TargetOptions &ExistingTargetOpts;
3940 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003941 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00003942 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003943
Guy Benyei11169dd2012-12-18 14:30:41 +00003944 public:
3945 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3946 const TargetOptions &ExistingTargetOpts,
3947 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003948 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00003949 FileManager &FileMgr)
3950 : ExistingLangOpts(ExistingLangOpts),
3951 ExistingTargetOpts(ExistingTargetOpts),
3952 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003953 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00003954 FileMgr(FileMgr)
3955 {
3956 }
3957
Richard Smith1e2cf0d2014-10-31 02:28:58 +00003958 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
3959 bool AllowCompatibleDifferences) override {
3960 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
3961 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003962 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00003963 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
3964 bool AllowCompatibleDifferences) override {
3965 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
3966 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003967 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003968 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
3969 StringRef SpecificModuleCachePath,
3970 bool Complain) override {
3971 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
3972 ExistingModuleCachePath,
3973 nullptr, ExistingLangOpts);
3974 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003975 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3976 bool Complain,
3977 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00003978 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003979 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003980 }
3981 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003982}
Guy Benyei11169dd2012-12-18 14:30:41 +00003983
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003984bool ASTReader::readASTFileControlBlock(
3985 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003986 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003987 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003988 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00003989 // FIXME: This allows use of the VFS; we do not allow use of the
3990 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00003991 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00003992 if (!Buffer) {
3993 return true;
3994 }
3995
3996 // Initialize the stream
3997 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003998 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003999 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004000
4001 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004002 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004003 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004004
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004005 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004006 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004007 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004008
4009 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004010 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004011 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004012 BitstreamCursor InputFilesCursor;
4013 if (NeedsInputFiles) {
4014 InputFilesCursor = Stream;
4015 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4016 return true;
4017
4018 // Read the abbreviations
4019 while (true) {
4020 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4021 unsigned Code = InputFilesCursor.ReadCode();
4022
4023 // We expect all abbrevs to be at the start of the block.
4024 if (Code != llvm::bitc::DEFINE_ABBREV) {
4025 InputFilesCursor.JumpToBit(Offset);
4026 break;
4027 }
4028 InputFilesCursor.ReadAbbrevRecord();
4029 }
4030 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004031
4032 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004033 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004034 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004035 while (1) {
4036 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4037 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4038 return false;
4039
4040 if (Entry.Kind != llvm::BitstreamEntry::Record)
4041 return true;
4042
Guy Benyei11169dd2012-12-18 14:30:41 +00004043 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004044 StringRef Blob;
4045 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004046 switch ((ControlRecordTypes)RecCode) {
4047 case METADATA: {
4048 if (Record[0] != VERSION_MAJOR)
4049 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004050
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004051 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004052 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004053
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004054 break;
4055 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004056 case MODULE_NAME:
4057 Listener.ReadModuleName(Blob);
4058 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004059 case MODULE_DIRECTORY:
4060 ModuleDir = Blob;
4061 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004062 case MODULE_MAP_FILE: {
4063 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004064 auto Path = ReadString(Record, Idx);
4065 ResolveImportedPath(Path, ModuleDir);
4066 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004067 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004068 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004069 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004070 if (ParseLanguageOptions(Record, false, Listener,
4071 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004072 return true;
4073 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004074
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004075 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004076 if (ParseTargetOptions(Record, false, Listener,
4077 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004078 return true;
4079 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004080
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004081 case DIAGNOSTIC_OPTIONS:
4082 if (ParseDiagnosticOptions(Record, false, Listener))
4083 return true;
4084 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004085
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004086 case FILE_SYSTEM_OPTIONS:
4087 if (ParseFileSystemOptions(Record, false, Listener))
4088 return true;
4089 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004090
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004091 case HEADER_SEARCH_OPTIONS:
4092 if (ParseHeaderSearchOptions(Record, false, Listener))
4093 return true;
4094 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004095
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004096 case PREPROCESSOR_OPTIONS: {
4097 std::string IgnoredSuggestedPredefines;
4098 if (ParsePreprocessorOptions(Record, false, Listener,
4099 IgnoredSuggestedPredefines))
4100 return true;
4101 break;
4102 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004103
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004104 case INPUT_FILE_OFFSETS: {
4105 if (!NeedsInputFiles)
4106 break;
4107
4108 unsigned NumInputFiles = Record[0];
4109 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004110 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004111 for (unsigned I = 0; I != NumInputFiles; ++I) {
4112 // Go find this input file.
4113 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004114
4115 if (isSystemFile && !NeedsSystemInputFiles)
4116 break; // the rest are system input files
4117
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004118 BitstreamCursor &Cursor = InputFilesCursor;
4119 SavedStreamPosition SavedPosition(Cursor);
4120 Cursor.JumpToBit(InputFileOffs[I]);
4121
4122 unsigned Code = Cursor.ReadCode();
4123 RecordData Record;
4124 StringRef Blob;
4125 bool shouldContinue = false;
4126 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4127 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004128 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004129 std::string Filename = Blob;
4130 ResolveImportedPath(Filename, ModuleDir);
4131 shouldContinue =
4132 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004133 break;
4134 }
4135 if (!shouldContinue)
4136 break;
4137 }
4138 break;
4139 }
4140
Richard Smithd4b230b2014-10-27 23:01:16 +00004141 case IMPORTS: {
4142 if (!NeedsImports)
4143 break;
4144
4145 unsigned Idx = 0, N = Record.size();
4146 while (Idx < N) {
4147 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004148 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004149 std::string Filename = ReadString(Record, Idx);
4150 ResolveImportedPath(Filename, ModuleDir);
4151 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004152 }
4153 break;
4154 }
4155
Richard Smith7f330cd2015-03-18 01:42:29 +00004156 case KNOWN_MODULE_FILES: {
4157 // Known-but-not-technically-used module files are treated as imports.
4158 if (!NeedsImports)
4159 break;
4160
4161 unsigned Idx = 0, N = Record.size();
4162 while (Idx < N) {
4163 std::string Filename = ReadString(Record, Idx);
4164 ResolveImportedPath(Filename, ModuleDir);
4165 Listener.visitImport(Filename);
4166 }
4167 break;
4168 }
4169
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004170 default:
4171 // No other validation to perform.
4172 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004173 }
4174 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004175}
4176
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004177bool ASTReader::isAcceptableASTFile(
4178 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004179 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004180 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4181 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004182 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4183 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004184 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004185 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004186}
4187
Ben Langmuir2c9af442014-04-10 17:57:43 +00004188ASTReader::ASTReadResult
4189ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004190 // Enter the submodule block.
4191 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4192 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004193 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004194 }
4195
4196 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4197 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004198 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004199 RecordData Record;
4200 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004201 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4202
4203 switch (Entry.Kind) {
4204 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4205 case llvm::BitstreamEntry::Error:
4206 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004207 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004208 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004209 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004210 case llvm::BitstreamEntry::Record:
4211 // The interesting case.
4212 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004214
Guy Benyei11169dd2012-12-18 14:30:41 +00004215 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004216 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004217 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004218 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4219
4220 if ((Kind == SUBMODULE_METADATA) != First) {
4221 Error("submodule metadata record should be at beginning of block");
4222 return Failure;
4223 }
4224 First = false;
4225
4226 // Submodule information is only valid if we have a current module.
4227 // FIXME: Should we error on these cases?
4228 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4229 Kind != SUBMODULE_DEFINITION)
4230 continue;
4231
4232 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004233 default: // Default behavior: ignore.
4234 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004235
Richard Smith03478d92014-10-23 22:12:14 +00004236 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004237 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004238 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004239 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004240 }
Richard Smith03478d92014-10-23 22:12:14 +00004241
Chris Lattner0e6c9402013-01-20 02:38:54 +00004242 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004243 unsigned Idx = 0;
4244 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4245 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4246 bool IsFramework = Record[Idx++];
4247 bool IsExplicit = Record[Idx++];
4248 bool IsSystem = Record[Idx++];
4249 bool IsExternC = Record[Idx++];
4250 bool InferSubmodules = Record[Idx++];
4251 bool InferExplicitSubmodules = Record[Idx++];
4252 bool InferExportWildcard = Record[Idx++];
4253 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004254
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004255 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004256 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004257 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004258
Guy Benyei11169dd2012-12-18 14:30:41 +00004259 // Retrieve this (sub)module from the module map, creating it if
4260 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004261 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004262 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004263
4264 // FIXME: set the definition loc for CurrentModule, or call
4265 // ModMap.setInferredModuleAllowedBy()
4266
Guy Benyei11169dd2012-12-18 14:30:41 +00004267 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4268 if (GlobalIndex >= SubmodulesLoaded.size() ||
4269 SubmodulesLoaded[GlobalIndex]) {
4270 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004271 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004272 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004273
Douglas Gregor7029ce12013-03-19 00:28:20 +00004274 if (!ParentModule) {
4275 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4276 if (CurFile != F.File) {
4277 if (!Diags.isDiagnosticInFlight()) {
4278 Diag(diag::err_module_file_conflict)
4279 << CurrentModule->getTopLevelModuleName()
4280 << CurFile->getName()
4281 << F.File->getName();
4282 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004283 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004284 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004285 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004286
4287 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004288 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004289
Adrian Prantl15bcf702015-06-30 17:39:43 +00004290 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004291 CurrentModule->IsFromModuleFile = true;
4292 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004293 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004294 CurrentModule->InferSubmodules = InferSubmodules;
4295 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4296 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004297 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004298 if (DeserializationListener)
4299 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4300
4301 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004302
Douglas Gregorfb912652013-03-20 21:10:35 +00004303 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004304 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004305 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004306 CurrentModule->UnresolvedConflicts.clear();
4307 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004308 break;
4309 }
4310
4311 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004312 std::string Filename = Blob;
4313 ResolveImportedPath(F, Filename);
4314 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004315 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004316 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4317 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004318 // This can be a spurious difference caused by changing the VFS to
4319 // point to a different copy of the file, and it is too late to
4320 // to rebuild safely.
4321 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4322 // after input file validation only real problems would remain and we
4323 // could just error. For now, assume it's okay.
4324 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004325 }
4326 }
4327 break;
4328 }
4329
Richard Smith202210b2014-10-24 20:23:01 +00004330 case SUBMODULE_HEADER:
4331 case SUBMODULE_EXCLUDED_HEADER:
4332 case SUBMODULE_PRIVATE_HEADER:
4333 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004334 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4335 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004336 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004337
Richard Smith202210b2014-10-24 20:23:01 +00004338 case SUBMODULE_TEXTUAL_HEADER:
4339 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4340 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4341 // them here.
4342 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004343
Guy Benyei11169dd2012-12-18 14:30:41 +00004344 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004345 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004346 break;
4347 }
4348
4349 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004350 std::string Dirname = Blob;
4351 ResolveImportedPath(F, Dirname);
4352 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004354 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4355 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004356 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4357 Error("mismatched umbrella directories in submodule");
4358 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004359 }
4360 }
4361 break;
4362 }
4363
4364 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004365 F.BaseSubmoduleID = getTotalNumSubmodules();
4366 F.LocalNumSubmodules = Record[0];
4367 unsigned LocalBaseSubmoduleID = Record[1];
4368 if (F.LocalNumSubmodules > 0) {
4369 // Introduce the global -> local mapping for submodules within this
4370 // module.
4371 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4372
4373 // Introduce the local -> global mapping for submodules within this
4374 // module.
4375 F.SubmoduleRemap.insertOrReplace(
4376 std::make_pair(LocalBaseSubmoduleID,
4377 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004378
Ben Langmuir52ca6782014-10-20 16:27:32 +00004379 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4380 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004381 break;
4382 }
4383
4384 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004385 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004386 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 Unresolved.File = &F;
4388 Unresolved.Mod = CurrentModule;
4389 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004390 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004391 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004392 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004393 }
4394 break;
4395 }
4396
4397 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004398 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004399 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004400 Unresolved.File = &F;
4401 Unresolved.Mod = CurrentModule;
4402 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004403 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004405 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004406 }
4407
4408 // Once we've loaded the set of exports, there's no reason to keep
4409 // the parsed, unresolved exports around.
4410 CurrentModule->UnresolvedExports.clear();
4411 break;
4412 }
4413 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004414 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 Context.getTargetInfo());
4416 break;
4417 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004418
4419 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004420 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004421 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004422 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004423
4424 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004425 CurrentModule->ConfigMacros.push_back(Blob.str());
4426 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004427
4428 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004429 UnresolvedModuleRef Unresolved;
4430 Unresolved.File = &F;
4431 Unresolved.Mod = CurrentModule;
4432 Unresolved.ID = Record[0];
4433 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4434 Unresolved.IsWildcard = false;
4435 Unresolved.String = Blob;
4436 UnresolvedModuleRefs.push_back(Unresolved);
4437 break;
4438 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 }
4440 }
4441}
4442
4443/// \brief Parse the record that corresponds to a LangOptions data
4444/// structure.
4445///
4446/// This routine parses the language options from the AST file and then gives
4447/// them to the AST listener if one is set.
4448///
4449/// \returns true if the listener deems the file unacceptable, false otherwise.
4450bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4451 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004452 ASTReaderListener &Listener,
4453 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004454 LangOptions LangOpts;
4455 unsigned Idx = 0;
4456#define LANGOPT(Name, Bits, Default, Description) \
4457 LangOpts.Name = Record[Idx++];
4458#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4459 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4460#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004461#define SANITIZER(NAME, ID) \
4462 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004463#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004464
Ben Langmuircd98cb72015-06-23 18:20:18 +00004465 for (unsigned N = Record[Idx++]; N; --N)
4466 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4467
Guy Benyei11169dd2012-12-18 14:30:41 +00004468 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4469 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4470 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004471
Ben Langmuird4a667a2015-06-23 18:20:23 +00004472 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004473
4474 // Comment options.
4475 for (unsigned N = Record[Idx++]; N; --N) {
4476 LangOpts.CommentOpts.BlockCommandNames.push_back(
4477 ReadString(Record, Idx));
4478 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004479 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004480
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004481 return Listener.ReadLanguageOptions(LangOpts, Complain,
4482 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004483}
4484
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004485bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4486 ASTReaderListener &Listener,
4487 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004488 unsigned Idx = 0;
4489 TargetOptions TargetOpts;
4490 TargetOpts.Triple = ReadString(Record, Idx);
4491 TargetOpts.CPU = ReadString(Record, Idx);
4492 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004493 for (unsigned N = Record[Idx++]; N; --N) {
4494 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4495 }
4496 for (unsigned N = Record[Idx++]; N; --N) {
4497 TargetOpts.Features.push_back(ReadString(Record, Idx));
4498 }
4499
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004500 return Listener.ReadTargetOptions(TargetOpts, Complain,
4501 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004502}
4503
4504bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4505 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004506 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004507 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004508#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004509#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004510 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004511#include "clang/Basic/DiagnosticOptions.def"
4512
Richard Smith3be1cb22014-08-07 00:24:21 +00004513 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004514 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004515 for (unsigned N = Record[Idx++]; N; --N)
4516 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004517
4518 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4519}
4520
4521bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4522 ASTReaderListener &Listener) {
4523 FileSystemOptions FSOpts;
4524 unsigned Idx = 0;
4525 FSOpts.WorkingDir = ReadString(Record, Idx);
4526 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4527}
4528
4529bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4530 bool Complain,
4531 ASTReaderListener &Listener) {
4532 HeaderSearchOptions HSOpts;
4533 unsigned Idx = 0;
4534 HSOpts.Sysroot = ReadString(Record, Idx);
4535
4536 // Include entries.
4537 for (unsigned N = Record[Idx++]; N; --N) {
4538 std::string Path = ReadString(Record, Idx);
4539 frontend::IncludeDirGroup Group
4540 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004541 bool IsFramework = Record[Idx++];
4542 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004543 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4544 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 }
4546
4547 // System header prefixes.
4548 for (unsigned N = Record[Idx++]; N; --N) {
4549 std::string Prefix = ReadString(Record, Idx);
4550 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004551 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004552 }
4553
4554 HSOpts.ResourceDir = ReadString(Record, Idx);
4555 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004556 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 HSOpts.DisableModuleHash = Record[Idx++];
4558 HSOpts.UseBuiltinIncludes = Record[Idx++];
4559 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4560 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4561 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004562 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004563
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004564 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4565 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004566}
4567
4568bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4569 bool Complain,
4570 ASTReaderListener &Listener,
4571 std::string &SuggestedPredefines) {
4572 PreprocessorOptions PPOpts;
4573 unsigned Idx = 0;
4574
4575 // Macro definitions/undefs
4576 for (unsigned N = Record[Idx++]; N; --N) {
4577 std::string Macro = ReadString(Record, Idx);
4578 bool IsUndef = Record[Idx++];
4579 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4580 }
4581
4582 // Includes
4583 for (unsigned N = Record[Idx++]; N; --N) {
4584 PPOpts.Includes.push_back(ReadString(Record, Idx));
4585 }
4586
4587 // Macro Includes
4588 for (unsigned N = Record[Idx++]; N; --N) {
4589 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4590 }
4591
4592 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004593 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004594 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4595 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4596 PPOpts.ObjCXXARCStandardLibrary =
4597 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4598 SuggestedPredefines.clear();
4599 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4600 SuggestedPredefines);
4601}
4602
4603std::pair<ModuleFile *, unsigned>
4604ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4605 GlobalPreprocessedEntityMapType::iterator
4606 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4607 assert(I != GlobalPreprocessedEntityMap.end() &&
4608 "Corrupted global preprocessed entity map");
4609 ModuleFile *M = I->second;
4610 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4611 return std::make_pair(M, LocalIndex);
4612}
4613
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004614llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004615ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4616 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4617 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4618 Mod.NumPreprocessedEntities);
4619
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004620 return llvm::make_range(PreprocessingRecord::iterator(),
4621 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004622}
4623
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004624llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004625ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004626 return llvm::make_range(
4627 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4628 ModuleDeclIterator(this, &Mod,
4629 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004630}
4631
4632PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4633 PreprocessedEntityID PPID = Index+1;
4634 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4635 ModuleFile &M = *PPInfo.first;
4636 unsigned LocalIndex = PPInfo.second;
4637 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4638
Guy Benyei11169dd2012-12-18 14:30:41 +00004639 if (!PP.getPreprocessingRecord()) {
4640 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004641 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004642 }
4643
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004644 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4645 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4646
4647 llvm::BitstreamEntry Entry =
4648 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4649 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004650 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004651
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 // Read the record.
4653 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4654 ReadSourceLocation(M, PPOffs.End));
4655 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004656 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 RecordData Record;
4658 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004659 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4660 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 switch (RecType) {
4662 case PPD_MACRO_EXPANSION: {
4663 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004664 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004665 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004666 if (isBuiltin)
4667 Name = getLocalIdentifier(M, Record[1]);
4668 else {
Richard Smith66a81862015-05-04 02:25:31 +00004669 PreprocessedEntityID GlobalID =
4670 getGlobalPreprocessedEntityID(M, Record[1]);
4671 Def = cast<MacroDefinitionRecord>(
4672 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004673 }
4674
4675 MacroExpansion *ME;
4676 if (isBuiltin)
4677 ME = new (PPRec) MacroExpansion(Name, Range);
4678 else
4679 ME = new (PPRec) MacroExpansion(Def, Range);
4680
4681 return ME;
4682 }
4683
4684 case PPD_MACRO_DEFINITION: {
4685 // Decode the identifier info and then check again; if the macro is
4686 // still defined and associated with the identifier,
4687 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004688 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004689
4690 if (DeserializationListener)
4691 DeserializationListener->MacroDefinitionRead(PPID, MD);
4692
4693 return MD;
4694 }
4695
4696 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004697 const char *FullFileNameStart = Blob.data() + Record[0];
4698 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004699 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004700 if (!FullFileName.empty())
4701 File = PP.getFileManager().getFile(FullFileName);
4702
4703 // FIXME: Stable encoding
4704 InclusionDirective::InclusionKind Kind
4705 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4706 InclusionDirective *ID
4707 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004708 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004709 Record[1], Record[3],
4710 File,
4711 Range);
4712 return ID;
4713 }
4714 }
4715
4716 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4717}
4718
4719/// \brief \arg SLocMapI points at a chunk of a module that contains no
4720/// preprocessed entities or the entities it contains are not the ones we are
4721/// looking for. Find the next module that contains entities and return the ID
4722/// of the first entry.
4723PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4724 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4725 ++SLocMapI;
4726 for (GlobalSLocOffsetMapType::const_iterator
4727 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4728 ModuleFile &M = *SLocMapI->second;
4729 if (M.NumPreprocessedEntities)
4730 return M.BasePreprocessedEntityID;
4731 }
4732
4733 return getTotalNumPreprocessedEntities();
4734}
4735
4736namespace {
4737
4738template <unsigned PPEntityOffset::*PPLoc>
4739struct PPEntityComp {
4740 const ASTReader &Reader;
4741 ModuleFile &M;
4742
4743 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4744
4745 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4746 SourceLocation LHS = getLoc(L);
4747 SourceLocation RHS = getLoc(R);
4748 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4749 }
4750
4751 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4752 SourceLocation LHS = getLoc(L);
4753 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4754 }
4755
4756 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4757 SourceLocation RHS = getLoc(R);
4758 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4759 }
4760
4761 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4762 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4763 }
4764};
4765
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004766}
Guy Benyei11169dd2012-12-18 14:30:41 +00004767
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004768PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4769 bool EndsAfter) const {
4770 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 return getTotalNumPreprocessedEntities();
4772
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004773 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4774 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004775 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4776 "Corrupted global sloc offset map");
4777
4778 if (SLocMapI->second->NumPreprocessedEntities == 0)
4779 return findNextPreprocessedEntity(SLocMapI);
4780
4781 ModuleFile &M = *SLocMapI->second;
4782 typedef const PPEntityOffset *pp_iterator;
4783 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4784 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4785
4786 size_t Count = M.NumPreprocessedEntities;
4787 size_t Half;
4788 pp_iterator First = pp_begin;
4789 pp_iterator PPI;
4790
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004791 if (EndsAfter) {
4792 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4793 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4794 } else {
4795 // Do a binary search manually instead of using std::lower_bound because
4796 // The end locations of entities may be unordered (when a macro expansion
4797 // is inside another macro argument), but for this case it is not important
4798 // whether we get the first macro expansion or its containing macro.
4799 while (Count > 0) {
4800 Half = Count / 2;
4801 PPI = First;
4802 std::advance(PPI, Half);
4803 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4804 Loc)) {
4805 First = PPI;
4806 ++First;
4807 Count = Count - Half - 1;
4808 } else
4809 Count = Half;
4810 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004811 }
4812
4813 if (PPI == pp_end)
4814 return findNextPreprocessedEntity(SLocMapI);
4815
4816 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4817}
4818
Guy Benyei11169dd2012-12-18 14:30:41 +00004819/// \brief Returns a pair of [Begin, End) indices of preallocated
4820/// preprocessed entities that \arg Range encompasses.
4821std::pair<unsigned, unsigned>
4822 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4823 if (Range.isInvalid())
4824 return std::make_pair(0,0);
4825 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4826
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004827 PreprocessedEntityID BeginID =
4828 findPreprocessedEntity(Range.getBegin(), false);
4829 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004830 return std::make_pair(BeginID, EndID);
4831}
4832
4833/// \brief Optionally returns true or false if the preallocated preprocessed
4834/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004835Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004836 FileID FID) {
4837 if (FID.isInvalid())
4838 return false;
4839
4840 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4841 ModuleFile &M = *PPInfo.first;
4842 unsigned LocalIndex = PPInfo.second;
4843 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4844
4845 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4846 if (Loc.isInvalid())
4847 return false;
4848
4849 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4850 return true;
4851 else
4852 return false;
4853}
4854
4855namespace {
4856 /// \brief Visitor used to search for information about a header file.
4857 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004858 const FileEntry *FE;
4859
David Blaikie05785d12013-02-20 22:23:23 +00004860 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004861
4862 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004863 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4864 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004865
4866 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004867 HeaderFileInfoLookupTable *Table
4868 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4869 if (!Table)
4870 return false;
4871
4872 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00004873 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004874 if (Pos == Table->end())
4875 return false;
4876
Richard Smithbdf2d932015-07-30 03:37:16 +00004877 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00004878 return true;
4879 }
4880
David Blaikie05785d12013-02-20 22:23:23 +00004881 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004882 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004883}
Guy Benyei11169dd2012-12-18 14:30:41 +00004884
4885HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004886 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004887 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004888 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004889 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004890
4891 return HeaderFileInfo();
4892}
4893
4894void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4895 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004896 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004897 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4898 ModuleFile &F = *(*I);
4899 unsigned Idx = 0;
4900 DiagStates.clear();
4901 assert(!Diag.DiagStates.empty());
4902 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4903 while (Idx < F.PragmaDiagMappings.size()) {
4904 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4905 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4906 if (DiagStateID != 0) {
4907 Diag.DiagStatePoints.push_back(
4908 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4909 FullSourceLoc(Loc, SourceMgr)));
4910 continue;
4911 }
4912
4913 assert(DiagStateID == 0);
4914 // A new DiagState was created here.
4915 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4916 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4917 DiagStates.push_back(NewState);
4918 Diag.DiagStatePoints.push_back(
4919 DiagnosticsEngine::DiagStatePoint(NewState,
4920 FullSourceLoc(Loc, SourceMgr)));
4921 while (1) {
4922 assert(Idx < F.PragmaDiagMappings.size() &&
4923 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4924 if (Idx >= F.PragmaDiagMappings.size()) {
4925 break; // Something is messed up but at least avoid infinite loop in
4926 // release build.
4927 }
4928 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4929 if (DiagID == (unsigned)-1) {
4930 break; // no more diag/map pairs for this location.
4931 }
Alp Tokerc726c362014-06-10 09:31:37 +00004932 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4933 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4934 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00004935 }
4936 }
4937 }
4938}
4939
4940/// \brief Get the correct cursor and offset for loading a type.
4941ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4942 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4943 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4944 ModuleFile *M = I->second;
4945 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4946}
4947
4948/// \brief Read and return the type with the given index..
4949///
4950/// The index is the type ID, shifted and minus the number of predefs. This
4951/// routine actually reads the record corresponding to the type at the given
4952/// location. It is a helper routine for GetType, which deals with reading type
4953/// IDs.
4954QualType ASTReader::readTypeRecord(unsigned Index) {
4955 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004956 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004957
4958 // Keep track of where we are in the stream, then jump back there
4959 // after reading this type.
4960 SavedStreamPosition SavedPosition(DeclsCursor);
4961
4962 ReadingKindTracker ReadingKind(Read_Type, *this);
4963
4964 // Note that we are loading a type record.
4965 Deserializing AType(this);
4966
4967 unsigned Idx = 0;
4968 DeclsCursor.JumpToBit(Loc.Offset);
4969 RecordData Record;
4970 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004971 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004972 case TYPE_EXT_QUAL: {
4973 if (Record.size() != 2) {
4974 Error("Incorrect encoding of extended qualifier type");
4975 return QualType();
4976 }
4977 QualType Base = readType(*Loc.F, Record, Idx);
4978 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4979 return Context.getQualifiedType(Base, Quals);
4980 }
4981
4982 case TYPE_COMPLEX: {
4983 if (Record.size() != 1) {
4984 Error("Incorrect encoding of complex type");
4985 return QualType();
4986 }
4987 QualType ElemType = readType(*Loc.F, Record, Idx);
4988 return Context.getComplexType(ElemType);
4989 }
4990
4991 case TYPE_POINTER: {
4992 if (Record.size() != 1) {
4993 Error("Incorrect encoding of pointer type");
4994 return QualType();
4995 }
4996 QualType PointeeType = readType(*Loc.F, Record, Idx);
4997 return Context.getPointerType(PointeeType);
4998 }
4999
Reid Kleckner8a365022013-06-24 17:51:48 +00005000 case TYPE_DECAYED: {
5001 if (Record.size() != 1) {
5002 Error("Incorrect encoding of decayed type");
5003 return QualType();
5004 }
5005 QualType OriginalType = readType(*Loc.F, Record, Idx);
5006 QualType DT = Context.getAdjustedParameterType(OriginalType);
5007 if (!isa<DecayedType>(DT))
5008 Error("Decayed type does not decay");
5009 return DT;
5010 }
5011
Reid Kleckner0503a872013-12-05 01:23:43 +00005012 case TYPE_ADJUSTED: {
5013 if (Record.size() != 2) {
5014 Error("Incorrect encoding of adjusted type");
5015 return QualType();
5016 }
5017 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5018 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5019 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5020 }
5021
Guy Benyei11169dd2012-12-18 14:30:41 +00005022 case TYPE_BLOCK_POINTER: {
5023 if (Record.size() != 1) {
5024 Error("Incorrect encoding of block pointer type");
5025 return QualType();
5026 }
5027 QualType PointeeType = readType(*Loc.F, Record, Idx);
5028 return Context.getBlockPointerType(PointeeType);
5029 }
5030
5031 case TYPE_LVALUE_REFERENCE: {
5032 if (Record.size() != 2) {
5033 Error("Incorrect encoding of lvalue reference type");
5034 return QualType();
5035 }
5036 QualType PointeeType = readType(*Loc.F, Record, Idx);
5037 return Context.getLValueReferenceType(PointeeType, Record[1]);
5038 }
5039
5040 case TYPE_RVALUE_REFERENCE: {
5041 if (Record.size() != 1) {
5042 Error("Incorrect encoding of rvalue reference type");
5043 return QualType();
5044 }
5045 QualType PointeeType = readType(*Loc.F, Record, Idx);
5046 return Context.getRValueReferenceType(PointeeType);
5047 }
5048
5049 case TYPE_MEMBER_POINTER: {
5050 if (Record.size() != 2) {
5051 Error("Incorrect encoding of member pointer type");
5052 return QualType();
5053 }
5054 QualType PointeeType = readType(*Loc.F, Record, Idx);
5055 QualType ClassType = readType(*Loc.F, Record, Idx);
5056 if (PointeeType.isNull() || ClassType.isNull())
5057 return QualType();
5058
5059 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5060 }
5061
5062 case TYPE_CONSTANT_ARRAY: {
5063 QualType ElementType = readType(*Loc.F, Record, Idx);
5064 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5065 unsigned IndexTypeQuals = Record[2];
5066 unsigned Idx = 3;
5067 llvm::APInt Size = ReadAPInt(Record, Idx);
5068 return Context.getConstantArrayType(ElementType, Size,
5069 ASM, IndexTypeQuals);
5070 }
5071
5072 case TYPE_INCOMPLETE_ARRAY: {
5073 QualType ElementType = readType(*Loc.F, Record, Idx);
5074 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5075 unsigned IndexTypeQuals = Record[2];
5076 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5077 }
5078
5079 case TYPE_VARIABLE_ARRAY: {
5080 QualType ElementType = readType(*Loc.F, Record, Idx);
5081 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5082 unsigned IndexTypeQuals = Record[2];
5083 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5084 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5085 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5086 ASM, IndexTypeQuals,
5087 SourceRange(LBLoc, RBLoc));
5088 }
5089
5090 case TYPE_VECTOR: {
5091 if (Record.size() != 3) {
5092 Error("incorrect encoding of vector type in AST file");
5093 return QualType();
5094 }
5095
5096 QualType ElementType = readType(*Loc.F, Record, Idx);
5097 unsigned NumElements = Record[1];
5098 unsigned VecKind = Record[2];
5099 return Context.getVectorType(ElementType, NumElements,
5100 (VectorType::VectorKind)VecKind);
5101 }
5102
5103 case TYPE_EXT_VECTOR: {
5104 if (Record.size() != 3) {
5105 Error("incorrect encoding of extended vector type in AST file");
5106 return QualType();
5107 }
5108
5109 QualType ElementType = readType(*Loc.F, Record, Idx);
5110 unsigned NumElements = Record[1];
5111 return Context.getExtVectorType(ElementType, NumElements);
5112 }
5113
5114 case TYPE_FUNCTION_NO_PROTO: {
5115 if (Record.size() != 6) {
5116 Error("incorrect encoding of no-proto function type");
5117 return QualType();
5118 }
5119 QualType ResultType = readType(*Loc.F, Record, Idx);
5120 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5121 (CallingConv)Record[4], Record[5]);
5122 return Context.getFunctionNoProtoType(ResultType, Info);
5123 }
5124
5125 case TYPE_FUNCTION_PROTO: {
5126 QualType ResultType = readType(*Loc.F, Record, Idx);
5127
5128 FunctionProtoType::ExtProtoInfo EPI;
5129 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5130 /*hasregparm*/ Record[2],
5131 /*regparm*/ Record[3],
5132 static_cast<CallingConv>(Record[4]),
5133 /*produces*/ Record[5]);
5134
5135 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005136
5137 EPI.Variadic = Record[Idx++];
5138 EPI.HasTrailingReturn = Record[Idx++];
5139 EPI.TypeQuals = Record[Idx++];
5140 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005141 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005142 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005143
5144 unsigned NumParams = Record[Idx++];
5145 SmallVector<QualType, 16> ParamTypes;
5146 for (unsigned I = 0; I != NumParams; ++I)
5147 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5148
Jordan Rose5c382722013-03-08 21:51:21 +00005149 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 }
5151
5152 case TYPE_UNRESOLVED_USING: {
5153 unsigned Idx = 0;
5154 return Context.getTypeDeclType(
5155 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5156 }
5157
5158 case TYPE_TYPEDEF: {
5159 if (Record.size() != 2) {
5160 Error("incorrect encoding of typedef type");
5161 return QualType();
5162 }
5163 unsigned Idx = 0;
5164 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5165 QualType Canonical = readType(*Loc.F, Record, Idx);
5166 if (!Canonical.isNull())
5167 Canonical = Context.getCanonicalType(Canonical);
5168 return Context.getTypedefType(Decl, Canonical);
5169 }
5170
5171 case TYPE_TYPEOF_EXPR:
5172 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5173
5174 case TYPE_TYPEOF: {
5175 if (Record.size() != 1) {
5176 Error("incorrect encoding of typeof(type) in AST file");
5177 return QualType();
5178 }
5179 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5180 return Context.getTypeOfType(UnderlyingType);
5181 }
5182
5183 case TYPE_DECLTYPE: {
5184 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5185 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5186 }
5187
5188 case TYPE_UNARY_TRANSFORM: {
5189 QualType BaseType = readType(*Loc.F, Record, Idx);
5190 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5191 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5192 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5193 }
5194
Richard Smith74aeef52013-04-26 16:15:35 +00005195 case TYPE_AUTO: {
5196 QualType Deduced = readType(*Loc.F, Record, Idx);
5197 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005198 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005199 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005200 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005201
5202 case TYPE_RECORD: {
5203 if (Record.size() != 2) {
5204 Error("incorrect encoding of record type");
5205 return QualType();
5206 }
5207 unsigned Idx = 0;
5208 bool IsDependent = Record[Idx++];
5209 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5210 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5211 QualType T = Context.getRecordType(RD);
5212 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5213 return T;
5214 }
5215
5216 case TYPE_ENUM: {
5217 if (Record.size() != 2) {
5218 Error("incorrect encoding of enum type");
5219 return QualType();
5220 }
5221 unsigned Idx = 0;
5222 bool IsDependent = Record[Idx++];
5223 QualType T
5224 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5225 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5226 return T;
5227 }
5228
5229 case TYPE_ATTRIBUTED: {
5230 if (Record.size() != 3) {
5231 Error("incorrect encoding of attributed type");
5232 return QualType();
5233 }
5234 QualType modifiedType = readType(*Loc.F, Record, Idx);
5235 QualType equivalentType = readType(*Loc.F, Record, Idx);
5236 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5237 return Context.getAttributedType(kind, modifiedType, equivalentType);
5238 }
5239
5240 case TYPE_PAREN: {
5241 if (Record.size() != 1) {
5242 Error("incorrect encoding of paren type");
5243 return QualType();
5244 }
5245 QualType InnerType = readType(*Loc.F, Record, Idx);
5246 return Context.getParenType(InnerType);
5247 }
5248
5249 case TYPE_PACK_EXPANSION: {
5250 if (Record.size() != 2) {
5251 Error("incorrect encoding of pack expansion type");
5252 return QualType();
5253 }
5254 QualType Pattern = readType(*Loc.F, Record, Idx);
5255 if (Pattern.isNull())
5256 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005257 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005258 if (Record[1])
5259 NumExpansions = Record[1] - 1;
5260 return Context.getPackExpansionType(Pattern, NumExpansions);
5261 }
5262
5263 case TYPE_ELABORATED: {
5264 unsigned Idx = 0;
5265 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5266 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5267 QualType NamedType = readType(*Loc.F, Record, Idx);
5268 return Context.getElaboratedType(Keyword, NNS, NamedType);
5269 }
5270
5271 case TYPE_OBJC_INTERFACE: {
5272 unsigned Idx = 0;
5273 ObjCInterfaceDecl *ItfD
5274 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5275 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5276 }
5277
5278 case TYPE_OBJC_OBJECT: {
5279 unsigned Idx = 0;
5280 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005281 unsigned NumTypeArgs = Record[Idx++];
5282 SmallVector<QualType, 4> TypeArgs;
5283 for (unsigned I = 0; I != NumTypeArgs; ++I)
5284 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005285 unsigned NumProtos = Record[Idx++];
5286 SmallVector<ObjCProtocolDecl*, 4> Protos;
5287 for (unsigned I = 0; I != NumProtos; ++I)
5288 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005289 bool IsKindOf = Record[Idx++];
5290 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005291 }
5292
5293 case TYPE_OBJC_OBJECT_POINTER: {
5294 unsigned Idx = 0;
5295 QualType Pointee = readType(*Loc.F, Record, Idx);
5296 return Context.getObjCObjectPointerType(Pointee);
5297 }
5298
5299 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5300 unsigned Idx = 0;
5301 QualType Parm = readType(*Loc.F, Record, Idx);
5302 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005303 return Context.getSubstTemplateTypeParmType(
5304 cast<TemplateTypeParmType>(Parm),
5305 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005306 }
5307
5308 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5309 unsigned Idx = 0;
5310 QualType Parm = readType(*Loc.F, Record, Idx);
5311 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5312 return Context.getSubstTemplateTypeParmPackType(
5313 cast<TemplateTypeParmType>(Parm),
5314 ArgPack);
5315 }
5316
5317 case TYPE_INJECTED_CLASS_NAME: {
5318 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5319 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5320 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5321 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005322 const Type *T = nullptr;
5323 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5324 if (const Type *Existing = DI->getTypeForDecl()) {
5325 T = Existing;
5326 break;
5327 }
5328 }
5329 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005330 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005331 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5332 DI->setTypeForDecl(T);
5333 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005334 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005335 }
5336
5337 case TYPE_TEMPLATE_TYPE_PARM: {
5338 unsigned Idx = 0;
5339 unsigned Depth = Record[Idx++];
5340 unsigned Index = Record[Idx++];
5341 bool Pack = Record[Idx++];
5342 TemplateTypeParmDecl *D
5343 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5344 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5345 }
5346
5347 case TYPE_DEPENDENT_NAME: {
5348 unsigned Idx = 0;
5349 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5350 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005351 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005352 QualType Canon = readType(*Loc.F, Record, Idx);
5353 if (!Canon.isNull())
5354 Canon = Context.getCanonicalType(Canon);
5355 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5356 }
5357
5358 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5359 unsigned Idx = 0;
5360 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5361 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005362 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005363 unsigned NumArgs = Record[Idx++];
5364 SmallVector<TemplateArgument, 8> Args;
5365 Args.reserve(NumArgs);
5366 while (NumArgs--)
5367 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5368 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5369 Args.size(), Args.data());
5370 }
5371
5372 case TYPE_DEPENDENT_SIZED_ARRAY: {
5373 unsigned Idx = 0;
5374
5375 // ArrayType
5376 QualType ElementType = readType(*Loc.F, Record, Idx);
5377 ArrayType::ArraySizeModifier ASM
5378 = (ArrayType::ArraySizeModifier)Record[Idx++];
5379 unsigned IndexTypeQuals = Record[Idx++];
5380
5381 // DependentSizedArrayType
5382 Expr *NumElts = ReadExpr(*Loc.F);
5383 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5384
5385 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5386 IndexTypeQuals, Brackets);
5387 }
5388
5389 case TYPE_TEMPLATE_SPECIALIZATION: {
5390 unsigned Idx = 0;
5391 bool IsDependent = Record[Idx++];
5392 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5393 SmallVector<TemplateArgument, 8> Args;
5394 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5395 QualType Underlying = readType(*Loc.F, Record, Idx);
5396 QualType T;
5397 if (Underlying.isNull())
5398 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5399 Args.size());
5400 else
5401 T = Context.getTemplateSpecializationType(Name, Args.data(),
5402 Args.size(), Underlying);
5403 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5404 return T;
5405 }
5406
5407 case TYPE_ATOMIC: {
5408 if (Record.size() != 1) {
5409 Error("Incorrect encoding of atomic type");
5410 return QualType();
5411 }
5412 QualType ValueType = readType(*Loc.F, Record, Idx);
5413 return Context.getAtomicType(ValueType);
5414 }
5415 }
5416 llvm_unreachable("Invalid TypeCode!");
5417}
5418
Richard Smith564417a2014-03-20 21:47:22 +00005419void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5420 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005421 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005422 const RecordData &Record, unsigned &Idx) {
5423 ExceptionSpecificationType EST =
5424 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005425 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005426 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005427 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005428 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005429 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005430 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005431 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005432 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005433 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5434 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005435 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005436 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005437 }
5438}
5439
Guy Benyei11169dd2012-12-18 14:30:41 +00005440class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5441 ASTReader &Reader;
5442 ModuleFile &F;
5443 const ASTReader::RecordData &Record;
5444 unsigned &Idx;
5445
5446 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5447 unsigned &I) {
5448 return Reader.ReadSourceLocation(F, R, I);
5449 }
5450
5451 template<typename T>
5452 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5453 return Reader.ReadDeclAs<T>(F, Record, Idx);
5454 }
5455
5456public:
5457 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5458 const ASTReader::RecordData &Record, unsigned &Idx)
5459 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5460 { }
5461
5462 // We want compile-time assurance that we've enumerated all of
5463 // these, so unfortunately we have to declare them first, then
5464 // define them out-of-line.
5465#define ABSTRACT_TYPELOC(CLASS, PARENT)
5466#define TYPELOC(CLASS, PARENT) \
5467 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5468#include "clang/AST/TypeLocNodes.def"
5469
5470 void VisitFunctionTypeLoc(FunctionTypeLoc);
5471 void VisitArrayTypeLoc(ArrayTypeLoc);
5472};
5473
5474void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5475 // nothing to do
5476}
5477void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5478 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5479 if (TL.needsExtraLocalData()) {
5480 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5481 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5482 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5483 TL.setModeAttr(Record[Idx++]);
5484 }
5485}
5486void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5487 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5488}
5489void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5490 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5491}
Reid Kleckner8a365022013-06-24 17:51:48 +00005492void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5493 // nothing to do
5494}
Reid Kleckner0503a872013-12-05 01:23:43 +00005495void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5496 // nothing to do
5497}
Guy Benyei11169dd2012-12-18 14:30:41 +00005498void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5499 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5500}
5501void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5502 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5503}
5504void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5505 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5506}
5507void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5508 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5509 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5510}
5511void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5512 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5513 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5514 if (Record[Idx++])
5515 TL.setSizeExpr(Reader.ReadExpr(F));
5516 else
Craig Toppera13603a2014-05-22 05:54:18 +00005517 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005518}
5519void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5520 VisitArrayTypeLoc(TL);
5521}
5522void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5523 VisitArrayTypeLoc(TL);
5524}
5525void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5526 VisitArrayTypeLoc(TL);
5527}
5528void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5529 DependentSizedArrayTypeLoc TL) {
5530 VisitArrayTypeLoc(TL);
5531}
5532void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5533 DependentSizedExtVectorTypeLoc TL) {
5534 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5535}
5536void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5537 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5538}
5539void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5540 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5541}
5542void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5543 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5544 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5545 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5546 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005547 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5548 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005549 }
5550}
5551void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5552 VisitFunctionTypeLoc(TL);
5553}
5554void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5555 VisitFunctionTypeLoc(TL);
5556}
5557void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5558 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5559}
5560void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5561 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5562}
5563void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5564 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5565 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5566 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5567}
5568void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5569 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5570 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5571 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5572 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5573}
5574void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5575 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5576}
5577void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5578 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5579 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5580 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5581 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5582}
5583void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5584 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5585}
5586void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5587 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5588}
5589void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5590 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5591}
5592void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5593 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5594 if (TL.hasAttrOperand()) {
5595 SourceRange range;
5596 range.setBegin(ReadSourceLocation(Record, Idx));
5597 range.setEnd(ReadSourceLocation(Record, Idx));
5598 TL.setAttrOperandParensRange(range);
5599 }
5600 if (TL.hasAttrExprOperand()) {
5601 if (Record[Idx++])
5602 TL.setAttrExprOperand(Reader.ReadExpr(F));
5603 else
Craig Toppera13603a2014-05-22 05:54:18 +00005604 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005605 } else if (TL.hasAttrEnumOperand())
5606 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5607}
5608void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5609 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5610}
5611void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5612 SubstTemplateTypeParmTypeLoc TL) {
5613 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5614}
5615void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5616 SubstTemplateTypeParmPackTypeLoc TL) {
5617 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5618}
5619void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5620 TemplateSpecializationTypeLoc TL) {
5621 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5622 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5623 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5624 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5625 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5626 TL.setArgLocInfo(i,
5627 Reader.GetTemplateArgumentLocInfo(F,
5628 TL.getTypePtr()->getArg(i).getKind(),
5629 Record, Idx));
5630}
5631void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5632 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5633 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5634}
5635void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5636 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5637 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5638}
5639void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5640 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5641}
5642void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5643 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5644 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5645 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5646}
5647void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5648 DependentTemplateSpecializationTypeLoc TL) {
5649 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5650 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5651 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5652 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5653 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5654 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5655 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5656 TL.setArgLocInfo(I,
5657 Reader.GetTemplateArgumentLocInfo(F,
5658 TL.getTypePtr()->getArg(I).getKind(),
5659 Record, Idx));
5660}
5661void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5662 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5663}
5664void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5665 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5666}
5667void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5668 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005669 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5670 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5671 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5672 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5673 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5674 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005675 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5676 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5677}
5678void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5679 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5680}
5681void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5682 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5683 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5684 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5685}
5686
5687TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5688 const RecordData &Record,
5689 unsigned &Idx) {
5690 QualType InfoTy = readType(F, Record, Idx);
5691 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005692 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005693
5694 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5695 TypeLocReader TLR(*this, F, Record, Idx);
5696 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5697 TLR.Visit(TL);
5698 return TInfo;
5699}
5700
5701QualType ASTReader::GetType(TypeID ID) {
5702 unsigned FastQuals = ID & Qualifiers::FastMask;
5703 unsigned Index = ID >> Qualifiers::FastWidth;
5704
5705 if (Index < NUM_PREDEF_TYPE_IDS) {
5706 QualType T;
5707 switch ((PredefinedTypeIDs)Index) {
5708 case PREDEF_TYPE_NULL_ID: return QualType();
5709 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5710 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5711
5712 case PREDEF_TYPE_CHAR_U_ID:
5713 case PREDEF_TYPE_CHAR_S_ID:
5714 // FIXME: Check that the signedness of CharTy is correct!
5715 T = Context.CharTy;
5716 break;
5717
5718 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5719 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5720 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5721 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5722 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5723 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5724 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5725 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5726 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5727 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5728 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5729 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5730 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5731 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5732 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5733 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5734 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5735 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5736 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5737 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5738 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5739 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5740 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5741 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5742 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5743 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5744 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5745 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005746 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5747 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5748 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5749 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5750 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5751 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005752 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005753 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005754 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5755
5756 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5757 T = Context.getAutoRRefDeductType();
5758 break;
5759
5760 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5761 T = Context.ARCUnbridgedCastTy;
5762 break;
5763
Guy Benyei11169dd2012-12-18 14:30:41 +00005764 case PREDEF_TYPE_BUILTIN_FN:
5765 T = Context.BuiltinFnTy;
5766 break;
5767 }
5768
5769 assert(!T.isNull() && "Unknown predefined type");
5770 return T.withFastQualifiers(FastQuals);
5771 }
5772
5773 Index -= NUM_PREDEF_TYPE_IDS;
5774 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5775 if (TypesLoaded[Index].isNull()) {
5776 TypesLoaded[Index] = readTypeRecord(Index);
5777 if (TypesLoaded[Index].isNull())
5778 return QualType();
5779
5780 TypesLoaded[Index]->setFromAST();
5781 if (DeserializationListener)
5782 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5783 TypesLoaded[Index]);
5784 }
5785
5786 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5787}
5788
5789QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5790 return GetType(getGlobalTypeID(F, LocalID));
5791}
5792
5793serialization::TypeID
5794ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5795 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5796 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5797
5798 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5799 return LocalID;
5800
5801 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5802 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5803 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5804
5805 unsigned GlobalIndex = LocalIndex + I->second;
5806 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5807}
5808
5809TemplateArgumentLocInfo
5810ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5811 TemplateArgument::ArgKind Kind,
5812 const RecordData &Record,
5813 unsigned &Index) {
5814 switch (Kind) {
5815 case TemplateArgument::Expression:
5816 return ReadExpr(F);
5817 case TemplateArgument::Type:
5818 return GetTypeSourceInfo(F, Record, Index);
5819 case TemplateArgument::Template: {
5820 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5821 Index);
5822 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5823 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5824 SourceLocation());
5825 }
5826 case TemplateArgument::TemplateExpansion: {
5827 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5828 Index);
5829 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5830 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5831 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5832 EllipsisLoc);
5833 }
5834 case TemplateArgument::Null:
5835 case TemplateArgument::Integral:
5836 case TemplateArgument::Declaration:
5837 case TemplateArgument::NullPtr:
5838 case TemplateArgument::Pack:
5839 // FIXME: Is this right?
5840 return TemplateArgumentLocInfo();
5841 }
5842 llvm_unreachable("unexpected template argument loc");
5843}
5844
5845TemplateArgumentLoc
5846ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5847 const RecordData &Record, unsigned &Index) {
5848 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5849
5850 if (Arg.getKind() == TemplateArgument::Expression) {
5851 if (Record[Index++]) // bool InfoHasSameExpr.
5852 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5853 }
5854 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5855 Record, Index));
5856}
5857
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005858const ASTTemplateArgumentListInfo*
5859ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5860 const RecordData &Record,
5861 unsigned &Index) {
5862 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5863 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5864 unsigned NumArgsAsWritten = Record[Index++];
5865 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5866 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5867 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5868 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5869}
5870
Guy Benyei11169dd2012-12-18 14:30:41 +00005871Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5872 return GetDecl(ID);
5873}
5874
Richard Smith50895422015-01-31 03:04:55 +00005875template<typename TemplateSpecializationDecl>
5876static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5877 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5878 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5879}
5880
Richard Smith053f6c62014-05-16 23:01:30 +00005881void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005882 if (NumCurrentElementsDeserializing) {
5883 // We arrange to not care about the complete redeclaration chain while we're
5884 // deserializing. Just remember that the AST has marked this one as complete
5885 // but that it's not actually complete yet, so we know we still need to
5886 // complete it later.
5887 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5888 return;
5889 }
5890
Richard Smith053f6c62014-05-16 23:01:30 +00005891 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5892
Richard Smith053f6c62014-05-16 23:01:30 +00005893 // If this is a named declaration, complete it by looking it up
5894 // within its context.
5895 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005896 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005897 // all mergeable entities within it.
5898 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5899 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5900 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00005901 if (!getContext().getLangOpts().CPlusPlus &&
5902 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00005903 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00005904 // the identifier instead. (For C++ modules, we don't store decls
5905 // in the serialized identifier table, so we do the lookup in the TU.)
5906 auto *II = Name.getAsIdentifierInfo();
5907 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00005908 if (II->isOutOfDate())
5909 updateOutOfDateIdentifier(*II);
5910 } else
5911 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005912 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
5913 // FIXME: It'd be nice to do something a bit more targeted here.
5914 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00005915 }
5916 }
Richard Smith50895422015-01-31 03:04:55 +00005917
5918 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5919 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5920 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5921 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5922 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5923 if (auto *Template = FD->getPrimaryTemplate())
5924 Template->LoadLazySpecializations();
5925 }
Richard Smith053f6c62014-05-16 23:01:30 +00005926}
5927
Richard Smithc2bb8182015-03-24 06:36:48 +00005928uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5929 const RecordData &Record,
5930 unsigned &Idx) {
5931 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5932 Error("malformed AST file: missing C++ ctor initializers");
5933 return 0;
5934 }
5935
5936 unsigned LocalID = Record[Idx++];
5937 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
5938}
5939
5940CXXCtorInitializer **
5941ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
5942 RecordLocation Loc = getLocalBitOffset(Offset);
5943 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
5944 SavedStreamPosition SavedPosition(Cursor);
5945 Cursor.JumpToBit(Loc.Offset);
5946 ReadingKindTracker ReadingKind(Read_Decl, *this);
5947
5948 RecordData Record;
5949 unsigned Code = Cursor.ReadCode();
5950 unsigned RecCode = Cursor.readRecord(Code, Record);
5951 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
5952 Error("malformed AST file: missing C++ ctor initializers");
5953 return nullptr;
5954 }
5955
5956 unsigned Idx = 0;
5957 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
5958}
5959
Richard Smithcd45dbc2014-04-19 03:48:30 +00005960uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5961 const RecordData &Record,
5962 unsigned &Idx) {
5963 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5964 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005965 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005966 }
5967
Guy Benyei11169dd2012-12-18 14:30:41 +00005968 unsigned LocalID = Record[Idx++];
5969 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5970}
5971
5972CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5973 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005974 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005975 SavedStreamPosition SavedPosition(Cursor);
5976 Cursor.JumpToBit(Loc.Offset);
5977 ReadingKindTracker ReadingKind(Read_Decl, *this);
5978 RecordData Record;
5979 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005980 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005981 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005982 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00005983 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005984 }
5985
5986 unsigned Idx = 0;
5987 unsigned NumBases = Record[Idx++];
5988 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5989 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5990 for (unsigned I = 0; I != NumBases; ++I)
5991 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5992 return Bases;
5993}
5994
5995serialization::DeclID
5996ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5997 if (LocalID < NUM_PREDEF_DECL_IDS)
5998 return LocalID;
5999
6000 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6001 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6002 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6003
6004 return LocalID + I->second;
6005}
6006
6007bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6008 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006009 // Predefined decls aren't from any module.
6010 if (ID < NUM_PREDEF_DECL_IDS)
6011 return false;
6012
Richard Smithbcda1a92015-07-12 23:51:20 +00006013 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6014 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006015}
6016
Douglas Gregor9f782892013-01-21 15:25:38 +00006017ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006018 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006019 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006020 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6021 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6022 return I->second;
6023}
6024
6025SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6026 if (ID < NUM_PREDEF_DECL_IDS)
6027 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006028
Guy Benyei11169dd2012-12-18 14:30:41 +00006029 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6030
6031 if (Index > DeclsLoaded.size()) {
6032 Error("declaration ID out-of-range for AST file");
6033 return SourceLocation();
6034 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006035
Guy Benyei11169dd2012-12-18 14:30:41 +00006036 if (Decl *D = DeclsLoaded[Index])
6037 return D->getLocation();
6038
6039 unsigned RawLocation = 0;
6040 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6041 return ReadSourceLocation(*Rec.F, RawLocation);
6042}
6043
Richard Smithfe620d22015-03-05 23:24:12 +00006044static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6045 switch (ID) {
6046 case PREDEF_DECL_NULL_ID:
6047 return nullptr;
6048
6049 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6050 return Context.getTranslationUnitDecl();
6051
6052 case PREDEF_DECL_OBJC_ID_ID:
6053 return Context.getObjCIdDecl();
6054
6055 case PREDEF_DECL_OBJC_SEL_ID:
6056 return Context.getObjCSelDecl();
6057
6058 case PREDEF_DECL_OBJC_CLASS_ID:
6059 return Context.getObjCClassDecl();
6060
6061 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6062 return Context.getObjCProtocolDecl();
6063
6064 case PREDEF_DECL_INT_128_ID:
6065 return Context.getInt128Decl();
6066
6067 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6068 return Context.getUInt128Decl();
6069
6070 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6071 return Context.getObjCInstanceTypeDecl();
6072
6073 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6074 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006075
Richard Smith9b88a4c2015-07-27 05:40:23 +00006076 case PREDEF_DECL_VA_LIST_TAG:
6077 return Context.getVaListTagDecl();
6078
Richard Smithf19e1272015-03-07 00:04:49 +00006079 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6080 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006081 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006082 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006083}
6084
Richard Smithcd45dbc2014-04-19 03:48:30 +00006085Decl *ASTReader::GetExistingDecl(DeclID ID) {
6086 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006087 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6088 if (D) {
6089 // Track that we have merged the declaration with ID \p ID into the
6090 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006091 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006092 if (Merged.empty())
6093 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006094 }
Richard Smithfe620d22015-03-05 23:24:12 +00006095 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006096 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006097
Guy Benyei11169dd2012-12-18 14:30:41 +00006098 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6099
6100 if (Index >= DeclsLoaded.size()) {
6101 assert(0 && "declaration ID out-of-range for AST file");
6102 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006103 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006104 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006105
6106 return DeclsLoaded[Index];
6107}
6108
6109Decl *ASTReader::GetDecl(DeclID ID) {
6110 if (ID < NUM_PREDEF_DECL_IDS)
6111 return GetExistingDecl(ID);
6112
6113 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6114
6115 if (Index >= DeclsLoaded.size()) {
6116 assert(0 && "declaration ID out-of-range for AST file");
6117 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006118 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006119 }
6120
Guy Benyei11169dd2012-12-18 14:30:41 +00006121 if (!DeclsLoaded[Index]) {
6122 ReadDeclRecord(ID);
6123 if (DeserializationListener)
6124 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6125 }
6126
6127 return DeclsLoaded[Index];
6128}
6129
6130DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6131 DeclID GlobalID) {
6132 if (GlobalID < NUM_PREDEF_DECL_IDS)
6133 return GlobalID;
6134
6135 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6136 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6137 ModuleFile *Owner = I->second;
6138
6139 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6140 = M.GlobalToLocalDeclIDs.find(Owner);
6141 if (Pos == M.GlobalToLocalDeclIDs.end())
6142 return 0;
6143
6144 return GlobalID - Owner->BaseDeclID + Pos->second;
6145}
6146
6147serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6148 const RecordData &Record,
6149 unsigned &Idx) {
6150 if (Idx >= Record.size()) {
6151 Error("Corrupted AST file");
6152 return 0;
6153 }
6154
6155 return getGlobalDeclID(F, Record[Idx++]);
6156}
6157
6158/// \brief Resolve the offset of a statement into a statement.
6159///
6160/// This operation will read a new statement from the external
6161/// source each time it is called, and is meant to be used via a
6162/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6163Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6164 // Switch case IDs are per Decl.
6165 ClearSwitchCaseIDs();
6166
6167 // Offset here is a global offset across the entire chain.
6168 RecordLocation Loc = getLocalBitOffset(Offset);
6169 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6170 return ReadStmtFromStream(*Loc.F);
6171}
6172
6173namespace {
6174 class FindExternalLexicalDeclsVisitor {
6175 ASTReader &Reader;
6176 const DeclContext *DC;
6177 bool (*isKindWeWant)(Decl::Kind);
6178
6179 SmallVectorImpl<Decl*> &Decls;
6180 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6181
6182 public:
6183 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6184 bool (*isKindWeWant)(Decl::Kind),
6185 SmallVectorImpl<Decl*> &Decls)
6186 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6187 {
6188 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6189 PredefsVisited[I] = false;
6190 }
6191
Manuel Klimek9eff8b12015-05-20 10:29:23 +00006192 static bool visitPostorder(ModuleFile &M, void *UserData) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006193 FindExternalLexicalDeclsVisitor *This
6194 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6195
6196 ModuleFile::DeclContextInfosMap::iterator Info
6197 = M.DeclContextInfos.find(This->DC);
Richard Smith787c0e42015-07-23 00:53:59 +00006198 if (Info == M.DeclContextInfos.end() || Info->second.LexicalDecls.empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006199 return false;
6200
6201 // Load all of the declaration IDs
Richard Smith787c0e42015-07-23 00:53:59 +00006202 for (const KindDeclIDPair &P : Info->second.LexicalDecls) {
6203 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)P.first))
Guy Benyei11169dd2012-12-18 14:30:41 +00006204 continue;
6205
6206 // Don't add predefined declarations to the lexical context more
6207 // than once.
Richard Smith787c0e42015-07-23 00:53:59 +00006208 if (P.second < NUM_PREDEF_DECL_IDS) {
6209 if (This->PredefsVisited[P.second])
Guy Benyei11169dd2012-12-18 14:30:41 +00006210 continue;
6211
Richard Smith787c0e42015-07-23 00:53:59 +00006212 This->PredefsVisited[P.second] = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00006213 }
6214
Richard Smith787c0e42015-07-23 00:53:59 +00006215 if (Decl *D = This->Reader.GetLocalDecl(M, P.second)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006216 if (!This->DC->isDeclInLexicalTraversal(D))
6217 This->Decls.push_back(D);
6218 }
6219 }
6220
6221 return false;
6222 }
6223 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006224}
Guy Benyei11169dd2012-12-18 14:30:41 +00006225
6226ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6227 bool (*isKindWeWant)(Decl::Kind),
6228 SmallVectorImpl<Decl*> &Decls) {
6229 // There might be lexical decls in multiple modules, for the TU at
6230 // least. Walk all of the modules in the order they were loaded.
6231 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
Manuel Klimek9eff8b12015-05-20 10:29:23 +00006232 ModuleMgr.visitDepthFirst(
6233 nullptr, &FindExternalLexicalDeclsVisitor::visitPostorder, &Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006234 ++NumLexicalDeclContextsRead;
6235 return ELR_Success;
6236}
6237
6238namespace {
6239
6240class DeclIDComp {
6241 ASTReader &Reader;
6242 ModuleFile &Mod;
6243
6244public:
6245 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6246
6247 bool operator()(LocalDeclID L, LocalDeclID R) const {
6248 SourceLocation LHS = getLocation(L);
6249 SourceLocation RHS = getLocation(R);
6250 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6251 }
6252
6253 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6254 SourceLocation RHS = getLocation(R);
6255 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6256 }
6257
6258 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6259 SourceLocation LHS = getLocation(L);
6260 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6261 }
6262
6263 SourceLocation getLocation(LocalDeclID ID) const {
6264 return Reader.getSourceManager().getFileLoc(
6265 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6266 }
6267};
6268
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006269}
Guy Benyei11169dd2012-12-18 14:30:41 +00006270
6271void ASTReader::FindFileRegionDecls(FileID File,
6272 unsigned Offset, unsigned Length,
6273 SmallVectorImpl<Decl *> &Decls) {
6274 SourceManager &SM = getSourceManager();
6275
6276 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6277 if (I == FileDeclIDs.end())
6278 return;
6279
6280 FileDeclsInfo &DInfo = I->second;
6281 if (DInfo.Decls.empty())
6282 return;
6283
6284 SourceLocation
6285 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6286 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6287
6288 DeclIDComp DIDComp(*this, *DInfo.Mod);
6289 ArrayRef<serialization::LocalDeclID>::iterator
6290 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6291 BeginLoc, DIDComp);
6292 if (BeginIt != DInfo.Decls.begin())
6293 --BeginIt;
6294
6295 // If we are pointing at a top-level decl inside an objc container, we need
6296 // to backtrack until we find it otherwise we will fail to report that the
6297 // region overlaps with an objc container.
6298 while (BeginIt != DInfo.Decls.begin() &&
6299 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6300 ->isTopLevelDeclInObjCContainer())
6301 --BeginIt;
6302
6303 ArrayRef<serialization::LocalDeclID>::iterator
6304 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6305 EndLoc, DIDComp);
6306 if (EndIt != DInfo.Decls.end())
6307 ++EndIt;
6308
6309 for (ArrayRef<serialization::LocalDeclID>::iterator
6310 DIt = BeginIt; DIt != EndIt; ++DIt)
6311 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6312}
6313
Richard Smith3b637412015-07-14 18:42:41 +00006314/// \brief Retrieve the "definitive" module file for the definition of the
6315/// given declaration context, if there is one.
6316///
6317/// The "definitive" module file is the only place where we need to look to
6318/// find information about the declarations within the given declaration
6319/// context. For example, C++ and Objective-C classes, C structs/unions, and
6320/// Objective-C protocols, categories, and extensions are all defined in a
6321/// single place in the source code, so they have definitive module files
6322/// associated with them. C++ namespaces, on the other hand, can have
6323/// definitions in multiple different module files.
6324///
6325/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6326/// NDEBUG checking.
6327static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6328 ASTReader &Reader) {
6329 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6330 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6331
6332 return nullptr;
6333}
6334
Guy Benyei11169dd2012-12-18 14:30:41 +00006335namespace {
6336 /// \brief ModuleFile visitor used to perform name lookup into a
6337 /// declaration context.
6338 class DeclContextNameLookupVisitor {
6339 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006340 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006341 DeclarationName Name;
Richard Smith3b637412015-07-14 18:42:41 +00006342 ASTDeclContextNameLookupTrait::DeclNameKey NameKey;
6343 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00006344 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006345 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006346
6347 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006348 DeclContextNameLookupVisitor(ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006349 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006350 SmallVectorImpl<NamedDecl *> &Decls,
6351 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
Richard Smith3b637412015-07-14 18:42:41 +00006352 : Reader(Reader), Name(Name),
6353 NameKey(ASTDeclContextNameLookupTrait::GetInternalKey(Name)),
6354 NameHash(ASTDeclContextNameLookupTrait::ComputeHash(NameKey)),
6355 Decls(Decls), DeclSet(DeclSet) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006356
Richard Smith3b637412015-07-14 18:42:41 +00006357 void visitContexts(ArrayRef<const DeclContext*> Contexts) {
6358 if (Contexts.empty())
6359 return;
6360 this->Contexts = Contexts;
6361
6362 // If we can definitively determine which module file to look into,
6363 // only look there. Otherwise, look in all module files.
6364 ModuleFile *Definitive;
6365 if (Contexts.size() == 1 &&
6366 (Definitive = getDefinitiveModuleFileFor(Contexts[0], Reader))) {
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006367 (*this)(*Definitive);
Richard Smith3b637412015-07-14 18:42:41 +00006368 } else {
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006369 Reader.getModuleManager().visit(*this);
Richard Smith3b637412015-07-14 18:42:41 +00006370 }
6371 }
6372
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006373 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006374 // Check whether we have any visible declaration information for
6375 // this context in this module.
6376 ModuleFile::DeclContextInfosMap::iterator Info;
6377 bool FoundInfo = false;
Richard Smithbdf2d932015-07-30 03:37:16 +00006378 for (auto *DC : Contexts) {
Richard Smith8c913ec2014-08-14 02:21:01 +00006379 Info = M.DeclContextInfos.find(DC);
6380 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006381 Info->second.NameLookupTableData) {
6382 FoundInfo = true;
6383 break;
6384 }
6385 }
6386
6387 if (!FoundInfo)
6388 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006389
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006391 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006392 Info->second.NameLookupTableData;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006393 ASTDeclContextNameLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00006394 LookupTable->find_hashed(NameKey, NameHash);
Guy Benyei11169dd2012-12-18 14:30:41 +00006395 if (Pos == LookupTable->end())
6396 return false;
6397
6398 bool FoundAnything = false;
6399 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6400 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006401 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006402 if (!ND)
6403 continue;
6404
Richard Smithbdf2d932015-07-30 03:37:16 +00006405 if (ND->getDeclName() != Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006406 // A name might be null because the decl's redeclarable part is
6407 // currently read before reading its name. The lookup is triggered by
6408 // building that decl (likely indirectly), and so it is later in the
6409 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006410 // FIXME: This should not happen; deserializing declarations should
6411 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006412 continue;
6413 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006414
Guy Benyei11169dd2012-12-18 14:30:41 +00006415 // Record this declaration.
6416 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006417 if (DeclSet.insert(ND).second)
6418 Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006419 }
6420
6421 return FoundAnything;
6422 }
6423 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006424}
Guy Benyei11169dd2012-12-18 14:30:41 +00006425
Richard Smith9ce12e32013-02-07 03:30:24 +00006426bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006427ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6428 DeclarationName Name) {
6429 assert(DC->hasExternalVisibleStorage() &&
6430 "DeclContext has no visible decls in storage");
6431 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006432 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006433
Richard Smith8c913ec2014-08-14 02:21:01 +00006434 Deserializing LookupResults(this);
6435
Guy Benyei11169dd2012-12-18 14:30:41 +00006436 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006437 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006438
Guy Benyei11169dd2012-12-18 14:30:41 +00006439 // Compute the declaration contexts we need to look into. Multiple such
6440 // declaration contexts occur when two declaration contexts from disjoint
6441 // modules get merged, e.g., when two namespaces with the same name are
6442 // independently defined in separate modules.
6443 SmallVector<const DeclContext *, 2> Contexts;
6444 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006445
Guy Benyei11169dd2012-12-18 14:30:41 +00006446 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006447 auto Key = KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6448 if (Key != KeyDecls.end()) {
6449 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6450 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006451 }
6452 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006453
Richard Smith3b637412015-07-14 18:42:41 +00006454 DeclContextNameLookupVisitor Visitor(*this, Name, Decls, DeclSet);
6455 Visitor.visitContexts(Contexts);
Richard Smith8c913ec2014-08-14 02:21:01 +00006456
6457 // If this might be an implicit special member function, then also search
6458 // all merged definitions of the surrounding class. We need to search them
6459 // individually, because finding an entity in one of them doesn't imply that
6460 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006461 if (isa<CXXRecordDecl>(DC)) {
Richard Smith02793752015-03-27 21:16:39 +00006462 auto Merged = MergedLookups.find(DC);
6463 if (Merged != MergedLookups.end()) {
6464 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6465 const DeclContext *Context = Merged->second[I];
Richard Smith3b637412015-07-14 18:42:41 +00006466 Visitor.visitContexts(Context);
Richard Smith02793752015-03-27 21:16:39 +00006467 // We might have just added some more merged lookups. If so, our
6468 // iterator is now invalid, so grab a fresh one before continuing.
6469 Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006470 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006471 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006472 }
6473
Guy Benyei11169dd2012-12-18 14:30:41 +00006474 ++NumVisibleDeclContextsRead;
6475 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006476 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006477}
6478
6479namespace {
6480 /// \brief ModuleFile visitor used to retrieve all visible names in a
6481 /// declaration context.
6482 class DeclContextAllNamesVisitor {
6483 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006484 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006485 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006486 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006487 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006488
6489 public:
6490 DeclContextAllNamesVisitor(ASTReader &Reader,
6491 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006492 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006493 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006494
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006495 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006496 // Check whether we have any visible declaration information for
6497 // this context in this module.
6498 ModuleFile::DeclContextInfosMap::iterator Info;
6499 bool FoundInfo = false;
Richard Smithbdf2d932015-07-30 03:37:16 +00006500 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
6501 Info = M.DeclContextInfos.find(Contexts[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006502 if (Info != M.DeclContextInfos.end() &&
6503 Info->second.NameLookupTableData) {
6504 FoundInfo = true;
6505 break;
6506 }
6507 }
6508
6509 if (!FoundInfo)
6510 return false;
6511
Richard Smith52e3fba2014-03-11 07:17:35 +00006512 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006513 Info->second.NameLookupTableData;
6514 bool FoundAnything = false;
6515 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006516 I = LookupTable->data_begin(), E = LookupTable->data_end();
6517 I != E;
6518 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006519 ASTDeclContextNameLookupTrait::data_type Data = *I;
6520 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006521 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006522 if (!ND)
6523 continue;
6524
6525 // Record this declaration.
6526 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006527 if (DeclSet.insert(ND).second)
6528 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006529 }
6530 }
6531
Richard Smithbdf2d932015-07-30 03:37:16 +00006532 return FoundAnything && !VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006533 }
6534 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006535}
Guy Benyei11169dd2012-12-18 14:30:41 +00006536
6537void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6538 if (!DC->hasExternalVisibleStorage())
6539 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006540 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006541
6542 // Compute the declaration contexts we need to look into. Multiple such
6543 // declaration contexts occur when two declaration contexts from disjoint
6544 // modules get merged, e.g., when two namespaces with the same name are
6545 // independently defined in separate modules.
6546 SmallVector<const DeclContext *, 2> Contexts;
6547 Contexts.push_back(DC);
6548
6549 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006550 KeyDeclsMap::iterator Key =
6551 KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6552 if (Key != KeyDecls.end()) {
6553 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6554 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006555 }
6556 }
6557
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006558 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6559 /*VisitAll=*/DC->isFileContext());
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006560 ModuleMgr.visit(Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006561 ++NumVisibleDeclContextsRead;
6562
Craig Topper79be4cd2013-07-05 04:33:53 +00006563 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006564 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6565 }
6566 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6567}
6568
6569/// \brief Under non-PCH compilation the consumer receives the objc methods
6570/// before receiving the implementation, and codegen depends on this.
6571/// We simulate this by deserializing and passing to consumer the methods of the
6572/// implementation before passing the deserialized implementation decl.
6573static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6574 ASTConsumer *Consumer) {
6575 assert(ImplD && Consumer);
6576
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006577 for (auto *I : ImplD->methods())
6578 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006579
6580 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6581}
6582
6583void ASTReader::PassInterestingDeclsToConsumer() {
6584 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006585
6586 if (PassingDeclsToConsumer)
6587 return;
6588
6589 // Guard variable to avoid recursively redoing the process of passing
6590 // decls to consumer.
6591 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6592 true);
6593
Richard Smith9e2341d2015-03-23 03:25:59 +00006594 // Ensure that we've loaded all potentially-interesting declarations
6595 // that need to be eagerly loaded.
6596 for (auto ID : EagerlyDeserializedDecls)
6597 GetDecl(ID);
6598 EagerlyDeserializedDecls.clear();
6599
Guy Benyei11169dd2012-12-18 14:30:41 +00006600 while (!InterestingDecls.empty()) {
6601 Decl *D = InterestingDecls.front();
6602 InterestingDecls.pop_front();
6603
6604 PassInterestingDeclToConsumer(D);
6605 }
6606}
6607
6608void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6609 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6610 PassObjCImplDeclToConsumer(ImplD, Consumer);
6611 else
6612 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6613}
6614
6615void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6616 this->Consumer = Consumer;
6617
Richard Smith9e2341d2015-03-23 03:25:59 +00006618 if (Consumer)
6619 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006620
6621 if (DeserializationListener)
6622 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006623}
6624
6625void ASTReader::PrintStats() {
6626 std::fprintf(stderr, "*** AST File Statistics:\n");
6627
6628 unsigned NumTypesLoaded
6629 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6630 QualType());
6631 unsigned NumDeclsLoaded
6632 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006633 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006634 unsigned NumIdentifiersLoaded
6635 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6636 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006637 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006638 unsigned NumMacrosLoaded
6639 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6640 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006641 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006642 unsigned NumSelectorsLoaded
6643 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6644 SelectorsLoaded.end(),
6645 Selector());
6646
6647 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6648 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6649 NumSLocEntriesRead, TotalNumSLocEntries,
6650 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6651 if (!TypesLoaded.empty())
6652 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6653 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6654 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6655 if (!DeclsLoaded.empty())
6656 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6657 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6658 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6659 if (!IdentifiersLoaded.empty())
6660 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6661 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6662 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6663 if (!MacrosLoaded.empty())
6664 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6665 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6666 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6667 if (!SelectorsLoaded.empty())
6668 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6669 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6670 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6671 if (TotalNumStatements)
6672 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6673 NumStatementsRead, TotalNumStatements,
6674 ((float)NumStatementsRead/TotalNumStatements * 100));
6675 if (TotalNumMacros)
6676 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6677 NumMacrosRead, TotalNumMacros,
6678 ((float)NumMacrosRead/TotalNumMacros * 100));
6679 if (TotalLexicalDeclContexts)
6680 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6681 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6682 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6683 * 100));
6684 if (TotalVisibleDeclContexts)
6685 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6686 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6687 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6688 * 100));
6689 if (TotalNumMethodPoolEntries) {
6690 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6691 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6692 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6693 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006694 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006695 if (NumMethodPoolLookups) {
6696 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6697 NumMethodPoolHits, NumMethodPoolLookups,
6698 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6699 }
6700 if (NumMethodPoolTableLookups) {
6701 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6702 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6703 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6704 * 100.0));
6705 }
6706
Douglas Gregor00a50f72013-01-25 00:38:33 +00006707 if (NumIdentifierLookupHits) {
6708 std::fprintf(stderr,
6709 " %u / %u identifier table lookups succeeded (%f%%)\n",
6710 NumIdentifierLookupHits, NumIdentifierLookups,
6711 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6712 }
6713
Douglas Gregore060e572013-01-25 01:03:03 +00006714 if (GlobalIndex) {
6715 std::fprintf(stderr, "\n");
6716 GlobalIndex->printStats();
6717 }
6718
Guy Benyei11169dd2012-12-18 14:30:41 +00006719 std::fprintf(stderr, "\n");
6720 dump();
6721 std::fprintf(stderr, "\n");
6722}
6723
6724template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6725static void
6726dumpModuleIDMap(StringRef Name,
6727 const ContinuousRangeMap<Key, ModuleFile *,
6728 InitialCapacity> &Map) {
6729 if (Map.begin() == Map.end())
6730 return;
6731
6732 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6733 llvm::errs() << Name << ":\n";
6734 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6735 I != IEnd; ++I) {
6736 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6737 << "\n";
6738 }
6739}
6740
6741void ASTReader::dump() {
6742 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6743 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6744 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6745 dumpModuleIDMap("Global type map", GlobalTypeMap);
6746 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6747 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6748 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6749 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6750 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6751 dumpModuleIDMap("Global preprocessed entity map",
6752 GlobalPreprocessedEntityMap);
6753
6754 llvm::errs() << "\n*** PCH/Modules Loaded:";
6755 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6756 MEnd = ModuleMgr.end();
6757 M != MEnd; ++M)
6758 (*M)->dump();
6759}
6760
6761/// Return the amount of memory used by memory buffers, breaking down
6762/// by heap-backed versus mmap'ed memory.
6763void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6764 for (ModuleConstIterator I = ModuleMgr.begin(),
6765 E = ModuleMgr.end(); I != E; ++I) {
6766 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6767 size_t bytes = buf->getBufferSize();
6768 switch (buf->getBufferKind()) {
6769 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6770 sizes.malloc_bytes += bytes;
6771 break;
6772 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6773 sizes.mmap_bytes += bytes;
6774 break;
6775 }
6776 }
6777 }
6778}
6779
6780void ASTReader::InitializeSema(Sema &S) {
6781 SemaObj = &S;
6782 S.addExternalSource(this);
6783
6784 // Makes sure any declarations that were deserialized "too early"
6785 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006786 for (uint64_t ID : PreloadedDeclIDs) {
6787 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6788 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006789 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006790 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006791
Richard Smith3d8e97e2013-10-18 06:54:39 +00006792 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006793 if (!FPPragmaOptions.empty()) {
6794 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6795 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6796 }
6797
Richard Smith3d8e97e2013-10-18 06:54:39 +00006798 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006799 if (!OpenCLExtensions.empty()) {
6800 unsigned I = 0;
6801#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6802#include "clang/Basic/OpenCLExtensions.def"
6803
6804 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6805 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006806
6807 UpdateSema();
6808}
6809
6810void ASTReader::UpdateSema() {
6811 assert(SemaObj && "no Sema to update");
6812
6813 // Load the offsets of the declarations that Sema references.
6814 // They will be lazily deserialized when needed.
6815 if (!SemaDeclRefs.empty()) {
6816 assert(SemaDeclRefs.size() % 2 == 0);
6817 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6818 if (!SemaObj->StdNamespace)
6819 SemaObj->StdNamespace = SemaDeclRefs[I];
6820 if (!SemaObj->StdBadAlloc)
6821 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6822 }
6823 SemaDeclRefs.clear();
6824 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006825
6826 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6827 // encountered the pragma in the source.
6828 if(OptimizeOffPragmaLocation.isValid())
6829 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006830}
6831
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006832IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006833 // Note that we are loading an identifier.
6834 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006835
Douglas Gregor7211ac12013-01-25 23:32:03 +00006836 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006837 NumIdentifierLookups,
6838 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006839
6840 // We don't need to do identifier table lookups in C++ modules (we preload
6841 // all interesting declarations, and don't need to use the scope for name
6842 // lookups). Perform the lookup in PCH files, though, since we don't build
6843 // a complete initial identifier table if we're carrying on from a PCH.
6844 if (Context.getLangOpts().CPlusPlus) {
6845 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006846 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006847 break;
6848 } else {
6849 // If there is a global index, look there first to determine which modules
6850 // provably do not have any results for this identifier.
6851 GlobalModuleIndex::HitSet Hits;
6852 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6853 if (!loadGlobalIndex()) {
6854 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6855 HitsPtr = &Hits;
6856 }
6857 }
6858
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006859 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006860 }
6861
Guy Benyei11169dd2012-12-18 14:30:41 +00006862 IdentifierInfo *II = Visitor.getIdentifierInfo();
6863 markIdentifierUpToDate(II);
6864 return II;
6865}
6866
6867namespace clang {
6868 /// \brief An identifier-lookup iterator that enumerates all of the
6869 /// identifiers stored within a set of AST files.
6870 class ASTIdentifierIterator : public IdentifierIterator {
6871 /// \brief The AST reader whose identifiers are being enumerated.
6872 const ASTReader &Reader;
6873
6874 /// \brief The current index into the chain of AST files stored in
6875 /// the AST reader.
6876 unsigned Index;
6877
6878 /// \brief The current position within the identifier lookup table
6879 /// of the current AST file.
6880 ASTIdentifierLookupTable::key_iterator Current;
6881
6882 /// \brief The end position within the identifier lookup table of
6883 /// the current AST file.
6884 ASTIdentifierLookupTable::key_iterator End;
6885
6886 public:
6887 explicit ASTIdentifierIterator(const ASTReader &Reader);
6888
Craig Topper3e89dfe2014-03-13 02:13:41 +00006889 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006890 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006891}
Guy Benyei11169dd2012-12-18 14:30:41 +00006892
6893ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6894 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6895 ASTIdentifierLookupTable *IdTable
6896 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6897 Current = IdTable->key_begin();
6898 End = IdTable->key_end();
6899}
6900
6901StringRef ASTIdentifierIterator::Next() {
6902 while (Current == End) {
6903 // If we have exhausted all of our AST files, we're done.
6904 if (Index == 0)
6905 return StringRef();
6906
6907 --Index;
6908 ASTIdentifierLookupTable *IdTable
6909 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6910 IdentifierLookupTable;
6911 Current = IdTable->key_begin();
6912 End = IdTable->key_end();
6913 }
6914
6915 // We have any identifiers remaining in the current AST file; return
6916 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006917 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006918 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006919 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006920}
6921
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006922IdentifierIterator *ASTReader::getIdentifiers() {
6923 if (!loadGlobalIndex())
6924 return GlobalIndex->createIdentifierIterator();
6925
Guy Benyei11169dd2012-12-18 14:30:41 +00006926 return new ASTIdentifierIterator(*this);
6927}
6928
6929namespace clang { namespace serialization {
6930 class ReadMethodPoolVisitor {
6931 ASTReader &Reader;
6932 Selector Sel;
6933 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006934 unsigned InstanceBits;
6935 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006936 bool InstanceHasMoreThanOneDecl;
6937 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006938 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6939 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006940
6941 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006942 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006943 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006944 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006945 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6946 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006947
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006948 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006949 if (!M.SelectorLookupTable)
6950 return false;
6951
6952 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00006953 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00006954 return true;
6955
Richard Smithbdf2d932015-07-30 03:37:16 +00006956 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006957 ASTSelectorLookupTable *PoolTable
6958 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00006959 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00006960 if (Pos == PoolTable->end())
6961 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006962
Richard Smithbdf2d932015-07-30 03:37:16 +00006963 ++Reader.NumMethodPoolTableHits;
6964 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006965 // FIXME: Not quite happy with the statistics here. We probably should
6966 // disable this tracking when called via LoadSelector.
6967 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00006968 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006969 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00006970 if (Reader.DeserializationListener)
6971 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006972
Richard Smithbdf2d932015-07-30 03:37:16 +00006973 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6974 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6975 InstanceBits = Data.InstanceBits;
6976 FactoryBits = Data.FactoryBits;
6977 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6978 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006979 return true;
6980 }
6981
6982 /// \brief Retrieve the instance methods found by this visitor.
6983 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6984 return InstanceMethods;
6985 }
6986
6987 /// \brief Retrieve the instance methods found by this visitor.
6988 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6989 return FactoryMethods;
6990 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006991
6992 unsigned getInstanceBits() const { return InstanceBits; }
6993 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006994 bool instanceHasMoreThanOneDecl() const {
6995 return InstanceHasMoreThanOneDecl;
6996 }
6997 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006998 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006999} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00007000
7001/// \brief Add the given set of methods to the method list.
7002static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7003 ObjCMethodList &List) {
7004 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7005 S.addMethodToGlobalList(&List, Methods[I]);
7006 }
7007}
7008
7009void ASTReader::ReadMethodPool(Selector Sel) {
7010 // Get the selector generation and update it to the current generation.
7011 unsigned &Generation = SelectorGeneration[Sel];
7012 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007013 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007014
7015 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007016 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007017 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007018 ModuleMgr.visit(Visitor);
7019
Guy Benyei11169dd2012-12-18 14:30:41 +00007020 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007021 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007022 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007023
7024 ++NumMethodPoolHits;
7025
Guy Benyei11169dd2012-12-18 14:30:41 +00007026 if (!getSema())
7027 return;
7028
7029 Sema &S = *getSema();
7030 Sema::GlobalMethodPool::iterator Pos
7031 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007032
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007033 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007034 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007035 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007036 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007037
7038 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7039 // when building a module we keep every method individually and may need to
7040 // update hasMoreThanOneDecl as we add the methods.
7041 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7042 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007043}
7044
7045void ASTReader::ReadKnownNamespaces(
7046 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7047 Namespaces.clear();
7048
7049 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7050 if (NamespaceDecl *Namespace
7051 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7052 Namespaces.push_back(Namespace);
7053 }
7054}
7055
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007056void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007057 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007058 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7059 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007060 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007061 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007062 Undefined.insert(std::make_pair(D, Loc));
7063 }
7064}
Nick Lewycky8334af82013-01-26 00:35:08 +00007065
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007066void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7067 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7068 Exprs) {
7069 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7070 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7071 uint64_t Count = DelayedDeleteExprs[Idx++];
7072 for (uint64_t C = 0; C < Count; ++C) {
7073 SourceLocation DeleteLoc =
7074 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7075 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7076 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7077 }
7078 }
7079}
7080
Guy Benyei11169dd2012-12-18 14:30:41 +00007081void ASTReader::ReadTentativeDefinitions(
7082 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7083 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7084 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7085 if (Var)
7086 TentativeDefs.push_back(Var);
7087 }
7088 TentativeDefinitions.clear();
7089}
7090
7091void ASTReader::ReadUnusedFileScopedDecls(
7092 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7093 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7094 DeclaratorDecl *D
7095 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7096 if (D)
7097 Decls.push_back(D);
7098 }
7099 UnusedFileScopedDecls.clear();
7100}
7101
7102void ASTReader::ReadDelegatingConstructors(
7103 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7104 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7105 CXXConstructorDecl *D
7106 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7107 if (D)
7108 Decls.push_back(D);
7109 }
7110 DelegatingCtorDecls.clear();
7111}
7112
7113void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7114 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7115 TypedefNameDecl *D
7116 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7117 if (D)
7118 Decls.push_back(D);
7119 }
7120 ExtVectorDecls.clear();
7121}
7122
Nico Weber72889432014-09-06 01:25:55 +00007123void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7124 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7125 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7126 ++I) {
7127 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7128 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7129 if (D)
7130 Decls.insert(D);
7131 }
7132 UnusedLocalTypedefNameCandidates.clear();
7133}
7134
Guy Benyei11169dd2012-12-18 14:30:41 +00007135void ASTReader::ReadReferencedSelectors(
7136 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7137 if (ReferencedSelectorsData.empty())
7138 return;
7139
7140 // If there are @selector references added them to its pool. This is for
7141 // implementation of -Wselector.
7142 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7143 unsigned I = 0;
7144 while (I < DataSize) {
7145 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7146 SourceLocation SelLoc
7147 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7148 Sels.push_back(std::make_pair(Sel, SelLoc));
7149 }
7150 ReferencedSelectorsData.clear();
7151}
7152
7153void ASTReader::ReadWeakUndeclaredIdentifiers(
7154 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7155 if (WeakUndeclaredIdentifiers.empty())
7156 return;
7157
7158 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7159 IdentifierInfo *WeakId
7160 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7161 IdentifierInfo *AliasId
7162 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7163 SourceLocation Loc
7164 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7165 bool Used = WeakUndeclaredIdentifiers[I++];
7166 WeakInfo WI(AliasId, Loc);
7167 WI.setUsed(Used);
7168 WeakIDs.push_back(std::make_pair(WeakId, WI));
7169 }
7170 WeakUndeclaredIdentifiers.clear();
7171}
7172
7173void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7174 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7175 ExternalVTableUse VT;
7176 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7177 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7178 VT.DefinitionRequired = VTableUses[Idx++];
7179 VTables.push_back(VT);
7180 }
7181
7182 VTableUses.clear();
7183}
7184
7185void ASTReader::ReadPendingInstantiations(
7186 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7187 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7188 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7189 SourceLocation Loc
7190 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7191
7192 Pending.push_back(std::make_pair(D, Loc));
7193 }
7194 PendingInstantiations.clear();
7195}
7196
Richard Smithe40f2ba2013-08-07 21:41:30 +00007197void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007198 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007199 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7200 /* In loop */) {
7201 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7202
7203 LateParsedTemplate *LT = new LateParsedTemplate;
7204 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7205
7206 ModuleFile *F = getOwningModuleFile(LT->D);
7207 assert(F && "No module");
7208
7209 unsigned TokN = LateParsedTemplates[Idx++];
7210 LT->Toks.reserve(TokN);
7211 for (unsigned T = 0; T < TokN; ++T)
7212 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7213
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007214 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007215 }
7216
7217 LateParsedTemplates.clear();
7218}
7219
Guy Benyei11169dd2012-12-18 14:30:41 +00007220void ASTReader::LoadSelector(Selector Sel) {
7221 // It would be complicated to avoid reading the methods anyway. So don't.
7222 ReadMethodPool(Sel);
7223}
7224
7225void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7226 assert(ID && "Non-zero identifier ID required");
7227 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7228 IdentifiersLoaded[ID - 1] = II;
7229 if (DeserializationListener)
7230 DeserializationListener->IdentifierRead(ID, II);
7231}
7232
7233/// \brief Set the globally-visible declarations associated with the given
7234/// identifier.
7235///
7236/// If the AST reader is currently in a state where the given declaration IDs
7237/// cannot safely be resolved, they are queued until it is safe to resolve
7238/// them.
7239///
7240/// \param II an IdentifierInfo that refers to one or more globally-visible
7241/// declarations.
7242///
7243/// \param DeclIDs the set of declaration IDs with the name @p II that are
7244/// visible at global scope.
7245///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007246/// \param Decls if non-null, this vector will be populated with the set of
7247/// deserialized declarations. These declarations will not be pushed into
7248/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007249void
7250ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7251 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007252 SmallVectorImpl<Decl *> *Decls) {
7253 if (NumCurrentElementsDeserializing && !Decls) {
7254 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007255 return;
7256 }
7257
7258 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007259 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007260 // Queue this declaration so that it will be added to the
7261 // translation unit scope and identifier's declaration chain
7262 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007263 PreloadedDeclIDs.push_back(DeclIDs[I]);
7264 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007265 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007266
7267 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7268
7269 // If we're simply supposed to record the declarations, do so now.
7270 if (Decls) {
7271 Decls->push_back(D);
7272 continue;
7273 }
7274
7275 // Introduce this declaration into the translation-unit scope
7276 // and add it to the declaration chain for this identifier, so
7277 // that (unqualified) name lookup will find it.
7278 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007279 }
7280}
7281
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007282IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007283 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007284 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007285
7286 if (IdentifiersLoaded.empty()) {
7287 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007288 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007289 }
7290
7291 ID -= 1;
7292 if (!IdentifiersLoaded[ID]) {
7293 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7294 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7295 ModuleFile *M = I->second;
7296 unsigned Index = ID - M->BaseIdentifierID;
7297 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7298
7299 // All of the strings in the AST file are preceded by a 16-bit length.
7300 // Extract that 16-bit length to avoid having to execute strlen().
7301 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7302 // unsigned integers. This is important to avoid integer overflow when
7303 // we cast them to 'unsigned'.
7304 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7305 unsigned StrLen = (((unsigned) StrLenPtr[0])
7306 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007307 IdentifiersLoaded[ID]
7308 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007309 if (DeserializationListener)
7310 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7311 }
7312
7313 return IdentifiersLoaded[ID];
7314}
7315
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007316IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7317 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007318}
7319
7320IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7321 if (LocalID < NUM_PREDEF_IDENT_IDS)
7322 return LocalID;
7323
7324 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7325 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7326 assert(I != M.IdentifierRemap.end()
7327 && "Invalid index into identifier index remap");
7328
7329 return LocalID + I->second;
7330}
7331
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007332MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007333 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007334 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007335
7336 if (MacrosLoaded.empty()) {
7337 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007338 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007339 }
7340
7341 ID -= NUM_PREDEF_MACRO_IDS;
7342 if (!MacrosLoaded[ID]) {
7343 GlobalMacroMapType::iterator I
7344 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7345 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7346 ModuleFile *M = I->second;
7347 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007348 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7349
7350 if (DeserializationListener)
7351 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7352 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007353 }
7354
7355 return MacrosLoaded[ID];
7356}
7357
7358MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7359 if (LocalID < NUM_PREDEF_MACRO_IDS)
7360 return LocalID;
7361
7362 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7363 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7364 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7365
7366 return LocalID + I->second;
7367}
7368
7369serialization::SubmoduleID
7370ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7371 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7372 return LocalID;
7373
7374 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7375 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7376 assert(I != M.SubmoduleRemap.end()
7377 && "Invalid index into submodule index remap");
7378
7379 return LocalID + I->second;
7380}
7381
7382Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7383 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7384 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007385 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007386 }
7387
7388 if (GlobalID > SubmodulesLoaded.size()) {
7389 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007390 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007391 }
7392
7393 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7394}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007395
7396Module *ASTReader::getModule(unsigned ID) {
7397 return getSubmodule(ID);
7398}
7399
Adrian Prantl15bcf702015-06-30 17:39:43 +00007400ExternalASTSource::ASTSourceDescriptor
7401ASTReader::getSourceDescriptor(const Module &M) {
7402 StringRef Dir, Filename;
7403 if (M.Directory)
7404 Dir = M.Directory->getName();
7405 if (auto *File = M.getASTFile())
7406 Filename = File->getName();
7407 return ASTReader::ASTSourceDescriptor{
7408 M.getFullModuleName(), Dir, Filename,
7409 M.Signature
7410 };
7411}
7412
7413llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7414ASTReader::getSourceDescriptor(unsigned ID) {
7415 if (const Module *M = getSubmodule(ID))
7416 return getSourceDescriptor(*M);
7417
7418 // If there is only a single PCH, return it instead.
7419 // Chained PCH are not suported.
7420 if (ModuleMgr.size() == 1) {
7421 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7422 return ASTReader::ASTSourceDescriptor{
7423 MF.OriginalSourceFileName, MF.OriginalDir,
7424 MF.FileName,
7425 MF.Signature
7426 };
7427 }
7428 return None;
7429}
7430
Guy Benyei11169dd2012-12-18 14:30:41 +00007431Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7432 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7433}
7434
7435Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7436 if (ID == 0)
7437 return Selector();
7438
7439 if (ID > SelectorsLoaded.size()) {
7440 Error("selector ID out of range in AST file");
7441 return Selector();
7442 }
7443
Craig Toppera13603a2014-05-22 05:54:18 +00007444 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007445 // Load this selector from the selector table.
7446 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7447 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7448 ModuleFile &M = *I->second;
7449 ASTSelectorLookupTrait Trait(*this, M);
7450 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7451 SelectorsLoaded[ID - 1] =
7452 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7453 if (DeserializationListener)
7454 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7455 }
7456
7457 return SelectorsLoaded[ID - 1];
7458}
7459
7460Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7461 return DecodeSelector(ID);
7462}
7463
7464uint32_t ASTReader::GetNumExternalSelectors() {
7465 // ID 0 (the null selector) is considered an external selector.
7466 return getTotalNumSelectors() + 1;
7467}
7468
7469serialization::SelectorID
7470ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7471 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7472 return LocalID;
7473
7474 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7475 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7476 assert(I != M.SelectorRemap.end()
7477 && "Invalid index into selector index remap");
7478
7479 return LocalID + I->second;
7480}
7481
7482DeclarationName
7483ASTReader::ReadDeclarationName(ModuleFile &F,
7484 const RecordData &Record, unsigned &Idx) {
7485 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7486 switch (Kind) {
7487 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007488 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007489
7490 case DeclarationName::ObjCZeroArgSelector:
7491 case DeclarationName::ObjCOneArgSelector:
7492 case DeclarationName::ObjCMultiArgSelector:
7493 return DeclarationName(ReadSelector(F, Record, Idx));
7494
7495 case DeclarationName::CXXConstructorName:
7496 return Context.DeclarationNames.getCXXConstructorName(
7497 Context.getCanonicalType(readType(F, Record, Idx)));
7498
7499 case DeclarationName::CXXDestructorName:
7500 return Context.DeclarationNames.getCXXDestructorName(
7501 Context.getCanonicalType(readType(F, Record, Idx)));
7502
7503 case DeclarationName::CXXConversionFunctionName:
7504 return Context.DeclarationNames.getCXXConversionFunctionName(
7505 Context.getCanonicalType(readType(F, Record, Idx)));
7506
7507 case DeclarationName::CXXOperatorName:
7508 return Context.DeclarationNames.getCXXOperatorName(
7509 (OverloadedOperatorKind)Record[Idx++]);
7510
7511 case DeclarationName::CXXLiteralOperatorName:
7512 return Context.DeclarationNames.getCXXLiteralOperatorName(
7513 GetIdentifierInfo(F, Record, Idx));
7514
7515 case DeclarationName::CXXUsingDirective:
7516 return DeclarationName::getUsingDirectiveName();
7517 }
7518
7519 llvm_unreachable("Invalid NameKind!");
7520}
7521
7522void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7523 DeclarationNameLoc &DNLoc,
7524 DeclarationName Name,
7525 const RecordData &Record, unsigned &Idx) {
7526 switch (Name.getNameKind()) {
7527 case DeclarationName::CXXConstructorName:
7528 case DeclarationName::CXXDestructorName:
7529 case DeclarationName::CXXConversionFunctionName:
7530 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7531 break;
7532
7533 case DeclarationName::CXXOperatorName:
7534 DNLoc.CXXOperatorName.BeginOpNameLoc
7535 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7536 DNLoc.CXXOperatorName.EndOpNameLoc
7537 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7538 break;
7539
7540 case DeclarationName::CXXLiteralOperatorName:
7541 DNLoc.CXXLiteralOperatorName.OpNameLoc
7542 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7543 break;
7544
7545 case DeclarationName::Identifier:
7546 case DeclarationName::ObjCZeroArgSelector:
7547 case DeclarationName::ObjCOneArgSelector:
7548 case DeclarationName::ObjCMultiArgSelector:
7549 case DeclarationName::CXXUsingDirective:
7550 break;
7551 }
7552}
7553
7554void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7555 DeclarationNameInfo &NameInfo,
7556 const RecordData &Record, unsigned &Idx) {
7557 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7558 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7559 DeclarationNameLoc DNLoc;
7560 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7561 NameInfo.setInfo(DNLoc);
7562}
7563
7564void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7565 const RecordData &Record, unsigned &Idx) {
7566 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7567 unsigned NumTPLists = Record[Idx++];
7568 Info.NumTemplParamLists = NumTPLists;
7569 if (NumTPLists) {
7570 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7571 for (unsigned i=0; i != NumTPLists; ++i)
7572 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7573 }
7574}
7575
7576TemplateName
7577ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7578 unsigned &Idx) {
7579 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7580 switch (Kind) {
7581 case TemplateName::Template:
7582 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7583
7584 case TemplateName::OverloadedTemplate: {
7585 unsigned size = Record[Idx++];
7586 UnresolvedSet<8> Decls;
7587 while (size--)
7588 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7589
7590 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7591 }
7592
7593 case TemplateName::QualifiedTemplate: {
7594 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7595 bool hasTemplKeyword = Record[Idx++];
7596 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7597 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7598 }
7599
7600 case TemplateName::DependentTemplate: {
7601 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7602 if (Record[Idx++]) // isIdentifier
7603 return Context.getDependentTemplateName(NNS,
7604 GetIdentifierInfo(F, Record,
7605 Idx));
7606 return Context.getDependentTemplateName(NNS,
7607 (OverloadedOperatorKind)Record[Idx++]);
7608 }
7609
7610 case TemplateName::SubstTemplateTemplateParm: {
7611 TemplateTemplateParmDecl *param
7612 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7613 if (!param) return TemplateName();
7614 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7615 return Context.getSubstTemplateTemplateParm(param, replacement);
7616 }
7617
7618 case TemplateName::SubstTemplateTemplateParmPack: {
7619 TemplateTemplateParmDecl *Param
7620 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7621 if (!Param)
7622 return TemplateName();
7623
7624 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7625 if (ArgPack.getKind() != TemplateArgument::Pack)
7626 return TemplateName();
7627
7628 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7629 }
7630 }
7631
7632 llvm_unreachable("Unhandled template name kind!");
7633}
7634
7635TemplateArgument
7636ASTReader::ReadTemplateArgument(ModuleFile &F,
7637 const RecordData &Record, unsigned &Idx) {
7638 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7639 switch (Kind) {
7640 case TemplateArgument::Null:
7641 return TemplateArgument();
7642 case TemplateArgument::Type:
7643 return TemplateArgument(readType(F, Record, Idx));
7644 case TemplateArgument::Declaration: {
7645 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007646 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007647 }
7648 case TemplateArgument::NullPtr:
7649 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7650 case TemplateArgument::Integral: {
7651 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7652 QualType T = readType(F, Record, Idx);
7653 return TemplateArgument(Context, Value, T);
7654 }
7655 case TemplateArgument::Template:
7656 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7657 case TemplateArgument::TemplateExpansion: {
7658 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007659 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007660 if (unsigned NumExpansions = Record[Idx++])
7661 NumTemplateExpansions = NumExpansions - 1;
7662 return TemplateArgument(Name, NumTemplateExpansions);
7663 }
7664 case TemplateArgument::Expression:
7665 return TemplateArgument(ReadExpr(F));
7666 case TemplateArgument::Pack: {
7667 unsigned NumArgs = Record[Idx++];
7668 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7669 for (unsigned I = 0; I != NumArgs; ++I)
7670 Args[I] = ReadTemplateArgument(F, Record, Idx);
7671 return TemplateArgument(Args, NumArgs);
7672 }
7673 }
7674
7675 llvm_unreachable("Unhandled template argument kind!");
7676}
7677
7678TemplateParameterList *
7679ASTReader::ReadTemplateParameterList(ModuleFile &F,
7680 const RecordData &Record, unsigned &Idx) {
7681 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7682 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7683 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7684
7685 unsigned NumParams = Record[Idx++];
7686 SmallVector<NamedDecl *, 16> Params;
7687 Params.reserve(NumParams);
7688 while (NumParams--)
7689 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7690
7691 TemplateParameterList* TemplateParams =
7692 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7693 Params.data(), Params.size(), RAngleLoc);
7694 return TemplateParams;
7695}
7696
7697void
7698ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007699ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007700 ModuleFile &F, const RecordData &Record,
7701 unsigned &Idx) {
7702 unsigned NumTemplateArgs = Record[Idx++];
7703 TemplArgs.reserve(NumTemplateArgs);
7704 while (NumTemplateArgs--)
7705 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7706}
7707
7708/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007709void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007710 const RecordData &Record, unsigned &Idx) {
7711 unsigned NumDecls = Record[Idx++];
7712 Set.reserve(Context, NumDecls);
7713 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007714 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007715 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007716 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007717 }
7718}
7719
7720CXXBaseSpecifier
7721ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7722 const RecordData &Record, unsigned &Idx) {
7723 bool isVirtual = static_cast<bool>(Record[Idx++]);
7724 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7725 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7726 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7727 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7728 SourceRange Range = ReadSourceRange(F, Record, Idx);
7729 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7730 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7731 EllipsisLoc);
7732 Result.setInheritConstructors(inheritConstructors);
7733 return Result;
7734}
7735
Richard Smithc2bb8182015-03-24 06:36:48 +00007736CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007737ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7738 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007739 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007740 assert(NumInitializers && "wrote ctor initializers but have no inits");
7741 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7742 for (unsigned i = 0; i != NumInitializers; ++i) {
7743 TypeSourceInfo *TInfo = nullptr;
7744 bool IsBaseVirtual = false;
7745 FieldDecl *Member = nullptr;
7746 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007747
Richard Smithc2bb8182015-03-24 06:36:48 +00007748 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7749 switch (Type) {
7750 case CTOR_INITIALIZER_BASE:
7751 TInfo = GetTypeSourceInfo(F, Record, Idx);
7752 IsBaseVirtual = Record[Idx++];
7753 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007754
Richard Smithc2bb8182015-03-24 06:36:48 +00007755 case CTOR_INITIALIZER_DELEGATING:
7756 TInfo = GetTypeSourceInfo(F, Record, Idx);
7757 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007758
Richard Smithc2bb8182015-03-24 06:36:48 +00007759 case CTOR_INITIALIZER_MEMBER:
7760 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7761 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007762
Richard Smithc2bb8182015-03-24 06:36:48 +00007763 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7764 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7765 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007766 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007767
7768 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7769 Expr *Init = ReadExpr(F);
7770 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7771 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7772 bool IsWritten = Record[Idx++];
7773 unsigned SourceOrderOrNumArrayIndices;
7774 SmallVector<VarDecl *, 8> Indices;
7775 if (IsWritten) {
7776 SourceOrderOrNumArrayIndices = Record[Idx++];
7777 } else {
7778 SourceOrderOrNumArrayIndices = Record[Idx++];
7779 Indices.reserve(SourceOrderOrNumArrayIndices);
7780 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7781 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7782 }
7783
7784 CXXCtorInitializer *BOMInit;
7785 if (Type == CTOR_INITIALIZER_BASE) {
7786 BOMInit = new (Context)
7787 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7788 RParenLoc, MemberOrEllipsisLoc);
7789 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7790 BOMInit = new (Context)
7791 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7792 } else if (IsWritten) {
7793 if (Member)
7794 BOMInit = new (Context) CXXCtorInitializer(
7795 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7796 else
7797 BOMInit = new (Context)
7798 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7799 LParenLoc, Init, RParenLoc);
7800 } else {
7801 if (IndirectMember) {
7802 assert(Indices.empty() && "Indirect field improperly initialized");
7803 BOMInit = new (Context)
7804 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7805 LParenLoc, Init, RParenLoc);
7806 } else {
7807 BOMInit = CXXCtorInitializer::Create(
7808 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7809 Indices.data(), Indices.size());
7810 }
7811 }
7812
7813 if (IsWritten)
7814 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7815 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007816 }
7817
Richard Smithc2bb8182015-03-24 06:36:48 +00007818 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007819}
7820
7821NestedNameSpecifier *
7822ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7823 const RecordData &Record, unsigned &Idx) {
7824 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007825 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007826 for (unsigned I = 0; I != N; ++I) {
7827 NestedNameSpecifier::SpecifierKind Kind
7828 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7829 switch (Kind) {
7830 case NestedNameSpecifier::Identifier: {
7831 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7832 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7833 break;
7834 }
7835
7836 case NestedNameSpecifier::Namespace: {
7837 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7838 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7839 break;
7840 }
7841
7842 case NestedNameSpecifier::NamespaceAlias: {
7843 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7844 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7845 break;
7846 }
7847
7848 case NestedNameSpecifier::TypeSpec:
7849 case NestedNameSpecifier::TypeSpecWithTemplate: {
7850 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7851 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007852 return nullptr;
7853
Guy Benyei11169dd2012-12-18 14:30:41 +00007854 bool Template = Record[Idx++];
7855 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7856 break;
7857 }
7858
7859 case NestedNameSpecifier::Global: {
7860 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7861 // No associated value, and there can't be a prefix.
7862 break;
7863 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007864
7865 case NestedNameSpecifier::Super: {
7866 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7867 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7868 break;
7869 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007870 }
7871 Prev = NNS;
7872 }
7873 return NNS;
7874}
7875
7876NestedNameSpecifierLoc
7877ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7878 unsigned &Idx) {
7879 unsigned N = Record[Idx++];
7880 NestedNameSpecifierLocBuilder Builder;
7881 for (unsigned I = 0; I != N; ++I) {
7882 NestedNameSpecifier::SpecifierKind Kind
7883 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7884 switch (Kind) {
7885 case NestedNameSpecifier::Identifier: {
7886 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7887 SourceRange Range = ReadSourceRange(F, Record, Idx);
7888 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7889 break;
7890 }
7891
7892 case NestedNameSpecifier::Namespace: {
7893 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7894 SourceRange Range = ReadSourceRange(F, Record, Idx);
7895 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7896 break;
7897 }
7898
7899 case NestedNameSpecifier::NamespaceAlias: {
7900 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7901 SourceRange Range = ReadSourceRange(F, Record, Idx);
7902 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7903 break;
7904 }
7905
7906 case NestedNameSpecifier::TypeSpec:
7907 case NestedNameSpecifier::TypeSpecWithTemplate: {
7908 bool Template = Record[Idx++];
7909 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7910 if (!T)
7911 return NestedNameSpecifierLoc();
7912 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7913
7914 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7915 Builder.Extend(Context,
7916 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7917 T->getTypeLoc(), ColonColonLoc);
7918 break;
7919 }
7920
7921 case NestedNameSpecifier::Global: {
7922 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7923 Builder.MakeGlobal(Context, ColonColonLoc);
7924 break;
7925 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007926
7927 case NestedNameSpecifier::Super: {
7928 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7929 SourceRange Range = ReadSourceRange(F, Record, Idx);
7930 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7931 break;
7932 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007933 }
7934 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007935
Guy Benyei11169dd2012-12-18 14:30:41 +00007936 return Builder.getWithLocInContext(Context);
7937}
7938
7939SourceRange
7940ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7941 unsigned &Idx) {
7942 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7943 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7944 return SourceRange(beg, end);
7945}
7946
7947/// \brief Read an integral value
7948llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7949 unsigned BitWidth = Record[Idx++];
7950 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7951 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7952 Idx += NumWords;
7953 return Result;
7954}
7955
7956/// \brief Read a signed integral value
7957llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7958 bool isUnsigned = Record[Idx++];
7959 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7960}
7961
7962/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007963llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7964 const llvm::fltSemantics &Sem,
7965 unsigned &Idx) {
7966 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007967}
7968
7969// \brief Read a string
7970std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7971 unsigned Len = Record[Idx++];
7972 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7973 Idx += Len;
7974 return Result;
7975}
7976
Richard Smith7ed1bc92014-12-05 22:42:13 +00007977std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7978 unsigned &Idx) {
7979 std::string Filename = ReadString(Record, Idx);
7980 ResolveImportedPath(F, Filename);
7981 return Filename;
7982}
7983
Guy Benyei11169dd2012-12-18 14:30:41 +00007984VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7985 unsigned &Idx) {
7986 unsigned Major = Record[Idx++];
7987 unsigned Minor = Record[Idx++];
7988 unsigned Subminor = Record[Idx++];
7989 if (Minor == 0)
7990 return VersionTuple(Major);
7991 if (Subminor == 0)
7992 return VersionTuple(Major, Minor - 1);
7993 return VersionTuple(Major, Minor - 1, Subminor - 1);
7994}
7995
7996CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7997 const RecordData &Record,
7998 unsigned &Idx) {
7999 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8000 return CXXTemporary::Create(Context, Decl);
8001}
8002
8003DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008004 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008005}
8006
8007DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8008 return Diags.Report(Loc, DiagID);
8009}
8010
8011/// \brief Retrieve the identifier table associated with the
8012/// preprocessor.
8013IdentifierTable &ASTReader::getIdentifierTable() {
8014 return PP.getIdentifierTable();
8015}
8016
8017/// \brief Record that the given ID maps to the given switch-case
8018/// statement.
8019void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008020 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008021 "Already have a SwitchCase with this ID");
8022 (*CurrSwitchCaseStmts)[ID] = SC;
8023}
8024
8025/// \brief Retrieve the switch-case statement with the given ID.
8026SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008027 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008028 return (*CurrSwitchCaseStmts)[ID];
8029}
8030
8031void ASTReader::ClearSwitchCaseIDs() {
8032 CurrSwitchCaseStmts->clear();
8033}
8034
8035void ASTReader::ReadComments() {
8036 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008037 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008038 serialization::ModuleFile *> >::iterator
8039 I = CommentsCursors.begin(),
8040 E = CommentsCursors.end();
8041 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008042 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008043 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008044 serialization::ModuleFile &F = *I->second;
8045 SavedStreamPosition SavedPosition(Cursor);
8046
8047 RecordData Record;
8048 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008049 llvm::BitstreamEntry Entry =
8050 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008051
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008052 switch (Entry.Kind) {
8053 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8054 case llvm::BitstreamEntry::Error:
8055 Error("malformed block record in AST file");
8056 return;
8057 case llvm::BitstreamEntry::EndBlock:
8058 goto NextCursor;
8059 case llvm::BitstreamEntry::Record:
8060 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008061 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008062 }
8063
8064 // Read a record.
8065 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008066 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008067 case COMMENTS_RAW_COMMENT: {
8068 unsigned Idx = 0;
8069 SourceRange SR = ReadSourceRange(F, Record, Idx);
8070 RawComment::CommentKind Kind =
8071 (RawComment::CommentKind) Record[Idx++];
8072 bool IsTrailingComment = Record[Idx++];
8073 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008074 Comments.push_back(new (Context) RawComment(
8075 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8076 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008077 break;
8078 }
8079 }
8080 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008081 NextCursor:
8082 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008083 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008084}
8085
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008086void ASTReader::getInputFiles(ModuleFile &F,
8087 SmallVectorImpl<serialization::InputFile> &Files) {
8088 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8089 unsigned ID = I+1;
8090 Files.push_back(getInputFile(F, ID));
8091 }
8092}
8093
Richard Smithcd45dbc2014-04-19 03:48:30 +00008094std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8095 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008096 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008097 return M->getFullModuleName();
8098
8099 // Otherwise, use the name of the top-level module the decl is within.
8100 if (ModuleFile *M = getOwningModuleFile(D))
8101 return M->ModuleName;
8102
8103 // Not from a module.
8104 return "";
8105}
8106
Guy Benyei11169dd2012-12-18 14:30:41 +00008107void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008108 while (!PendingIdentifierInfos.empty() ||
8109 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008110 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008111 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008112 // If any identifiers with corresponding top-level declarations have
8113 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008114 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8115 TopLevelDeclsMap;
8116 TopLevelDeclsMap TopLevelDecls;
8117
Guy Benyei11169dd2012-12-18 14:30:41 +00008118 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008119 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008120 SmallVector<uint32_t, 4> DeclIDs =
8121 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008122 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008123
8124 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008125 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008126
Richard Smith851072e2014-05-19 20:59:20 +00008127 // For each decl chain that we wanted to complete while deserializing, mark
8128 // it as "still needs to be completed".
8129 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8130 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8131 }
8132 PendingIncompleteDeclChains.clear();
8133
Guy Benyei11169dd2012-12-18 14:30:41 +00008134 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008135 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008136 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008137 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008138 }
8139 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008140 PendingDeclChains.clear();
8141
Richard Smith9b88a4c2015-07-27 05:40:23 +00008142 assert(RedeclsDeserialized.empty() && "some redecls not wired up");
8143
Douglas Gregor6168bd22013-02-18 15:53:43 +00008144 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008145 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8146 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008147 IdentifierInfo *II = TLD->first;
8148 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008149 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008150 }
8151 }
8152
Guy Benyei11169dd2012-12-18 14:30:41 +00008153 // Load any pending macro definitions.
8154 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008155 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8156 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8157 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8158 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008159 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008160 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008161 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008162 if (Info.M->Kind != MK_ImplicitModule &&
8163 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008164 resolvePendingMacro(II, Info);
8165 }
8166 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008167 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008168 ++IDIdx) {
8169 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008170 if (Info.M->Kind == MK_ImplicitModule ||
8171 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008172 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008173 }
8174 }
8175 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008176
8177 // Wire up the DeclContexts for Decls that we delayed setting until
8178 // recursive loading is completed.
8179 while (!PendingDeclContextInfos.empty()) {
8180 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8181 PendingDeclContextInfos.pop_front();
8182 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8183 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8184 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8185 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008186
Richard Smithd1c46742014-04-30 02:24:17 +00008187 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008188 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008189 auto Update = PendingUpdateRecords.pop_back_val();
8190 ReadingKindTracker ReadingKind(Read_Decl, *this);
8191 loadDeclUpdateRecords(Update.first, Update.second);
8192 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008193 }
Richard Smith8a639892015-01-24 01:07:20 +00008194
8195 // At this point, all update records for loaded decls are in place, so any
8196 // fake class definitions should have become real.
8197 assert(PendingFakeDefinitionData.empty() &&
8198 "faked up a class definition but never saw the real one");
8199
Guy Benyei11169dd2012-12-18 14:30:41 +00008200 // If we deserialized any C++ or Objective-C class definitions, any
8201 // Objective-C protocol definitions, or any redeclarable templates, make sure
8202 // that all redeclarations point to the definitions. Note that this can only
8203 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008204 for (Decl *D : PendingDefinitions) {
8205 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008206 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008207 // Make sure that the TagType points at the definition.
8208 const_cast<TagType*>(TagT)->decl = TD;
8209 }
Richard Smith8ce51082015-03-11 01:44:51 +00008210
Craig Topperc6914d02014-08-25 04:15:02 +00008211 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008212 for (auto *R = getMostRecentExistingDecl(RD); R;
8213 R = R->getPreviousDecl()) {
8214 assert((R == D) ==
8215 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008216 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008217 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008218 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008219 }
8220
8221 continue;
8222 }
Richard Smith8ce51082015-03-11 01:44:51 +00008223
Craig Topperc6914d02014-08-25 04:15:02 +00008224 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008225 // Make sure that the ObjCInterfaceType points at the definition.
8226 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8227 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008228
8229 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8230 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8231
Guy Benyei11169dd2012-12-18 14:30:41 +00008232 continue;
8233 }
Richard Smith8ce51082015-03-11 01:44:51 +00008234
Craig Topperc6914d02014-08-25 04:15:02 +00008235 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008236 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8237 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8238
Guy Benyei11169dd2012-12-18 14:30:41 +00008239 continue;
8240 }
Richard Smith8ce51082015-03-11 01:44:51 +00008241
Craig Topperc6914d02014-08-25 04:15:02 +00008242 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008243 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8244 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008245 }
8246 PendingDefinitions.clear();
8247
8248 // Load the bodies of any functions or methods we've encountered. We do
8249 // this now (delayed) so that we can be sure that the declaration chains
8250 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008251 // FIXME: There seems to be no point in delaying this, it does not depend
8252 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008253 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8254 PBEnd = PendingBodies.end();
8255 PB != PBEnd; ++PB) {
8256 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8257 // FIXME: Check for =delete/=default?
8258 // FIXME: Complain about ODR violations here?
8259 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8260 FD->setLazyBody(PB->second);
8261 continue;
8262 }
8263
8264 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8265 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8266 MD->setLazyBody(PB->second);
8267 }
8268 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008269
8270 // Do some cleanup.
8271 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8272 getContext().deduplicateMergedDefinitonsFor(ND);
8273 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008274}
8275
8276void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008277 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8278 return;
8279
Richard Smitha0ce9c42014-07-29 23:23:27 +00008280 // Trigger the import of the full definition of each class that had any
8281 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008282 // These updates may in turn find and diagnose some ODR failures, so take
8283 // ownership of the set first.
8284 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8285 PendingOdrMergeFailures.clear();
8286 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008287 Merge.first->buildLookup();
8288 Merge.first->decls_begin();
8289 Merge.first->bases_begin();
8290 Merge.first->vbases_begin();
8291 for (auto *RD : Merge.second) {
8292 RD->decls_begin();
8293 RD->bases_begin();
8294 RD->vbases_begin();
8295 }
8296 }
8297
8298 // For each declaration from a merged context, check that the canonical
8299 // definition of that context also contains a declaration of the same
8300 // entity.
8301 //
8302 // Caution: this loop does things that might invalidate iterators into
8303 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8304 while (!PendingOdrMergeChecks.empty()) {
8305 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8306
8307 // FIXME: Skip over implicit declarations for now. This matters for things
8308 // like implicitly-declared special member functions. This isn't entirely
8309 // correct; we can end up with multiple unmerged declarations of the same
8310 // implicit entity.
8311 if (D->isImplicit())
8312 continue;
8313
8314 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008315
8316 bool Found = false;
8317 const Decl *DCanon = D->getCanonicalDecl();
8318
Richard Smith01bdb7a2014-08-28 05:44:07 +00008319 for (auto RI : D->redecls()) {
8320 if (RI->getLexicalDeclContext() == CanonDef) {
8321 Found = true;
8322 break;
8323 }
8324 }
8325 if (Found)
8326 continue;
8327
Richard Smitha0ce9c42014-07-29 23:23:27 +00008328 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008329 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008330 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8331 !Found && I != E; ++I) {
8332 for (auto RI : (*I)->redecls()) {
8333 if (RI->getLexicalDeclContext() == CanonDef) {
8334 // This declaration is present in the canonical definition. If it's
8335 // in the same redecl chain, it's the one we're looking for.
8336 if (RI->getCanonicalDecl() == DCanon)
8337 Found = true;
8338 else
8339 Candidates.push_back(cast<NamedDecl>(RI));
8340 break;
8341 }
8342 }
8343 }
8344
8345 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008346 // The AST doesn't like TagDecls becoming invalid after they've been
8347 // completed. We only really need to mark FieldDecls as invalid here.
8348 if (!isa<TagDecl>(D))
8349 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008350
8351 // Ensure we don't accidentally recursively enter deserialization while
8352 // we're producing our diagnostic.
8353 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008354
8355 std::string CanonDefModule =
8356 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8357 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8358 << D << getOwningModuleNameForDiagnostic(D)
8359 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8360
8361 if (Candidates.empty())
8362 Diag(cast<Decl>(CanonDef)->getLocation(),
8363 diag::note_module_odr_violation_no_possible_decls) << D;
8364 else {
8365 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8366 Diag(Candidates[I]->getLocation(),
8367 diag::note_module_odr_violation_possible_decl)
8368 << Candidates[I];
8369 }
8370
8371 DiagnosedOdrMergeFailures.insert(CanonDef);
8372 }
8373 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008374
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008375 if (OdrMergeFailures.empty())
8376 return;
8377
8378 // Ensure we don't accidentally recursively enter deserialization while
8379 // we're producing our diagnostics.
8380 Deserializing RecursionGuard(this);
8381
Richard Smithcd45dbc2014-04-19 03:48:30 +00008382 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008383 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008384 // If we've already pointed out a specific problem with this class, don't
8385 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008386 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008387 continue;
8388
8389 bool Diagnosed = false;
8390 for (auto *RD : Merge.second) {
8391 // Multiple different declarations got merged together; tell the user
8392 // where they came from.
8393 if (Merge.first != RD) {
8394 // FIXME: Walk the definition, figure out what's different,
8395 // and diagnose that.
8396 if (!Diagnosed) {
8397 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8398 Diag(Merge.first->getLocation(),
8399 diag::err_module_odr_violation_different_definitions)
8400 << Merge.first << Module.empty() << Module;
8401 Diagnosed = true;
8402 }
8403
8404 Diag(RD->getLocation(),
8405 diag::note_module_odr_violation_different_definitions)
8406 << getOwningModuleNameForDiagnostic(RD);
8407 }
8408 }
8409
8410 if (!Diagnosed) {
8411 // All definitions are updates to the same declaration. This happens if a
8412 // module instantiates the declaration of a class template specialization
8413 // and two or more other modules instantiate its definition.
8414 //
8415 // FIXME: Indicate which modules had instantiations of this definition.
8416 // FIXME: How can this even happen?
8417 Diag(Merge.first->getLocation(),
8418 diag::err_module_odr_violation_different_instantiations)
8419 << Merge.first;
8420 }
8421 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008422}
8423
Richard Smithce18a182015-07-14 00:26:00 +00008424void ASTReader::StartedDeserializing() {
8425 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8426 ReadTimer->startTimer();
8427}
8428
Guy Benyei11169dd2012-12-18 14:30:41 +00008429void ASTReader::FinishedDeserializing() {
8430 assert(NumCurrentElementsDeserializing &&
8431 "FinishedDeserializing not paired with StartedDeserializing");
8432 if (NumCurrentElementsDeserializing == 1) {
8433 // We decrease NumCurrentElementsDeserializing only after pending actions
8434 // are finished, to avoid recursively re-calling finishPendingActions().
8435 finishPendingActions();
8436 }
8437 --NumCurrentElementsDeserializing;
8438
Richard Smitha0ce9c42014-07-29 23:23:27 +00008439 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008440 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008441 while (!PendingExceptionSpecUpdates.empty()) {
8442 auto Updates = std::move(PendingExceptionSpecUpdates);
8443 PendingExceptionSpecUpdates.clear();
8444 for (auto Update : Updates) {
8445 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8446 SemaObj->UpdateExceptionSpec(Update.second,
8447 FPT->getExtProtoInfo().ExceptionSpec);
8448 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008449 }
8450
Richard Smitha0ce9c42014-07-29 23:23:27 +00008451 diagnoseOdrViolations();
8452
Richard Smithce18a182015-07-14 00:26:00 +00008453 if (ReadTimer)
8454 ReadTimer->stopTimer();
8455
Richard Smith04d05b52014-03-23 00:27:18 +00008456 // We are not in recursive loading, so it's safe to pass the "interesting"
8457 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008458 if (Consumer)
8459 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008460 }
8461}
8462
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008463void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008464 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8465 // Remove any fake results before adding any real ones.
8466 auto It = PendingFakeLookupResults.find(II);
8467 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008468 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008469 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008470 // FIXME: this works around module+PCH performance issue.
8471 // Rather than erase the result from the map, which is O(n), just clear
8472 // the vector of NamedDecls.
8473 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008474 }
8475 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008476
8477 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8478 SemaObj->TUScope->AddDecl(D);
8479 } else if (SemaObj->TUScope) {
8480 // Adding the decl to IdResolver may have failed because it was already in
8481 // (even though it was not added in scope). If it is already in, make sure
8482 // it gets in the scope as well.
8483 if (std::find(SemaObj->IdResolver.begin(Name),
8484 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8485 SemaObj->TUScope->AddDecl(D);
8486 }
8487}
8488
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008489ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008490 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008491 StringRef isysroot, bool DisableValidation,
8492 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008493 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Richard Smithce18a182015-07-14 00:26:00 +00008494 bool UseGlobalIndex,
8495 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008496 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008497 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008498 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008499 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008500 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008501 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008502 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008503 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8504 AllowConfigurationMismatch(AllowConfigurationMismatch),
8505 ValidateSystemInputs(ValidateSystemInputs),
8506 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008507 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8508 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8509 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8510 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008511 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8512 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8513 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8514 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8515 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8516 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008517 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008518 SourceMgr.setExternalSLocEntrySource(this);
8519}
8520
8521ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008522 if (OwnsDeserializationListener)
8523 delete DeserializationListener;
8524
Guy Benyei11169dd2012-12-18 14:30:41 +00008525 for (DeclContextVisibleUpdatesPending::iterator
8526 I = PendingVisibleUpdates.begin(),
8527 E = PendingVisibleUpdates.end();
8528 I != E; ++I) {
8529 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8530 F = I->second.end();
8531 J != F; ++J)
8532 delete J->first;
8533 }
8534}