blob: e950bdf40fa8058e5521f349e495af8fb84c1183 [file] [log] [blame]
Richard Smith9e2341d2015-03-23 03:25:59 +00001//===-- ASTReader.cpp - AST File Reader ----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
Adrian Prantlbb165fb2015-06-20 18:53:08 +000022#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000023#include "clang/AST/NestedNameSpecifier.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000026#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/SourceManagerInternals.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Basic/TargetOptions.h"
32#include "clang/Basic/Version.h"
33#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000034#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/HeaderSearchOptions.h"
37#include "clang/Lex/MacroInfo.h"
38#include "clang/Lex/PreprocessingRecord.h"
39#include "clang/Lex/Preprocessor.h"
40#include "clang/Lex/PreprocessorOptions.h"
41#include "clang/Sema/Scope.h"
42#include "clang/Sema/Sema.h"
43#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000044#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000045#include "clang/Serialization/ModuleManager.h"
46#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000047#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "llvm/ADT/StringExtras.h"
49#include "llvm/Bitcode/BitstreamReader.h"
50#include "llvm/Support/ErrorHandling.h"
51#include "llvm/Support/FileSystem.h"
52#include "llvm/Support/MemoryBuffer.h"
53#include "llvm/Support/Path.h"
54#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000055#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000056#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000057#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000058#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000059#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000060
61using namespace clang;
62using namespace clang::serialization;
63using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000064using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000065
Ben Langmuircb69b572014-03-07 06:40:32 +000066
67//===----------------------------------------------------------------------===//
68// ChainedASTReaderListener implementation
69//===----------------------------------------------------------------------===//
70
71bool
72ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
73 return First->ReadFullVersionInformation(FullVersion) ||
74 Second->ReadFullVersionInformation(FullVersion);
75}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000076void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
77 First->ReadModuleName(ModuleName);
78 Second->ReadModuleName(ModuleName);
79}
80void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
81 First->ReadModuleMapFile(ModuleMapPath);
82 Second->ReadModuleMapFile(ModuleMapPath);
83}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000084bool
85ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
86 bool Complain,
87 bool AllowCompatibleDifferences) {
88 return First->ReadLanguageOptions(LangOpts, Complain,
89 AllowCompatibleDifferences) ||
90 Second->ReadLanguageOptions(LangOpts, Complain,
91 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000092}
Chandler Carruth0d745bc2015-03-14 04:47:43 +000093bool ChainedASTReaderListener::ReadTargetOptions(
94 const TargetOptions &TargetOpts, bool Complain,
95 bool AllowCompatibleDifferences) {
96 return First->ReadTargetOptions(TargetOpts, Complain,
97 AllowCompatibleDifferences) ||
98 Second->ReadTargetOptions(TargetOpts, Complain,
99 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000100}
101bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000102 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000103 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
104 Second->ReadDiagnosticOptions(DiagOpts, Complain);
105}
106bool
107ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
108 bool Complain) {
109 return First->ReadFileSystemOptions(FSOpts, Complain) ||
110 Second->ReadFileSystemOptions(FSOpts, Complain);
111}
112
113bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000114 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
115 bool Complain) {
116 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
117 Complain) ||
118 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
119 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000120}
121bool ChainedASTReaderListener::ReadPreprocessorOptions(
122 const PreprocessorOptions &PPOpts, bool Complain,
123 std::string &SuggestedPredefines) {
124 return First->ReadPreprocessorOptions(PPOpts, Complain,
125 SuggestedPredefines) ||
126 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
127}
128void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
129 unsigned Value) {
130 First->ReadCounter(M, Value);
131 Second->ReadCounter(M, Value);
132}
133bool ChainedASTReaderListener::needsInputFileVisitation() {
134 return First->needsInputFileVisitation() ||
135 Second->needsInputFileVisitation();
136}
137bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
138 return First->needsSystemInputFileVisitation() ||
139 Second->needsSystemInputFileVisitation();
140}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000141void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
142 First->visitModuleFile(Filename);
143 Second->visitModuleFile(Filename);
144}
Ben Langmuircb69b572014-03-07 06:40:32 +0000145bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000146 bool isSystem,
147 bool isOverridden) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000148 bool Continue = false;
149 if (First->needsInputFileVisitation() &&
150 (!isSystem || First->needsSystemInputFileVisitation()))
151 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
152 if (Second->needsInputFileVisitation() &&
153 (!isSystem || Second->needsSystemInputFileVisitation()))
154 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
155 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000156}
157
Guy Benyei11169dd2012-12-18 14:30:41 +0000158//===----------------------------------------------------------------------===//
159// PCH validator implementation
160//===----------------------------------------------------------------------===//
161
162ASTReaderListener::~ASTReaderListener() {}
163
164/// \brief Compare the given set of language options against an existing set of
165/// language options.
166///
167/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000168/// \param AllowCompatibleDifferences If true, differences between compatible
169/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000170///
171/// \returns true if the languagae options mis-match, false otherwise.
172static bool checkLanguageOptions(const LangOptions &LangOpts,
173 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000174 DiagnosticsEngine *Diags,
175 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000176#define LANGOPT(Name, Bits, Default, Description) \
177 if (ExistingLangOpts.Name != LangOpts.Name) { \
178 if (Diags) \
179 Diags->Report(diag::err_pch_langopt_mismatch) \
180 << Description << LangOpts.Name << ExistingLangOpts.Name; \
181 return true; \
182 }
183
184#define VALUE_LANGOPT(Name, Bits, Default, Description) \
185 if (ExistingLangOpts.Name != LangOpts.Name) { \
186 if (Diags) \
187 Diags->Report(diag::err_pch_langopt_value_mismatch) \
188 << Description; \
189 return true; \
190 }
191
192#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
193 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
194 if (Diags) \
195 Diags->Report(diag::err_pch_langopt_value_mismatch) \
196 << Description; \
197 return true; \
198 }
199
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000200#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
201 if (!AllowCompatibleDifferences) \
202 LANGOPT(Name, Bits, Default, Description)
203
204#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
205 if (!AllowCompatibleDifferences) \
206 ENUM_LANGOPT(Name, Bits, Default, Description)
207
Guy Benyei11169dd2012-12-18 14:30:41 +0000208#define BENIGN_LANGOPT(Name, Bits, Default, Description)
209#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
210#include "clang/Basic/LangOptions.def"
211
Ben Langmuircd98cb72015-06-23 18:20:18 +0000212 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
213 if (Diags)
214 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
215 return true;
216 }
217
Guy Benyei11169dd2012-12-18 14:30:41 +0000218 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
219 if (Diags)
220 Diags->Report(diag::err_pch_langopt_value_mismatch)
221 << "target Objective-C runtime";
222 return true;
223 }
224
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000225 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
226 LangOpts.CommentOpts.BlockCommandNames) {
227 if (Diags)
228 Diags->Report(diag::err_pch_langopt_value_mismatch)
229 << "block command names";
230 return true;
231 }
232
Guy Benyei11169dd2012-12-18 14:30:41 +0000233 return false;
234}
235
236/// \brief Compare the given set of target options against an existing set of
237/// target options.
238///
239/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
240///
241/// \returns true if the target options mis-match, false otherwise.
242static bool checkTargetOptions(const TargetOptions &TargetOpts,
243 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000244 DiagnosticsEngine *Diags,
245 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000246#define CHECK_TARGET_OPT(Field, Name) \
247 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
248 if (Diags) \
249 Diags->Report(diag::err_pch_targetopt_mismatch) \
250 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
251 return true; \
252 }
253
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000254 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000255 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000256 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000257
258 // We can tolerate different CPUs in many cases, notably when one CPU
259 // supports a strict superset of another. When allowing compatible
260 // differences skip this check.
261 if (!AllowCompatibleDifferences)
262 CHECK_TARGET_OPT(CPU, "target CPU");
263
Guy Benyei11169dd2012-12-18 14:30:41 +0000264#undef CHECK_TARGET_OPT
265
266 // Compare feature sets.
267 SmallVector<StringRef, 4> ExistingFeatures(
268 ExistingTargetOpts.FeaturesAsWritten.begin(),
269 ExistingTargetOpts.FeaturesAsWritten.end());
270 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
271 TargetOpts.FeaturesAsWritten.end());
272 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
273 std::sort(ReadFeatures.begin(), ReadFeatures.end());
274
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000275 // We compute the set difference in both directions explicitly so that we can
276 // diagnose the differences differently.
277 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
278 std::set_difference(
279 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
280 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
281 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
282 ExistingFeatures.begin(), ExistingFeatures.end(),
283 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000284
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000285 // If we are allowing compatible differences and the read feature set is
286 // a strict subset of the existing feature set, there is nothing to diagnose.
287 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
288 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000289
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000290 if (Diags) {
291 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000292 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000293 << /* is-existing-feature */ false << Feature;
294 for (StringRef Feature : UnmatchedExistingFeatures)
295 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
296 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000297 }
298
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000299 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000300}
301
302bool
303PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000304 bool Complain,
305 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000306 const LangOptions &ExistingLangOpts = PP.getLangOpts();
307 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000308 Complain ? &Reader.Diags : nullptr,
309 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000310}
311
312bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000313 bool Complain,
314 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000315 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
316 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000317 Complain ? &Reader.Diags : nullptr,
318 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000319}
320
321namespace {
322 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
323 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000324 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
325 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000326}
327
Ben Langmuirb92de022014-04-29 16:25:26 +0000328static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
329 DiagnosticsEngine &Diags,
330 bool Complain) {
331 typedef DiagnosticsEngine::Level Level;
332
333 // Check current mappings for new -Werror mappings, and the stored mappings
334 // for cases that were explicitly mapped to *not* be errors that are now
335 // errors because of options like -Werror.
336 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
337
338 for (DiagnosticsEngine *MappingSource : MappingSources) {
339 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
340 diag::kind DiagID = DiagIDMappingPair.first;
341 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
342 if (CurLevel < DiagnosticsEngine::Error)
343 continue; // not significant
344 Level StoredLevel =
345 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
346 if (StoredLevel < DiagnosticsEngine::Error) {
347 if (Complain)
348 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
349 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
350 return true;
351 }
352 }
353 }
354
355 return false;
356}
357
Alp Tokerac4e8e52014-06-22 21:58:33 +0000358static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
359 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
360 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
361 return true;
362 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000363}
364
365static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
366 DiagnosticsEngine &Diags,
367 bool IsSystem, bool Complain) {
368 // Top-level options
369 if (IsSystem) {
370 if (Diags.getSuppressSystemWarnings())
371 return false;
372 // If -Wsystem-headers was not enabled before, be conservative
373 if (StoredDiags.getSuppressSystemWarnings()) {
374 if (Complain)
375 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
376 return true;
377 }
378 }
379
380 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
381 if (Complain)
382 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
383 return true;
384 }
385
386 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
387 !StoredDiags.getEnableAllWarnings()) {
388 if (Complain)
389 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
390 return true;
391 }
392
393 if (isExtHandlingFromDiagsError(Diags) &&
394 !isExtHandlingFromDiagsError(StoredDiags)) {
395 if (Complain)
396 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
397 return true;
398 }
399
400 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
401}
402
403bool PCHValidator::ReadDiagnosticOptions(
404 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
405 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
406 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
407 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000408 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000409 // This should never fail, because we would have processed these options
410 // before writing them to an ASTFile.
411 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
412
413 ModuleManager &ModuleMgr = Reader.getModuleManager();
414 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
415
416 // If the original import came from a file explicitly generated by the user,
417 // don't check the diagnostic mappings.
418 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000419 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000420 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
421 // the transitive closure of its imports, since unrelated modules cannot be
422 // imported until after this module finishes validation.
423 ModuleFile *TopImport = *ModuleMgr.rbegin();
424 while (!TopImport->ImportedBy.empty())
425 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000426 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000427 return false;
428
429 StringRef ModuleName = TopImport->ModuleName;
430 assert(!ModuleName.empty() && "diagnostic options read before module name");
431
432 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
433 assert(M && "missing module");
434
435 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
436 // contains the union of their flags.
437 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
438}
439
Guy Benyei11169dd2012-12-18 14:30:41 +0000440/// \brief Collect the macro definitions provided by the given preprocessor
441/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000442static void
443collectMacroDefinitions(const PreprocessorOptions &PPOpts,
444 MacroDefinitionsMap &Macros,
445 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000446 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
447 StringRef Macro = PPOpts.Macros[I].first;
448 bool IsUndef = PPOpts.Macros[I].second;
449
450 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
451 StringRef MacroName = MacroPair.first;
452 StringRef MacroBody = MacroPair.second;
453
454 // For an #undef'd macro, we only care about the name.
455 if (IsUndef) {
456 if (MacroNames && !Macros.count(MacroName))
457 MacroNames->push_back(MacroName);
458
459 Macros[MacroName] = std::make_pair("", true);
460 continue;
461 }
462
463 // For a #define'd macro, figure out the actual definition.
464 if (MacroName.size() == Macro.size())
465 MacroBody = "1";
466 else {
467 // Note: GCC drops anything following an end-of-line character.
468 StringRef::size_type End = MacroBody.find_first_of("\n\r");
469 MacroBody = MacroBody.substr(0, End);
470 }
471
472 if (MacroNames && !Macros.count(MacroName))
473 MacroNames->push_back(MacroName);
474 Macros[MacroName] = std::make_pair(MacroBody, false);
475 }
476}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000477
Guy Benyei11169dd2012-12-18 14:30:41 +0000478/// \brief Check the preprocessor options deserialized from the control block
479/// against the preprocessor options in an existing preprocessor.
480///
481/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
482static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
483 const PreprocessorOptions &ExistingPPOpts,
484 DiagnosticsEngine *Diags,
485 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000486 std::string &SuggestedPredefines,
487 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000488 // Check macro definitions.
489 MacroDefinitionsMap ASTFileMacros;
490 collectMacroDefinitions(PPOpts, ASTFileMacros);
491 MacroDefinitionsMap ExistingMacros;
492 SmallVector<StringRef, 4> ExistingMacroNames;
493 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
494
495 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
496 // Dig out the macro definition in the existing preprocessor options.
497 StringRef MacroName = ExistingMacroNames[I];
498 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
499
500 // Check whether we know anything about this macro name or not.
501 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
502 = ASTFileMacros.find(MacroName);
503 if (Known == ASTFileMacros.end()) {
504 // FIXME: Check whether this identifier was referenced anywhere in the
505 // AST file. If so, we should reject the AST file. Unfortunately, this
506 // information isn't in the control block. What shall we do about it?
507
508 if (Existing.second) {
509 SuggestedPredefines += "#undef ";
510 SuggestedPredefines += MacroName.str();
511 SuggestedPredefines += '\n';
512 } else {
513 SuggestedPredefines += "#define ";
514 SuggestedPredefines += MacroName.str();
515 SuggestedPredefines += ' ';
516 SuggestedPredefines += Existing.first.str();
517 SuggestedPredefines += '\n';
518 }
519 continue;
520 }
521
522 // If the macro was defined in one but undef'd in the other, we have a
523 // conflict.
524 if (Existing.second != Known->second.second) {
525 if (Diags) {
526 Diags->Report(diag::err_pch_macro_def_undef)
527 << MacroName << Known->second.second;
528 }
529 return true;
530 }
531
532 // If the macro was #undef'd in both, or if the macro bodies are identical,
533 // it's fine.
534 if (Existing.second || Existing.first == Known->second.first)
535 continue;
536
537 // The macro bodies differ; complain.
538 if (Diags) {
539 Diags->Report(diag::err_pch_macro_def_conflict)
540 << MacroName << Known->second.first << Existing.first;
541 }
542 return true;
543 }
544
545 // Check whether we're using predefines.
546 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
547 if (Diags) {
548 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
549 }
550 return true;
551 }
552
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000553 // Detailed record is important since it is used for the module cache hash.
554 if (LangOpts.Modules &&
555 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
556 if (Diags) {
557 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
558 }
559 return true;
560 }
561
Guy Benyei11169dd2012-12-18 14:30:41 +0000562 // Compute the #include and #include_macros lines we need.
563 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
564 StringRef File = ExistingPPOpts.Includes[I];
565 if (File == ExistingPPOpts.ImplicitPCHInclude)
566 continue;
567
568 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
569 != PPOpts.Includes.end())
570 continue;
571
572 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000573 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000574 SuggestedPredefines += "\"\n";
575 }
576
577 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
578 StringRef File = ExistingPPOpts.MacroIncludes[I];
579 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
580 File)
581 != PPOpts.MacroIncludes.end())
582 continue;
583
584 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000585 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000586 SuggestedPredefines += "\"\n##\n";
587 }
588
589 return false;
590}
591
592bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
593 bool Complain,
594 std::string &SuggestedPredefines) {
595 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
596
597 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000598 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000599 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000600 SuggestedPredefines,
601 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000602}
603
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000604/// Check the header search options deserialized from the control block
605/// against the header search options in an existing preprocessor.
606///
607/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
608static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
609 StringRef SpecificModuleCachePath,
610 StringRef ExistingModuleCachePath,
611 DiagnosticsEngine *Diags,
612 const LangOptions &LangOpts) {
613 if (LangOpts.Modules) {
614 if (SpecificModuleCachePath != ExistingModuleCachePath) {
615 if (Diags)
616 Diags->Report(diag::err_pch_modulecache_mismatch)
617 << SpecificModuleCachePath << ExistingModuleCachePath;
618 return true;
619 }
620 }
621
622 return false;
623}
624
625bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
626 StringRef SpecificModuleCachePath,
627 bool Complain) {
628 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
629 PP.getHeaderSearchInfo().getModuleCachePath(),
630 Complain ? &Reader.Diags : nullptr,
631 PP.getLangOpts());
632}
633
Guy Benyei11169dd2012-12-18 14:30:41 +0000634void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
635 PP.setCounterValue(Value);
636}
637
638//===----------------------------------------------------------------------===//
639// AST reader implementation
640//===----------------------------------------------------------------------===//
641
Nico Weber824285e2014-05-08 04:26:47 +0000642void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
643 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000644 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000645 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000646}
647
648
649
650unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
651 return serialization::ComputeHash(Sel);
652}
653
654
655std::pair<unsigned, unsigned>
656ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000657 using namespace llvm::support;
658 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
659 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000660 return std::make_pair(KeyLen, DataLen);
661}
662
663ASTSelectorLookupTrait::internal_key_type
664ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000665 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000666 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000667 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
668 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
669 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000670 if (N == 0)
671 return SelTable.getNullarySelector(FirstII);
672 else if (N == 1)
673 return SelTable.getUnarySelector(FirstII);
674
675 SmallVector<IdentifierInfo *, 16> Args;
676 Args.push_back(FirstII);
677 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000678 Args.push_back(Reader.getLocalIdentifier(
679 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000680
681 return SelTable.getSelector(N, Args.data());
682}
683
684ASTSelectorLookupTrait::data_type
685ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
686 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000687 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000688
689 data_type Result;
690
Justin Bogner57ba0b22014-03-28 22:03:24 +0000691 Result.ID = Reader.getGlobalSelectorID(
692 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000693 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
694 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
695 Result.InstanceBits = FullInstanceBits & 0x3;
696 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
697 Result.FactoryBits = FullFactoryBits & 0x3;
698 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
699 unsigned NumInstanceMethods = FullInstanceBits >> 3;
700 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000701
702 // Load instance methods
703 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000704 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
705 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000706 Result.Instance.push_back(Method);
707 }
708
709 // Load factory methods
710 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000711 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
712 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000713 Result.Factory.push_back(Method);
714 }
715
716 return Result;
717}
718
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000719unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
720 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000721}
722
723std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000724ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000725 using namespace llvm::support;
726 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
727 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000728 return std::make_pair(KeyLen, DataLen);
729}
730
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000731ASTIdentifierLookupTraitBase::internal_key_type
732ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000733 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000734 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000735}
736
Douglas Gregordcf25082013-02-11 18:16:18 +0000737/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000738static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
739 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000740 return II.hadMacroDefinition() ||
741 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000742 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000743 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000744 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
745 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000746}
747
Richard Smith76c2f2c2015-07-17 20:09:43 +0000748static bool readBit(unsigned &Bits) {
749 bool Value = Bits & 0x1;
750 Bits >>= 1;
751 return Value;
752}
753
Guy Benyei11169dd2012-12-18 14:30:41 +0000754IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
755 const unsigned char* d,
756 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000757 using namespace llvm::support;
758 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000759 bool IsInteresting = RawID & 0x01;
760
761 // Wipe out the "is interesting" bit.
762 RawID = RawID >> 1;
763
Richard Smith76c2f2c2015-07-17 20:09:43 +0000764 // Build the IdentifierInfo and link the identifier ID with it.
765 IdentifierInfo *II = KnownII;
766 if (!II) {
767 II = &Reader.getIdentifierTable().getOwn(k);
768 KnownII = II;
769 }
770 if (!II->isFromAST()) {
771 II->setIsFromAST();
Richard Smitha534a312015-07-21 23:54:07 +0000772 if (isInterestingIdentifier(Reader, *II, F.isModule()))
Richard Smith76c2f2c2015-07-17 20:09:43 +0000773 II->setChangedSinceDeserialization();
774 }
775 Reader.markIdentifierUpToDate(II);
776
Guy Benyei11169dd2012-12-18 14:30:41 +0000777 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
778 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000779 // For uninteresting identifiers, there's nothing else to do. Just notify
780 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000781 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000782 return II;
783 }
784
Justin Bogner57ba0b22014-03-28 22:03:24 +0000785 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
786 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000787 bool CPlusPlusOperatorKeyword = readBit(Bits);
788 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000789 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000790 bool Poisoned = readBit(Bits);
791 bool ExtensionToken = readBit(Bits);
792 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000793
794 assert(Bits == 0 && "Extra bits in the identifier?");
795 DataLen -= 8;
796
Guy Benyei11169dd2012-12-18 14:30:41 +0000797 // Set or check the various bits in the IdentifierInfo structure.
798 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000799 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000800 II->revertTokenIDToIdentifier();
801 if (!F.isModule())
802 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
803 else if (HasRevertedBuiltin && II->getBuiltinID()) {
804 II->revertBuiltin();
805 assert((II->hasRevertedBuiltin() ||
806 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
807 "Incorrect ObjC keyword or builtin ID");
808 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000809 assert(II->isExtensionToken() == ExtensionToken &&
810 "Incorrect extension token flag");
811 (void)ExtensionToken;
812 if (Poisoned)
813 II->setIsPoisoned(true);
814 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
815 "Incorrect C++ operator keyword flag");
816 (void)CPlusPlusOperatorKeyword;
817
818 // If this identifier is a macro, deserialize the macro
819 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000820 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000821 uint32_t MacroDirectivesOffset =
822 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000823 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000824
Richard Smithd7329392015-04-21 21:46:32 +0000825 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000826 }
827
828 Reader.SetIdentifierInfo(ID, II);
829
830 // Read all of the declarations visible at global scope with this
831 // name.
832 if (DataLen > 0) {
833 SmallVector<uint32_t, 4> DeclIDs;
834 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000835 DeclIDs.push_back(Reader.getGlobalDeclID(
836 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000837 Reader.SetGloballyVisibleDecls(II, DeclIDs);
838 }
839
840 return II;
841}
842
843unsigned
Richard Smith3b637412015-07-14 18:42:41 +0000844ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000845 llvm::FoldingSetNodeID ID;
846 ID.AddInteger(Key.Kind);
847
848 switch (Key.Kind) {
849 case DeclarationName::Identifier:
850 case DeclarationName::CXXLiteralOperatorName:
851 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
852 break;
853 case DeclarationName::ObjCZeroArgSelector:
854 case DeclarationName::ObjCOneArgSelector:
855 case DeclarationName::ObjCMultiArgSelector:
856 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
857 break;
858 case DeclarationName::CXXOperatorName:
859 ID.AddInteger((OverloadedOperatorKind)Key.Data);
860 break;
861 case DeclarationName::CXXConstructorName:
862 case DeclarationName::CXXDestructorName:
863 case DeclarationName::CXXConversionFunctionName:
864 case DeclarationName::CXXUsingDirective:
865 break;
866 }
867
868 return ID.ComputeHash();
869}
870
871ASTDeclContextNameLookupTrait::internal_key_type
872ASTDeclContextNameLookupTrait::GetInternalKey(
Richard Smith3b637412015-07-14 18:42:41 +0000873 const external_key_type& Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000874 DeclNameKey Key;
875 Key.Kind = Name.getNameKind();
876 switch (Name.getNameKind()) {
877 case DeclarationName::Identifier:
878 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
879 break;
880 case DeclarationName::ObjCZeroArgSelector:
881 case DeclarationName::ObjCOneArgSelector:
882 case DeclarationName::ObjCMultiArgSelector:
883 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
884 break;
885 case DeclarationName::CXXOperatorName:
886 Key.Data = Name.getCXXOverloadedOperator();
887 break;
888 case DeclarationName::CXXLiteralOperatorName:
889 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
890 break;
891 case DeclarationName::CXXConstructorName:
892 case DeclarationName::CXXDestructorName:
893 case DeclarationName::CXXConversionFunctionName:
894 case DeclarationName::CXXUsingDirective:
895 Key.Data = 0;
896 break;
897 }
898
899 return Key;
900}
901
902std::pair<unsigned, unsigned>
903ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000904 using namespace llvm::support;
905 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
906 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000907 return std::make_pair(KeyLen, DataLen);
908}
909
910ASTDeclContextNameLookupTrait::internal_key_type
911ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000912 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000913
914 DeclNameKey Key;
915 Key.Kind = (DeclarationName::NameKind)*d++;
916 switch (Key.Kind) {
917 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000918 Key.Data = (uint64_t)Reader.getLocalIdentifier(
919 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000920 break;
921 case DeclarationName::ObjCZeroArgSelector:
922 case DeclarationName::ObjCOneArgSelector:
923 case DeclarationName::ObjCMultiArgSelector:
924 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000925 (uint64_t)Reader.getLocalSelector(
926 F, endian::readNext<uint32_t, little, unaligned>(
927 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000928 break;
929 case DeclarationName::CXXOperatorName:
930 Key.Data = *d++; // OverloadedOperatorKind
931 break;
932 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000933 Key.Data = (uint64_t)Reader.getLocalIdentifier(
934 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000935 break;
936 case DeclarationName::CXXConstructorName:
937 case DeclarationName::CXXDestructorName:
938 case DeclarationName::CXXConversionFunctionName:
939 case DeclarationName::CXXUsingDirective:
940 Key.Data = 0;
941 break;
942 }
943
944 return Key;
945}
946
Richard Smithf02662d2015-07-30 03:17:16 +0000947ASTDeclContextNameLookupTrait::data_type
948ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
949 const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000950 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000951 using namespace llvm::support;
Richard Smithf02662d2015-07-30 03:17:16 +0000952 unsigned NumDecls = DataLen / 4;
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000953 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
954 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000955 return std::make_pair(Start, Start + NumDecls);
956}
957
Richard Smith0f4e2c42015-08-06 04:23:48 +0000958bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
959 BitstreamCursor &Cursor,
960 uint64_t Offset,
961 DeclContext *DC) {
962 assert(Offset != 0);
963
Guy Benyei11169dd2012-12-18 14:30:41 +0000964 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +0000965 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000966
Richard Smith0f4e2c42015-08-06 04:23:48 +0000967 RecordData Record;
968 StringRef Blob;
969 unsigned Code = Cursor.ReadCode();
970 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
971 if (RecCode != DECL_CONTEXT_LEXICAL) {
972 Error("Expected lexical block");
973 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000974 }
975
Richard Smith82f8fcd2015-08-06 22:07:25 +0000976 assert(!isa<TranslationUnitDecl>(DC) &&
977 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +0000978 // If we are handling a C++ class template instantiation, we can see multiple
979 // lexical updates for the same record. It's important that we select only one
980 // of them, so that field numbering works properly. Just pick the first one we
981 // see.
982 auto &Lex = LexicalDecls[DC];
983 if (!Lex.first) {
984 Lex = std::make_pair(
985 &M, llvm::makeArrayRef(
986 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
987 Blob.data()),
988 Blob.size() / 4));
989 }
Richard Smith0f4e2c42015-08-06 04:23:48 +0000990 DC->setHasExternalLexicalStorage(true);
991 return false;
992}
Guy Benyei11169dd2012-12-18 14:30:41 +0000993
Richard Smith0f4e2c42015-08-06 04:23:48 +0000994bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
995 BitstreamCursor &Cursor,
996 uint64_t Offset,
997 DeclID ID) {
998 assert(Offset != 0);
999
1000 SavedStreamPosition SavedPosition(Cursor);
1001 Cursor.JumpToBit(Offset);
1002
1003 RecordData Record;
1004 StringRef Blob;
1005 unsigned Code = Cursor.ReadCode();
1006 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1007 if (RecCode != DECL_CONTEXT_VISIBLE) {
1008 Error("Expected visible lookup table block");
1009 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001010 }
1011
Richard Smith0f4e2c42015-08-06 04:23:48 +00001012 // We can't safely determine the primary context yet, so delay attaching the
1013 // lookup table until we're done with recursive deserialization.
1014 unsigned BucketOffset = Record[0];
1015 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{
1016 &M, (const unsigned char *)Blob.data(), BucketOffset});
Guy Benyei11169dd2012-12-18 14:30:41 +00001017 return false;
1018}
1019
1020void ASTReader::Error(StringRef Msg) {
1021 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001022 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1023 Diag(diag::note_module_cache_path)
1024 << PP.getHeaderSearchInfo().getModuleCachePath();
1025 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001026}
1027
1028void ASTReader::Error(unsigned DiagID,
1029 StringRef Arg1, StringRef Arg2) {
1030 if (Diags.isDiagnosticInFlight())
1031 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1032 else
1033 Diag(DiagID) << Arg1 << Arg2;
1034}
1035
1036//===----------------------------------------------------------------------===//
1037// Source Manager Deserialization
1038//===----------------------------------------------------------------------===//
1039
1040/// \brief Read the line table in the source manager block.
1041/// \returns true if there was an error.
1042bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001043 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001044 unsigned Idx = 0;
1045 LineTableInfo &LineTable = SourceMgr.getLineTable();
1046
1047 // Parse the file names
1048 std::map<int, int> FileIDs;
1049 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1050 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001051 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001052 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1053 }
1054
1055 // Parse the line entries
1056 std::vector<LineEntry> Entries;
1057 while (Idx < Record.size()) {
1058 int FID = Record[Idx++];
1059 assert(FID >= 0 && "Serialized line entries for non-local file.");
1060 // Remap FileID from 1-based old view.
1061 FID += F.SLocEntryBaseID - 1;
1062
1063 // Extract the line entries
1064 unsigned NumEntries = Record[Idx++];
1065 assert(NumEntries && "Numentries is 00000");
1066 Entries.clear();
1067 Entries.reserve(NumEntries);
1068 for (unsigned I = 0; I != NumEntries; ++I) {
1069 unsigned FileOffset = Record[Idx++];
1070 unsigned LineNo = Record[Idx++];
1071 int FilenameID = FileIDs[Record[Idx++]];
1072 SrcMgr::CharacteristicKind FileKind
1073 = (SrcMgr::CharacteristicKind)Record[Idx++];
1074 unsigned IncludeOffset = Record[Idx++];
1075 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1076 FileKind, IncludeOffset));
1077 }
1078 LineTable.AddEntry(FileID::get(FID), Entries);
1079 }
1080
1081 return false;
1082}
1083
1084/// \brief Read a source manager block
1085bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1086 using namespace SrcMgr;
1087
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001088 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001089
1090 // Set the source-location entry cursor to the current position in
1091 // the stream. This cursor will be used to read the contents of the
1092 // source manager block initially, and then lazily read
1093 // source-location entries as needed.
1094 SLocEntryCursor = F.Stream;
1095
1096 // The stream itself is going to skip over the source manager block.
1097 if (F.Stream.SkipBlock()) {
1098 Error("malformed block record in AST file");
1099 return true;
1100 }
1101
1102 // Enter the source manager block.
1103 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1104 Error("malformed source manager block record in AST file");
1105 return true;
1106 }
1107
1108 RecordData Record;
1109 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001110 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1111
1112 switch (E.Kind) {
1113 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1114 case llvm::BitstreamEntry::Error:
1115 Error("malformed block record in AST file");
1116 return true;
1117 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001118 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001119 case llvm::BitstreamEntry::Record:
1120 // The interesting case.
1121 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001122 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001123
Guy Benyei11169dd2012-12-18 14:30:41 +00001124 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001125 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001126 StringRef Blob;
1127 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001128 default: // Default behavior: ignore.
1129 break;
1130
1131 case SM_SLOC_FILE_ENTRY:
1132 case SM_SLOC_BUFFER_ENTRY:
1133 case SM_SLOC_EXPANSION_ENTRY:
1134 // Once we hit one of the source location entries, we're done.
1135 return false;
1136 }
1137 }
1138}
1139
1140/// \brief If a header file is not found at the path that we expect it to be
1141/// and the PCH file was moved from its original location, try to resolve the
1142/// file by assuming that header+PCH were moved together and the header is in
1143/// the same place relative to the PCH.
1144static std::string
1145resolveFileRelativeToOriginalDir(const std::string &Filename,
1146 const std::string &OriginalDir,
1147 const std::string &CurrDir) {
1148 assert(OriginalDir != CurrDir &&
1149 "No point trying to resolve the file if the PCH dir didn't change");
1150 using namespace llvm::sys;
1151 SmallString<128> filePath(Filename);
1152 fs::make_absolute(filePath);
1153 assert(path::is_absolute(OriginalDir));
1154 SmallString<128> currPCHPath(CurrDir);
1155
1156 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1157 fileDirE = path::end(path::parent_path(filePath));
1158 path::const_iterator origDirI = path::begin(OriginalDir),
1159 origDirE = path::end(OriginalDir);
1160 // Skip the common path components from filePath and OriginalDir.
1161 while (fileDirI != fileDirE && origDirI != origDirE &&
1162 *fileDirI == *origDirI) {
1163 ++fileDirI;
1164 ++origDirI;
1165 }
1166 for (; origDirI != origDirE; ++origDirI)
1167 path::append(currPCHPath, "..");
1168 path::append(currPCHPath, fileDirI, fileDirE);
1169 path::append(currPCHPath, path::filename(Filename));
1170 return currPCHPath.str();
1171}
1172
1173bool ASTReader::ReadSLocEntry(int ID) {
1174 if (ID == 0)
1175 return false;
1176
1177 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1178 Error("source location entry ID out-of-range for AST file");
1179 return true;
1180 }
1181
1182 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1183 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001184 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001185 unsigned BaseOffset = F->SLocEntryBaseOffset;
1186
1187 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001188 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1189 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001190 Error("incorrectly-formatted source location entry in AST file");
1191 return true;
1192 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001193
Guy Benyei11169dd2012-12-18 14:30:41 +00001194 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001195 StringRef Blob;
1196 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001197 default:
1198 Error("incorrectly-formatted source location entry in AST file");
1199 return true;
1200
1201 case SM_SLOC_FILE_ENTRY: {
1202 // We will detect whether a file changed and return 'Failure' for it, but
1203 // we will also try to fail gracefully by setting up the SLocEntry.
1204 unsigned InputID = Record[4];
1205 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001206 const FileEntry *File = IF.getFile();
1207 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001208
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001209 // Note that we only check if a File was returned. If it was out-of-date
1210 // we have complained but we will continue creating a FileID to recover
1211 // gracefully.
1212 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001213 return true;
1214
1215 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1216 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1217 // This is the module's main file.
1218 IncludeLoc = getImportLocation(F);
1219 }
1220 SrcMgr::CharacteristicKind
1221 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1222 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1223 ID, BaseOffset + Record[0]);
1224 SrcMgr::FileInfo &FileInfo =
1225 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1226 FileInfo.NumCreatedFIDs = Record[5];
1227 if (Record[3])
1228 FileInfo.setHasLineDirectives();
1229
1230 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1231 unsigned NumFileDecls = Record[7];
1232 if (NumFileDecls) {
1233 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1234 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1235 NumFileDecls));
1236 }
1237
1238 const SrcMgr::ContentCache *ContentCache
1239 = SourceMgr.getOrCreateContentCache(File,
1240 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1241 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1242 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1243 unsigned Code = SLocEntryCursor.ReadCode();
1244 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001245 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001246
1247 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1248 Error("AST record has invalid code");
1249 return true;
1250 }
1251
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001252 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001253 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001254 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001255 }
1256
1257 break;
1258 }
1259
1260 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001261 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001262 unsigned Offset = Record[0];
1263 SrcMgr::CharacteristicKind
1264 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1265 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001266 if (IncludeLoc.isInvalid() &&
1267 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001268 IncludeLoc = getImportLocation(F);
1269 }
1270 unsigned Code = SLocEntryCursor.ReadCode();
1271 Record.clear();
1272 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001273 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001274
1275 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1276 Error("AST record has invalid code");
1277 return true;
1278 }
1279
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001280 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1281 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001282 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001283 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001284 break;
1285 }
1286
1287 case SM_SLOC_EXPANSION_ENTRY: {
1288 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1289 SourceMgr.createExpansionLoc(SpellingLoc,
1290 ReadSourceLocation(*F, Record[2]),
1291 ReadSourceLocation(*F, Record[3]),
1292 Record[4],
1293 ID,
1294 BaseOffset + Record[0]);
1295 break;
1296 }
1297 }
1298
1299 return false;
1300}
1301
1302std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1303 if (ID == 0)
1304 return std::make_pair(SourceLocation(), "");
1305
1306 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1307 Error("source location entry ID out-of-range for AST file");
1308 return std::make_pair(SourceLocation(), "");
1309 }
1310
1311 // Find which module file this entry lands in.
1312 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001313 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001314 return std::make_pair(SourceLocation(), "");
1315
1316 // FIXME: Can we map this down to a particular submodule? That would be
1317 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001318 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001319}
1320
1321/// \brief Find the location where the module F is imported.
1322SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1323 if (F->ImportLoc.isValid())
1324 return F->ImportLoc;
1325
1326 // Otherwise we have a PCH. It's considered to be "imported" at the first
1327 // location of its includer.
1328 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001329 // Main file is the importer.
1330 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1331 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001332 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001333 return F->ImportedBy[0]->FirstLoc;
1334}
1335
1336/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1337/// specified cursor. Read the abbreviations that are at the top of the block
1338/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001339bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001340 if (Cursor.EnterSubBlock(BlockID)) {
1341 Error("malformed block record in AST file");
1342 return Failure;
1343 }
1344
1345 while (true) {
1346 uint64_t Offset = Cursor.GetCurrentBitNo();
1347 unsigned Code = Cursor.ReadCode();
1348
1349 // We expect all abbrevs to be at the start of the block.
1350 if (Code != llvm::bitc::DEFINE_ABBREV) {
1351 Cursor.JumpToBit(Offset);
1352 return false;
1353 }
1354 Cursor.ReadAbbrevRecord();
1355 }
1356}
1357
Richard Smithe40f2ba2013-08-07 21:41:30 +00001358Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001359 unsigned &Idx) {
1360 Token Tok;
1361 Tok.startToken();
1362 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1363 Tok.setLength(Record[Idx++]);
1364 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1365 Tok.setIdentifierInfo(II);
1366 Tok.setKind((tok::TokenKind)Record[Idx++]);
1367 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1368 return Tok;
1369}
1370
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001371MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001372 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001373
1374 // Keep track of where we are in the stream, then jump back there
1375 // after reading this macro.
1376 SavedStreamPosition SavedPosition(Stream);
1377
1378 Stream.JumpToBit(Offset);
1379 RecordData Record;
1380 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001381 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001382
Guy Benyei11169dd2012-12-18 14:30:41 +00001383 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001384 // Advance to the next record, but if we get to the end of the block, don't
1385 // pop it (removing all the abbreviations from the cursor) since we want to
1386 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001387 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001388 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1389
1390 switch (Entry.Kind) {
1391 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1392 case llvm::BitstreamEntry::Error:
1393 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001394 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001395 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001396 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001397 case llvm::BitstreamEntry::Record:
1398 // The interesting case.
1399 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 }
1401
1402 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001403 Record.clear();
1404 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001405 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001406 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001407 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001408 case PP_MACRO_DIRECTIVE_HISTORY:
1409 return Macro;
1410
Guy Benyei11169dd2012-12-18 14:30:41 +00001411 case PP_MACRO_OBJECT_LIKE:
1412 case PP_MACRO_FUNCTION_LIKE: {
1413 // If we already have a macro, that means that we've hit the end
1414 // of the definition of the macro we were looking for. We're
1415 // done.
1416 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001417 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001418
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001419 unsigned NextIndex = 1; // Skip identifier ID.
1420 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001421 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001422 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001423 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001424 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001425 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001426
Guy Benyei11169dd2012-12-18 14:30:41 +00001427 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1428 // Decode function-like macro info.
1429 bool isC99VarArgs = Record[NextIndex++];
1430 bool isGNUVarArgs = Record[NextIndex++];
1431 bool hasCommaPasting = Record[NextIndex++];
1432 MacroArgs.clear();
1433 unsigned NumArgs = Record[NextIndex++];
1434 for (unsigned i = 0; i != NumArgs; ++i)
1435 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1436
1437 // Install function-like macro info.
1438 MI->setIsFunctionLike();
1439 if (isC99VarArgs) MI->setIsC99Varargs();
1440 if (isGNUVarArgs) MI->setIsGNUVarargs();
1441 if (hasCommaPasting) MI->setHasCommaPasting();
1442 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1443 PP.getPreprocessorAllocator());
1444 }
1445
Guy Benyei11169dd2012-12-18 14:30:41 +00001446 // Remember that we saw this macro last so that we add the tokens that
1447 // form its body to it.
1448 Macro = MI;
1449
1450 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1451 Record[NextIndex]) {
1452 // We have a macro definition. Register the association
1453 PreprocessedEntityID
1454 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1455 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001456 PreprocessingRecord::PPEntityID PPID =
1457 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1458 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1459 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001460 if (PPDef)
1461 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001462 }
1463
1464 ++NumMacrosRead;
1465 break;
1466 }
1467
1468 case PP_TOKEN: {
1469 // If we see a TOKEN before a PP_MACRO_*, then the file is
1470 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001471 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001472
John McCallf413f5e2013-05-03 00:10:13 +00001473 unsigned Idx = 0;
1474 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001475 Macro->AddTokenToBody(Tok);
1476 break;
1477 }
1478 }
1479 }
1480}
1481
1482PreprocessedEntityID
1483ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1484 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1485 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1486 assert(I != M.PreprocessedEntityRemap.end()
1487 && "Invalid index into preprocessed entity index remap");
1488
1489 return LocalID + I->second;
1490}
1491
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001492unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1493 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001494}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001495
Guy Benyei11169dd2012-12-18 14:30:41 +00001496HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001497HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1498 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001499 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001500 return ikey;
1501}
Guy Benyei11169dd2012-12-18 14:30:41 +00001502
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001503bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1504 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001505 return false;
1506
Richard Smith7ed1bc92014-12-05 22:42:13 +00001507 if (llvm::sys::path::is_absolute(a.Filename) &&
1508 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001509 return true;
1510
Guy Benyei11169dd2012-12-18 14:30:41 +00001511 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001512 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001513 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1514 if (!Key.Imported)
1515 return FileMgr.getFile(Key.Filename);
1516
1517 std::string Resolved = Key.Filename;
1518 Reader.ResolveImportedPath(M, Resolved);
1519 return FileMgr.getFile(Resolved);
1520 };
1521
1522 const FileEntry *FEA = GetFile(a);
1523 const FileEntry *FEB = GetFile(b);
1524 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001525}
1526
1527std::pair<unsigned, unsigned>
1528HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001529 using namespace llvm::support;
1530 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001531 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001532 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001533}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001534
1535HeaderFileInfoTrait::internal_key_type
1536HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001537 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001538 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001539 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1540 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001541 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001542 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001543 return ikey;
1544}
1545
Guy Benyei11169dd2012-12-18 14:30:41 +00001546HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001547HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001548 unsigned DataLen) {
1549 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001550 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001551 HeaderFileInfo HFI;
1552 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001553 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1554 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001555 HFI.isImport = (Flags >> 5) & 0x01;
1556 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1557 HFI.DirInfo = (Flags >> 2) & 0x03;
1558 HFI.Resolved = (Flags >> 1) & 0x01;
1559 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001560 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1561 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1562 M, endian::readNext<uint32_t, little, unaligned>(d));
1563 if (unsigned FrameworkOffset =
1564 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001565 // The framework offset is 1 greater than the actual offset,
1566 // since 0 is used as an indicator for "no framework name".
1567 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1568 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1569 }
1570
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001571 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001572 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001573 if (LocalSMID) {
1574 // This header is part of a module. Associate it with the module to enable
1575 // implicit module import.
1576 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1577 Module *Mod = Reader.getSubmodule(GlobalSMID);
1578 HFI.isModuleHeader = true;
1579 FileManager &FileMgr = Reader.getFileManager();
1580 ModuleMap &ModMap =
1581 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001582 // FIXME: This information should be propagated through the
1583 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001584 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001585 std::string Filename = key.Filename;
1586 if (key.Imported)
1587 Reader.ResolveImportedPath(M, Filename);
1588 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001589 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001590 }
1591 }
1592
Guy Benyei11169dd2012-12-18 14:30:41 +00001593 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1594 (void)End;
1595
1596 // This HeaderFileInfo was externally loaded.
1597 HFI.External = true;
1598 return HFI;
1599}
1600
Richard Smithd7329392015-04-21 21:46:32 +00001601void ASTReader::addPendingMacro(IdentifierInfo *II,
1602 ModuleFile *M,
1603 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001604 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1605 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001606}
1607
1608void ASTReader::ReadDefinedMacros() {
1609 // Note that we are loading defined macros.
1610 Deserializing Macros(this);
1611
Pete Cooper57d3f142015-07-30 17:22:52 +00001612 for (auto &I : llvm::reverse(ModuleMgr)) {
1613 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001614
1615 // If there was no preprocessor block, skip this file.
1616 if (!MacroCursor.getBitStreamReader())
1617 continue;
1618
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001619 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001620 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001621
1622 RecordData Record;
1623 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001624 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1625
1626 switch (E.Kind) {
1627 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1628 case llvm::BitstreamEntry::Error:
1629 Error("malformed block record in AST file");
1630 return;
1631 case llvm::BitstreamEntry::EndBlock:
1632 goto NextCursor;
1633
1634 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001635 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001636 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001637 default: // Default behavior: ignore.
1638 break;
1639
1640 case PP_MACRO_OBJECT_LIKE:
1641 case PP_MACRO_FUNCTION_LIKE:
Pete Cooper57d3f142015-07-30 17:22:52 +00001642 getLocalIdentifier(*I, Record[0]);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001643 break;
1644
1645 case PP_TOKEN:
1646 // Ignore tokens.
1647 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001648 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 break;
1650 }
1651 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001652 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001653 }
1654}
1655
1656namespace {
1657 /// \brief Visitor class used to look up identifirs in an AST file.
1658 class IdentifierLookupVisitor {
1659 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001660 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001661 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001662 unsigned &NumIdentifierLookups;
1663 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001664 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001665
Guy Benyei11169dd2012-12-18 14:30:41 +00001666 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001667 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1668 unsigned &NumIdentifierLookups,
1669 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001670 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1671 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001672 NumIdentifierLookups(NumIdentifierLookups),
1673 NumIdentifierLookupHits(NumIdentifierLookupHits),
1674 Found()
1675 {
1676 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001677
1678 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001679 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001680 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001681 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001682
Guy Benyei11169dd2012-12-18 14:30:41 +00001683 ASTIdentifierLookupTable *IdTable
1684 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1685 if (!IdTable)
1686 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001687
1688 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001689 Found);
1690 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001691 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001692 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001693 if (Pos == IdTable->end())
1694 return false;
1695
1696 // Dereferencing the iterator has the effect of building the
1697 // IdentifierInfo node and populating it with the various
1698 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001699 ++NumIdentifierLookupHits;
1700 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001701 return true;
1702 }
1703
1704 // \brief Retrieve the identifier info found within the module
1705 // files.
1706 IdentifierInfo *getIdentifierInfo() const { return Found; }
1707 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001708}
Guy Benyei11169dd2012-12-18 14:30:41 +00001709
1710void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1711 // Note that we are loading an identifier.
1712 Deserializing AnIdentifier(this);
1713
1714 unsigned PriorGeneration = 0;
1715 if (getContext().getLangOpts().Modules)
1716 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001717
1718 // If there is a global index, look there first to determine which modules
1719 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001720 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001721 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001722 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001723 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1724 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001725 }
1726 }
1727
Douglas Gregor7211ac12013-01-25 23:32:03 +00001728 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001729 NumIdentifierLookups,
1730 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001731 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001732 markIdentifierUpToDate(&II);
1733}
1734
1735void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1736 if (!II)
1737 return;
1738
1739 II->setOutOfDate(false);
1740
1741 // Update the generation for this identifier.
1742 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001743 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001744}
1745
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001746void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1747 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001748 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001749
1750 BitstreamCursor &Cursor = M.MacroCursor;
1751 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001752 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001753
Richard Smith713369b2015-04-23 20:40:50 +00001754 struct ModuleMacroRecord {
1755 SubmoduleID SubModID;
1756 MacroInfo *MI;
1757 SmallVector<SubmoduleID, 8> Overrides;
1758 };
1759 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001760
Richard Smithd7329392015-04-21 21:46:32 +00001761 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1762 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1763 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001764 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001765 while (true) {
1766 llvm::BitstreamEntry Entry =
1767 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1768 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1769 Error("malformed block record in AST file");
1770 return;
1771 }
1772
1773 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001774 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001775 case PP_MACRO_DIRECTIVE_HISTORY:
1776 break;
1777
1778 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001779 ModuleMacros.push_back(ModuleMacroRecord());
1780 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001781 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1782 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001783 for (int I = 2, N = Record.size(); I != N; ++I)
1784 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001785 continue;
1786 }
1787
1788 default:
1789 Error("malformed block record in AST file");
1790 return;
1791 }
1792
1793 // We found the macro directive history; that's the last record
1794 // for this macro.
1795 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001796 }
1797
Richard Smithd7329392015-04-21 21:46:32 +00001798 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001799 {
1800 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001801 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001802 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001803 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001804 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001805 Module *Mod = getSubmodule(ModID);
1806 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001807 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001808 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001809 }
1810
1811 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001812 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001813 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001814 }
1815 }
1816
1817 // Don't read the directive history for a module; we don't have anywhere
1818 // to put it.
1819 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1820 return;
1821
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001822 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001823 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001824 unsigned Idx = 0, N = Record.size();
1825 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001826 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001827 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001828 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1829 switch (K) {
1830 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001831 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001832 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001833 break;
1834 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001835 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001836 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001837 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001838 }
1839 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001840 bool isPublic = Record[Idx++];
1841 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1842 break;
1843 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001844
1845 if (!Latest)
1846 Latest = MD;
1847 if (Earliest)
1848 Earliest->setPrevious(MD);
1849 Earliest = MD;
1850 }
1851
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001852 if (Latest)
1853 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001854}
1855
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001856ASTReader::InputFileInfo
1857ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001858 // Go find this input file.
1859 BitstreamCursor &Cursor = F.InputFilesCursor;
1860 SavedStreamPosition SavedPosition(Cursor);
1861 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1862
1863 unsigned Code = Cursor.ReadCode();
1864 RecordData Record;
1865 StringRef Blob;
1866
1867 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1868 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1869 "invalid record type for input file");
1870 (void)Result;
1871
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001872 std::string Filename;
1873 off_t StoredSize;
1874 time_t StoredTime;
1875 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001876
Ben Langmuir198c1682014-03-07 07:27:49 +00001877 assert(Record[0] == ID && "Bogus stored ID or offset");
1878 StoredSize = static_cast<off_t>(Record[1]);
1879 StoredTime = static_cast<time_t>(Record[2]);
1880 Overridden = static_cast<bool>(Record[3]);
1881 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001882 ResolveImportedPath(F, Filename);
1883
Hans Wennborg73945142014-03-14 17:45:06 +00001884 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1885 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001886}
1887
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001888InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001889 // If this ID is bogus, just return an empty input file.
1890 if (ID == 0 || ID > F.InputFilesLoaded.size())
1891 return InputFile();
1892
1893 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001894 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001895 return F.InputFilesLoaded[ID-1];
1896
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001897 if (F.InputFilesLoaded[ID-1].isNotFound())
1898 return InputFile();
1899
Guy Benyei11169dd2012-12-18 14:30:41 +00001900 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001901 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001902 SavedStreamPosition SavedPosition(Cursor);
1903 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1904
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001905 InputFileInfo FI = readInputFileInfo(F, ID);
1906 off_t StoredSize = FI.StoredSize;
1907 time_t StoredTime = FI.StoredTime;
1908 bool Overridden = FI.Overridden;
1909 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001910
Ben Langmuir198c1682014-03-07 07:27:49 +00001911 const FileEntry *File
1912 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1913 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1914
1915 // If we didn't find the file, resolve it relative to the
1916 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001917 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001918 F.OriginalDir != CurrentDir) {
1919 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1920 F.OriginalDir,
1921 CurrentDir);
1922 if (!Resolved.empty())
1923 File = FileMgr.getFile(Resolved);
1924 }
1925
1926 // For an overridden file, create a virtual file with the stored
1927 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001928 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001929 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1930 }
1931
Craig Toppera13603a2014-05-22 05:54:18 +00001932 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001933 if (Complain) {
1934 std::string ErrorStr = "could not find file '";
1935 ErrorStr += Filename;
1936 ErrorStr += "' referenced by AST file";
1937 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001938 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001939 // Record that we didn't find the file.
1940 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1941 return InputFile();
1942 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001943
Ben Langmuir198c1682014-03-07 07:27:49 +00001944 // Check if there was a request to override the contents of the file
1945 // that was part of the precompiled header. Overridding such a file
1946 // can lead to problems when lexing using the source locations from the
1947 // PCH.
1948 SourceManager &SM = getSourceManager();
1949 if (!Overridden && SM.isFileOverridden(File)) {
1950 if (Complain)
1951 Error(diag::err_fe_pch_file_overridden, Filename);
1952 // After emitting the diagnostic, recover by disabling the override so
1953 // that the original file will be used.
1954 SM.disableFileContentsOverride(File);
1955 // The FileEntry is a virtual file entry with the size of the contents
1956 // that would override the original contents. Set it to the original's
1957 // size/time.
1958 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1959 StoredSize, StoredTime);
1960 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001961
Ben Langmuir198c1682014-03-07 07:27:49 +00001962 bool IsOutOfDate = false;
1963
1964 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001965 if (!Overridden && //
1966 (StoredSize != File->getSize() ||
1967#if defined(LLVM_ON_WIN32)
1968 false
1969#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001970 // In our regression testing, the Windows file system seems to
1971 // have inconsistent modification times that sometimes
1972 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001973 //
1974 // This also happens in networked file systems, so disable this
1975 // check if validation is disabled or if we have an explicitly
1976 // built PCM file.
1977 //
1978 // FIXME: Should we also do this for PCH files? They could also
1979 // reasonably get shared across a network during a distributed build.
1980 (StoredTime != File->getModificationTime() && !DisableValidation &&
1981 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001982#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001983 )) {
1984 if (Complain) {
1985 // Build a list of the PCH imports that got us here (in reverse).
1986 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1987 while (ImportStack.back()->ImportedBy.size() > 0)
1988 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001989
Ben Langmuir198c1682014-03-07 07:27:49 +00001990 // The top-level PCH is stale.
1991 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1992 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00001993
Ben Langmuir198c1682014-03-07 07:27:49 +00001994 // Print the import stack.
1995 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1996 Diag(diag::note_pch_required_by)
1997 << Filename << ImportStack[0]->FileName;
1998 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00001999 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002000 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002001 }
2002
Ben Langmuir198c1682014-03-07 07:27:49 +00002003 if (!Diags.isDiagnosticInFlight())
2004 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002005 }
2006
Ben Langmuir198c1682014-03-07 07:27:49 +00002007 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002008 }
2009
Ben Langmuir198c1682014-03-07 07:27:49 +00002010 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2011
2012 // Note that we've loaded this input file.
2013 F.InputFilesLoaded[ID-1] = IF;
2014 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002015}
2016
Richard Smith7ed1bc92014-12-05 22:42:13 +00002017/// \brief If we are loading a relocatable PCH or module file, and the filename
2018/// is not an absolute path, add the system or module root to the beginning of
2019/// the file name.
2020void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2021 // Resolve relative to the base directory, if we have one.
2022 if (!M.BaseDirectory.empty())
2023 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002024}
2025
Richard Smith7ed1bc92014-12-05 22:42:13 +00002026void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002027 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2028 return;
2029
Richard Smith7ed1bc92014-12-05 22:42:13 +00002030 SmallString<128> Buffer;
2031 llvm::sys::path::append(Buffer, Prefix, Filename);
2032 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002033}
2034
Richard Smith0f99d6a2015-08-09 08:48:41 +00002035static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2036 switch (ARR) {
2037 case ASTReader::Failure: return true;
2038 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2039 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2040 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2041 case ASTReader::ConfigurationMismatch:
2042 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2043 case ASTReader::HadErrors: return true;
2044 case ASTReader::Success: return false;
2045 }
2046
2047 llvm_unreachable("unknown ASTReadResult");
2048}
2049
Guy Benyei11169dd2012-12-18 14:30:41 +00002050ASTReader::ASTReadResult
2051ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002052 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002053 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002054 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002055 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002056
2057 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2058 Error("malformed block record in AST file");
2059 return Failure;
2060 }
2061
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002062 // Should we allow the configuration of the module file to differ from the
2063 // configuration of the current translation unit in a compatible way?
2064 //
2065 // FIXME: Allow this for files explicitly specified with -include-pch too.
2066 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2067
Guy Benyei11169dd2012-12-18 14:30:41 +00002068 // Read all of the records and blocks in the control block.
2069 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002070 unsigned NumInputs = 0;
2071 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002072 while (1) {
2073 llvm::BitstreamEntry Entry = Stream.advance();
2074
2075 switch (Entry.Kind) {
2076 case llvm::BitstreamEntry::Error:
2077 Error("malformed block record in AST file");
2078 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002079 case llvm::BitstreamEntry::EndBlock: {
2080 // Validate input files.
2081 const HeaderSearchOptions &HSOpts =
2082 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002083
Richard Smitha1825302014-10-23 22:18:29 +00002084 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002085 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2086 // loaded module files, ignore missing inputs.
2087 if (!DisableValidation && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002088 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002089
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002090 // If we are reading a module, we will create a verification timestamp,
2091 // so we verify all input files. Otherwise, verify only user input
2092 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002093
2094 unsigned N = NumUserInputs;
2095 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002096 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002097 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002098 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002099 N = NumInputs;
2100
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002101 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002102 InputFile IF = getInputFile(F, I+1, Complain);
2103 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002104 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002105 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002106 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002107
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002108 if (Listener)
2109 Listener->visitModuleFile(F.FileName);
2110
Ben Langmuircb69b572014-03-07 06:40:32 +00002111 if (Listener && Listener->needsInputFileVisitation()) {
2112 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2113 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002114 for (unsigned I = 0; I < N; ++I) {
2115 bool IsSystem = I >= NumUserInputs;
2116 InputFileInfo FI = readInputFileInfo(F, I+1);
2117 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2118 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002119 }
2120
Guy Benyei11169dd2012-12-18 14:30:41 +00002121 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002122 }
2123
Chris Lattnere7b154b2013-01-19 21:39:22 +00002124 case llvm::BitstreamEntry::SubBlock:
2125 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002126 case INPUT_FILES_BLOCK_ID:
2127 F.InputFilesCursor = Stream;
2128 if (Stream.SkipBlock() || // Skip with the main cursor
2129 // Read the abbreviations
2130 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2131 Error("malformed block record in AST file");
2132 return Failure;
2133 }
2134 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002135
Guy Benyei11169dd2012-12-18 14:30:41 +00002136 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002137 if (Stream.SkipBlock()) {
2138 Error("malformed block record in AST file");
2139 return Failure;
2140 }
2141 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002142 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002143
2144 case llvm::BitstreamEntry::Record:
2145 // The interesting case.
2146 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002147 }
2148
2149 // Read and process a record.
2150 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002151 StringRef Blob;
2152 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002153 case METADATA: {
2154 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2155 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002156 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2157 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002158 return VersionMismatch;
2159 }
2160
2161 bool hasErrors = Record[5];
2162 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2163 Diag(diag::err_pch_with_compiler_errors);
2164 return HadErrors;
2165 }
2166
2167 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002168 // Relative paths in a relocatable PCH are relative to our sysroot.
2169 if (F.RelocatablePCH)
2170 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002171
2172 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002173 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002174 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2175 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002176 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002177 return VersionMismatch;
2178 }
2179 break;
2180 }
2181
Ben Langmuir487ea142014-10-23 18:05:36 +00002182 case SIGNATURE:
2183 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2184 F.Signature = Record[0];
2185 break;
2186
Guy Benyei11169dd2012-12-18 14:30:41 +00002187 case IMPORTS: {
2188 // Load each of the imported PCH files.
2189 unsigned Idx = 0, N = Record.size();
2190 while (Idx < N) {
2191 // Read information about the AST file.
2192 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2193 // The import location will be the local one for now; we will adjust
2194 // all import locations of module imports after the global source
2195 // location info are setup.
2196 SourceLocation ImportLoc =
2197 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002198 off_t StoredSize = (off_t)Record[Idx++];
2199 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002200 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002201 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002202
Richard Smith0f99d6a2015-08-09 08:48:41 +00002203 // If our client can't cope with us being out of date, we can't cope with
2204 // our dependency being missing.
2205 unsigned Capabilities = ClientLoadCapabilities;
2206 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2207 Capabilities &= ~ARR_Missing;
2208
Guy Benyei11169dd2012-12-18 14:30:41 +00002209 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002210 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2211 Loaded, StoredSize, StoredModTime,
2212 StoredSignature, Capabilities);
2213
2214 // If we diagnosed a problem, produce a backtrace.
2215 if (isDiagnosedResult(Result, Capabilities))
2216 Diag(diag::note_module_file_imported_by)
2217 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2218
2219 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002220 case Failure: return Failure;
2221 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002222 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002223 case OutOfDate: return OutOfDate;
2224 case VersionMismatch: return VersionMismatch;
2225 case ConfigurationMismatch: return ConfigurationMismatch;
2226 case HadErrors: return HadErrors;
2227 case Success: break;
2228 }
2229 }
2230 break;
2231 }
2232
2233 case LANGUAGE_OPTIONS: {
2234 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002235 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002236 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002237 ParseLanguageOptions(Record, Complain, *Listener,
2238 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002239 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002240 return ConfigurationMismatch;
2241 break;
2242 }
2243
2244 case TARGET_OPTIONS: {
2245 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2246 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002247 ParseTargetOptions(Record, Complain, *Listener,
2248 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002249 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002250 return ConfigurationMismatch;
2251 break;
2252 }
2253
2254 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002255 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002256 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002257 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002258 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002259 !DisableValidation)
2260 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002261 break;
2262 }
2263
2264 case FILE_SYSTEM_OPTIONS: {
2265 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2266 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002267 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002268 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002269 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002270 return ConfigurationMismatch;
2271 break;
2272 }
2273
2274 case HEADER_SEARCH_OPTIONS: {
2275 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2276 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002277 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002278 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002279 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002280 return ConfigurationMismatch;
2281 break;
2282 }
2283
2284 case PREPROCESSOR_OPTIONS: {
2285 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2286 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002287 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 ParsePreprocessorOptions(Record, Complain, *Listener,
2289 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002290 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002291 return ConfigurationMismatch;
2292 break;
2293 }
2294
2295 case ORIGINAL_FILE:
2296 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002297 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002298 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002299 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002300 break;
2301
2302 case ORIGINAL_FILE_ID:
2303 F.OriginalSourceFileID = FileID::get(Record[0]);
2304 break;
2305
2306 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002307 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002308 break;
2309
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002310 case MODULE_NAME:
2311 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002312 if (Listener)
2313 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002314 break;
2315
Richard Smith223d3f22014-12-06 03:21:08 +00002316 case MODULE_DIRECTORY: {
2317 assert(!F.ModuleName.empty() &&
2318 "MODULE_DIRECTORY found before MODULE_NAME");
2319 // If we've already loaded a module map file covering this module, we may
2320 // have a better path for it (relative to the current build).
2321 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2322 if (M && M->Directory) {
2323 // If we're implicitly loading a module, the base directory can't
2324 // change between the build and use.
2325 if (F.Kind != MK_ExplicitModule) {
2326 const DirectoryEntry *BuildDir =
2327 PP.getFileManager().getDirectory(Blob);
2328 if (!BuildDir || BuildDir != M->Directory) {
2329 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2330 Diag(diag::err_imported_module_relocated)
2331 << F.ModuleName << Blob << M->Directory->getName();
2332 return OutOfDate;
2333 }
2334 }
2335 F.BaseDirectory = M->Directory->getName();
2336 } else {
2337 F.BaseDirectory = Blob;
2338 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002339 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002340 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002341
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002342 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002343 if (ASTReadResult Result =
2344 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2345 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002346 break;
2347
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002348 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002349 NumInputs = Record[0];
2350 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002351 F.InputFileOffsets =
2352 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002353 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002354 break;
2355 }
2356 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002357}
2358
Ben Langmuir2c9af442014-04-10 17:57:43 +00002359ASTReader::ASTReadResult
2360ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002361 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002362
2363 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2364 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002365 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002366 }
2367
2368 // Read all of the records and blocks for the AST file.
2369 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002370 while (1) {
2371 llvm::BitstreamEntry Entry = Stream.advance();
2372
2373 switch (Entry.Kind) {
2374 case llvm::BitstreamEntry::Error:
2375 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002376 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002377 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002378 // Outside of C++, we do not store a lookup map for the translation unit.
2379 // Instead, mark it as needing a lookup map to be built if this module
2380 // contains any declarations lexically within it (which it always does!).
2381 // This usually has no cost, since we very rarely need the lookup map for
2382 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002383 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002384 if (DC->hasExternalLexicalStorage() &&
2385 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002386 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002387
Ben Langmuir2c9af442014-04-10 17:57:43 +00002388 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002390 case llvm::BitstreamEntry::SubBlock:
2391 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 case DECLTYPES_BLOCK_ID:
2393 // We lazily load the decls block, but we want to set up the
2394 // DeclsCursor cursor to point into it. Clone our current bitcode
2395 // cursor to it, enter the block and read the abbrevs in that block.
2396 // With the main cursor, we just skip over it.
2397 F.DeclsCursor = Stream;
2398 if (Stream.SkipBlock() || // Skip with the main cursor.
2399 // Read the abbrevs.
2400 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2401 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002402 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 }
2404 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002405
Guy Benyei11169dd2012-12-18 14:30:41 +00002406 case PREPROCESSOR_BLOCK_ID:
2407 F.MacroCursor = Stream;
2408 if (!PP.getExternalSource())
2409 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002410
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 if (Stream.SkipBlock() ||
2412 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2413 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002414 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002415 }
2416 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2417 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002418
Guy Benyei11169dd2012-12-18 14:30:41 +00002419 case PREPROCESSOR_DETAIL_BLOCK_ID:
2420 F.PreprocessorDetailCursor = Stream;
2421 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002422 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002423 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002424 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002425 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002426 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002427 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002428 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2429
Guy Benyei11169dd2012-12-18 14:30:41 +00002430 if (!PP.getPreprocessingRecord())
2431 PP.createPreprocessingRecord();
2432 if (!PP.getPreprocessingRecord()->getExternalSource())
2433 PP.getPreprocessingRecord()->SetExternalSource(*this);
2434 break;
2435
2436 case SOURCE_MANAGER_BLOCK_ID:
2437 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002438 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002439 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002440
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002442 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2443 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002444 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002445
Guy Benyei11169dd2012-12-18 14:30:41 +00002446 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002447 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002448 if (Stream.SkipBlock() ||
2449 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2450 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002451 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002452 }
2453 CommentsCursors.push_back(std::make_pair(C, &F));
2454 break;
2455 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002456
Guy Benyei11169dd2012-12-18 14:30:41 +00002457 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002458 if (Stream.SkipBlock()) {
2459 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002460 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002461 }
2462 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 }
2464 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002465
2466 case llvm::BitstreamEntry::Record:
2467 // The interesting case.
2468 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 }
2470
2471 // Read and process a record.
2472 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002473 StringRef Blob;
2474 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 default: // Default behavior: ignore.
2476 break;
2477
2478 case TYPE_OFFSET: {
2479 if (F.LocalNumTypes != 0) {
2480 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002481 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002482 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002483 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002484 F.LocalNumTypes = Record[0];
2485 unsigned LocalBaseTypeIndex = Record[1];
2486 F.BaseTypeIndex = getTotalNumTypes();
2487
2488 if (F.LocalNumTypes > 0) {
2489 // Introduce the global -> local mapping for types within this module.
2490 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2491
2492 // Introduce the local -> global mapping for types within this module.
2493 F.TypeRemap.insertOrReplace(
2494 std::make_pair(LocalBaseTypeIndex,
2495 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002496
2497 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 }
2499 break;
2500 }
2501
2502 case DECL_OFFSET: {
2503 if (F.LocalNumDecls != 0) {
2504 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002505 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002506 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002507 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002508 F.LocalNumDecls = Record[0];
2509 unsigned LocalBaseDeclID = Record[1];
2510 F.BaseDeclID = getTotalNumDecls();
2511
2512 if (F.LocalNumDecls > 0) {
2513 // Introduce the global -> local mapping for declarations within this
2514 // module.
2515 GlobalDeclMap.insert(
2516 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2517
2518 // Introduce the local -> global mapping for declarations within this
2519 // module.
2520 F.DeclRemap.insertOrReplace(
2521 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2522
2523 // Introduce the global -> local mapping for declarations within this
2524 // module.
2525 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002526
Ben Langmuir52ca6782014-10-20 16:27:32 +00002527 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2528 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002529 break;
2530 }
2531
2532 case TU_UPDATE_LEXICAL: {
2533 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002534 LexicalContents Contents(
2535 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2536 Blob.data()),
2537 static_cast<unsigned int>(Blob.size() / 4));
2538 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 TU->setHasExternalLexicalStorage(true);
2540 break;
2541 }
2542
2543 case UPDATE_VISIBLE: {
2544 unsigned Idx = 0;
2545 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002546 auto *Data = (const unsigned char*)Blob.data();
2547 unsigned BucketOffset = Record[Idx++];
2548 PendingVisibleUpdates[ID].push_back(
2549 PendingVisibleUpdate{&F, Data, BucketOffset});
2550 // If we've already loaded the decl, perform the updates when we finish
2551 // loading this block.
2552 if (Decl *D = GetExistingDecl(ID))
2553 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 break;
2555 }
2556
2557 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002558 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002560 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2561 (const unsigned char *)F.IdentifierTableData + Record[0],
2562 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2563 (const unsigned char *)F.IdentifierTableData,
2564 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002565
2566 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2567 }
2568 break;
2569
2570 case IDENTIFIER_OFFSET: {
2571 if (F.LocalNumIdentifiers != 0) {
2572 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002573 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002575 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 F.LocalNumIdentifiers = Record[0];
2577 unsigned LocalBaseIdentifierID = Record[1];
2578 F.BaseIdentifierID = getTotalNumIdentifiers();
2579
2580 if (F.LocalNumIdentifiers > 0) {
2581 // Introduce the global -> local mapping for identifiers within this
2582 // module.
2583 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2584 &F));
2585
2586 // Introduce the local -> global mapping for identifiers within this
2587 // module.
2588 F.IdentifierRemap.insertOrReplace(
2589 std::make_pair(LocalBaseIdentifierID,
2590 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002591
Ben Langmuir52ca6782014-10-20 16:27:32 +00002592 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2593 + F.LocalNumIdentifiers);
2594 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 break;
2596 }
2597
Richard Smith33e0f7e2015-07-22 02:08:40 +00002598 case INTERESTING_IDENTIFIERS:
2599 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2600 break;
2601
Ben Langmuir332aafe2014-01-31 01:06:56 +00002602 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002603 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2604 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002606 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002607 break;
2608
2609 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002610 if (SpecialTypes.empty()) {
2611 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2612 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2613 break;
2614 }
2615
2616 if (SpecialTypes.size() != Record.size()) {
2617 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002618 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002619 }
2620
2621 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2622 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2623 if (!SpecialTypes[I])
2624 SpecialTypes[I] = ID;
2625 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2626 // merge step?
2627 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002628 break;
2629
2630 case STATISTICS:
2631 TotalNumStatements += Record[0];
2632 TotalNumMacros += Record[1];
2633 TotalLexicalDeclContexts += Record[2];
2634 TotalVisibleDeclContexts += Record[3];
2635 break;
2636
2637 case UNUSED_FILESCOPED_DECLS:
2638 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2639 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2640 break;
2641
2642 case DELEGATING_CTORS:
2643 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2644 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2645 break;
2646
2647 case WEAK_UNDECLARED_IDENTIFIERS:
2648 if (Record.size() % 4 != 0) {
2649 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002650 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002651 }
2652
2653 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2654 // files. This isn't the way to do it :)
2655 WeakUndeclaredIdentifiers.clear();
2656
2657 // Translate the weak, undeclared identifiers into global IDs.
2658 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2659 WeakUndeclaredIdentifiers.push_back(
2660 getGlobalIdentifierID(F, Record[I++]));
2661 WeakUndeclaredIdentifiers.push_back(
2662 getGlobalIdentifierID(F, Record[I++]));
2663 WeakUndeclaredIdentifiers.push_back(
2664 ReadSourceLocation(F, Record, I).getRawEncoding());
2665 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2666 }
2667 break;
2668
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002670 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002671 F.LocalNumSelectors = Record[0];
2672 unsigned LocalBaseSelectorID = Record[1];
2673 F.BaseSelectorID = getTotalNumSelectors();
2674
2675 if (F.LocalNumSelectors > 0) {
2676 // Introduce the global -> local mapping for selectors within this
2677 // module.
2678 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2679
2680 // Introduce the local -> global mapping for selectors within this
2681 // module.
2682 F.SelectorRemap.insertOrReplace(
2683 std::make_pair(LocalBaseSelectorID,
2684 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002685
2686 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 }
2688 break;
2689 }
2690
2691 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002692 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 if (Record[0])
2694 F.SelectorLookupTable
2695 = ASTSelectorLookupTable::Create(
2696 F.SelectorLookupTableData + Record[0],
2697 F.SelectorLookupTableData,
2698 ASTSelectorLookupTrait(*this, F));
2699 TotalNumMethodPoolEntries += Record[1];
2700 break;
2701
2702 case REFERENCED_SELECTOR_POOL:
2703 if (!Record.empty()) {
2704 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2705 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2706 Record[Idx++]));
2707 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2708 getRawEncoding());
2709 }
2710 }
2711 break;
2712
2713 case PP_COUNTER_VALUE:
2714 if (!Record.empty() && Listener)
2715 Listener->ReadCounter(F, Record[0]);
2716 break;
2717
2718 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002719 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002720 F.NumFileSortedDecls = Record[0];
2721 break;
2722
2723 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002724 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 F.LocalNumSLocEntries = Record[0];
2726 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002727 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002728 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002729 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002730 if (!F.SLocEntryBaseID) {
2731 Error("ran out of source locations");
2732 break;
2733 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 // Make our entry in the range map. BaseID is negative and growing, so
2735 // we invert it. Because we invert it, though, we need the other end of
2736 // the range.
2737 unsigned RangeStart =
2738 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2739 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2740 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2741
2742 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2743 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2744 GlobalSLocOffsetMap.insert(
2745 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2746 - SLocSpaceSize,&F));
2747
2748 // Initialize the remapping table.
2749 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002750 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002751 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002752 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002753 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2754
2755 TotalNumSLocEntries += F.LocalNumSLocEntries;
2756 break;
2757 }
2758
2759 case MODULE_OFFSET_MAP: {
2760 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002761 const unsigned char *Data = (const unsigned char*)Blob.data();
2762 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002763
2764 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2765 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2766 F.SLocRemap.insert(std::make_pair(0U, 0));
2767 F.SLocRemap.insert(std::make_pair(2U, 1));
2768 }
2769
Guy Benyei11169dd2012-12-18 14:30:41 +00002770 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002771 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2772 RemapBuilder;
2773 RemapBuilder SLocRemap(F.SLocRemap);
2774 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2775 RemapBuilder MacroRemap(F.MacroRemap);
2776 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2777 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2778 RemapBuilder SelectorRemap(F.SelectorRemap);
2779 RemapBuilder DeclRemap(F.DeclRemap);
2780 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002781
2782 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002783 using namespace llvm::support;
2784 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002785 StringRef Name = StringRef((const char*)Data, Len);
2786 Data += Len;
2787 ModuleFile *OM = ModuleMgr.lookup(Name);
2788 if (!OM) {
2789 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002790 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002791 }
2792
Justin Bogner57ba0b22014-03-28 22:03:24 +00002793 uint32_t SLocOffset =
2794 endian::readNext<uint32_t, little, unaligned>(Data);
2795 uint32_t IdentifierIDOffset =
2796 endian::readNext<uint32_t, little, unaligned>(Data);
2797 uint32_t MacroIDOffset =
2798 endian::readNext<uint32_t, little, unaligned>(Data);
2799 uint32_t PreprocessedEntityIDOffset =
2800 endian::readNext<uint32_t, little, unaligned>(Data);
2801 uint32_t SubmoduleIDOffset =
2802 endian::readNext<uint32_t, little, unaligned>(Data);
2803 uint32_t SelectorIDOffset =
2804 endian::readNext<uint32_t, little, unaligned>(Data);
2805 uint32_t DeclIDOffset =
2806 endian::readNext<uint32_t, little, unaligned>(Data);
2807 uint32_t TypeIndexOffset =
2808 endian::readNext<uint32_t, little, unaligned>(Data);
2809
Ben Langmuir785180e2014-10-20 16:27:30 +00002810 uint32_t None = std::numeric_limits<uint32_t>::max();
2811
2812 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2813 RemapBuilder &Remap) {
2814 if (Offset != None)
2815 Remap.insert(std::make_pair(Offset,
2816 static_cast<int>(BaseOffset - Offset)));
2817 };
2818 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2819 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2820 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2821 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2822 PreprocessedEntityRemap);
2823 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2824 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2825 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2826 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002827
2828 // Global -> local mappings.
2829 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2830 }
2831 break;
2832 }
2833
2834 case SOURCE_MANAGER_LINE_TABLE:
2835 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002836 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002837 break;
2838
2839 case SOURCE_LOCATION_PRELOADS: {
2840 // Need to transform from the local view (1-based IDs) to the global view,
2841 // which is based off F.SLocEntryBaseID.
2842 if (!F.PreloadSLocEntries.empty()) {
2843 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002844 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002845 }
2846
2847 F.PreloadSLocEntries.swap(Record);
2848 break;
2849 }
2850
2851 case EXT_VECTOR_DECLS:
2852 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2853 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2854 break;
2855
2856 case VTABLE_USES:
2857 if (Record.size() % 3 != 0) {
2858 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002859 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 }
2861
2862 // Later tables overwrite earlier ones.
2863 // FIXME: Modules will have some trouble with this. This is clearly not
2864 // the right way to do this.
2865 VTableUses.clear();
2866
2867 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2868 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2869 VTableUses.push_back(
2870 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2871 VTableUses.push_back(Record[Idx++]);
2872 }
2873 break;
2874
Guy Benyei11169dd2012-12-18 14:30:41 +00002875 case PENDING_IMPLICIT_INSTANTIATIONS:
2876 if (PendingInstantiations.size() % 2 != 0) {
2877 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002878 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002879 }
2880
2881 if (Record.size() % 2 != 0) {
2882 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002883 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002884 }
2885
2886 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2887 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2888 PendingInstantiations.push_back(
2889 ReadSourceLocation(F, Record, I).getRawEncoding());
2890 }
2891 break;
2892
2893 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002894 if (Record.size() != 2) {
2895 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002896 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002897 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002898 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2899 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2900 break;
2901
2902 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002903 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2904 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2905 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002906
2907 unsigned LocalBasePreprocessedEntityID = Record[0];
2908
2909 unsigned StartingID;
2910 if (!PP.getPreprocessingRecord())
2911 PP.createPreprocessingRecord();
2912 if (!PP.getPreprocessingRecord()->getExternalSource())
2913 PP.getPreprocessingRecord()->SetExternalSource(*this);
2914 StartingID
2915 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002916 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002917 F.BasePreprocessedEntityID = StartingID;
2918
2919 if (F.NumPreprocessedEntities > 0) {
2920 // Introduce the global -> local mapping for preprocessed entities in
2921 // this module.
2922 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2923
2924 // Introduce the local -> global mapping for preprocessed entities in
2925 // this module.
2926 F.PreprocessedEntityRemap.insertOrReplace(
2927 std::make_pair(LocalBasePreprocessedEntityID,
2928 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2929 }
2930
2931 break;
2932 }
2933
2934 case DECL_UPDATE_OFFSETS: {
2935 if (Record.size() % 2 != 0) {
2936 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002937 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002938 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002939 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2940 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2941 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2942
2943 // If we've already loaded the decl, perform the updates when we finish
2944 // loading this block.
2945 if (Decl *D = GetExistingDecl(ID))
2946 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2947 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002948 break;
2949 }
2950
2951 case DECL_REPLACEMENTS: {
2952 if (Record.size() % 3 != 0) {
2953 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002954 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002955 }
2956 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2957 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2958 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2959 break;
2960 }
2961
2962 case OBJC_CATEGORIES_MAP: {
2963 if (F.LocalNumObjCCategoriesInMap != 0) {
2964 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002965 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002966 }
2967
2968 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002969 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002970 break;
2971 }
2972
2973 case OBJC_CATEGORIES:
2974 F.ObjCCategories.swap(Record);
2975 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00002976
Guy Benyei11169dd2012-12-18 14:30:41 +00002977 case CXX_BASE_SPECIFIER_OFFSETS: {
2978 if (F.LocalNumCXXBaseSpecifiers != 0) {
2979 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002980 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 }
Richard Smithc2bb8182015-03-24 06:36:48 +00002982
Guy Benyei11169dd2012-12-18 14:30:41 +00002983 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002984 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00002985 break;
2986 }
2987
2988 case CXX_CTOR_INITIALIZERS_OFFSETS: {
2989 if (F.LocalNumCXXCtorInitializers != 0) {
2990 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2991 return Failure;
2992 }
2993
2994 F.LocalNumCXXCtorInitializers = Record[0];
2995 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002996 break;
2997 }
2998
2999 case DIAG_PRAGMA_MAPPINGS:
3000 if (F.PragmaDiagMappings.empty())
3001 F.PragmaDiagMappings.swap(Record);
3002 else
3003 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3004 Record.begin(), Record.end());
3005 break;
3006
3007 case CUDA_SPECIAL_DECL_REFS:
3008 // Later tables overwrite earlier ones.
3009 // FIXME: Modules will have trouble with this.
3010 CUDASpecialDeclRefs.clear();
3011 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3012 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3013 break;
3014
3015 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003016 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003017 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003018 if (Record[0]) {
3019 F.HeaderFileInfoTable
3020 = HeaderFileInfoLookupTable::Create(
3021 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3022 (const unsigned char *)F.HeaderFileInfoTableData,
3023 HeaderFileInfoTrait(*this, F,
3024 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003025 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003026
3027 PP.getHeaderSearchInfo().SetExternalSource(this);
3028 if (!PP.getHeaderSearchInfo().getExternalLookup())
3029 PP.getHeaderSearchInfo().SetExternalLookup(this);
3030 }
3031 break;
3032 }
3033
3034 case FP_PRAGMA_OPTIONS:
3035 // Later tables overwrite earlier ones.
3036 FPPragmaOptions.swap(Record);
3037 break;
3038
3039 case OPENCL_EXTENSIONS:
3040 // Later tables overwrite earlier ones.
3041 OpenCLExtensions.swap(Record);
3042 break;
3043
3044 case TENTATIVE_DEFINITIONS:
3045 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3046 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3047 break;
3048
3049 case KNOWN_NAMESPACES:
3050 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3051 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3052 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003053
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003054 case UNDEFINED_BUT_USED:
3055 if (UndefinedButUsed.size() % 2 != 0) {
3056 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003057 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003058 }
3059
3060 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003061 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003062 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003063 }
3064 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003065 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3066 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003067 ReadSourceLocation(F, Record, I).getRawEncoding());
3068 }
3069 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003070 case DELETE_EXPRS_TO_ANALYZE:
3071 for (unsigned I = 0, N = Record.size(); I != N;) {
3072 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3073 const uint64_t Count = Record[I++];
3074 DelayedDeleteExprs.push_back(Count);
3075 for (uint64_t C = 0; C < Count; ++C) {
3076 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3077 bool IsArrayForm = Record[I++] == 1;
3078 DelayedDeleteExprs.push_back(IsArrayForm);
3079 }
3080 }
3081 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003082
Guy Benyei11169dd2012-12-18 14:30:41 +00003083 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003084 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003085 // If we aren't loading a module (which has its own exports), make
3086 // all of the imported modules visible.
3087 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003088 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3089 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3090 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3091 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003092 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003093 }
3094 }
3095 break;
3096 }
3097
3098 case LOCAL_REDECLARATIONS: {
3099 F.RedeclarationChains.swap(Record);
3100 break;
3101 }
3102
3103 case LOCAL_REDECLARATIONS_MAP: {
3104 if (F.LocalNumRedeclarationsInMap != 0) {
3105 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003106 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 }
3108
3109 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003110 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 break;
3112 }
3113
Guy Benyei11169dd2012-12-18 14:30:41 +00003114 case MACRO_OFFSET: {
3115 if (F.LocalNumMacros != 0) {
3116 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003117 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003118 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003119 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 F.LocalNumMacros = Record[0];
3121 unsigned LocalBaseMacroID = Record[1];
3122 F.BaseMacroID = getTotalNumMacros();
3123
3124 if (F.LocalNumMacros > 0) {
3125 // Introduce the global -> local mapping for macros within this module.
3126 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3127
3128 // Introduce the local -> global mapping for macros within this module.
3129 F.MacroRemap.insertOrReplace(
3130 std::make_pair(LocalBaseMacroID,
3131 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003132
3133 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003134 }
3135 break;
3136 }
3137
Richard Smithe40f2ba2013-08-07 21:41:30 +00003138 case LATE_PARSED_TEMPLATE: {
3139 LateParsedTemplates.append(Record.begin(), Record.end());
3140 break;
3141 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003142
3143 case OPTIMIZE_PRAGMA_OPTIONS:
3144 if (Record.size() != 1) {
3145 Error("invalid pragma optimize record");
3146 return Failure;
3147 }
3148 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3149 break;
Nico Weber72889432014-09-06 01:25:55 +00003150
3151 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3152 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3153 UnusedLocalTypedefNameCandidates.push_back(
3154 getGlobalDeclID(F, Record[I]));
3155 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003156 }
3157 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003158}
3159
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003160ASTReader::ASTReadResult
3161ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3162 const ModuleFile *ImportedBy,
3163 unsigned ClientLoadCapabilities) {
3164 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003165 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003166
Richard Smithe842a472014-10-22 02:05:46 +00003167 if (F.Kind == MK_ExplicitModule) {
3168 // For an explicitly-loaded module, we don't care whether the original
3169 // module map file exists or matches.
3170 return Success;
3171 }
3172
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003173 // Try to resolve ModuleName in the current header search context and
3174 // verify that it is found in the same module map file as we saved. If the
3175 // top-level AST file is a main file, skip this check because there is no
3176 // usable header search context.
3177 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003178 "MODULE_NAME should come before MODULE_MAP_FILE");
3179 if (F.Kind == MK_ImplicitModule &&
3180 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3181 // An implicitly-loaded module file should have its module listed in some
3182 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003183 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003184 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3185 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3186 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003187 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003188 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3189 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3190 // This module was defined by an imported (explicit) module.
3191 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3192 << ASTFE->getName();
3193 else
3194 // This module was built with a different module map.
3195 Diag(diag::err_imported_module_not_found)
3196 << F.ModuleName << F.FileName << ImportedBy->FileName
3197 << F.ModuleMapPath;
3198 }
3199 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003200 }
3201
Richard Smithe842a472014-10-22 02:05:46 +00003202 assert(M->Name == F.ModuleName && "found module with different name");
3203
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003204 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003205 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003206 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3207 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003208 assert(ImportedBy && "top-level import should be verified");
3209 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3210 Diag(diag::err_imported_module_modmap_changed)
3211 << F.ModuleName << ImportedBy->FileName
3212 << ModMap->getName() << F.ModuleMapPath;
3213 return OutOfDate;
3214 }
3215
3216 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3217 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3218 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003219 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003220 const FileEntry *F =
3221 FileMgr.getFile(Filename, false, false);
3222 if (F == nullptr) {
3223 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3224 Error("could not find file '" + Filename +"' referenced by AST file");
3225 return OutOfDate;
3226 }
3227 AdditionalStoredMaps.insert(F);
3228 }
3229
3230 // Check any additional module map files (e.g. module.private.modulemap)
3231 // that are not in the pcm.
3232 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3233 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3234 // Remove files that match
3235 // Note: SmallPtrSet::erase is really remove
3236 if (!AdditionalStoredMaps.erase(ModMap)) {
3237 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3238 Diag(diag::err_module_different_modmap)
3239 << F.ModuleName << /*new*/0 << ModMap->getName();
3240 return OutOfDate;
3241 }
3242 }
3243 }
3244
3245 // Check any additional module map files that are in the pcm, but not
3246 // found in header search. Cases that match are already removed.
3247 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3248 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3249 Diag(diag::err_module_different_modmap)
3250 << F.ModuleName << /*not new*/1 << ModMap->getName();
3251 return OutOfDate;
3252 }
3253 }
3254
3255 if (Listener)
3256 Listener->ReadModuleMapFile(F.ModuleMapPath);
3257 return Success;
3258}
3259
3260
Douglas Gregorc1489562013-02-12 23:36:21 +00003261/// \brief Move the given method to the back of the global list of methods.
3262static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3263 // Find the entry for this selector in the method pool.
3264 Sema::GlobalMethodPool::iterator Known
3265 = S.MethodPool.find(Method->getSelector());
3266 if (Known == S.MethodPool.end())
3267 return;
3268
3269 // Retrieve the appropriate method list.
3270 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3271 : Known->second.second;
3272 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003273 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003274 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003275 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003276 Found = true;
3277 } else {
3278 // Keep searching.
3279 continue;
3280 }
3281 }
3282
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003283 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003284 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003285 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003286 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003287 }
3288}
3289
Richard Smithde711422015-04-23 21:20:19 +00003290void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003291 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003292 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003293 bool wasHidden = D->Hidden;
3294 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003295
Richard Smith49f906a2014-03-01 00:08:04 +00003296 if (wasHidden && SemaObj) {
3297 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3298 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003299 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003300 }
3301 }
3302}
3303
Richard Smith49f906a2014-03-01 00:08:04 +00003304void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003305 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003306 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003307 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003308 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003309 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003310 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003311 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003312
3313 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003314 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003315 // there is nothing more to do.
3316 continue;
3317 }
Richard Smith49f906a2014-03-01 00:08:04 +00003318
Guy Benyei11169dd2012-12-18 14:30:41 +00003319 if (!Mod->isAvailable()) {
3320 // Modules that aren't available cannot be made visible.
3321 continue;
3322 }
3323
3324 // Update the module's name visibility.
3325 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003326
Guy Benyei11169dd2012-12-18 14:30:41 +00003327 // If we've already deserialized any names from this module,
3328 // mark them as visible.
3329 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3330 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003331 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003332 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003333 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003334 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3335 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003336 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003337
Guy Benyei11169dd2012-12-18 14:30:41 +00003338 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003339 SmallVector<Module *, 16> Exports;
3340 Mod->getExportedModules(Exports);
3341 for (SmallVectorImpl<Module *>::iterator
3342 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3343 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003344 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003345 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003346 }
3347 }
3348}
3349
Douglas Gregore060e572013-01-25 01:03:03 +00003350bool ASTReader::loadGlobalIndex() {
3351 if (GlobalIndex)
3352 return false;
3353
3354 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3355 !Context.getLangOpts().Modules)
3356 return true;
3357
3358 // Try to load the global index.
3359 TriedLoadingGlobalIndex = true;
3360 StringRef ModuleCachePath
3361 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3362 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003363 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003364 if (!Result.first)
3365 return true;
3366
3367 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003368 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003369 return false;
3370}
3371
3372bool ASTReader::isGlobalIndexUnavailable() const {
3373 return Context.getLangOpts().Modules && UseGlobalIndex &&
3374 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3375}
3376
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003377static void updateModuleTimestamp(ModuleFile &MF) {
3378 // Overwrite the timestamp file contents so that file's mtime changes.
3379 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003380 std::error_code EC;
3381 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3382 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003383 return;
3384 OS << "Timestamp file\n";
3385}
3386
Guy Benyei11169dd2012-12-18 14:30:41 +00003387ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3388 ModuleKind Type,
3389 SourceLocation ImportLoc,
3390 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003391 llvm::SaveAndRestore<SourceLocation>
3392 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3393
Richard Smithd1c46742014-04-30 02:24:17 +00003394 // Defer any pending actions until we get to the end of reading the AST file.
3395 Deserializing AnASTFile(this);
3396
Guy Benyei11169dd2012-12-18 14:30:41 +00003397 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003398 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003399
3400 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003401 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003402 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003403 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003404 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003405 ClientLoadCapabilities)) {
3406 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003407 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003408 case OutOfDate:
3409 case VersionMismatch:
3410 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003411 case HadErrors: {
3412 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3413 for (const ImportedModule &IM : Loaded)
3414 LoadedSet.insert(IM.Mod);
3415
Douglas Gregor7029ce12013-03-19 00:28:20 +00003416 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003417 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003418 Context.getLangOpts().Modules
3419 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003420 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003421
3422 // If we find that any modules are unusable, the global index is going
3423 // to be out-of-date. Just remove it.
3424 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003425 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003426 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003427 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003428 case Success:
3429 break;
3430 }
3431
3432 // Here comes stuff that we only do once the entire chain is loaded.
3433
3434 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003435 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3436 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003437 M != MEnd; ++M) {
3438 ModuleFile &F = *M->Mod;
3439
3440 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003441 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3442 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003443
3444 // Once read, set the ModuleFile bit base offset and update the size in
3445 // bits of all files we've seen.
3446 F.GlobalBitOffset = TotalModulesSizeInBits;
3447 TotalModulesSizeInBits += F.SizeInBits;
3448 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3449
3450 // Preload SLocEntries.
3451 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3452 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3453 // Load it through the SourceManager and don't call ReadSLocEntry()
3454 // directly because the entry may have already been loaded in which case
3455 // calling ReadSLocEntry() directly would trigger an assertion in
3456 // SourceManager.
3457 SourceMgr.getLoadedSLocEntryByID(Index);
3458 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003459
3460 // Preload all the pending interesting identifiers by marking them out of
3461 // date.
3462 for (auto Offset : F.PreloadIdentifierOffsets) {
3463 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3464 F.IdentifierTableData + Offset);
3465
3466 ASTIdentifierLookupTrait Trait(*this, F);
3467 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3468 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3469 PP.getIdentifierTable().getOwn(Key).setOutOfDate(true);
3470 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003471 }
3472
Douglas Gregor603cd862013-03-22 18:50:14 +00003473 // Setup the import locations and notify the module manager that we've
3474 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003475 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3476 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003477 M != MEnd; ++M) {
3478 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003479
3480 ModuleMgr.moduleFileAccepted(&F);
3481
3482 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003483 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003484 if (!M->ImportedBy)
3485 F.ImportLoc = M->ImportLoc;
3486 else
3487 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3488 M->ImportLoc.getRawEncoding());
3489 }
3490
Richard Smith33e0f7e2015-07-22 02:08:40 +00003491 if (!Context.getLangOpts().CPlusPlus ||
3492 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3493 // Mark all of the identifiers in the identifier table as being out of date,
3494 // so that various accessors know to check the loaded modules when the
3495 // identifier is used.
3496 //
3497 // For C++ modules, we don't need information on many identifiers (just
3498 // those that provide macros or are poisoned), so we mark all of
3499 // the interesting ones via PreloadIdentifierOffsets.
3500 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3501 IdEnd = PP.getIdentifierTable().end();
3502 Id != IdEnd; ++Id)
3503 Id->second->setOutOfDate(true);
3504 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003505
3506 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003507 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3508 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003509 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3510 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003511
3512 switch (Unresolved.Kind) {
3513 case UnresolvedModuleRef::Conflict:
3514 if (ResolvedMod) {
3515 Module::Conflict Conflict;
3516 Conflict.Other = ResolvedMod;
3517 Conflict.Message = Unresolved.String.str();
3518 Unresolved.Mod->Conflicts.push_back(Conflict);
3519 }
3520 continue;
3521
3522 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003523 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003524 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003525 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003526
Douglas Gregorfb912652013-03-20 21:10:35 +00003527 case UnresolvedModuleRef::Export:
3528 if (ResolvedMod || Unresolved.IsWildcard)
3529 Unresolved.Mod->Exports.push_back(
3530 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3531 continue;
3532 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003533 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003534 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003535
3536 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3537 // Might be unnecessary as use declarations are only used to build the
3538 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003539
3540 InitializeContext();
3541
Richard Smith3d8e97e2013-10-18 06:54:39 +00003542 if (SemaObj)
3543 UpdateSema();
3544
Guy Benyei11169dd2012-12-18 14:30:41 +00003545 if (DeserializationListener)
3546 DeserializationListener->ReaderInitialized(this);
3547
3548 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3549 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3550 PrimaryModule.OriginalSourceFileID
3551 = FileID::get(PrimaryModule.SLocEntryBaseID
3552 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3553
3554 // If this AST file is a precompiled preamble, then set the
3555 // preamble file ID of the source manager to the file source file
3556 // from which the preamble was built.
3557 if (Type == MK_Preamble) {
3558 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3559 } else if (Type == MK_MainFile) {
3560 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3561 }
3562 }
3563
3564 // For any Objective-C class definitions we have already loaded, make sure
3565 // that we load any additional categories.
3566 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3567 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3568 ObjCClassesLoaded[I],
3569 PreviousGeneration);
3570 }
Douglas Gregore060e572013-01-25 01:03:03 +00003571
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003572 if (PP.getHeaderSearchInfo()
3573 .getHeaderSearchOpts()
3574 .ModulesValidateOncePerBuildSession) {
3575 // Now we are certain that the module and all modules it depends on are
3576 // up to date. Create or update timestamp files for modules that are
3577 // located in the module cache (not for PCH files that could be anywhere
3578 // in the filesystem).
3579 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3580 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003581 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003582 updateModuleTimestamp(*M.Mod);
3583 }
3584 }
3585 }
3586
Guy Benyei11169dd2012-12-18 14:30:41 +00003587 return Success;
3588}
3589
Ben Langmuir487ea142014-10-23 18:05:36 +00003590static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3591
Ben Langmuir70a1b812015-03-24 04:43:52 +00003592/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3593static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3594 return Stream.Read(8) == 'C' &&
3595 Stream.Read(8) == 'P' &&
3596 Stream.Read(8) == 'C' &&
3597 Stream.Read(8) == 'H';
3598}
3599
Richard Smith0f99d6a2015-08-09 08:48:41 +00003600static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3601 switch (Kind) {
3602 case MK_PCH:
3603 return 0; // PCH
3604 case MK_ImplicitModule:
3605 case MK_ExplicitModule:
3606 return 1; // module
3607 case MK_MainFile:
3608 case MK_Preamble:
3609 return 2; // main source file
3610 }
3611 llvm_unreachable("unknown module kind");
3612}
3613
Guy Benyei11169dd2012-12-18 14:30:41 +00003614ASTReader::ASTReadResult
3615ASTReader::ReadASTCore(StringRef FileName,
3616 ModuleKind Type,
3617 SourceLocation ImportLoc,
3618 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003619 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003620 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003621 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003622 unsigned ClientLoadCapabilities) {
3623 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003624 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003625 ModuleManager::AddModuleResult AddResult
3626 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003627 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003628 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003629 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003630
Douglas Gregor7029ce12013-03-19 00:28:20 +00003631 switch (AddResult) {
3632 case ModuleManager::AlreadyLoaded:
3633 return Success;
3634
3635 case ModuleManager::NewlyLoaded:
3636 // Load module file below.
3637 break;
3638
3639 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003640 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003641 // it.
3642 if (ClientLoadCapabilities & ARR_Missing)
3643 return Missing;
3644
3645 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003646 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3647 << FileName << ErrorStr.empty()
3648 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003649 return Failure;
3650
3651 case ModuleManager::OutOfDate:
3652 // We couldn't load the module file because it is out-of-date. If the
3653 // client can handle out-of-date, return it.
3654 if (ClientLoadCapabilities & ARR_OutOfDate)
3655 return OutOfDate;
3656
3657 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003658 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3659 << FileName << ErrorStr.empty()
3660 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003661 return Failure;
3662 }
3663
Douglas Gregor7029ce12013-03-19 00:28:20 +00003664 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003665
3666 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3667 // module?
3668 if (FileName != "-") {
3669 CurrentDir = llvm::sys::path::parent_path(FileName);
3670 if (CurrentDir.empty()) CurrentDir = ".";
3671 }
3672
3673 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003674 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003675 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003676 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003677 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3678
Guy Benyei11169dd2012-12-18 14:30:41 +00003679 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003680 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003681 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3682 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003683 return Failure;
3684 }
3685
3686 // This is used for compatibility with older PCH formats.
3687 bool HaveReadControlBlock = false;
3688
Chris Lattnerefa77172013-01-20 00:00:22 +00003689 while (1) {
3690 llvm::BitstreamEntry Entry = Stream.advance();
3691
3692 switch (Entry.Kind) {
3693 case llvm::BitstreamEntry::Error:
3694 case llvm::BitstreamEntry::EndBlock:
3695 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003696 Error("invalid record at top-level of AST file");
3697 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003698
3699 case llvm::BitstreamEntry::SubBlock:
3700 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003701 }
3702
Guy Benyei11169dd2012-12-18 14:30:41 +00003703 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003704 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003705 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3706 if (Stream.ReadBlockInfoBlock()) {
3707 Error("malformed BlockInfoBlock in AST file");
3708 return Failure;
3709 }
3710 break;
3711 case CONTROL_BLOCK_ID:
3712 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003713 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003714 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003715 // Check that we didn't try to load a non-module AST file as a module.
3716 //
3717 // FIXME: Should we also perform the converse check? Loading a module as
3718 // a PCH file sort of works, but it's a bit wonky.
3719 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule) &&
3720 F.ModuleName.empty()) {
3721 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3722 if (Result != OutOfDate ||
3723 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3724 Diag(diag::err_module_file_not_module) << FileName;
3725 return Result;
3726 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003727 break;
3728
3729 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003730 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003731 case OutOfDate: return OutOfDate;
3732 case VersionMismatch: return VersionMismatch;
3733 case ConfigurationMismatch: return ConfigurationMismatch;
3734 case HadErrors: return HadErrors;
3735 }
3736 break;
3737 case AST_BLOCK_ID:
3738 if (!HaveReadControlBlock) {
3739 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003740 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003741 return VersionMismatch;
3742 }
3743
3744 // Record that we've loaded this module.
3745 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3746 return Success;
3747
3748 default:
3749 if (Stream.SkipBlock()) {
3750 Error("malformed block record in AST file");
3751 return Failure;
3752 }
3753 break;
3754 }
3755 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003756}
3757
Richard Smitha7e2cc62015-05-01 01:53:09 +00003758void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003759 // If there's a listener, notify them that we "read" the translation unit.
3760 if (DeserializationListener)
3761 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3762 Context.getTranslationUnitDecl());
3763
Guy Benyei11169dd2012-12-18 14:30:41 +00003764 // FIXME: Find a better way to deal with collisions between these
3765 // built-in types. Right now, we just ignore the problem.
3766
3767 // Load the special types.
3768 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3769 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3770 if (!Context.CFConstantStringTypeDecl)
3771 Context.setCFConstantStringType(GetType(String));
3772 }
3773
3774 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3775 QualType FileType = GetType(File);
3776 if (FileType.isNull()) {
3777 Error("FILE type is NULL");
3778 return;
3779 }
3780
3781 if (!Context.FILEDecl) {
3782 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3783 Context.setFILEDecl(Typedef->getDecl());
3784 else {
3785 const TagType *Tag = FileType->getAs<TagType>();
3786 if (!Tag) {
3787 Error("Invalid FILE type in AST file");
3788 return;
3789 }
3790 Context.setFILEDecl(Tag->getDecl());
3791 }
3792 }
3793 }
3794
3795 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3796 QualType Jmp_bufType = GetType(Jmp_buf);
3797 if (Jmp_bufType.isNull()) {
3798 Error("jmp_buf type is NULL");
3799 return;
3800 }
3801
3802 if (!Context.jmp_bufDecl) {
3803 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3804 Context.setjmp_bufDecl(Typedef->getDecl());
3805 else {
3806 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3807 if (!Tag) {
3808 Error("Invalid jmp_buf type in AST file");
3809 return;
3810 }
3811 Context.setjmp_bufDecl(Tag->getDecl());
3812 }
3813 }
3814 }
3815
3816 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3817 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3818 if (Sigjmp_bufType.isNull()) {
3819 Error("sigjmp_buf type is NULL");
3820 return;
3821 }
3822
3823 if (!Context.sigjmp_bufDecl) {
3824 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3825 Context.setsigjmp_bufDecl(Typedef->getDecl());
3826 else {
3827 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3828 assert(Tag && "Invalid sigjmp_buf type in AST file");
3829 Context.setsigjmp_bufDecl(Tag->getDecl());
3830 }
3831 }
3832 }
3833
3834 if (unsigned ObjCIdRedef
3835 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3836 if (Context.ObjCIdRedefinitionType.isNull())
3837 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3838 }
3839
3840 if (unsigned ObjCClassRedef
3841 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3842 if (Context.ObjCClassRedefinitionType.isNull())
3843 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3844 }
3845
3846 if (unsigned ObjCSelRedef
3847 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3848 if (Context.ObjCSelRedefinitionType.isNull())
3849 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3850 }
3851
3852 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3853 QualType Ucontext_tType = GetType(Ucontext_t);
3854 if (Ucontext_tType.isNull()) {
3855 Error("ucontext_t type is NULL");
3856 return;
3857 }
3858
3859 if (!Context.ucontext_tDecl) {
3860 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3861 Context.setucontext_tDecl(Typedef->getDecl());
3862 else {
3863 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3864 assert(Tag && "Invalid ucontext_t type in AST file");
3865 Context.setucontext_tDecl(Tag->getDecl());
3866 }
3867 }
3868 }
3869 }
3870
3871 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3872
3873 // If there were any CUDA special declarations, deserialize them.
3874 if (!CUDASpecialDeclRefs.empty()) {
3875 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3876 Context.setcudaConfigureCallDecl(
3877 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3878 }
Richard Smith56be7542014-03-21 00:33:59 +00003879
Guy Benyei11169dd2012-12-18 14:30:41 +00003880 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003881 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003882 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003883 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003884 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003885 /*ImportLoc=*/Import.ImportLoc);
3886 PP.makeModuleVisible(Imported, Import.ImportLoc);
3887 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003888 }
3889 ImportedModules.clear();
3890}
3891
3892void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003893 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003894}
3895
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003896/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3897/// cursor into the start of the given block ID, returning false on success and
3898/// true on failure.
3899static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003900 while (1) {
3901 llvm::BitstreamEntry Entry = Cursor.advance();
3902 switch (Entry.Kind) {
3903 case llvm::BitstreamEntry::Error:
3904 case llvm::BitstreamEntry::EndBlock:
3905 return true;
3906
3907 case llvm::BitstreamEntry::Record:
3908 // Ignore top-level records.
3909 Cursor.skipRecord(Entry.ID);
3910 break;
3911
3912 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003913 if (Entry.ID == BlockID) {
3914 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003915 return true;
3916 // Found it!
3917 return false;
3918 }
3919
3920 if (Cursor.SkipBlock())
3921 return true;
3922 }
3923 }
3924}
3925
Ben Langmuir70a1b812015-03-24 04:43:52 +00003926/// \brief Reads and return the signature record from \p StreamFile's control
3927/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003928static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3929 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003930 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003931 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003932
3933 // Scan for the CONTROL_BLOCK_ID block.
3934 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3935 return 0;
3936
3937 // Scan for SIGNATURE inside the control block.
3938 ASTReader::RecordData Record;
3939 while (1) {
3940 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3941 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3942 Entry.Kind != llvm::BitstreamEntry::Record)
3943 return 0;
3944
3945 Record.clear();
3946 StringRef Blob;
3947 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3948 return Record[0];
3949 }
3950}
3951
Guy Benyei11169dd2012-12-18 14:30:41 +00003952/// \brief Retrieve the name of the original source file name
3953/// directly from the AST file, without actually loading the AST
3954/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003955std::string ASTReader::getOriginalSourceFile(
3956 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003957 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003958 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00003959 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00003960 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00003961 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3962 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00003963 return std::string();
3964 }
3965
3966 // Initialize the stream
3967 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003968 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003969 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003970
3971 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003972 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003973 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3974 return std::string();
3975 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003976
Chris Lattnere7b154b2013-01-19 21:39:22 +00003977 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003978 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003979 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3980 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003981 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003982
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003983 // Scan for ORIGINAL_FILE inside the control block.
3984 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003985 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003986 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003987 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3988 return std::string();
3989
3990 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3991 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3992 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003993 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003994
Guy Benyei11169dd2012-12-18 14:30:41 +00003995 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003996 StringRef Blob;
3997 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3998 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003999 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004000}
4001
4002namespace {
4003 class SimplePCHValidator : public ASTReaderListener {
4004 const LangOptions &ExistingLangOpts;
4005 const TargetOptions &ExistingTargetOpts;
4006 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004007 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004008 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004009
Guy Benyei11169dd2012-12-18 14:30:41 +00004010 public:
4011 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4012 const TargetOptions &ExistingTargetOpts,
4013 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004014 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004015 FileManager &FileMgr)
4016 : ExistingLangOpts(ExistingLangOpts),
4017 ExistingTargetOpts(ExistingTargetOpts),
4018 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004019 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004020 FileMgr(FileMgr)
4021 {
4022 }
4023
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004024 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4025 bool AllowCompatibleDifferences) override {
4026 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4027 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004028 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004029 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4030 bool AllowCompatibleDifferences) override {
4031 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4032 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004033 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004034 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4035 StringRef SpecificModuleCachePath,
4036 bool Complain) override {
4037 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4038 ExistingModuleCachePath,
4039 nullptr, ExistingLangOpts);
4040 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004041 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4042 bool Complain,
4043 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004044 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004045 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 }
4047 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004048}
Guy Benyei11169dd2012-12-18 14:30:41 +00004049
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004050bool ASTReader::readASTFileControlBlock(
4051 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004052 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004053 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004054 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004055 // FIXME: This allows use of the VFS; we do not allow use of the
4056 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004057 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004058 if (!Buffer) {
4059 return true;
4060 }
4061
4062 // Initialize the stream
4063 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004064 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004065 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004066
4067 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004068 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004069 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004070
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004071 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004072 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004073 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004074
4075 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004076 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004077 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004078 BitstreamCursor InputFilesCursor;
4079 if (NeedsInputFiles) {
4080 InputFilesCursor = Stream;
4081 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4082 return true;
4083
4084 // Read the abbreviations
4085 while (true) {
4086 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4087 unsigned Code = InputFilesCursor.ReadCode();
4088
4089 // We expect all abbrevs to be at the start of the block.
4090 if (Code != llvm::bitc::DEFINE_ABBREV) {
4091 InputFilesCursor.JumpToBit(Offset);
4092 break;
4093 }
4094 InputFilesCursor.ReadAbbrevRecord();
4095 }
4096 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004097
4098 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004099 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004100 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004101 while (1) {
4102 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4103 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4104 return false;
4105
4106 if (Entry.Kind != llvm::BitstreamEntry::Record)
4107 return true;
4108
Guy Benyei11169dd2012-12-18 14:30:41 +00004109 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004110 StringRef Blob;
4111 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004112 switch ((ControlRecordTypes)RecCode) {
4113 case METADATA: {
4114 if (Record[0] != VERSION_MAJOR)
4115 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004116
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004117 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004118 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004119
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004120 break;
4121 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004122 case MODULE_NAME:
4123 Listener.ReadModuleName(Blob);
4124 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004125 case MODULE_DIRECTORY:
4126 ModuleDir = Blob;
4127 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004128 case MODULE_MAP_FILE: {
4129 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004130 auto Path = ReadString(Record, Idx);
4131 ResolveImportedPath(Path, ModuleDir);
4132 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004133 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004134 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004135 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004136 if (ParseLanguageOptions(Record, false, Listener,
4137 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004138 return true;
4139 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004140
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004141 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004142 if (ParseTargetOptions(Record, false, Listener,
4143 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004144 return true;
4145 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004146
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004147 case DIAGNOSTIC_OPTIONS:
4148 if (ParseDiagnosticOptions(Record, false, Listener))
4149 return true;
4150 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004151
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004152 case FILE_SYSTEM_OPTIONS:
4153 if (ParseFileSystemOptions(Record, false, Listener))
4154 return true;
4155 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004156
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004157 case HEADER_SEARCH_OPTIONS:
4158 if (ParseHeaderSearchOptions(Record, false, Listener))
4159 return true;
4160 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004161
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004162 case PREPROCESSOR_OPTIONS: {
4163 std::string IgnoredSuggestedPredefines;
4164 if (ParsePreprocessorOptions(Record, false, Listener,
4165 IgnoredSuggestedPredefines))
4166 return true;
4167 break;
4168 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004169
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004170 case INPUT_FILE_OFFSETS: {
4171 if (!NeedsInputFiles)
4172 break;
4173
4174 unsigned NumInputFiles = Record[0];
4175 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004176 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004177 for (unsigned I = 0; I != NumInputFiles; ++I) {
4178 // Go find this input file.
4179 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004180
4181 if (isSystemFile && !NeedsSystemInputFiles)
4182 break; // the rest are system input files
4183
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004184 BitstreamCursor &Cursor = InputFilesCursor;
4185 SavedStreamPosition SavedPosition(Cursor);
4186 Cursor.JumpToBit(InputFileOffs[I]);
4187
4188 unsigned Code = Cursor.ReadCode();
4189 RecordData Record;
4190 StringRef Blob;
4191 bool shouldContinue = false;
4192 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4193 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004194 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004195 std::string Filename = Blob;
4196 ResolveImportedPath(Filename, ModuleDir);
4197 shouldContinue =
4198 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004199 break;
4200 }
4201 if (!shouldContinue)
4202 break;
4203 }
4204 break;
4205 }
4206
Richard Smithd4b230b2014-10-27 23:01:16 +00004207 case IMPORTS: {
4208 if (!NeedsImports)
4209 break;
4210
4211 unsigned Idx = 0, N = Record.size();
4212 while (Idx < N) {
4213 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004214 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004215 std::string Filename = ReadString(Record, Idx);
4216 ResolveImportedPath(Filename, ModuleDir);
4217 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004218 }
4219 break;
4220 }
4221
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004222 default:
4223 // No other validation to perform.
4224 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004225 }
4226 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004227}
4228
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004229bool ASTReader::isAcceptableASTFile(
4230 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004231 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004232 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4233 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004234 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4235 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004236 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004237 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004238}
4239
Ben Langmuir2c9af442014-04-10 17:57:43 +00004240ASTReader::ASTReadResult
4241ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004242 // Enter the submodule block.
4243 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4244 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004245 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004246 }
4247
4248 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4249 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004250 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004251 RecordData Record;
4252 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004253 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4254
4255 switch (Entry.Kind) {
4256 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4257 case llvm::BitstreamEntry::Error:
4258 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004259 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004260 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004261 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004262 case llvm::BitstreamEntry::Record:
4263 // The interesting case.
4264 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004265 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004266
Guy Benyei11169dd2012-12-18 14:30:41 +00004267 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004268 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004270 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4271
4272 if ((Kind == SUBMODULE_METADATA) != First) {
4273 Error("submodule metadata record should be at beginning of block");
4274 return Failure;
4275 }
4276 First = false;
4277
4278 // Submodule information is only valid if we have a current module.
4279 // FIXME: Should we error on these cases?
4280 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4281 Kind != SUBMODULE_DEFINITION)
4282 continue;
4283
4284 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004285 default: // Default behavior: ignore.
4286 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004287
Richard Smith03478d92014-10-23 22:12:14 +00004288 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004289 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004291 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004292 }
Richard Smith03478d92014-10-23 22:12:14 +00004293
Chris Lattner0e6c9402013-01-20 02:38:54 +00004294 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004295 unsigned Idx = 0;
4296 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4297 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4298 bool IsFramework = Record[Idx++];
4299 bool IsExplicit = Record[Idx++];
4300 bool IsSystem = Record[Idx++];
4301 bool IsExternC = Record[Idx++];
4302 bool InferSubmodules = Record[Idx++];
4303 bool InferExplicitSubmodules = Record[Idx++];
4304 bool InferExportWildcard = Record[Idx++];
4305 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004306
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004307 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004308 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004309 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004310
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 // Retrieve this (sub)module from the module map, creating it if
4312 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004313 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004314 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004315
4316 // FIXME: set the definition loc for CurrentModule, or call
4317 // ModMap.setInferredModuleAllowedBy()
4318
Guy Benyei11169dd2012-12-18 14:30:41 +00004319 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4320 if (GlobalIndex >= SubmodulesLoaded.size() ||
4321 SubmodulesLoaded[GlobalIndex]) {
4322 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004323 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004324 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004325
Douglas Gregor7029ce12013-03-19 00:28:20 +00004326 if (!ParentModule) {
4327 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4328 if (CurFile != F.File) {
4329 if (!Diags.isDiagnosticInFlight()) {
4330 Diag(diag::err_module_file_conflict)
4331 << CurrentModule->getTopLevelModuleName()
4332 << CurFile->getName()
4333 << F.File->getName();
4334 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004335 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004336 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004337 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004338
4339 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004340 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004341
Adrian Prantl15bcf702015-06-30 17:39:43 +00004342 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004343 CurrentModule->IsFromModuleFile = true;
4344 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004345 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004346 CurrentModule->InferSubmodules = InferSubmodules;
4347 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4348 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004349 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004350 if (DeserializationListener)
4351 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4352
4353 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004354
Douglas Gregorfb912652013-03-20 21:10:35 +00004355 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004356 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004357 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004358 CurrentModule->UnresolvedConflicts.clear();
4359 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004360 break;
4361 }
4362
4363 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004364 std::string Filename = Blob;
4365 ResolveImportedPath(F, Filename);
4366 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004368 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4369 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004370 // This can be a spurious difference caused by changing the VFS to
4371 // point to a different copy of the file, and it is too late to
4372 // to rebuild safely.
4373 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4374 // after input file validation only real problems would remain and we
4375 // could just error. For now, assume it's okay.
4376 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004377 }
4378 }
4379 break;
4380 }
4381
Richard Smith202210b2014-10-24 20:23:01 +00004382 case SUBMODULE_HEADER:
4383 case SUBMODULE_EXCLUDED_HEADER:
4384 case SUBMODULE_PRIVATE_HEADER:
4385 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004386 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4387 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004388 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004389
Richard Smith202210b2014-10-24 20:23:01 +00004390 case SUBMODULE_TEXTUAL_HEADER:
4391 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4392 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4393 // them here.
4394 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004395
Guy Benyei11169dd2012-12-18 14:30:41 +00004396 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004397 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004398 break;
4399 }
4400
4401 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004402 std::string Dirname = Blob;
4403 ResolveImportedPath(F, Dirname);
4404 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004405 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004406 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4407 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004408 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4409 Error("mismatched umbrella directories in submodule");
4410 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004411 }
4412 }
4413 break;
4414 }
4415
4416 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004417 F.BaseSubmoduleID = getTotalNumSubmodules();
4418 F.LocalNumSubmodules = Record[0];
4419 unsigned LocalBaseSubmoduleID = Record[1];
4420 if (F.LocalNumSubmodules > 0) {
4421 // Introduce the global -> local mapping for submodules within this
4422 // module.
4423 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4424
4425 // Introduce the local -> global mapping for submodules within this
4426 // module.
4427 F.SubmoduleRemap.insertOrReplace(
4428 std::make_pair(LocalBaseSubmoduleID,
4429 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004430
Ben Langmuir52ca6782014-10-20 16:27:32 +00004431 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4432 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 break;
4434 }
4435
4436 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004437 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004438 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 Unresolved.File = &F;
4440 Unresolved.Mod = CurrentModule;
4441 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004442 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004444 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 }
4446 break;
4447 }
4448
4449 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004450 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004451 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004452 Unresolved.File = &F;
4453 Unresolved.Mod = CurrentModule;
4454 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004455 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004456 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004457 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 }
4459
4460 // Once we've loaded the set of exports, there's no reason to keep
4461 // the parsed, unresolved exports around.
4462 CurrentModule->UnresolvedExports.clear();
4463 break;
4464 }
4465 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004466 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004467 Context.getTargetInfo());
4468 break;
4469 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004470
4471 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004472 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004473 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004474 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004475
4476 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004477 CurrentModule->ConfigMacros.push_back(Blob.str());
4478 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004479
4480 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004481 UnresolvedModuleRef Unresolved;
4482 Unresolved.File = &F;
4483 Unresolved.Mod = CurrentModule;
4484 Unresolved.ID = Record[0];
4485 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4486 Unresolved.IsWildcard = false;
4487 Unresolved.String = Blob;
4488 UnresolvedModuleRefs.push_back(Unresolved);
4489 break;
4490 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004491 }
4492 }
4493}
4494
4495/// \brief Parse the record that corresponds to a LangOptions data
4496/// structure.
4497///
4498/// This routine parses the language options from the AST file and then gives
4499/// them to the AST listener if one is set.
4500///
4501/// \returns true if the listener deems the file unacceptable, false otherwise.
4502bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4503 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004504 ASTReaderListener &Listener,
4505 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 LangOptions LangOpts;
4507 unsigned Idx = 0;
4508#define LANGOPT(Name, Bits, Default, Description) \
4509 LangOpts.Name = Record[Idx++];
4510#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4511 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4512#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004513#define SANITIZER(NAME, ID) \
4514 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004515#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004516
Ben Langmuircd98cb72015-06-23 18:20:18 +00004517 for (unsigned N = Record[Idx++]; N; --N)
4518 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4519
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4521 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4522 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004523
Ben Langmuird4a667a2015-06-23 18:20:23 +00004524 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004525
4526 // Comment options.
4527 for (unsigned N = Record[Idx++]; N; --N) {
4528 LangOpts.CommentOpts.BlockCommandNames.push_back(
4529 ReadString(Record, Idx));
4530 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004531 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004532
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004533 return Listener.ReadLanguageOptions(LangOpts, Complain,
4534 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004535}
4536
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004537bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4538 ASTReaderListener &Listener,
4539 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004540 unsigned Idx = 0;
4541 TargetOptions TargetOpts;
4542 TargetOpts.Triple = ReadString(Record, Idx);
4543 TargetOpts.CPU = ReadString(Record, Idx);
4544 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 for (unsigned N = Record[Idx++]; N; --N) {
4546 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4547 }
4548 for (unsigned N = Record[Idx++]; N; --N) {
4549 TargetOpts.Features.push_back(ReadString(Record, Idx));
4550 }
4551
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004552 return Listener.ReadTargetOptions(TargetOpts, Complain,
4553 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004554}
4555
4556bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4557 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004558 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004559 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004560#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004561#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004562 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004563#include "clang/Basic/DiagnosticOptions.def"
4564
Richard Smith3be1cb22014-08-07 00:24:21 +00004565 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004566 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004567 for (unsigned N = Record[Idx++]; N; --N)
4568 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004569
4570 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4571}
4572
4573bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4574 ASTReaderListener &Listener) {
4575 FileSystemOptions FSOpts;
4576 unsigned Idx = 0;
4577 FSOpts.WorkingDir = ReadString(Record, Idx);
4578 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4579}
4580
4581bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4582 bool Complain,
4583 ASTReaderListener &Listener) {
4584 HeaderSearchOptions HSOpts;
4585 unsigned Idx = 0;
4586 HSOpts.Sysroot = ReadString(Record, Idx);
4587
4588 // Include entries.
4589 for (unsigned N = Record[Idx++]; N; --N) {
4590 std::string Path = ReadString(Record, Idx);
4591 frontend::IncludeDirGroup Group
4592 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004593 bool IsFramework = Record[Idx++];
4594 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004595 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4596 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004597 }
4598
4599 // System header prefixes.
4600 for (unsigned N = Record[Idx++]; N; --N) {
4601 std::string Prefix = ReadString(Record, Idx);
4602 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004603 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004604 }
4605
4606 HSOpts.ResourceDir = ReadString(Record, Idx);
4607 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004608 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004609 HSOpts.DisableModuleHash = Record[Idx++];
4610 HSOpts.UseBuiltinIncludes = Record[Idx++];
4611 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4612 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4613 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004614 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004615
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004616 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4617 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004618}
4619
4620bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4621 bool Complain,
4622 ASTReaderListener &Listener,
4623 std::string &SuggestedPredefines) {
4624 PreprocessorOptions PPOpts;
4625 unsigned Idx = 0;
4626
4627 // Macro definitions/undefs
4628 for (unsigned N = Record[Idx++]; N; --N) {
4629 std::string Macro = ReadString(Record, Idx);
4630 bool IsUndef = Record[Idx++];
4631 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4632 }
4633
4634 // Includes
4635 for (unsigned N = Record[Idx++]; N; --N) {
4636 PPOpts.Includes.push_back(ReadString(Record, Idx));
4637 }
4638
4639 // Macro Includes
4640 for (unsigned N = Record[Idx++]; N; --N) {
4641 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4642 }
4643
4644 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004645 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004646 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4647 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4648 PPOpts.ObjCXXARCStandardLibrary =
4649 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4650 SuggestedPredefines.clear();
4651 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4652 SuggestedPredefines);
4653}
4654
4655std::pair<ModuleFile *, unsigned>
4656ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4657 GlobalPreprocessedEntityMapType::iterator
4658 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4659 assert(I != GlobalPreprocessedEntityMap.end() &&
4660 "Corrupted global preprocessed entity map");
4661 ModuleFile *M = I->second;
4662 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4663 return std::make_pair(M, LocalIndex);
4664}
4665
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004666llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004667ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4668 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4669 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4670 Mod.NumPreprocessedEntities);
4671
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004672 return llvm::make_range(PreprocessingRecord::iterator(),
4673 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004674}
4675
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004676llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004677ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004678 return llvm::make_range(
4679 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4680 ModuleDeclIterator(this, &Mod,
4681 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004682}
4683
4684PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4685 PreprocessedEntityID PPID = Index+1;
4686 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4687 ModuleFile &M = *PPInfo.first;
4688 unsigned LocalIndex = PPInfo.second;
4689 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4690
Guy Benyei11169dd2012-12-18 14:30:41 +00004691 if (!PP.getPreprocessingRecord()) {
4692 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004693 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004694 }
4695
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004696 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4697 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4698
4699 llvm::BitstreamEntry Entry =
4700 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4701 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004702 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004703
Guy Benyei11169dd2012-12-18 14:30:41 +00004704 // Read the record.
4705 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4706 ReadSourceLocation(M, PPOffs.End));
4707 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004708 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004709 RecordData Record;
4710 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004711 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4712 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004713 switch (RecType) {
4714 case PPD_MACRO_EXPANSION: {
4715 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004716 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004717 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004718 if (isBuiltin)
4719 Name = getLocalIdentifier(M, Record[1]);
4720 else {
Richard Smith66a81862015-05-04 02:25:31 +00004721 PreprocessedEntityID GlobalID =
4722 getGlobalPreprocessedEntityID(M, Record[1]);
4723 Def = cast<MacroDefinitionRecord>(
4724 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004725 }
4726
4727 MacroExpansion *ME;
4728 if (isBuiltin)
4729 ME = new (PPRec) MacroExpansion(Name, Range);
4730 else
4731 ME = new (PPRec) MacroExpansion(Def, Range);
4732
4733 return ME;
4734 }
4735
4736 case PPD_MACRO_DEFINITION: {
4737 // Decode the identifier info and then check again; if the macro is
4738 // still defined and associated with the identifier,
4739 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004740 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004741
4742 if (DeserializationListener)
4743 DeserializationListener->MacroDefinitionRead(PPID, MD);
4744
4745 return MD;
4746 }
4747
4748 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004749 const char *FullFileNameStart = Blob.data() + Record[0];
4750 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004751 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004752 if (!FullFileName.empty())
4753 File = PP.getFileManager().getFile(FullFileName);
4754
4755 // FIXME: Stable encoding
4756 InclusionDirective::InclusionKind Kind
4757 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4758 InclusionDirective *ID
4759 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004760 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004761 Record[1], Record[3],
4762 File,
4763 Range);
4764 return ID;
4765 }
4766 }
4767
4768 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4769}
4770
4771/// \brief \arg SLocMapI points at a chunk of a module that contains no
4772/// preprocessed entities or the entities it contains are not the ones we are
4773/// looking for. Find the next module that contains entities and return the ID
4774/// of the first entry.
4775PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4776 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4777 ++SLocMapI;
4778 for (GlobalSLocOffsetMapType::const_iterator
4779 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4780 ModuleFile &M = *SLocMapI->second;
4781 if (M.NumPreprocessedEntities)
4782 return M.BasePreprocessedEntityID;
4783 }
4784
4785 return getTotalNumPreprocessedEntities();
4786}
4787
4788namespace {
4789
4790template <unsigned PPEntityOffset::*PPLoc>
4791struct PPEntityComp {
4792 const ASTReader &Reader;
4793 ModuleFile &M;
4794
4795 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4796
4797 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4798 SourceLocation LHS = getLoc(L);
4799 SourceLocation RHS = getLoc(R);
4800 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4801 }
4802
4803 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4804 SourceLocation LHS = getLoc(L);
4805 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4806 }
4807
4808 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4809 SourceLocation RHS = getLoc(R);
4810 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4811 }
4812
4813 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4814 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4815 }
4816};
4817
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004818}
Guy Benyei11169dd2012-12-18 14:30:41 +00004819
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004820PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4821 bool EndsAfter) const {
4822 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004823 return getTotalNumPreprocessedEntities();
4824
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004825 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4826 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004827 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4828 "Corrupted global sloc offset map");
4829
4830 if (SLocMapI->second->NumPreprocessedEntities == 0)
4831 return findNextPreprocessedEntity(SLocMapI);
4832
4833 ModuleFile &M = *SLocMapI->second;
4834 typedef const PPEntityOffset *pp_iterator;
4835 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4836 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4837
4838 size_t Count = M.NumPreprocessedEntities;
4839 size_t Half;
4840 pp_iterator First = pp_begin;
4841 pp_iterator PPI;
4842
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004843 if (EndsAfter) {
4844 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4845 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4846 } else {
4847 // Do a binary search manually instead of using std::lower_bound because
4848 // The end locations of entities may be unordered (when a macro expansion
4849 // is inside another macro argument), but for this case it is not important
4850 // whether we get the first macro expansion or its containing macro.
4851 while (Count > 0) {
4852 Half = Count / 2;
4853 PPI = First;
4854 std::advance(PPI, Half);
4855 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4856 Loc)) {
4857 First = PPI;
4858 ++First;
4859 Count = Count - Half - 1;
4860 } else
4861 Count = Half;
4862 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004863 }
4864
4865 if (PPI == pp_end)
4866 return findNextPreprocessedEntity(SLocMapI);
4867
4868 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4869}
4870
Guy Benyei11169dd2012-12-18 14:30:41 +00004871/// \brief Returns a pair of [Begin, End) indices of preallocated
4872/// preprocessed entities that \arg Range encompasses.
4873std::pair<unsigned, unsigned>
4874 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4875 if (Range.isInvalid())
4876 return std::make_pair(0,0);
4877 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4878
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004879 PreprocessedEntityID BeginID =
4880 findPreprocessedEntity(Range.getBegin(), false);
4881 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004882 return std::make_pair(BeginID, EndID);
4883}
4884
4885/// \brief Optionally returns true or false if the preallocated preprocessed
4886/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004887Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004888 FileID FID) {
4889 if (FID.isInvalid())
4890 return false;
4891
4892 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4893 ModuleFile &M = *PPInfo.first;
4894 unsigned LocalIndex = PPInfo.second;
4895 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4896
4897 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4898 if (Loc.isInvalid())
4899 return false;
4900
4901 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4902 return true;
4903 else
4904 return false;
4905}
4906
4907namespace {
4908 /// \brief Visitor used to search for information about a header file.
4909 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004910 const FileEntry *FE;
4911
David Blaikie05785d12013-02-20 22:23:23 +00004912 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004913
4914 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004915 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4916 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004917
4918 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004919 HeaderFileInfoLookupTable *Table
4920 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4921 if (!Table)
4922 return false;
4923
4924 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00004925 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004926 if (Pos == Table->end())
4927 return false;
4928
Richard Smithbdf2d932015-07-30 03:37:16 +00004929 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00004930 return true;
4931 }
4932
David Blaikie05785d12013-02-20 22:23:23 +00004933 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004934 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004935}
Guy Benyei11169dd2012-12-18 14:30:41 +00004936
4937HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004938 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004939 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004940 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004941 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004942
4943 return HeaderFileInfo();
4944}
4945
4946void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4947 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004948 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004949 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4950 ModuleFile &F = *(*I);
4951 unsigned Idx = 0;
4952 DiagStates.clear();
4953 assert(!Diag.DiagStates.empty());
4954 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4955 while (Idx < F.PragmaDiagMappings.size()) {
4956 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4957 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4958 if (DiagStateID != 0) {
4959 Diag.DiagStatePoints.push_back(
4960 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4961 FullSourceLoc(Loc, SourceMgr)));
4962 continue;
4963 }
4964
4965 assert(DiagStateID == 0);
4966 // A new DiagState was created here.
4967 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4968 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4969 DiagStates.push_back(NewState);
4970 Diag.DiagStatePoints.push_back(
4971 DiagnosticsEngine::DiagStatePoint(NewState,
4972 FullSourceLoc(Loc, SourceMgr)));
4973 while (1) {
4974 assert(Idx < F.PragmaDiagMappings.size() &&
4975 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4976 if (Idx >= F.PragmaDiagMappings.size()) {
4977 break; // Something is messed up but at least avoid infinite loop in
4978 // release build.
4979 }
4980 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4981 if (DiagID == (unsigned)-1) {
4982 break; // no more diag/map pairs for this location.
4983 }
Alp Tokerc726c362014-06-10 09:31:37 +00004984 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4985 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4986 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00004987 }
4988 }
4989 }
4990}
4991
4992/// \brief Get the correct cursor and offset for loading a type.
4993ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4994 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4995 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4996 ModuleFile *M = I->second;
4997 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4998}
4999
5000/// \brief Read and return the type with the given index..
5001///
5002/// The index is the type ID, shifted and minus the number of predefs. This
5003/// routine actually reads the record corresponding to the type at the given
5004/// location. It is a helper routine for GetType, which deals with reading type
5005/// IDs.
5006QualType ASTReader::readTypeRecord(unsigned Index) {
5007 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005008 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005009
5010 // Keep track of where we are in the stream, then jump back there
5011 // after reading this type.
5012 SavedStreamPosition SavedPosition(DeclsCursor);
5013
5014 ReadingKindTracker ReadingKind(Read_Type, *this);
5015
5016 // Note that we are loading a type record.
5017 Deserializing AType(this);
5018
5019 unsigned Idx = 0;
5020 DeclsCursor.JumpToBit(Loc.Offset);
5021 RecordData Record;
5022 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005023 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005024 case TYPE_EXT_QUAL: {
5025 if (Record.size() != 2) {
5026 Error("Incorrect encoding of extended qualifier type");
5027 return QualType();
5028 }
5029 QualType Base = readType(*Loc.F, Record, Idx);
5030 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5031 return Context.getQualifiedType(Base, Quals);
5032 }
5033
5034 case TYPE_COMPLEX: {
5035 if (Record.size() != 1) {
5036 Error("Incorrect encoding of complex type");
5037 return QualType();
5038 }
5039 QualType ElemType = readType(*Loc.F, Record, Idx);
5040 return Context.getComplexType(ElemType);
5041 }
5042
5043 case TYPE_POINTER: {
5044 if (Record.size() != 1) {
5045 Error("Incorrect encoding of pointer type");
5046 return QualType();
5047 }
5048 QualType PointeeType = readType(*Loc.F, Record, Idx);
5049 return Context.getPointerType(PointeeType);
5050 }
5051
Reid Kleckner8a365022013-06-24 17:51:48 +00005052 case TYPE_DECAYED: {
5053 if (Record.size() != 1) {
5054 Error("Incorrect encoding of decayed type");
5055 return QualType();
5056 }
5057 QualType OriginalType = readType(*Loc.F, Record, Idx);
5058 QualType DT = Context.getAdjustedParameterType(OriginalType);
5059 if (!isa<DecayedType>(DT))
5060 Error("Decayed type does not decay");
5061 return DT;
5062 }
5063
Reid Kleckner0503a872013-12-05 01:23:43 +00005064 case TYPE_ADJUSTED: {
5065 if (Record.size() != 2) {
5066 Error("Incorrect encoding of adjusted type");
5067 return QualType();
5068 }
5069 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5070 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5071 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5072 }
5073
Guy Benyei11169dd2012-12-18 14:30:41 +00005074 case TYPE_BLOCK_POINTER: {
5075 if (Record.size() != 1) {
5076 Error("Incorrect encoding of block pointer type");
5077 return QualType();
5078 }
5079 QualType PointeeType = readType(*Loc.F, Record, Idx);
5080 return Context.getBlockPointerType(PointeeType);
5081 }
5082
5083 case TYPE_LVALUE_REFERENCE: {
5084 if (Record.size() != 2) {
5085 Error("Incorrect encoding of lvalue reference type");
5086 return QualType();
5087 }
5088 QualType PointeeType = readType(*Loc.F, Record, Idx);
5089 return Context.getLValueReferenceType(PointeeType, Record[1]);
5090 }
5091
5092 case TYPE_RVALUE_REFERENCE: {
5093 if (Record.size() != 1) {
5094 Error("Incorrect encoding of rvalue reference type");
5095 return QualType();
5096 }
5097 QualType PointeeType = readType(*Loc.F, Record, Idx);
5098 return Context.getRValueReferenceType(PointeeType);
5099 }
5100
5101 case TYPE_MEMBER_POINTER: {
5102 if (Record.size() != 2) {
5103 Error("Incorrect encoding of member pointer type");
5104 return QualType();
5105 }
5106 QualType PointeeType = readType(*Loc.F, Record, Idx);
5107 QualType ClassType = readType(*Loc.F, Record, Idx);
5108 if (PointeeType.isNull() || ClassType.isNull())
5109 return QualType();
5110
5111 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5112 }
5113
5114 case TYPE_CONSTANT_ARRAY: {
5115 QualType ElementType = readType(*Loc.F, Record, Idx);
5116 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5117 unsigned IndexTypeQuals = Record[2];
5118 unsigned Idx = 3;
5119 llvm::APInt Size = ReadAPInt(Record, Idx);
5120 return Context.getConstantArrayType(ElementType, Size,
5121 ASM, IndexTypeQuals);
5122 }
5123
5124 case TYPE_INCOMPLETE_ARRAY: {
5125 QualType ElementType = readType(*Loc.F, Record, Idx);
5126 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5127 unsigned IndexTypeQuals = Record[2];
5128 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5129 }
5130
5131 case TYPE_VARIABLE_ARRAY: {
5132 QualType ElementType = readType(*Loc.F, Record, Idx);
5133 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5134 unsigned IndexTypeQuals = Record[2];
5135 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5136 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5137 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5138 ASM, IndexTypeQuals,
5139 SourceRange(LBLoc, RBLoc));
5140 }
5141
5142 case TYPE_VECTOR: {
5143 if (Record.size() != 3) {
5144 Error("incorrect encoding of vector type in AST file");
5145 return QualType();
5146 }
5147
5148 QualType ElementType = readType(*Loc.F, Record, Idx);
5149 unsigned NumElements = Record[1];
5150 unsigned VecKind = Record[2];
5151 return Context.getVectorType(ElementType, NumElements,
5152 (VectorType::VectorKind)VecKind);
5153 }
5154
5155 case TYPE_EXT_VECTOR: {
5156 if (Record.size() != 3) {
5157 Error("incorrect encoding of extended vector type in AST file");
5158 return QualType();
5159 }
5160
5161 QualType ElementType = readType(*Loc.F, Record, Idx);
5162 unsigned NumElements = Record[1];
5163 return Context.getExtVectorType(ElementType, NumElements);
5164 }
5165
5166 case TYPE_FUNCTION_NO_PROTO: {
5167 if (Record.size() != 6) {
5168 Error("incorrect encoding of no-proto function type");
5169 return QualType();
5170 }
5171 QualType ResultType = readType(*Loc.F, Record, Idx);
5172 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5173 (CallingConv)Record[4], Record[5]);
5174 return Context.getFunctionNoProtoType(ResultType, Info);
5175 }
5176
5177 case TYPE_FUNCTION_PROTO: {
5178 QualType ResultType = readType(*Loc.F, Record, Idx);
5179
5180 FunctionProtoType::ExtProtoInfo EPI;
5181 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5182 /*hasregparm*/ Record[2],
5183 /*regparm*/ Record[3],
5184 static_cast<CallingConv>(Record[4]),
5185 /*produces*/ Record[5]);
5186
5187 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005188
5189 EPI.Variadic = Record[Idx++];
5190 EPI.HasTrailingReturn = Record[Idx++];
5191 EPI.TypeQuals = Record[Idx++];
5192 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005193 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005194 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005195
5196 unsigned NumParams = Record[Idx++];
5197 SmallVector<QualType, 16> ParamTypes;
5198 for (unsigned I = 0; I != NumParams; ++I)
5199 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5200
Jordan Rose5c382722013-03-08 21:51:21 +00005201 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 }
5203
5204 case TYPE_UNRESOLVED_USING: {
5205 unsigned Idx = 0;
5206 return Context.getTypeDeclType(
5207 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5208 }
5209
5210 case TYPE_TYPEDEF: {
5211 if (Record.size() != 2) {
5212 Error("incorrect encoding of typedef type");
5213 return QualType();
5214 }
5215 unsigned Idx = 0;
5216 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5217 QualType Canonical = readType(*Loc.F, Record, Idx);
5218 if (!Canonical.isNull())
5219 Canonical = Context.getCanonicalType(Canonical);
5220 return Context.getTypedefType(Decl, Canonical);
5221 }
5222
5223 case TYPE_TYPEOF_EXPR:
5224 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5225
5226 case TYPE_TYPEOF: {
5227 if (Record.size() != 1) {
5228 Error("incorrect encoding of typeof(type) in AST file");
5229 return QualType();
5230 }
5231 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5232 return Context.getTypeOfType(UnderlyingType);
5233 }
5234
5235 case TYPE_DECLTYPE: {
5236 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5237 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5238 }
5239
5240 case TYPE_UNARY_TRANSFORM: {
5241 QualType BaseType = readType(*Loc.F, Record, Idx);
5242 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5243 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5244 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5245 }
5246
Richard Smith74aeef52013-04-26 16:15:35 +00005247 case TYPE_AUTO: {
5248 QualType Deduced = readType(*Loc.F, Record, Idx);
5249 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005250 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005251 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005252 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005253
5254 case TYPE_RECORD: {
5255 if (Record.size() != 2) {
5256 Error("incorrect encoding of record type");
5257 return QualType();
5258 }
5259 unsigned Idx = 0;
5260 bool IsDependent = Record[Idx++];
5261 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5262 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5263 QualType T = Context.getRecordType(RD);
5264 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5265 return T;
5266 }
5267
5268 case TYPE_ENUM: {
5269 if (Record.size() != 2) {
5270 Error("incorrect encoding of enum type");
5271 return QualType();
5272 }
5273 unsigned Idx = 0;
5274 bool IsDependent = Record[Idx++];
5275 QualType T
5276 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5277 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5278 return T;
5279 }
5280
5281 case TYPE_ATTRIBUTED: {
5282 if (Record.size() != 3) {
5283 Error("incorrect encoding of attributed type");
5284 return QualType();
5285 }
5286 QualType modifiedType = readType(*Loc.F, Record, Idx);
5287 QualType equivalentType = readType(*Loc.F, Record, Idx);
5288 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5289 return Context.getAttributedType(kind, modifiedType, equivalentType);
5290 }
5291
5292 case TYPE_PAREN: {
5293 if (Record.size() != 1) {
5294 Error("incorrect encoding of paren type");
5295 return QualType();
5296 }
5297 QualType InnerType = readType(*Loc.F, Record, Idx);
5298 return Context.getParenType(InnerType);
5299 }
5300
5301 case TYPE_PACK_EXPANSION: {
5302 if (Record.size() != 2) {
5303 Error("incorrect encoding of pack expansion type");
5304 return QualType();
5305 }
5306 QualType Pattern = readType(*Loc.F, Record, Idx);
5307 if (Pattern.isNull())
5308 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005309 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 if (Record[1])
5311 NumExpansions = Record[1] - 1;
5312 return Context.getPackExpansionType(Pattern, NumExpansions);
5313 }
5314
5315 case TYPE_ELABORATED: {
5316 unsigned Idx = 0;
5317 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5318 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5319 QualType NamedType = readType(*Loc.F, Record, Idx);
5320 return Context.getElaboratedType(Keyword, NNS, NamedType);
5321 }
5322
5323 case TYPE_OBJC_INTERFACE: {
5324 unsigned Idx = 0;
5325 ObjCInterfaceDecl *ItfD
5326 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5327 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5328 }
5329
5330 case TYPE_OBJC_OBJECT: {
5331 unsigned Idx = 0;
5332 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005333 unsigned NumTypeArgs = Record[Idx++];
5334 SmallVector<QualType, 4> TypeArgs;
5335 for (unsigned I = 0; I != NumTypeArgs; ++I)
5336 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005337 unsigned NumProtos = Record[Idx++];
5338 SmallVector<ObjCProtocolDecl*, 4> Protos;
5339 for (unsigned I = 0; I != NumProtos; ++I)
5340 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005341 bool IsKindOf = Record[Idx++];
5342 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005343 }
5344
5345 case TYPE_OBJC_OBJECT_POINTER: {
5346 unsigned Idx = 0;
5347 QualType Pointee = readType(*Loc.F, Record, Idx);
5348 return Context.getObjCObjectPointerType(Pointee);
5349 }
5350
5351 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5352 unsigned Idx = 0;
5353 QualType Parm = readType(*Loc.F, Record, Idx);
5354 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005355 return Context.getSubstTemplateTypeParmType(
5356 cast<TemplateTypeParmType>(Parm),
5357 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005358 }
5359
5360 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5361 unsigned Idx = 0;
5362 QualType Parm = readType(*Loc.F, Record, Idx);
5363 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5364 return Context.getSubstTemplateTypeParmPackType(
5365 cast<TemplateTypeParmType>(Parm),
5366 ArgPack);
5367 }
5368
5369 case TYPE_INJECTED_CLASS_NAME: {
5370 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5371 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5372 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5373 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005374 const Type *T = nullptr;
5375 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5376 if (const Type *Existing = DI->getTypeForDecl()) {
5377 T = Existing;
5378 break;
5379 }
5380 }
5381 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005382 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005383 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5384 DI->setTypeForDecl(T);
5385 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005386 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005387 }
5388
5389 case TYPE_TEMPLATE_TYPE_PARM: {
5390 unsigned Idx = 0;
5391 unsigned Depth = Record[Idx++];
5392 unsigned Index = Record[Idx++];
5393 bool Pack = Record[Idx++];
5394 TemplateTypeParmDecl *D
5395 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5396 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5397 }
5398
5399 case TYPE_DEPENDENT_NAME: {
5400 unsigned Idx = 0;
5401 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5402 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005403 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005404 QualType Canon = readType(*Loc.F, Record, Idx);
5405 if (!Canon.isNull())
5406 Canon = Context.getCanonicalType(Canon);
5407 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5408 }
5409
5410 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5411 unsigned Idx = 0;
5412 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5413 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005414 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005415 unsigned NumArgs = Record[Idx++];
5416 SmallVector<TemplateArgument, 8> Args;
5417 Args.reserve(NumArgs);
5418 while (NumArgs--)
5419 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5420 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5421 Args.size(), Args.data());
5422 }
5423
5424 case TYPE_DEPENDENT_SIZED_ARRAY: {
5425 unsigned Idx = 0;
5426
5427 // ArrayType
5428 QualType ElementType = readType(*Loc.F, Record, Idx);
5429 ArrayType::ArraySizeModifier ASM
5430 = (ArrayType::ArraySizeModifier)Record[Idx++];
5431 unsigned IndexTypeQuals = Record[Idx++];
5432
5433 // DependentSizedArrayType
5434 Expr *NumElts = ReadExpr(*Loc.F);
5435 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5436
5437 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5438 IndexTypeQuals, Brackets);
5439 }
5440
5441 case TYPE_TEMPLATE_SPECIALIZATION: {
5442 unsigned Idx = 0;
5443 bool IsDependent = Record[Idx++];
5444 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5445 SmallVector<TemplateArgument, 8> Args;
5446 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5447 QualType Underlying = readType(*Loc.F, Record, Idx);
5448 QualType T;
5449 if (Underlying.isNull())
5450 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5451 Args.size());
5452 else
5453 T = Context.getTemplateSpecializationType(Name, Args.data(),
5454 Args.size(), Underlying);
5455 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5456 return T;
5457 }
5458
5459 case TYPE_ATOMIC: {
5460 if (Record.size() != 1) {
5461 Error("Incorrect encoding of atomic type");
5462 return QualType();
5463 }
5464 QualType ValueType = readType(*Loc.F, Record, Idx);
5465 return Context.getAtomicType(ValueType);
5466 }
5467 }
5468 llvm_unreachable("Invalid TypeCode!");
5469}
5470
Richard Smith564417a2014-03-20 21:47:22 +00005471void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5472 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005473 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005474 const RecordData &Record, unsigned &Idx) {
5475 ExceptionSpecificationType EST =
5476 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005477 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005478 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005479 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005480 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005481 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005482 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005483 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005484 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005485 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5486 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005487 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005488 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005489 }
5490}
5491
Guy Benyei11169dd2012-12-18 14:30:41 +00005492class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5493 ASTReader &Reader;
5494 ModuleFile &F;
5495 const ASTReader::RecordData &Record;
5496 unsigned &Idx;
5497
5498 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5499 unsigned &I) {
5500 return Reader.ReadSourceLocation(F, R, I);
5501 }
5502
5503 template<typename T>
5504 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5505 return Reader.ReadDeclAs<T>(F, Record, Idx);
5506 }
5507
5508public:
5509 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5510 const ASTReader::RecordData &Record, unsigned &Idx)
5511 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5512 { }
5513
5514 // We want compile-time assurance that we've enumerated all of
5515 // these, so unfortunately we have to declare them first, then
5516 // define them out-of-line.
5517#define ABSTRACT_TYPELOC(CLASS, PARENT)
5518#define TYPELOC(CLASS, PARENT) \
5519 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5520#include "clang/AST/TypeLocNodes.def"
5521
5522 void VisitFunctionTypeLoc(FunctionTypeLoc);
5523 void VisitArrayTypeLoc(ArrayTypeLoc);
5524};
5525
5526void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5527 // nothing to do
5528}
5529void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5530 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5531 if (TL.needsExtraLocalData()) {
5532 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5533 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5534 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5535 TL.setModeAttr(Record[Idx++]);
5536 }
5537}
5538void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5539 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5540}
5541void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5542 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5543}
Reid Kleckner8a365022013-06-24 17:51:48 +00005544void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5545 // nothing to do
5546}
Reid Kleckner0503a872013-12-05 01:23:43 +00005547void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5548 // nothing to do
5549}
Guy Benyei11169dd2012-12-18 14:30:41 +00005550void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5551 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5552}
5553void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5554 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5555}
5556void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5557 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5558}
5559void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5560 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5561 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5562}
5563void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5564 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5565 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5566 if (Record[Idx++])
5567 TL.setSizeExpr(Reader.ReadExpr(F));
5568 else
Craig Toppera13603a2014-05-22 05:54:18 +00005569 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005570}
5571void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5572 VisitArrayTypeLoc(TL);
5573}
5574void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5575 VisitArrayTypeLoc(TL);
5576}
5577void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5578 VisitArrayTypeLoc(TL);
5579}
5580void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5581 DependentSizedArrayTypeLoc TL) {
5582 VisitArrayTypeLoc(TL);
5583}
5584void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5585 DependentSizedExtVectorTypeLoc TL) {
5586 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5587}
5588void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5589 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5590}
5591void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5592 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5593}
5594void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5595 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5596 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5597 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5598 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005599 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5600 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005601 }
5602}
5603void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5604 VisitFunctionTypeLoc(TL);
5605}
5606void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5607 VisitFunctionTypeLoc(TL);
5608}
5609void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5610 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5611}
5612void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5613 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5614}
5615void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5616 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5617 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5618 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5619}
5620void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5621 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5622 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5623 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5624 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5625}
5626void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5627 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5628}
5629void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5630 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5631 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5632 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5633 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5634}
5635void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5636 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5637}
5638void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5639 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5640}
5641void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5642 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5643}
5644void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5645 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5646 if (TL.hasAttrOperand()) {
5647 SourceRange range;
5648 range.setBegin(ReadSourceLocation(Record, Idx));
5649 range.setEnd(ReadSourceLocation(Record, Idx));
5650 TL.setAttrOperandParensRange(range);
5651 }
5652 if (TL.hasAttrExprOperand()) {
5653 if (Record[Idx++])
5654 TL.setAttrExprOperand(Reader.ReadExpr(F));
5655 else
Craig Toppera13603a2014-05-22 05:54:18 +00005656 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005657 } else if (TL.hasAttrEnumOperand())
5658 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5659}
5660void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5661 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5662}
5663void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5664 SubstTemplateTypeParmTypeLoc TL) {
5665 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5666}
5667void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5668 SubstTemplateTypeParmPackTypeLoc TL) {
5669 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5670}
5671void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5672 TemplateSpecializationTypeLoc TL) {
5673 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5674 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5675 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5676 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5677 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5678 TL.setArgLocInfo(i,
5679 Reader.GetTemplateArgumentLocInfo(F,
5680 TL.getTypePtr()->getArg(i).getKind(),
5681 Record, Idx));
5682}
5683void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5684 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5685 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5686}
5687void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5688 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5689 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5690}
5691void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5692 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5693}
5694void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5695 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5696 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5697 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5698}
5699void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5700 DependentTemplateSpecializationTypeLoc TL) {
5701 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5702 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5703 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5704 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5705 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5706 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5707 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5708 TL.setArgLocInfo(I,
5709 Reader.GetTemplateArgumentLocInfo(F,
5710 TL.getTypePtr()->getArg(I).getKind(),
5711 Record, Idx));
5712}
5713void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5714 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5715}
5716void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5717 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5718}
5719void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5720 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005721 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5722 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5723 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5724 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5725 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5726 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005727 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5728 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5729}
5730void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5731 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5732}
5733void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5734 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5735 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5736 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5737}
5738
5739TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5740 const RecordData &Record,
5741 unsigned &Idx) {
5742 QualType InfoTy = readType(F, Record, Idx);
5743 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005744 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005745
5746 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5747 TypeLocReader TLR(*this, F, Record, Idx);
5748 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5749 TLR.Visit(TL);
5750 return TInfo;
5751}
5752
5753QualType ASTReader::GetType(TypeID ID) {
5754 unsigned FastQuals = ID & Qualifiers::FastMask;
5755 unsigned Index = ID >> Qualifiers::FastWidth;
5756
5757 if (Index < NUM_PREDEF_TYPE_IDS) {
5758 QualType T;
5759 switch ((PredefinedTypeIDs)Index) {
5760 case PREDEF_TYPE_NULL_ID: return QualType();
5761 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5762 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5763
5764 case PREDEF_TYPE_CHAR_U_ID:
5765 case PREDEF_TYPE_CHAR_S_ID:
5766 // FIXME: Check that the signedness of CharTy is correct!
5767 T = Context.CharTy;
5768 break;
5769
5770 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5771 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5772 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5773 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5774 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5775 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5776 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5777 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5778 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5779 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5780 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5781 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5782 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5783 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5784 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5785 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5786 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5787 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5788 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5789 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5790 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5791 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5792 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5793 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5794 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5795 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5796 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5797 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005798 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5799 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5800 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5801 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5802 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5803 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005804 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005805 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005806 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5807
5808 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5809 T = Context.getAutoRRefDeductType();
5810 break;
5811
5812 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5813 T = Context.ARCUnbridgedCastTy;
5814 break;
5815
Guy Benyei11169dd2012-12-18 14:30:41 +00005816 case PREDEF_TYPE_BUILTIN_FN:
5817 T = Context.BuiltinFnTy;
5818 break;
5819 }
5820
5821 assert(!T.isNull() && "Unknown predefined type");
5822 return T.withFastQualifiers(FastQuals);
5823 }
5824
5825 Index -= NUM_PREDEF_TYPE_IDS;
5826 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5827 if (TypesLoaded[Index].isNull()) {
5828 TypesLoaded[Index] = readTypeRecord(Index);
5829 if (TypesLoaded[Index].isNull())
5830 return QualType();
5831
5832 TypesLoaded[Index]->setFromAST();
5833 if (DeserializationListener)
5834 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5835 TypesLoaded[Index]);
5836 }
5837
5838 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5839}
5840
5841QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5842 return GetType(getGlobalTypeID(F, LocalID));
5843}
5844
5845serialization::TypeID
5846ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5847 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5848 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5849
5850 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5851 return LocalID;
5852
5853 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5854 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5855 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5856
5857 unsigned GlobalIndex = LocalIndex + I->second;
5858 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5859}
5860
5861TemplateArgumentLocInfo
5862ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5863 TemplateArgument::ArgKind Kind,
5864 const RecordData &Record,
5865 unsigned &Index) {
5866 switch (Kind) {
5867 case TemplateArgument::Expression:
5868 return ReadExpr(F);
5869 case TemplateArgument::Type:
5870 return GetTypeSourceInfo(F, Record, Index);
5871 case TemplateArgument::Template: {
5872 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5873 Index);
5874 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5875 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5876 SourceLocation());
5877 }
5878 case TemplateArgument::TemplateExpansion: {
5879 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5880 Index);
5881 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5882 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5883 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5884 EllipsisLoc);
5885 }
5886 case TemplateArgument::Null:
5887 case TemplateArgument::Integral:
5888 case TemplateArgument::Declaration:
5889 case TemplateArgument::NullPtr:
5890 case TemplateArgument::Pack:
5891 // FIXME: Is this right?
5892 return TemplateArgumentLocInfo();
5893 }
5894 llvm_unreachable("unexpected template argument loc");
5895}
5896
5897TemplateArgumentLoc
5898ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5899 const RecordData &Record, unsigned &Index) {
5900 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5901
5902 if (Arg.getKind() == TemplateArgument::Expression) {
5903 if (Record[Index++]) // bool InfoHasSameExpr.
5904 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5905 }
5906 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5907 Record, Index));
5908}
5909
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005910const ASTTemplateArgumentListInfo*
5911ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5912 const RecordData &Record,
5913 unsigned &Index) {
5914 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5915 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5916 unsigned NumArgsAsWritten = Record[Index++];
5917 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5918 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5919 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5920 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5921}
5922
Guy Benyei11169dd2012-12-18 14:30:41 +00005923Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5924 return GetDecl(ID);
5925}
5926
Richard Smith50895422015-01-31 03:04:55 +00005927template<typename TemplateSpecializationDecl>
5928static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5929 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5930 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5931}
5932
Richard Smith053f6c62014-05-16 23:01:30 +00005933void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005934 if (NumCurrentElementsDeserializing) {
5935 // We arrange to not care about the complete redeclaration chain while we're
5936 // deserializing. Just remember that the AST has marked this one as complete
5937 // but that it's not actually complete yet, so we know we still need to
5938 // complete it later.
5939 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5940 return;
5941 }
5942
Richard Smith053f6c62014-05-16 23:01:30 +00005943 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5944
Richard Smith053f6c62014-05-16 23:01:30 +00005945 // If this is a named declaration, complete it by looking it up
5946 // within its context.
5947 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005948 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005949 // all mergeable entities within it.
5950 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5951 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5952 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00005953 if (!getContext().getLangOpts().CPlusPlus &&
5954 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00005955 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00005956 // the identifier instead. (For C++ modules, we don't store decls
5957 // in the serialized identifier table, so we do the lookup in the TU.)
5958 auto *II = Name.getAsIdentifierInfo();
5959 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00005960 if (II->isOutOfDate())
5961 updateOutOfDateIdentifier(*II);
5962 } else
5963 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005964 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00005965 // Find all declarations of this kind from the relevant context.
5966 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
5967 auto *DC = cast<DeclContext>(DCDecl);
5968 SmallVector<Decl*, 8> Decls;
5969 FindExternalLexicalDecls(
5970 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
5971 }
Richard Smith053f6c62014-05-16 23:01:30 +00005972 }
5973 }
Richard Smith50895422015-01-31 03:04:55 +00005974
5975 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5976 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5977 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5978 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5979 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5980 if (auto *Template = FD->getPrimaryTemplate())
5981 Template->LoadLazySpecializations();
5982 }
Richard Smith053f6c62014-05-16 23:01:30 +00005983}
5984
Richard Smithc2bb8182015-03-24 06:36:48 +00005985uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5986 const RecordData &Record,
5987 unsigned &Idx) {
5988 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5989 Error("malformed AST file: missing C++ ctor initializers");
5990 return 0;
5991 }
5992
5993 unsigned LocalID = Record[Idx++];
5994 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
5995}
5996
5997CXXCtorInitializer **
5998ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
5999 RecordLocation Loc = getLocalBitOffset(Offset);
6000 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6001 SavedStreamPosition SavedPosition(Cursor);
6002 Cursor.JumpToBit(Loc.Offset);
6003 ReadingKindTracker ReadingKind(Read_Decl, *this);
6004
6005 RecordData Record;
6006 unsigned Code = Cursor.ReadCode();
6007 unsigned RecCode = Cursor.readRecord(Code, Record);
6008 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6009 Error("malformed AST file: missing C++ ctor initializers");
6010 return nullptr;
6011 }
6012
6013 unsigned Idx = 0;
6014 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6015}
6016
Richard Smithcd45dbc2014-04-19 03:48:30 +00006017uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6018 const RecordData &Record,
6019 unsigned &Idx) {
6020 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6021 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006022 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006023 }
6024
Guy Benyei11169dd2012-12-18 14:30:41 +00006025 unsigned LocalID = Record[Idx++];
6026 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6027}
6028
6029CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6030 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006031 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006032 SavedStreamPosition SavedPosition(Cursor);
6033 Cursor.JumpToBit(Loc.Offset);
6034 ReadingKindTracker ReadingKind(Read_Decl, *this);
6035 RecordData Record;
6036 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006037 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006038 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006039 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006040 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006041 }
6042
6043 unsigned Idx = 0;
6044 unsigned NumBases = Record[Idx++];
6045 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6046 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6047 for (unsigned I = 0; I != NumBases; ++I)
6048 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6049 return Bases;
6050}
6051
6052serialization::DeclID
6053ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6054 if (LocalID < NUM_PREDEF_DECL_IDS)
6055 return LocalID;
6056
6057 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6058 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6059 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6060
6061 return LocalID + I->second;
6062}
6063
6064bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6065 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006066 // Predefined decls aren't from any module.
6067 if (ID < NUM_PREDEF_DECL_IDS)
6068 return false;
6069
Richard Smithbcda1a92015-07-12 23:51:20 +00006070 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6071 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006072}
6073
Douglas Gregor9f782892013-01-21 15:25:38 +00006074ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006075 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006076 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006077 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6078 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6079 return I->second;
6080}
6081
6082SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6083 if (ID < NUM_PREDEF_DECL_IDS)
6084 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006085
Guy Benyei11169dd2012-12-18 14:30:41 +00006086 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6087
6088 if (Index > DeclsLoaded.size()) {
6089 Error("declaration ID out-of-range for AST file");
6090 return SourceLocation();
6091 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006092
Guy Benyei11169dd2012-12-18 14:30:41 +00006093 if (Decl *D = DeclsLoaded[Index])
6094 return D->getLocation();
6095
6096 unsigned RawLocation = 0;
6097 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6098 return ReadSourceLocation(*Rec.F, RawLocation);
6099}
6100
Richard Smithfe620d22015-03-05 23:24:12 +00006101static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6102 switch (ID) {
6103 case PREDEF_DECL_NULL_ID:
6104 return nullptr;
6105
6106 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6107 return Context.getTranslationUnitDecl();
6108
6109 case PREDEF_DECL_OBJC_ID_ID:
6110 return Context.getObjCIdDecl();
6111
6112 case PREDEF_DECL_OBJC_SEL_ID:
6113 return Context.getObjCSelDecl();
6114
6115 case PREDEF_DECL_OBJC_CLASS_ID:
6116 return Context.getObjCClassDecl();
6117
6118 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6119 return Context.getObjCProtocolDecl();
6120
6121 case PREDEF_DECL_INT_128_ID:
6122 return Context.getInt128Decl();
6123
6124 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6125 return Context.getUInt128Decl();
6126
6127 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6128 return Context.getObjCInstanceTypeDecl();
6129
6130 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6131 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006132
Richard Smith9b88a4c2015-07-27 05:40:23 +00006133 case PREDEF_DECL_VA_LIST_TAG:
6134 return Context.getVaListTagDecl();
6135
Richard Smithf19e1272015-03-07 00:04:49 +00006136 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6137 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006138 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006139 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006140}
6141
Richard Smithcd45dbc2014-04-19 03:48:30 +00006142Decl *ASTReader::GetExistingDecl(DeclID ID) {
6143 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006144 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6145 if (D) {
6146 // Track that we have merged the declaration with ID \p ID into the
6147 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006148 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006149 if (Merged.empty())
6150 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006151 }
Richard Smithfe620d22015-03-05 23:24:12 +00006152 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006153 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006154
Guy Benyei11169dd2012-12-18 14:30:41 +00006155 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6156
6157 if (Index >= DeclsLoaded.size()) {
6158 assert(0 && "declaration ID out-of-range for AST file");
6159 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006160 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006161 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006162
6163 return DeclsLoaded[Index];
6164}
6165
6166Decl *ASTReader::GetDecl(DeclID ID) {
6167 if (ID < NUM_PREDEF_DECL_IDS)
6168 return GetExistingDecl(ID);
6169
6170 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6171
6172 if (Index >= DeclsLoaded.size()) {
6173 assert(0 && "declaration ID out-of-range for AST file");
6174 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006175 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006176 }
6177
Guy Benyei11169dd2012-12-18 14:30:41 +00006178 if (!DeclsLoaded[Index]) {
6179 ReadDeclRecord(ID);
6180 if (DeserializationListener)
6181 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6182 }
6183
6184 return DeclsLoaded[Index];
6185}
6186
6187DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6188 DeclID GlobalID) {
6189 if (GlobalID < NUM_PREDEF_DECL_IDS)
6190 return GlobalID;
6191
6192 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6193 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6194 ModuleFile *Owner = I->second;
6195
6196 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6197 = M.GlobalToLocalDeclIDs.find(Owner);
6198 if (Pos == M.GlobalToLocalDeclIDs.end())
6199 return 0;
6200
6201 return GlobalID - Owner->BaseDeclID + Pos->second;
6202}
6203
6204serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6205 const RecordData &Record,
6206 unsigned &Idx) {
6207 if (Idx >= Record.size()) {
6208 Error("Corrupted AST file");
6209 return 0;
6210 }
6211
6212 return getGlobalDeclID(F, Record[Idx++]);
6213}
6214
6215/// \brief Resolve the offset of a statement into a statement.
6216///
6217/// This operation will read a new statement from the external
6218/// source each time it is called, and is meant to be used via a
6219/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6220Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6221 // Switch case IDs are per Decl.
6222 ClearSwitchCaseIDs();
6223
6224 // Offset here is a global offset across the entire chain.
6225 RecordLocation Loc = getLocalBitOffset(Offset);
6226 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6227 return ReadStmtFromStream(*Loc.F);
6228}
6229
Richard Smith3cb15722015-08-05 22:41:45 +00006230void ASTReader::FindExternalLexicalDecls(
6231 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6232 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006233 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6234
Richard Smith9ccdd932015-08-06 22:14:12 +00006235 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006236 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6237 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6238 auto K = (Decl::Kind)+LexicalDecls[I];
6239 if (!IsKindWeWant(K))
6240 continue;
6241
6242 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6243
6244 // Don't add predefined declarations to the lexical context more
6245 // than once.
6246 if (ID < NUM_PREDEF_DECL_IDS) {
6247 if (PredefsVisited[ID])
6248 continue;
6249
6250 PredefsVisited[ID] = true;
6251 }
6252
6253 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006254 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006255 if (!DC->isDeclInLexicalTraversal(D))
6256 Decls.push_back(D);
6257 }
6258 }
6259 };
6260
6261 if (isa<TranslationUnitDecl>(DC)) {
6262 for (auto Lexical : TULexicalDecls)
6263 Visit(Lexical.first, Lexical.second);
6264 } else {
6265 auto I = LexicalDecls.find(DC);
6266 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006267 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006268 }
6269
Guy Benyei11169dd2012-12-18 14:30:41 +00006270 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006271}
6272
6273namespace {
6274
6275class DeclIDComp {
6276 ASTReader &Reader;
6277 ModuleFile &Mod;
6278
6279public:
6280 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6281
6282 bool operator()(LocalDeclID L, LocalDeclID R) const {
6283 SourceLocation LHS = getLocation(L);
6284 SourceLocation RHS = getLocation(R);
6285 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6286 }
6287
6288 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6289 SourceLocation RHS = getLocation(R);
6290 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6291 }
6292
6293 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6294 SourceLocation LHS = getLocation(L);
6295 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6296 }
6297
6298 SourceLocation getLocation(LocalDeclID ID) const {
6299 return Reader.getSourceManager().getFileLoc(
6300 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6301 }
6302};
6303
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006304}
Guy Benyei11169dd2012-12-18 14:30:41 +00006305
6306void ASTReader::FindFileRegionDecls(FileID File,
6307 unsigned Offset, unsigned Length,
6308 SmallVectorImpl<Decl *> &Decls) {
6309 SourceManager &SM = getSourceManager();
6310
6311 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6312 if (I == FileDeclIDs.end())
6313 return;
6314
6315 FileDeclsInfo &DInfo = I->second;
6316 if (DInfo.Decls.empty())
6317 return;
6318
6319 SourceLocation
6320 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6321 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6322
6323 DeclIDComp DIDComp(*this, *DInfo.Mod);
6324 ArrayRef<serialization::LocalDeclID>::iterator
6325 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6326 BeginLoc, DIDComp);
6327 if (BeginIt != DInfo.Decls.begin())
6328 --BeginIt;
6329
6330 // If we are pointing at a top-level decl inside an objc container, we need
6331 // to backtrack until we find it otherwise we will fail to report that the
6332 // region overlaps with an objc container.
6333 while (BeginIt != DInfo.Decls.begin() &&
6334 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6335 ->isTopLevelDeclInObjCContainer())
6336 --BeginIt;
6337
6338 ArrayRef<serialization::LocalDeclID>::iterator
6339 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6340 EndLoc, DIDComp);
6341 if (EndIt != DInfo.Decls.end())
6342 ++EndIt;
6343
6344 for (ArrayRef<serialization::LocalDeclID>::iterator
6345 DIt = BeginIt; DIt != EndIt; ++DIt)
6346 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6347}
6348
Richard Smith3b637412015-07-14 18:42:41 +00006349/// \brief Retrieve the "definitive" module file for the definition of the
6350/// given declaration context, if there is one.
6351///
6352/// The "definitive" module file is the only place where we need to look to
6353/// find information about the declarations within the given declaration
6354/// context. For example, C++ and Objective-C classes, C structs/unions, and
6355/// Objective-C protocols, categories, and extensions are all defined in a
6356/// single place in the source code, so they have definitive module files
6357/// associated with them. C++ namespaces, on the other hand, can have
6358/// definitions in multiple different module files.
6359///
6360/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6361/// NDEBUG checking.
6362static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6363 ASTReader &Reader) {
6364 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6365 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6366
6367 return nullptr;
6368}
6369
Guy Benyei11169dd2012-12-18 14:30:41 +00006370namespace {
6371 /// \brief ModuleFile visitor used to perform name lookup into a
6372 /// declaration context.
6373 class DeclContextNameLookupVisitor {
6374 ASTReader &Reader;
Richard Smithf13c68d2015-08-06 21:05:21 +00006375 const DeclContext *Context;
Guy Benyei11169dd2012-12-18 14:30:41 +00006376 DeclarationName Name;
Richard Smith3b637412015-07-14 18:42:41 +00006377 ASTDeclContextNameLookupTrait::DeclNameKey NameKey;
6378 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00006379 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006380 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006381
6382 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006383 DeclContextNameLookupVisitor(ASTReader &Reader,
Richard Smithf13c68d2015-08-06 21:05:21 +00006384 const DeclContext *Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00006385 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006386 SmallVectorImpl<NamedDecl *> &Decls,
6387 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
Richard Smithf13c68d2015-08-06 21:05:21 +00006388 : Reader(Reader), Context(Context), Name(Name),
Richard Smith3b637412015-07-14 18:42:41 +00006389 NameKey(ASTDeclContextNameLookupTrait::GetInternalKey(Name)),
6390 NameHash(ASTDeclContextNameLookupTrait::ComputeHash(NameKey)),
6391 Decls(Decls), DeclSet(DeclSet) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006392
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006393 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006394 // Check whether we have any visible declaration information for
6395 // this context in this module.
Richard Smithf13c68d2015-08-06 21:05:21 +00006396 auto Info = M.DeclContextInfos.find(Context);
6397 if (Info == M.DeclContextInfos.end() || !Info->second.NameLookupTableData)
Guy Benyei11169dd2012-12-18 14:30:41 +00006398 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006399
Guy Benyei11169dd2012-12-18 14:30:41 +00006400 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006401 ASTDeclContextNameLookupTable *LookupTable =
Richard Smithf13c68d2015-08-06 21:05:21 +00006402 Info->second.NameLookupTableData;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006403 ASTDeclContextNameLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00006404 LookupTable->find_hashed(NameKey, NameHash);
Guy Benyei11169dd2012-12-18 14:30:41 +00006405 if (Pos == LookupTable->end())
6406 return false;
6407
6408 bool FoundAnything = false;
6409 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6410 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006411 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006412 if (!ND)
6413 continue;
6414
Richard Smithbdf2d932015-07-30 03:37:16 +00006415 if (ND->getDeclName() != Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006416 // A name might be null because the decl's redeclarable part is
6417 // currently read before reading its name. The lookup is triggered by
6418 // building that decl (likely indirectly), and so it is later in the
6419 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006420 // FIXME: This should not happen; deserializing declarations should
6421 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006422 continue;
6423 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006424
Guy Benyei11169dd2012-12-18 14:30:41 +00006425 // Record this declaration.
6426 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006427 if (DeclSet.insert(ND).second)
6428 Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006429 }
6430
6431 return FoundAnything;
6432 }
6433 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006434}
Guy Benyei11169dd2012-12-18 14:30:41 +00006435
Richard Smith9ce12e32013-02-07 03:30:24 +00006436bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006437ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6438 DeclarationName Name) {
6439 assert(DC->hasExternalVisibleStorage() &&
6440 "DeclContext has no visible decls in storage");
6441 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006442 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006443
Richard Smith8c913ec2014-08-14 02:21:01 +00006444 Deserializing LookupResults(this);
6445
Guy Benyei11169dd2012-12-18 14:30:41 +00006446 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006447 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006448
Richard Smithf13c68d2015-08-06 21:05:21 +00006449 DeclContextNameLookupVisitor Visitor(*this, DC, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006450
Richard Smithf13c68d2015-08-06 21:05:21 +00006451 // If we can definitively determine which module file to look into,
6452 // only look there. Otherwise, look in all module files.
6453 if (ModuleFile *Definitive = getDefinitiveModuleFileFor(DC, *this))
6454 Visitor(*Definitive);
6455 else
6456 ModuleMgr.visit(Visitor);
Richard Smithcd45dbc2014-04-19 03:48:30 +00006457
Guy Benyei11169dd2012-12-18 14:30:41 +00006458 ++NumVisibleDeclContextsRead;
6459 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006460 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006461}
6462
6463namespace {
6464 /// \brief ModuleFile visitor used to retrieve all visible names in a
6465 /// declaration context.
6466 class DeclContextAllNamesVisitor {
6467 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006468 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006469 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006470 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006471 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006472
6473 public:
6474 DeclContextAllNamesVisitor(ASTReader &Reader,
6475 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006476 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006477 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006478
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006479 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006480 // Check whether we have any visible declaration information for
6481 // this context in this module.
6482 ModuleFile::DeclContextInfosMap::iterator Info;
6483 bool FoundInfo = false;
Richard Smithbdf2d932015-07-30 03:37:16 +00006484 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
6485 Info = M.DeclContextInfos.find(Contexts[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006486 if (Info != M.DeclContextInfos.end() &&
6487 Info->second.NameLookupTableData) {
6488 FoundInfo = true;
6489 break;
6490 }
6491 }
6492
6493 if (!FoundInfo)
6494 return false;
6495
Richard Smith52e3fba2014-03-11 07:17:35 +00006496 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006497 Info->second.NameLookupTableData;
6498 bool FoundAnything = false;
6499 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006500 I = LookupTable->data_begin(), E = LookupTable->data_end();
6501 I != E;
6502 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006503 ASTDeclContextNameLookupTrait::data_type Data = *I;
6504 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006505 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006506 if (!ND)
6507 continue;
6508
6509 // Record this declaration.
6510 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006511 if (DeclSet.insert(ND).second)
6512 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006513 }
6514 }
6515
Richard Smithbdf2d932015-07-30 03:37:16 +00006516 return FoundAnything && !VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006517 }
6518 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006519}
Guy Benyei11169dd2012-12-18 14:30:41 +00006520
6521void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6522 if (!DC->hasExternalVisibleStorage())
6523 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006524 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006525
6526 // Compute the declaration contexts we need to look into. Multiple such
6527 // declaration contexts occur when two declaration contexts from disjoint
6528 // modules get merged, e.g., when two namespaces with the same name are
6529 // independently defined in separate modules.
6530 SmallVector<const DeclContext *, 2> Contexts;
6531 Contexts.push_back(DC);
6532
6533 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006534 KeyDeclsMap::iterator Key =
6535 KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6536 if (Key != KeyDecls.end()) {
6537 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6538 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006539 }
6540 }
6541
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006542 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6543 /*VisitAll=*/DC->isFileContext());
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006544 ModuleMgr.visit(Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006545 ++NumVisibleDeclContextsRead;
6546
Craig Topper79be4cd2013-07-05 04:33:53 +00006547 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006548 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6549 }
6550 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6551}
6552
6553/// \brief Under non-PCH compilation the consumer receives the objc methods
6554/// before receiving the implementation, and codegen depends on this.
6555/// We simulate this by deserializing and passing to consumer the methods of the
6556/// implementation before passing the deserialized implementation decl.
6557static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6558 ASTConsumer *Consumer) {
6559 assert(ImplD && Consumer);
6560
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006561 for (auto *I : ImplD->methods())
6562 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006563
6564 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6565}
6566
6567void ASTReader::PassInterestingDeclsToConsumer() {
6568 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006569
6570 if (PassingDeclsToConsumer)
6571 return;
6572
6573 // Guard variable to avoid recursively redoing the process of passing
6574 // decls to consumer.
6575 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6576 true);
6577
Richard Smith9e2341d2015-03-23 03:25:59 +00006578 // Ensure that we've loaded all potentially-interesting declarations
6579 // that need to be eagerly loaded.
6580 for (auto ID : EagerlyDeserializedDecls)
6581 GetDecl(ID);
6582 EagerlyDeserializedDecls.clear();
6583
Guy Benyei11169dd2012-12-18 14:30:41 +00006584 while (!InterestingDecls.empty()) {
6585 Decl *D = InterestingDecls.front();
6586 InterestingDecls.pop_front();
6587
6588 PassInterestingDeclToConsumer(D);
6589 }
6590}
6591
6592void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6593 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6594 PassObjCImplDeclToConsumer(ImplD, Consumer);
6595 else
6596 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6597}
6598
6599void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6600 this->Consumer = Consumer;
6601
Richard Smith9e2341d2015-03-23 03:25:59 +00006602 if (Consumer)
6603 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006604
6605 if (DeserializationListener)
6606 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006607}
6608
6609void ASTReader::PrintStats() {
6610 std::fprintf(stderr, "*** AST File Statistics:\n");
6611
6612 unsigned NumTypesLoaded
6613 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6614 QualType());
6615 unsigned NumDeclsLoaded
6616 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006617 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006618 unsigned NumIdentifiersLoaded
6619 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6620 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006621 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006622 unsigned NumMacrosLoaded
6623 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6624 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006625 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006626 unsigned NumSelectorsLoaded
6627 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6628 SelectorsLoaded.end(),
6629 Selector());
6630
6631 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6632 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6633 NumSLocEntriesRead, TotalNumSLocEntries,
6634 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6635 if (!TypesLoaded.empty())
6636 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6637 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6638 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6639 if (!DeclsLoaded.empty())
6640 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6641 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6642 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6643 if (!IdentifiersLoaded.empty())
6644 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6645 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6646 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6647 if (!MacrosLoaded.empty())
6648 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6649 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6650 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6651 if (!SelectorsLoaded.empty())
6652 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6653 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6654 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6655 if (TotalNumStatements)
6656 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6657 NumStatementsRead, TotalNumStatements,
6658 ((float)NumStatementsRead/TotalNumStatements * 100));
6659 if (TotalNumMacros)
6660 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6661 NumMacrosRead, TotalNumMacros,
6662 ((float)NumMacrosRead/TotalNumMacros * 100));
6663 if (TotalLexicalDeclContexts)
6664 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6665 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6666 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6667 * 100));
6668 if (TotalVisibleDeclContexts)
6669 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6670 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6671 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6672 * 100));
6673 if (TotalNumMethodPoolEntries) {
6674 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6675 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6676 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6677 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006678 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006679 if (NumMethodPoolLookups) {
6680 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6681 NumMethodPoolHits, NumMethodPoolLookups,
6682 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6683 }
6684 if (NumMethodPoolTableLookups) {
6685 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6686 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6687 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6688 * 100.0));
6689 }
6690
Douglas Gregor00a50f72013-01-25 00:38:33 +00006691 if (NumIdentifierLookupHits) {
6692 std::fprintf(stderr,
6693 " %u / %u identifier table lookups succeeded (%f%%)\n",
6694 NumIdentifierLookupHits, NumIdentifierLookups,
6695 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6696 }
6697
Douglas Gregore060e572013-01-25 01:03:03 +00006698 if (GlobalIndex) {
6699 std::fprintf(stderr, "\n");
6700 GlobalIndex->printStats();
6701 }
6702
Guy Benyei11169dd2012-12-18 14:30:41 +00006703 std::fprintf(stderr, "\n");
6704 dump();
6705 std::fprintf(stderr, "\n");
6706}
6707
6708template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6709static void
6710dumpModuleIDMap(StringRef Name,
6711 const ContinuousRangeMap<Key, ModuleFile *,
6712 InitialCapacity> &Map) {
6713 if (Map.begin() == Map.end())
6714 return;
6715
6716 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6717 llvm::errs() << Name << ":\n";
6718 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6719 I != IEnd; ++I) {
6720 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6721 << "\n";
6722 }
6723}
6724
6725void ASTReader::dump() {
6726 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6727 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6728 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6729 dumpModuleIDMap("Global type map", GlobalTypeMap);
6730 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6731 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6732 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6733 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6734 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6735 dumpModuleIDMap("Global preprocessed entity map",
6736 GlobalPreprocessedEntityMap);
6737
6738 llvm::errs() << "\n*** PCH/Modules Loaded:";
6739 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6740 MEnd = ModuleMgr.end();
6741 M != MEnd; ++M)
6742 (*M)->dump();
6743}
6744
6745/// Return the amount of memory used by memory buffers, breaking down
6746/// by heap-backed versus mmap'ed memory.
6747void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6748 for (ModuleConstIterator I = ModuleMgr.begin(),
6749 E = ModuleMgr.end(); I != E; ++I) {
6750 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6751 size_t bytes = buf->getBufferSize();
6752 switch (buf->getBufferKind()) {
6753 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6754 sizes.malloc_bytes += bytes;
6755 break;
6756 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6757 sizes.mmap_bytes += bytes;
6758 break;
6759 }
6760 }
6761 }
6762}
6763
6764void ASTReader::InitializeSema(Sema &S) {
6765 SemaObj = &S;
6766 S.addExternalSource(this);
6767
6768 // Makes sure any declarations that were deserialized "too early"
6769 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006770 for (uint64_t ID : PreloadedDeclIDs) {
6771 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6772 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006773 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006774 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006775
Richard Smith3d8e97e2013-10-18 06:54:39 +00006776 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006777 if (!FPPragmaOptions.empty()) {
6778 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6779 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6780 }
6781
Richard Smith3d8e97e2013-10-18 06:54:39 +00006782 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006783 if (!OpenCLExtensions.empty()) {
6784 unsigned I = 0;
6785#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6786#include "clang/Basic/OpenCLExtensions.def"
6787
6788 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6789 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006790
6791 UpdateSema();
6792}
6793
6794void ASTReader::UpdateSema() {
6795 assert(SemaObj && "no Sema to update");
6796
6797 // Load the offsets of the declarations that Sema references.
6798 // They will be lazily deserialized when needed.
6799 if (!SemaDeclRefs.empty()) {
6800 assert(SemaDeclRefs.size() % 2 == 0);
6801 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6802 if (!SemaObj->StdNamespace)
6803 SemaObj->StdNamespace = SemaDeclRefs[I];
6804 if (!SemaObj->StdBadAlloc)
6805 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6806 }
6807 SemaDeclRefs.clear();
6808 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006809
6810 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6811 // encountered the pragma in the source.
6812 if(OptimizeOffPragmaLocation.isValid())
6813 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006814}
6815
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006816IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006817 // Note that we are loading an identifier.
6818 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006819
Douglas Gregor7211ac12013-01-25 23:32:03 +00006820 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006821 NumIdentifierLookups,
6822 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006823
6824 // We don't need to do identifier table lookups in C++ modules (we preload
6825 // all interesting declarations, and don't need to use the scope for name
6826 // lookups). Perform the lookup in PCH files, though, since we don't build
6827 // a complete initial identifier table if we're carrying on from a PCH.
6828 if (Context.getLangOpts().CPlusPlus) {
6829 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006830 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006831 break;
6832 } else {
6833 // If there is a global index, look there first to determine which modules
6834 // provably do not have any results for this identifier.
6835 GlobalModuleIndex::HitSet Hits;
6836 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6837 if (!loadGlobalIndex()) {
6838 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6839 HitsPtr = &Hits;
6840 }
6841 }
6842
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006843 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006844 }
6845
Guy Benyei11169dd2012-12-18 14:30:41 +00006846 IdentifierInfo *II = Visitor.getIdentifierInfo();
6847 markIdentifierUpToDate(II);
6848 return II;
6849}
6850
6851namespace clang {
6852 /// \brief An identifier-lookup iterator that enumerates all of the
6853 /// identifiers stored within a set of AST files.
6854 class ASTIdentifierIterator : public IdentifierIterator {
6855 /// \brief The AST reader whose identifiers are being enumerated.
6856 const ASTReader &Reader;
6857
6858 /// \brief The current index into the chain of AST files stored in
6859 /// the AST reader.
6860 unsigned Index;
6861
6862 /// \brief The current position within the identifier lookup table
6863 /// of the current AST file.
6864 ASTIdentifierLookupTable::key_iterator Current;
6865
6866 /// \brief The end position within the identifier lookup table of
6867 /// the current AST file.
6868 ASTIdentifierLookupTable::key_iterator End;
6869
6870 public:
6871 explicit ASTIdentifierIterator(const ASTReader &Reader);
6872
Craig Topper3e89dfe2014-03-13 02:13:41 +00006873 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006874 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006875}
Guy Benyei11169dd2012-12-18 14:30:41 +00006876
6877ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6878 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6879 ASTIdentifierLookupTable *IdTable
6880 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6881 Current = IdTable->key_begin();
6882 End = IdTable->key_end();
6883}
6884
6885StringRef ASTIdentifierIterator::Next() {
6886 while (Current == End) {
6887 // If we have exhausted all of our AST files, we're done.
6888 if (Index == 0)
6889 return StringRef();
6890
6891 --Index;
6892 ASTIdentifierLookupTable *IdTable
6893 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6894 IdentifierLookupTable;
6895 Current = IdTable->key_begin();
6896 End = IdTable->key_end();
6897 }
6898
6899 // We have any identifiers remaining in the current AST file; return
6900 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006901 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006902 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006903 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006904}
6905
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006906IdentifierIterator *ASTReader::getIdentifiers() {
6907 if (!loadGlobalIndex())
6908 return GlobalIndex->createIdentifierIterator();
6909
Guy Benyei11169dd2012-12-18 14:30:41 +00006910 return new ASTIdentifierIterator(*this);
6911}
6912
6913namespace clang { namespace serialization {
6914 class ReadMethodPoolVisitor {
6915 ASTReader &Reader;
6916 Selector Sel;
6917 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006918 unsigned InstanceBits;
6919 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006920 bool InstanceHasMoreThanOneDecl;
6921 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006922 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6923 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006924
6925 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006926 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006927 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006928 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006929 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6930 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006931
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006932 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006933 if (!M.SelectorLookupTable)
6934 return false;
6935
6936 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00006937 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00006938 return true;
6939
Richard Smithbdf2d932015-07-30 03:37:16 +00006940 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006941 ASTSelectorLookupTable *PoolTable
6942 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00006943 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00006944 if (Pos == PoolTable->end())
6945 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006946
Richard Smithbdf2d932015-07-30 03:37:16 +00006947 ++Reader.NumMethodPoolTableHits;
6948 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006949 // FIXME: Not quite happy with the statistics here. We probably should
6950 // disable this tracking when called via LoadSelector.
6951 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00006952 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006953 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00006954 if (Reader.DeserializationListener)
6955 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006956
Richard Smithbdf2d932015-07-30 03:37:16 +00006957 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6958 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6959 InstanceBits = Data.InstanceBits;
6960 FactoryBits = Data.FactoryBits;
6961 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6962 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006963 return true;
6964 }
6965
6966 /// \brief Retrieve the instance methods found by this visitor.
6967 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6968 return InstanceMethods;
6969 }
6970
6971 /// \brief Retrieve the instance methods found by this visitor.
6972 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6973 return FactoryMethods;
6974 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006975
6976 unsigned getInstanceBits() const { return InstanceBits; }
6977 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006978 bool instanceHasMoreThanOneDecl() const {
6979 return InstanceHasMoreThanOneDecl;
6980 }
6981 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006982 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006983} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00006984
6985/// \brief Add the given set of methods to the method list.
6986static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6987 ObjCMethodList &List) {
6988 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6989 S.addMethodToGlobalList(&List, Methods[I]);
6990 }
6991}
6992
6993void ASTReader::ReadMethodPool(Selector Sel) {
6994 // Get the selector generation and update it to the current generation.
6995 unsigned &Generation = SelectorGeneration[Sel];
6996 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00006997 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00006998
6999 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007000 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007001 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007002 ModuleMgr.visit(Visitor);
7003
Guy Benyei11169dd2012-12-18 14:30:41 +00007004 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007005 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007006 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007007
7008 ++NumMethodPoolHits;
7009
Guy Benyei11169dd2012-12-18 14:30:41 +00007010 if (!getSema())
7011 return;
7012
7013 Sema &S = *getSema();
7014 Sema::GlobalMethodPool::iterator Pos
7015 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007016
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007017 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007018 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007019 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007020 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007021
7022 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7023 // when building a module we keep every method individually and may need to
7024 // update hasMoreThanOneDecl as we add the methods.
7025 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7026 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007027}
7028
7029void ASTReader::ReadKnownNamespaces(
7030 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7031 Namespaces.clear();
7032
7033 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7034 if (NamespaceDecl *Namespace
7035 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7036 Namespaces.push_back(Namespace);
7037 }
7038}
7039
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007040void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007041 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007042 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7043 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007044 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007045 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007046 Undefined.insert(std::make_pair(D, Loc));
7047 }
7048}
Nick Lewycky8334af82013-01-26 00:35:08 +00007049
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007050void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7051 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7052 Exprs) {
7053 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7054 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7055 uint64_t Count = DelayedDeleteExprs[Idx++];
7056 for (uint64_t C = 0; C < Count; ++C) {
7057 SourceLocation DeleteLoc =
7058 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7059 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7060 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7061 }
7062 }
7063}
7064
Guy Benyei11169dd2012-12-18 14:30:41 +00007065void ASTReader::ReadTentativeDefinitions(
7066 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7067 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7068 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7069 if (Var)
7070 TentativeDefs.push_back(Var);
7071 }
7072 TentativeDefinitions.clear();
7073}
7074
7075void ASTReader::ReadUnusedFileScopedDecls(
7076 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7077 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7078 DeclaratorDecl *D
7079 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7080 if (D)
7081 Decls.push_back(D);
7082 }
7083 UnusedFileScopedDecls.clear();
7084}
7085
7086void ASTReader::ReadDelegatingConstructors(
7087 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7088 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7089 CXXConstructorDecl *D
7090 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7091 if (D)
7092 Decls.push_back(D);
7093 }
7094 DelegatingCtorDecls.clear();
7095}
7096
7097void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7098 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7099 TypedefNameDecl *D
7100 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7101 if (D)
7102 Decls.push_back(D);
7103 }
7104 ExtVectorDecls.clear();
7105}
7106
Nico Weber72889432014-09-06 01:25:55 +00007107void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7108 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7109 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7110 ++I) {
7111 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7112 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7113 if (D)
7114 Decls.insert(D);
7115 }
7116 UnusedLocalTypedefNameCandidates.clear();
7117}
7118
Guy Benyei11169dd2012-12-18 14:30:41 +00007119void ASTReader::ReadReferencedSelectors(
7120 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7121 if (ReferencedSelectorsData.empty())
7122 return;
7123
7124 // If there are @selector references added them to its pool. This is for
7125 // implementation of -Wselector.
7126 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7127 unsigned I = 0;
7128 while (I < DataSize) {
7129 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7130 SourceLocation SelLoc
7131 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7132 Sels.push_back(std::make_pair(Sel, SelLoc));
7133 }
7134 ReferencedSelectorsData.clear();
7135}
7136
7137void ASTReader::ReadWeakUndeclaredIdentifiers(
7138 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7139 if (WeakUndeclaredIdentifiers.empty())
7140 return;
7141
7142 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7143 IdentifierInfo *WeakId
7144 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7145 IdentifierInfo *AliasId
7146 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7147 SourceLocation Loc
7148 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7149 bool Used = WeakUndeclaredIdentifiers[I++];
7150 WeakInfo WI(AliasId, Loc);
7151 WI.setUsed(Used);
7152 WeakIDs.push_back(std::make_pair(WeakId, WI));
7153 }
7154 WeakUndeclaredIdentifiers.clear();
7155}
7156
7157void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7158 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7159 ExternalVTableUse VT;
7160 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7161 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7162 VT.DefinitionRequired = VTableUses[Idx++];
7163 VTables.push_back(VT);
7164 }
7165
7166 VTableUses.clear();
7167}
7168
7169void ASTReader::ReadPendingInstantiations(
7170 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7171 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7172 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7173 SourceLocation Loc
7174 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7175
7176 Pending.push_back(std::make_pair(D, Loc));
7177 }
7178 PendingInstantiations.clear();
7179}
7180
Richard Smithe40f2ba2013-08-07 21:41:30 +00007181void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007182 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007183 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7184 /* In loop */) {
7185 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7186
7187 LateParsedTemplate *LT = new LateParsedTemplate;
7188 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7189
7190 ModuleFile *F = getOwningModuleFile(LT->D);
7191 assert(F && "No module");
7192
7193 unsigned TokN = LateParsedTemplates[Idx++];
7194 LT->Toks.reserve(TokN);
7195 for (unsigned T = 0; T < TokN; ++T)
7196 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7197
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007198 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007199 }
7200
7201 LateParsedTemplates.clear();
7202}
7203
Guy Benyei11169dd2012-12-18 14:30:41 +00007204void ASTReader::LoadSelector(Selector Sel) {
7205 // It would be complicated to avoid reading the methods anyway. So don't.
7206 ReadMethodPool(Sel);
7207}
7208
7209void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7210 assert(ID && "Non-zero identifier ID required");
7211 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7212 IdentifiersLoaded[ID - 1] = II;
7213 if (DeserializationListener)
7214 DeserializationListener->IdentifierRead(ID, II);
7215}
7216
7217/// \brief Set the globally-visible declarations associated with the given
7218/// identifier.
7219///
7220/// If the AST reader is currently in a state where the given declaration IDs
7221/// cannot safely be resolved, they are queued until it is safe to resolve
7222/// them.
7223///
7224/// \param II an IdentifierInfo that refers to one or more globally-visible
7225/// declarations.
7226///
7227/// \param DeclIDs the set of declaration IDs with the name @p II that are
7228/// visible at global scope.
7229///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007230/// \param Decls if non-null, this vector will be populated with the set of
7231/// deserialized declarations. These declarations will not be pushed into
7232/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007233void
7234ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7235 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007236 SmallVectorImpl<Decl *> *Decls) {
7237 if (NumCurrentElementsDeserializing && !Decls) {
7238 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007239 return;
7240 }
7241
7242 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007243 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007244 // Queue this declaration so that it will be added to the
7245 // translation unit scope and identifier's declaration chain
7246 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007247 PreloadedDeclIDs.push_back(DeclIDs[I]);
7248 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007249 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007250
7251 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7252
7253 // If we're simply supposed to record the declarations, do so now.
7254 if (Decls) {
7255 Decls->push_back(D);
7256 continue;
7257 }
7258
7259 // Introduce this declaration into the translation-unit scope
7260 // and add it to the declaration chain for this identifier, so
7261 // that (unqualified) name lookup will find it.
7262 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007263 }
7264}
7265
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007266IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007267 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007268 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007269
7270 if (IdentifiersLoaded.empty()) {
7271 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007272 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007273 }
7274
7275 ID -= 1;
7276 if (!IdentifiersLoaded[ID]) {
7277 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7278 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7279 ModuleFile *M = I->second;
7280 unsigned Index = ID - M->BaseIdentifierID;
7281 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7282
7283 // All of the strings in the AST file are preceded by a 16-bit length.
7284 // Extract that 16-bit length to avoid having to execute strlen().
7285 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7286 // unsigned integers. This is important to avoid integer overflow when
7287 // we cast them to 'unsigned'.
7288 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7289 unsigned StrLen = (((unsigned) StrLenPtr[0])
7290 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007291 IdentifiersLoaded[ID]
7292 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007293 if (DeserializationListener)
7294 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7295 }
7296
7297 return IdentifiersLoaded[ID];
7298}
7299
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007300IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7301 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007302}
7303
7304IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7305 if (LocalID < NUM_PREDEF_IDENT_IDS)
7306 return LocalID;
7307
7308 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7309 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7310 assert(I != M.IdentifierRemap.end()
7311 && "Invalid index into identifier index remap");
7312
7313 return LocalID + I->second;
7314}
7315
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007316MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007317 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007318 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007319
7320 if (MacrosLoaded.empty()) {
7321 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007322 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007323 }
7324
7325 ID -= NUM_PREDEF_MACRO_IDS;
7326 if (!MacrosLoaded[ID]) {
7327 GlobalMacroMapType::iterator I
7328 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7329 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7330 ModuleFile *M = I->second;
7331 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007332 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7333
7334 if (DeserializationListener)
7335 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7336 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007337 }
7338
7339 return MacrosLoaded[ID];
7340}
7341
7342MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7343 if (LocalID < NUM_PREDEF_MACRO_IDS)
7344 return LocalID;
7345
7346 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7347 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7348 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7349
7350 return LocalID + I->second;
7351}
7352
7353serialization::SubmoduleID
7354ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7355 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7356 return LocalID;
7357
7358 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7359 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7360 assert(I != M.SubmoduleRemap.end()
7361 && "Invalid index into submodule index remap");
7362
7363 return LocalID + I->second;
7364}
7365
7366Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7367 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7368 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007369 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007370 }
7371
7372 if (GlobalID > SubmodulesLoaded.size()) {
7373 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007374 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007375 }
7376
7377 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7378}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007379
7380Module *ASTReader::getModule(unsigned ID) {
7381 return getSubmodule(ID);
7382}
7383
Adrian Prantl15bcf702015-06-30 17:39:43 +00007384ExternalASTSource::ASTSourceDescriptor
7385ASTReader::getSourceDescriptor(const Module &M) {
7386 StringRef Dir, Filename;
7387 if (M.Directory)
7388 Dir = M.Directory->getName();
7389 if (auto *File = M.getASTFile())
7390 Filename = File->getName();
7391 return ASTReader::ASTSourceDescriptor{
7392 M.getFullModuleName(), Dir, Filename,
7393 M.Signature
7394 };
7395}
7396
7397llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7398ASTReader::getSourceDescriptor(unsigned ID) {
7399 if (const Module *M = getSubmodule(ID))
7400 return getSourceDescriptor(*M);
7401
7402 // If there is only a single PCH, return it instead.
7403 // Chained PCH are not suported.
7404 if (ModuleMgr.size() == 1) {
7405 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7406 return ASTReader::ASTSourceDescriptor{
7407 MF.OriginalSourceFileName, MF.OriginalDir,
7408 MF.FileName,
7409 MF.Signature
7410 };
7411 }
7412 return None;
7413}
7414
Guy Benyei11169dd2012-12-18 14:30:41 +00007415Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7416 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7417}
7418
7419Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7420 if (ID == 0)
7421 return Selector();
7422
7423 if (ID > SelectorsLoaded.size()) {
7424 Error("selector ID out of range in AST file");
7425 return Selector();
7426 }
7427
Craig Toppera13603a2014-05-22 05:54:18 +00007428 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007429 // Load this selector from the selector table.
7430 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7431 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7432 ModuleFile &M = *I->second;
7433 ASTSelectorLookupTrait Trait(*this, M);
7434 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7435 SelectorsLoaded[ID - 1] =
7436 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7437 if (DeserializationListener)
7438 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7439 }
7440
7441 return SelectorsLoaded[ID - 1];
7442}
7443
7444Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7445 return DecodeSelector(ID);
7446}
7447
7448uint32_t ASTReader::GetNumExternalSelectors() {
7449 // ID 0 (the null selector) is considered an external selector.
7450 return getTotalNumSelectors() + 1;
7451}
7452
7453serialization::SelectorID
7454ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7455 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7456 return LocalID;
7457
7458 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7459 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7460 assert(I != M.SelectorRemap.end()
7461 && "Invalid index into selector index remap");
7462
7463 return LocalID + I->second;
7464}
7465
7466DeclarationName
7467ASTReader::ReadDeclarationName(ModuleFile &F,
7468 const RecordData &Record, unsigned &Idx) {
7469 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7470 switch (Kind) {
7471 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007472 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007473
7474 case DeclarationName::ObjCZeroArgSelector:
7475 case DeclarationName::ObjCOneArgSelector:
7476 case DeclarationName::ObjCMultiArgSelector:
7477 return DeclarationName(ReadSelector(F, Record, Idx));
7478
7479 case DeclarationName::CXXConstructorName:
7480 return Context.DeclarationNames.getCXXConstructorName(
7481 Context.getCanonicalType(readType(F, Record, Idx)));
7482
7483 case DeclarationName::CXXDestructorName:
7484 return Context.DeclarationNames.getCXXDestructorName(
7485 Context.getCanonicalType(readType(F, Record, Idx)));
7486
7487 case DeclarationName::CXXConversionFunctionName:
7488 return Context.DeclarationNames.getCXXConversionFunctionName(
7489 Context.getCanonicalType(readType(F, Record, Idx)));
7490
7491 case DeclarationName::CXXOperatorName:
7492 return Context.DeclarationNames.getCXXOperatorName(
7493 (OverloadedOperatorKind)Record[Idx++]);
7494
7495 case DeclarationName::CXXLiteralOperatorName:
7496 return Context.DeclarationNames.getCXXLiteralOperatorName(
7497 GetIdentifierInfo(F, Record, Idx));
7498
7499 case DeclarationName::CXXUsingDirective:
7500 return DeclarationName::getUsingDirectiveName();
7501 }
7502
7503 llvm_unreachable("Invalid NameKind!");
7504}
7505
7506void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7507 DeclarationNameLoc &DNLoc,
7508 DeclarationName Name,
7509 const RecordData &Record, unsigned &Idx) {
7510 switch (Name.getNameKind()) {
7511 case DeclarationName::CXXConstructorName:
7512 case DeclarationName::CXXDestructorName:
7513 case DeclarationName::CXXConversionFunctionName:
7514 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7515 break;
7516
7517 case DeclarationName::CXXOperatorName:
7518 DNLoc.CXXOperatorName.BeginOpNameLoc
7519 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7520 DNLoc.CXXOperatorName.EndOpNameLoc
7521 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7522 break;
7523
7524 case DeclarationName::CXXLiteralOperatorName:
7525 DNLoc.CXXLiteralOperatorName.OpNameLoc
7526 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7527 break;
7528
7529 case DeclarationName::Identifier:
7530 case DeclarationName::ObjCZeroArgSelector:
7531 case DeclarationName::ObjCOneArgSelector:
7532 case DeclarationName::ObjCMultiArgSelector:
7533 case DeclarationName::CXXUsingDirective:
7534 break;
7535 }
7536}
7537
7538void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7539 DeclarationNameInfo &NameInfo,
7540 const RecordData &Record, unsigned &Idx) {
7541 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7542 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7543 DeclarationNameLoc DNLoc;
7544 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7545 NameInfo.setInfo(DNLoc);
7546}
7547
7548void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7549 const RecordData &Record, unsigned &Idx) {
7550 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7551 unsigned NumTPLists = Record[Idx++];
7552 Info.NumTemplParamLists = NumTPLists;
7553 if (NumTPLists) {
7554 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7555 for (unsigned i=0; i != NumTPLists; ++i)
7556 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7557 }
7558}
7559
7560TemplateName
7561ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7562 unsigned &Idx) {
7563 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7564 switch (Kind) {
7565 case TemplateName::Template:
7566 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7567
7568 case TemplateName::OverloadedTemplate: {
7569 unsigned size = Record[Idx++];
7570 UnresolvedSet<8> Decls;
7571 while (size--)
7572 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7573
7574 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7575 }
7576
7577 case TemplateName::QualifiedTemplate: {
7578 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7579 bool hasTemplKeyword = Record[Idx++];
7580 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7581 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7582 }
7583
7584 case TemplateName::DependentTemplate: {
7585 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7586 if (Record[Idx++]) // isIdentifier
7587 return Context.getDependentTemplateName(NNS,
7588 GetIdentifierInfo(F, Record,
7589 Idx));
7590 return Context.getDependentTemplateName(NNS,
7591 (OverloadedOperatorKind)Record[Idx++]);
7592 }
7593
7594 case TemplateName::SubstTemplateTemplateParm: {
7595 TemplateTemplateParmDecl *param
7596 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7597 if (!param) return TemplateName();
7598 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7599 return Context.getSubstTemplateTemplateParm(param, replacement);
7600 }
7601
7602 case TemplateName::SubstTemplateTemplateParmPack: {
7603 TemplateTemplateParmDecl *Param
7604 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7605 if (!Param)
7606 return TemplateName();
7607
7608 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7609 if (ArgPack.getKind() != TemplateArgument::Pack)
7610 return TemplateName();
7611
7612 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7613 }
7614 }
7615
7616 llvm_unreachable("Unhandled template name kind!");
7617}
7618
Richard Smith2bb3c342015-08-09 01:05:31 +00007619TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7620 const RecordData &Record,
7621 unsigned &Idx,
7622 bool Canonicalize) {
7623 if (Canonicalize) {
7624 // The caller wants a canonical template argument. Sometimes the AST only
7625 // wants template arguments in canonical form (particularly as the template
7626 // argument lists of template specializations) so ensure we preserve that
7627 // canonical form across serialization.
7628 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7629 return Context.getCanonicalTemplateArgument(Arg);
7630 }
7631
Guy Benyei11169dd2012-12-18 14:30:41 +00007632 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7633 switch (Kind) {
7634 case TemplateArgument::Null:
7635 return TemplateArgument();
7636 case TemplateArgument::Type:
7637 return TemplateArgument(readType(F, Record, Idx));
7638 case TemplateArgument::Declaration: {
7639 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007640 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007641 }
7642 case TemplateArgument::NullPtr:
7643 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7644 case TemplateArgument::Integral: {
7645 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7646 QualType T = readType(F, Record, Idx);
7647 return TemplateArgument(Context, Value, T);
7648 }
7649 case TemplateArgument::Template:
7650 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7651 case TemplateArgument::TemplateExpansion: {
7652 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007653 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007654 if (unsigned NumExpansions = Record[Idx++])
7655 NumTemplateExpansions = NumExpansions - 1;
7656 return TemplateArgument(Name, NumTemplateExpansions);
7657 }
7658 case TemplateArgument::Expression:
7659 return TemplateArgument(ReadExpr(F));
7660 case TemplateArgument::Pack: {
7661 unsigned NumArgs = Record[Idx++];
7662 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7663 for (unsigned I = 0; I != NumArgs; ++I)
7664 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007665 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007666 }
7667 }
7668
7669 llvm_unreachable("Unhandled template argument kind!");
7670}
7671
7672TemplateParameterList *
7673ASTReader::ReadTemplateParameterList(ModuleFile &F,
7674 const RecordData &Record, unsigned &Idx) {
7675 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7676 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7677 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7678
7679 unsigned NumParams = Record[Idx++];
7680 SmallVector<NamedDecl *, 16> Params;
7681 Params.reserve(NumParams);
7682 while (NumParams--)
7683 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7684
7685 TemplateParameterList* TemplateParams =
7686 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7687 Params.data(), Params.size(), RAngleLoc);
7688 return TemplateParams;
7689}
7690
7691void
7692ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007693ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007694 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007695 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007696 unsigned NumTemplateArgs = Record[Idx++];
7697 TemplArgs.reserve(NumTemplateArgs);
7698 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007699 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007700}
7701
7702/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007703void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007704 const RecordData &Record, unsigned &Idx) {
7705 unsigned NumDecls = Record[Idx++];
7706 Set.reserve(Context, NumDecls);
7707 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007708 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007709 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007710 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007711 }
7712}
7713
7714CXXBaseSpecifier
7715ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7716 const RecordData &Record, unsigned &Idx) {
7717 bool isVirtual = static_cast<bool>(Record[Idx++]);
7718 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7719 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7720 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7721 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7722 SourceRange Range = ReadSourceRange(F, Record, Idx);
7723 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7724 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7725 EllipsisLoc);
7726 Result.setInheritConstructors(inheritConstructors);
7727 return Result;
7728}
7729
Richard Smithc2bb8182015-03-24 06:36:48 +00007730CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007731ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7732 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007733 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007734 assert(NumInitializers && "wrote ctor initializers but have no inits");
7735 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7736 for (unsigned i = 0; i != NumInitializers; ++i) {
7737 TypeSourceInfo *TInfo = nullptr;
7738 bool IsBaseVirtual = false;
7739 FieldDecl *Member = nullptr;
7740 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007741
Richard Smithc2bb8182015-03-24 06:36:48 +00007742 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7743 switch (Type) {
7744 case CTOR_INITIALIZER_BASE:
7745 TInfo = GetTypeSourceInfo(F, Record, Idx);
7746 IsBaseVirtual = Record[Idx++];
7747 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007748
Richard Smithc2bb8182015-03-24 06:36:48 +00007749 case CTOR_INITIALIZER_DELEGATING:
7750 TInfo = GetTypeSourceInfo(F, Record, Idx);
7751 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007752
Richard Smithc2bb8182015-03-24 06:36:48 +00007753 case CTOR_INITIALIZER_MEMBER:
7754 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7755 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007756
Richard Smithc2bb8182015-03-24 06:36:48 +00007757 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7758 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7759 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007760 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007761
7762 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7763 Expr *Init = ReadExpr(F);
7764 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7765 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7766 bool IsWritten = Record[Idx++];
7767 unsigned SourceOrderOrNumArrayIndices;
7768 SmallVector<VarDecl *, 8> Indices;
7769 if (IsWritten) {
7770 SourceOrderOrNumArrayIndices = Record[Idx++];
7771 } else {
7772 SourceOrderOrNumArrayIndices = Record[Idx++];
7773 Indices.reserve(SourceOrderOrNumArrayIndices);
7774 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7775 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7776 }
7777
7778 CXXCtorInitializer *BOMInit;
7779 if (Type == CTOR_INITIALIZER_BASE) {
7780 BOMInit = new (Context)
7781 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7782 RParenLoc, MemberOrEllipsisLoc);
7783 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7784 BOMInit = new (Context)
7785 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7786 } else if (IsWritten) {
7787 if (Member)
7788 BOMInit = new (Context) CXXCtorInitializer(
7789 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7790 else
7791 BOMInit = new (Context)
7792 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7793 LParenLoc, Init, RParenLoc);
7794 } else {
7795 if (IndirectMember) {
7796 assert(Indices.empty() && "Indirect field improperly initialized");
7797 BOMInit = new (Context)
7798 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7799 LParenLoc, Init, RParenLoc);
7800 } else {
7801 BOMInit = CXXCtorInitializer::Create(
7802 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7803 Indices.data(), Indices.size());
7804 }
7805 }
7806
7807 if (IsWritten)
7808 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7809 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007810 }
7811
Richard Smithc2bb8182015-03-24 06:36:48 +00007812 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007813}
7814
7815NestedNameSpecifier *
7816ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7817 const RecordData &Record, unsigned &Idx) {
7818 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007819 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007820 for (unsigned I = 0; I != N; ++I) {
7821 NestedNameSpecifier::SpecifierKind Kind
7822 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7823 switch (Kind) {
7824 case NestedNameSpecifier::Identifier: {
7825 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7826 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7827 break;
7828 }
7829
7830 case NestedNameSpecifier::Namespace: {
7831 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7832 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7833 break;
7834 }
7835
7836 case NestedNameSpecifier::NamespaceAlias: {
7837 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7838 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7839 break;
7840 }
7841
7842 case NestedNameSpecifier::TypeSpec:
7843 case NestedNameSpecifier::TypeSpecWithTemplate: {
7844 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7845 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007846 return nullptr;
7847
Guy Benyei11169dd2012-12-18 14:30:41 +00007848 bool Template = Record[Idx++];
7849 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7850 break;
7851 }
7852
7853 case NestedNameSpecifier::Global: {
7854 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7855 // No associated value, and there can't be a prefix.
7856 break;
7857 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007858
7859 case NestedNameSpecifier::Super: {
7860 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7861 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7862 break;
7863 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007864 }
7865 Prev = NNS;
7866 }
7867 return NNS;
7868}
7869
7870NestedNameSpecifierLoc
7871ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7872 unsigned &Idx) {
7873 unsigned N = Record[Idx++];
7874 NestedNameSpecifierLocBuilder Builder;
7875 for (unsigned I = 0; I != N; ++I) {
7876 NestedNameSpecifier::SpecifierKind Kind
7877 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7878 switch (Kind) {
7879 case NestedNameSpecifier::Identifier: {
7880 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7881 SourceRange Range = ReadSourceRange(F, Record, Idx);
7882 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7883 break;
7884 }
7885
7886 case NestedNameSpecifier::Namespace: {
7887 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7888 SourceRange Range = ReadSourceRange(F, Record, Idx);
7889 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7890 break;
7891 }
7892
7893 case NestedNameSpecifier::NamespaceAlias: {
7894 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7895 SourceRange Range = ReadSourceRange(F, Record, Idx);
7896 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7897 break;
7898 }
7899
7900 case NestedNameSpecifier::TypeSpec:
7901 case NestedNameSpecifier::TypeSpecWithTemplate: {
7902 bool Template = Record[Idx++];
7903 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7904 if (!T)
7905 return NestedNameSpecifierLoc();
7906 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7907
7908 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7909 Builder.Extend(Context,
7910 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7911 T->getTypeLoc(), ColonColonLoc);
7912 break;
7913 }
7914
7915 case NestedNameSpecifier::Global: {
7916 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7917 Builder.MakeGlobal(Context, ColonColonLoc);
7918 break;
7919 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007920
7921 case NestedNameSpecifier::Super: {
7922 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7923 SourceRange Range = ReadSourceRange(F, Record, Idx);
7924 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7925 break;
7926 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007927 }
7928 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007929
Guy Benyei11169dd2012-12-18 14:30:41 +00007930 return Builder.getWithLocInContext(Context);
7931}
7932
7933SourceRange
7934ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7935 unsigned &Idx) {
7936 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7937 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7938 return SourceRange(beg, end);
7939}
7940
7941/// \brief Read an integral value
7942llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7943 unsigned BitWidth = Record[Idx++];
7944 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7945 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7946 Idx += NumWords;
7947 return Result;
7948}
7949
7950/// \brief Read a signed integral value
7951llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7952 bool isUnsigned = Record[Idx++];
7953 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7954}
7955
7956/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007957llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7958 const llvm::fltSemantics &Sem,
7959 unsigned &Idx) {
7960 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007961}
7962
7963// \brief Read a string
7964std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7965 unsigned Len = Record[Idx++];
7966 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7967 Idx += Len;
7968 return Result;
7969}
7970
Richard Smith7ed1bc92014-12-05 22:42:13 +00007971std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7972 unsigned &Idx) {
7973 std::string Filename = ReadString(Record, Idx);
7974 ResolveImportedPath(F, Filename);
7975 return Filename;
7976}
7977
Guy Benyei11169dd2012-12-18 14:30:41 +00007978VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7979 unsigned &Idx) {
7980 unsigned Major = Record[Idx++];
7981 unsigned Minor = Record[Idx++];
7982 unsigned Subminor = Record[Idx++];
7983 if (Minor == 0)
7984 return VersionTuple(Major);
7985 if (Subminor == 0)
7986 return VersionTuple(Major, Minor - 1);
7987 return VersionTuple(Major, Minor - 1, Subminor - 1);
7988}
7989
7990CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7991 const RecordData &Record,
7992 unsigned &Idx) {
7993 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7994 return CXXTemporary::Create(Context, Decl);
7995}
7996
7997DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007998 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007999}
8000
8001DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8002 return Diags.Report(Loc, DiagID);
8003}
8004
8005/// \brief Retrieve the identifier table associated with the
8006/// preprocessor.
8007IdentifierTable &ASTReader::getIdentifierTable() {
8008 return PP.getIdentifierTable();
8009}
8010
8011/// \brief Record that the given ID maps to the given switch-case
8012/// statement.
8013void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008014 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008015 "Already have a SwitchCase with this ID");
8016 (*CurrSwitchCaseStmts)[ID] = SC;
8017}
8018
8019/// \brief Retrieve the switch-case statement with the given ID.
8020SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008021 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008022 return (*CurrSwitchCaseStmts)[ID];
8023}
8024
8025void ASTReader::ClearSwitchCaseIDs() {
8026 CurrSwitchCaseStmts->clear();
8027}
8028
8029void ASTReader::ReadComments() {
8030 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008031 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008032 serialization::ModuleFile *> >::iterator
8033 I = CommentsCursors.begin(),
8034 E = CommentsCursors.end();
8035 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008036 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008037 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008038 serialization::ModuleFile &F = *I->second;
8039 SavedStreamPosition SavedPosition(Cursor);
8040
8041 RecordData Record;
8042 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008043 llvm::BitstreamEntry Entry =
8044 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008045
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008046 switch (Entry.Kind) {
8047 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8048 case llvm::BitstreamEntry::Error:
8049 Error("malformed block record in AST file");
8050 return;
8051 case llvm::BitstreamEntry::EndBlock:
8052 goto NextCursor;
8053 case llvm::BitstreamEntry::Record:
8054 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008055 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008056 }
8057
8058 // Read a record.
8059 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008060 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008061 case COMMENTS_RAW_COMMENT: {
8062 unsigned Idx = 0;
8063 SourceRange SR = ReadSourceRange(F, Record, Idx);
8064 RawComment::CommentKind Kind =
8065 (RawComment::CommentKind) Record[Idx++];
8066 bool IsTrailingComment = Record[Idx++];
8067 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008068 Comments.push_back(new (Context) RawComment(
8069 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8070 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008071 break;
8072 }
8073 }
8074 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008075 NextCursor:
8076 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008077 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008078}
8079
Richard Smithcd45dbc2014-04-19 03:48:30 +00008080std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8081 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008082 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008083 return M->getFullModuleName();
8084
8085 // Otherwise, use the name of the top-level module the decl is within.
8086 if (ModuleFile *M = getOwningModuleFile(D))
8087 return M->ModuleName;
8088
8089 // Not from a module.
8090 return "";
8091}
8092
Guy Benyei11169dd2012-12-18 14:30:41 +00008093void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008094 while (!PendingIdentifierInfos.empty() ||
8095 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008096 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008097 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008098 // If any identifiers with corresponding top-level declarations have
8099 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008100 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8101 TopLevelDeclsMap;
8102 TopLevelDeclsMap TopLevelDecls;
8103
Guy Benyei11169dd2012-12-18 14:30:41 +00008104 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008105 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008106 SmallVector<uint32_t, 4> DeclIDs =
8107 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008108 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008109
8110 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008111 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008112
Richard Smith851072e2014-05-19 20:59:20 +00008113 // For each decl chain that we wanted to complete while deserializing, mark
8114 // it as "still needs to be completed".
8115 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8116 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8117 }
8118 PendingIncompleteDeclChains.clear();
8119
Guy Benyei11169dd2012-12-18 14:30:41 +00008120 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008121 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008122 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008123 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008124 }
8125 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008126 PendingDeclChains.clear();
8127
Richard Smith9b88a4c2015-07-27 05:40:23 +00008128 assert(RedeclsDeserialized.empty() && "some redecls not wired up");
8129
Douglas Gregor6168bd22013-02-18 15:53:43 +00008130 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008131 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8132 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008133 IdentifierInfo *II = TLD->first;
8134 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008135 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008136 }
8137 }
8138
Guy Benyei11169dd2012-12-18 14:30:41 +00008139 // Load any pending macro definitions.
8140 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008141 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8142 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8143 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8144 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008145 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008146 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008147 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008148 if (Info.M->Kind != MK_ImplicitModule &&
8149 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008150 resolvePendingMacro(II, Info);
8151 }
8152 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008153 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008154 ++IDIdx) {
8155 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008156 if (Info.M->Kind == MK_ImplicitModule ||
8157 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008158 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008159 }
8160 }
8161 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008162
8163 // Wire up the DeclContexts for Decls that we delayed setting until
8164 // recursive loading is completed.
8165 while (!PendingDeclContextInfos.empty()) {
8166 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8167 PendingDeclContextInfos.pop_front();
8168 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8169 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8170 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8171 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008172
Richard Smithd1c46742014-04-30 02:24:17 +00008173 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008174 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008175 auto Update = PendingUpdateRecords.pop_back_val();
8176 ReadingKindTracker ReadingKind(Read_Decl, *this);
8177 loadDeclUpdateRecords(Update.first, Update.second);
8178 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008179 }
Richard Smith8a639892015-01-24 01:07:20 +00008180
8181 // At this point, all update records for loaded decls are in place, so any
8182 // fake class definitions should have become real.
8183 assert(PendingFakeDefinitionData.empty() &&
8184 "faked up a class definition but never saw the real one");
8185
Guy Benyei11169dd2012-12-18 14:30:41 +00008186 // If we deserialized any C++ or Objective-C class definitions, any
8187 // Objective-C protocol definitions, or any redeclarable templates, make sure
8188 // that all redeclarations point to the definitions. Note that this can only
8189 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008190 for (Decl *D : PendingDefinitions) {
8191 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008192 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008193 // Make sure that the TagType points at the definition.
8194 const_cast<TagType*>(TagT)->decl = TD;
8195 }
Richard Smith8ce51082015-03-11 01:44:51 +00008196
Craig Topperc6914d02014-08-25 04:15:02 +00008197 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008198 for (auto *R = getMostRecentExistingDecl(RD); R;
8199 R = R->getPreviousDecl()) {
8200 assert((R == D) ==
8201 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008202 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008203 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008204 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008205 }
8206
8207 continue;
8208 }
Richard Smith8ce51082015-03-11 01:44:51 +00008209
Craig Topperc6914d02014-08-25 04:15:02 +00008210 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008211 // Make sure that the ObjCInterfaceType points at the definition.
8212 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8213 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008214
8215 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8216 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8217
Guy Benyei11169dd2012-12-18 14:30:41 +00008218 continue;
8219 }
Richard Smith8ce51082015-03-11 01:44:51 +00008220
Craig Topperc6914d02014-08-25 04:15:02 +00008221 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008222 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8223 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8224
Guy Benyei11169dd2012-12-18 14:30:41 +00008225 continue;
8226 }
Richard Smith8ce51082015-03-11 01:44:51 +00008227
Craig Topperc6914d02014-08-25 04:15:02 +00008228 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008229 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8230 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008231 }
8232 PendingDefinitions.clear();
8233
8234 // Load the bodies of any functions or methods we've encountered. We do
8235 // this now (delayed) so that we can be sure that the declaration chains
8236 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008237 // FIXME: There seems to be no point in delaying this, it does not depend
8238 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008239 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8240 PBEnd = PendingBodies.end();
8241 PB != PBEnd; ++PB) {
8242 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8243 // FIXME: Check for =delete/=default?
8244 // FIXME: Complain about ODR violations here?
8245 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8246 FD->setLazyBody(PB->second);
8247 continue;
8248 }
8249
8250 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8251 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8252 MD->setLazyBody(PB->second);
8253 }
8254 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008255
8256 // Do some cleanup.
8257 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8258 getContext().deduplicateMergedDefinitonsFor(ND);
8259 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008260}
8261
8262void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008263 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8264 return;
8265
Richard Smitha0ce9c42014-07-29 23:23:27 +00008266 // Trigger the import of the full definition of each class that had any
8267 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008268 // These updates may in turn find and diagnose some ODR failures, so take
8269 // ownership of the set first.
8270 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8271 PendingOdrMergeFailures.clear();
8272 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008273 Merge.first->buildLookup();
8274 Merge.first->decls_begin();
8275 Merge.first->bases_begin();
8276 Merge.first->vbases_begin();
8277 for (auto *RD : Merge.second) {
8278 RD->decls_begin();
8279 RD->bases_begin();
8280 RD->vbases_begin();
8281 }
8282 }
8283
8284 // For each declaration from a merged context, check that the canonical
8285 // definition of that context also contains a declaration of the same
8286 // entity.
8287 //
8288 // Caution: this loop does things that might invalidate iterators into
8289 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8290 while (!PendingOdrMergeChecks.empty()) {
8291 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8292
8293 // FIXME: Skip over implicit declarations for now. This matters for things
8294 // like implicitly-declared special member functions. This isn't entirely
8295 // correct; we can end up with multiple unmerged declarations of the same
8296 // implicit entity.
8297 if (D->isImplicit())
8298 continue;
8299
8300 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008301
8302 bool Found = false;
8303 const Decl *DCanon = D->getCanonicalDecl();
8304
Richard Smith01bdb7a2014-08-28 05:44:07 +00008305 for (auto RI : D->redecls()) {
8306 if (RI->getLexicalDeclContext() == CanonDef) {
8307 Found = true;
8308 break;
8309 }
8310 }
8311 if (Found)
8312 continue;
8313
Richard Smith0f4e2c42015-08-06 04:23:48 +00008314 // Quick check failed, time to do the slow thing. Note, we can't just
8315 // look up the name of D in CanonDef here, because the member that is
8316 // in CanonDef might not be found by name lookup (it might have been
8317 // replaced by a more recent declaration in the lookup table), and we
8318 // can't necessarily find it in the redeclaration chain because it might
8319 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008320 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008321 for (auto *CanonMember : CanonDef->decls()) {
8322 if (CanonMember->getCanonicalDecl() == DCanon) {
8323 // This can happen if the declaration is merely mergeable and not
8324 // actually redeclarable (we looked for redeclarations earlier).
8325 //
8326 // FIXME: We should be able to detect this more efficiently, without
8327 // pulling in all of the members of CanonDef.
8328 Found = true;
8329 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008330 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008331 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8332 if (ND->getDeclName() == D->getDeclName())
8333 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008334 }
8335
8336 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008337 // The AST doesn't like TagDecls becoming invalid after they've been
8338 // completed. We only really need to mark FieldDecls as invalid here.
8339 if (!isa<TagDecl>(D))
8340 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008341
8342 // Ensure we don't accidentally recursively enter deserialization while
8343 // we're producing our diagnostic.
8344 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008345
8346 std::string CanonDefModule =
8347 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8348 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8349 << D << getOwningModuleNameForDiagnostic(D)
8350 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8351
8352 if (Candidates.empty())
8353 Diag(cast<Decl>(CanonDef)->getLocation(),
8354 diag::note_module_odr_violation_no_possible_decls) << D;
8355 else {
8356 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8357 Diag(Candidates[I]->getLocation(),
8358 diag::note_module_odr_violation_possible_decl)
8359 << Candidates[I];
8360 }
8361
8362 DiagnosedOdrMergeFailures.insert(CanonDef);
8363 }
8364 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008365
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008366 if (OdrMergeFailures.empty())
8367 return;
8368
8369 // Ensure we don't accidentally recursively enter deserialization while
8370 // we're producing our diagnostics.
8371 Deserializing RecursionGuard(this);
8372
Richard Smithcd45dbc2014-04-19 03:48:30 +00008373 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008374 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008375 // If we've already pointed out a specific problem with this class, don't
8376 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008377 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008378 continue;
8379
8380 bool Diagnosed = false;
8381 for (auto *RD : Merge.second) {
8382 // Multiple different declarations got merged together; tell the user
8383 // where they came from.
8384 if (Merge.first != RD) {
8385 // FIXME: Walk the definition, figure out what's different,
8386 // and diagnose that.
8387 if (!Diagnosed) {
8388 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8389 Diag(Merge.first->getLocation(),
8390 diag::err_module_odr_violation_different_definitions)
8391 << Merge.first << Module.empty() << Module;
8392 Diagnosed = true;
8393 }
8394
8395 Diag(RD->getLocation(),
8396 diag::note_module_odr_violation_different_definitions)
8397 << getOwningModuleNameForDiagnostic(RD);
8398 }
8399 }
8400
8401 if (!Diagnosed) {
8402 // All definitions are updates to the same declaration. This happens if a
8403 // module instantiates the declaration of a class template specialization
8404 // and two or more other modules instantiate its definition.
8405 //
8406 // FIXME: Indicate which modules had instantiations of this definition.
8407 // FIXME: How can this even happen?
8408 Diag(Merge.first->getLocation(),
8409 diag::err_module_odr_violation_different_instantiations)
8410 << Merge.first;
8411 }
8412 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008413}
8414
Richard Smithce18a182015-07-14 00:26:00 +00008415void ASTReader::StartedDeserializing() {
8416 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8417 ReadTimer->startTimer();
8418}
8419
Guy Benyei11169dd2012-12-18 14:30:41 +00008420void ASTReader::FinishedDeserializing() {
8421 assert(NumCurrentElementsDeserializing &&
8422 "FinishedDeserializing not paired with StartedDeserializing");
8423 if (NumCurrentElementsDeserializing == 1) {
8424 // We decrease NumCurrentElementsDeserializing only after pending actions
8425 // are finished, to avoid recursively re-calling finishPendingActions().
8426 finishPendingActions();
8427 }
8428 --NumCurrentElementsDeserializing;
8429
Richard Smitha0ce9c42014-07-29 23:23:27 +00008430 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008431 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008432 while (!PendingExceptionSpecUpdates.empty()) {
8433 auto Updates = std::move(PendingExceptionSpecUpdates);
8434 PendingExceptionSpecUpdates.clear();
8435 for (auto Update : Updates) {
8436 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8437 SemaObj->UpdateExceptionSpec(Update.second,
8438 FPT->getExtProtoInfo().ExceptionSpec);
8439 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008440 }
8441
Richard Smithce18a182015-07-14 00:26:00 +00008442 if (ReadTimer)
8443 ReadTimer->stopTimer();
8444
Richard Smith0f4e2c42015-08-06 04:23:48 +00008445 diagnoseOdrViolations();
8446
Richard Smith04d05b52014-03-23 00:27:18 +00008447 // We are not in recursive loading, so it's safe to pass the "interesting"
8448 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008449 if (Consumer)
8450 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008451 }
8452}
8453
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008454void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008455 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8456 // Remove any fake results before adding any real ones.
8457 auto It = PendingFakeLookupResults.find(II);
8458 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008459 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008460 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008461 // FIXME: this works around module+PCH performance issue.
8462 // Rather than erase the result from the map, which is O(n), just clear
8463 // the vector of NamedDecls.
8464 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008465 }
8466 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008467
8468 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8469 SemaObj->TUScope->AddDecl(D);
8470 } else if (SemaObj->TUScope) {
8471 // Adding the decl to IdResolver may have failed because it was already in
8472 // (even though it was not added in scope). If it is already in, make sure
8473 // it gets in the scope as well.
8474 if (std::find(SemaObj->IdResolver.begin(Name),
8475 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8476 SemaObj->TUScope->AddDecl(D);
8477 }
8478}
8479
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008480ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008481 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008482 StringRef isysroot, bool DisableValidation,
8483 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008484 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Richard Smithce18a182015-07-14 00:26:00 +00008485 bool UseGlobalIndex,
8486 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008487 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008488 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008489 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008490 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008491 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008492 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008493 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008494 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8495 AllowConfigurationMismatch(AllowConfigurationMismatch),
8496 ValidateSystemInputs(ValidateSystemInputs),
8497 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008498 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8499 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8500 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8501 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008502 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8503 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8504 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8505 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8506 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8507 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008508 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008509 SourceMgr.setExternalSLocEntrySource(this);
8510}
8511
8512ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008513 if (OwnsDeserializationListener)
8514 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008515}