blob: 8e19c708f733d17e7ee010d5019951c1f0d9ead7 [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}
Richard Smith216a3bd2015-08-13 17:57:10 +0000141void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
142 ModuleKind Kind) {
143 First->visitModuleFile(Filename, Kind);
144 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000145}
Ben Langmuircb69b572014-03-07 06:40:32 +0000146bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000147 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000148 bool isOverridden,
149 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000150 bool Continue = false;
151 if (First->needsInputFileVisitation() &&
152 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000153 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
154 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000155 if (Second->needsInputFileVisitation() &&
156 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000157 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
158 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000159 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000160}
161
Guy Benyei11169dd2012-12-18 14:30:41 +0000162//===----------------------------------------------------------------------===//
163// PCH validator implementation
164//===----------------------------------------------------------------------===//
165
166ASTReaderListener::~ASTReaderListener() {}
167
168/// \brief Compare the given set of language options against an existing set of
169/// language options.
170///
171/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000172/// \param AllowCompatibleDifferences If true, differences between compatible
173/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000174///
175/// \returns true if the languagae options mis-match, false otherwise.
176static bool checkLanguageOptions(const LangOptions &LangOpts,
177 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000178 DiagnosticsEngine *Diags,
179 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000180#define LANGOPT(Name, Bits, Default, Description) \
181 if (ExistingLangOpts.Name != LangOpts.Name) { \
182 if (Diags) \
183 Diags->Report(diag::err_pch_langopt_mismatch) \
184 << Description << LangOpts.Name << ExistingLangOpts.Name; \
185 return true; \
186 }
187
188#define VALUE_LANGOPT(Name, Bits, Default, Description) \
189 if (ExistingLangOpts.Name != LangOpts.Name) { \
190 if (Diags) \
191 Diags->Report(diag::err_pch_langopt_value_mismatch) \
192 << Description; \
193 return true; \
194 }
195
196#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
197 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
198 if (Diags) \
199 Diags->Report(diag::err_pch_langopt_value_mismatch) \
200 << Description; \
201 return true; \
202 }
203
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000204#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
205 if (!AllowCompatibleDifferences) \
206 LANGOPT(Name, Bits, Default, Description)
207
208#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
209 if (!AllowCompatibleDifferences) \
210 ENUM_LANGOPT(Name, Bits, Default, Description)
211
Guy Benyei11169dd2012-12-18 14:30:41 +0000212#define BENIGN_LANGOPT(Name, Bits, Default, Description)
213#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
214#include "clang/Basic/LangOptions.def"
215
Ben Langmuircd98cb72015-06-23 18:20:18 +0000216 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
217 if (Diags)
218 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
219 return true;
220 }
221
Guy Benyei11169dd2012-12-18 14:30:41 +0000222 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
223 if (Diags)
224 Diags->Report(diag::err_pch_langopt_value_mismatch)
225 << "target Objective-C runtime";
226 return true;
227 }
228
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000229 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
230 LangOpts.CommentOpts.BlockCommandNames) {
231 if (Diags)
232 Diags->Report(diag::err_pch_langopt_value_mismatch)
233 << "block command names";
234 return true;
235 }
236
Guy Benyei11169dd2012-12-18 14:30:41 +0000237 return false;
238}
239
240/// \brief Compare the given set of target options against an existing set of
241/// target options.
242///
243/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
244///
245/// \returns true if the target options mis-match, false otherwise.
246static bool checkTargetOptions(const TargetOptions &TargetOpts,
247 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000248 DiagnosticsEngine *Diags,
249 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000250#define CHECK_TARGET_OPT(Field, Name) \
251 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
252 if (Diags) \
253 Diags->Report(diag::err_pch_targetopt_mismatch) \
254 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
255 return true; \
256 }
257
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000258 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000259 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000260 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000261
262 // We can tolerate different CPUs in many cases, notably when one CPU
263 // supports a strict superset of another. When allowing compatible
264 // differences skip this check.
265 if (!AllowCompatibleDifferences)
266 CHECK_TARGET_OPT(CPU, "target CPU");
267
Guy Benyei11169dd2012-12-18 14:30:41 +0000268#undef CHECK_TARGET_OPT
269
270 // Compare feature sets.
271 SmallVector<StringRef, 4> ExistingFeatures(
272 ExistingTargetOpts.FeaturesAsWritten.begin(),
273 ExistingTargetOpts.FeaturesAsWritten.end());
274 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
275 TargetOpts.FeaturesAsWritten.end());
276 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
277 std::sort(ReadFeatures.begin(), ReadFeatures.end());
278
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000279 // We compute the set difference in both directions explicitly so that we can
280 // diagnose the differences differently.
281 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
282 std::set_difference(
283 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
284 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
285 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
286 ExistingFeatures.begin(), ExistingFeatures.end(),
287 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000288
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000289 // If we are allowing compatible differences and the read feature set is
290 // a strict subset of the existing feature set, there is nothing to diagnose.
291 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
292 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000293
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000294 if (Diags) {
295 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000296 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000297 << /* is-existing-feature */ false << Feature;
298 for (StringRef Feature : UnmatchedExistingFeatures)
299 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
300 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000301 }
302
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000303 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000304}
305
306bool
307PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000308 bool Complain,
309 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000310 const LangOptions &ExistingLangOpts = PP.getLangOpts();
311 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000312 Complain ? &Reader.Diags : nullptr,
313 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000314}
315
316bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000317 bool Complain,
318 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000319 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
320 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000321 Complain ? &Reader.Diags : nullptr,
322 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000323}
324
325namespace {
326 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
327 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000328 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
329 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000330}
331
Ben Langmuirb92de022014-04-29 16:25:26 +0000332static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
333 DiagnosticsEngine &Diags,
334 bool Complain) {
335 typedef DiagnosticsEngine::Level Level;
336
337 // Check current mappings for new -Werror mappings, and the stored mappings
338 // for cases that were explicitly mapped to *not* be errors that are now
339 // errors because of options like -Werror.
340 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
341
342 for (DiagnosticsEngine *MappingSource : MappingSources) {
343 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
344 diag::kind DiagID = DiagIDMappingPair.first;
345 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
346 if (CurLevel < DiagnosticsEngine::Error)
347 continue; // not significant
348 Level StoredLevel =
349 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
350 if (StoredLevel < DiagnosticsEngine::Error) {
351 if (Complain)
352 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
353 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
354 return true;
355 }
356 }
357 }
358
359 return false;
360}
361
Alp Tokerac4e8e52014-06-22 21:58:33 +0000362static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
363 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
364 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
365 return true;
366 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000367}
368
369static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
370 DiagnosticsEngine &Diags,
371 bool IsSystem, bool Complain) {
372 // Top-level options
373 if (IsSystem) {
374 if (Diags.getSuppressSystemWarnings())
375 return false;
376 // If -Wsystem-headers was not enabled before, be conservative
377 if (StoredDiags.getSuppressSystemWarnings()) {
378 if (Complain)
379 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
380 return true;
381 }
382 }
383
384 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
385 if (Complain)
386 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
387 return true;
388 }
389
390 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
391 !StoredDiags.getEnableAllWarnings()) {
392 if (Complain)
393 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
394 return true;
395 }
396
397 if (isExtHandlingFromDiagsError(Diags) &&
398 !isExtHandlingFromDiagsError(StoredDiags)) {
399 if (Complain)
400 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
401 return true;
402 }
403
404 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
405}
406
407bool PCHValidator::ReadDiagnosticOptions(
408 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
409 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
410 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
411 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000412 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000413 // This should never fail, because we would have processed these options
414 // before writing them to an ASTFile.
415 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
416
417 ModuleManager &ModuleMgr = Reader.getModuleManager();
418 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
419
420 // If the original import came from a file explicitly generated by the user,
421 // don't check the diagnostic mappings.
422 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000423 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000424 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
425 // the transitive closure of its imports, since unrelated modules cannot be
426 // imported until after this module finishes validation.
427 ModuleFile *TopImport = *ModuleMgr.rbegin();
428 while (!TopImport->ImportedBy.empty())
429 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000430 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000431 return false;
432
433 StringRef ModuleName = TopImport->ModuleName;
434 assert(!ModuleName.empty() && "diagnostic options read before module name");
435
436 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
437 assert(M && "missing module");
438
439 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
440 // contains the union of their flags.
441 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
442}
443
Guy Benyei11169dd2012-12-18 14:30:41 +0000444/// \brief Collect the macro definitions provided by the given preprocessor
445/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000446static void
447collectMacroDefinitions(const PreprocessorOptions &PPOpts,
448 MacroDefinitionsMap &Macros,
449 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000450 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
451 StringRef Macro = PPOpts.Macros[I].first;
452 bool IsUndef = PPOpts.Macros[I].second;
453
454 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
455 StringRef MacroName = MacroPair.first;
456 StringRef MacroBody = MacroPair.second;
457
458 // For an #undef'd macro, we only care about the name.
459 if (IsUndef) {
460 if (MacroNames && !Macros.count(MacroName))
461 MacroNames->push_back(MacroName);
462
463 Macros[MacroName] = std::make_pair("", true);
464 continue;
465 }
466
467 // For a #define'd macro, figure out the actual definition.
468 if (MacroName.size() == Macro.size())
469 MacroBody = "1";
470 else {
471 // Note: GCC drops anything following an end-of-line character.
472 StringRef::size_type End = MacroBody.find_first_of("\n\r");
473 MacroBody = MacroBody.substr(0, End);
474 }
475
476 if (MacroNames && !Macros.count(MacroName))
477 MacroNames->push_back(MacroName);
478 Macros[MacroName] = std::make_pair(MacroBody, false);
479 }
480}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000481
Guy Benyei11169dd2012-12-18 14:30:41 +0000482/// \brief Check the preprocessor options deserialized from the control block
483/// against the preprocessor options in an existing preprocessor.
484///
485/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
486static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
487 const PreprocessorOptions &ExistingPPOpts,
488 DiagnosticsEngine *Diags,
489 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000490 std::string &SuggestedPredefines,
491 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000492 // Check macro definitions.
493 MacroDefinitionsMap ASTFileMacros;
494 collectMacroDefinitions(PPOpts, ASTFileMacros);
495 MacroDefinitionsMap ExistingMacros;
496 SmallVector<StringRef, 4> ExistingMacroNames;
497 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
498
499 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
500 // Dig out the macro definition in the existing preprocessor options.
501 StringRef MacroName = ExistingMacroNames[I];
502 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
503
504 // Check whether we know anything about this macro name or not.
505 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
506 = ASTFileMacros.find(MacroName);
507 if (Known == ASTFileMacros.end()) {
508 // FIXME: Check whether this identifier was referenced anywhere in the
509 // AST file. If so, we should reject the AST file. Unfortunately, this
510 // information isn't in the control block. What shall we do about it?
511
512 if (Existing.second) {
513 SuggestedPredefines += "#undef ";
514 SuggestedPredefines += MacroName.str();
515 SuggestedPredefines += '\n';
516 } else {
517 SuggestedPredefines += "#define ";
518 SuggestedPredefines += MacroName.str();
519 SuggestedPredefines += ' ';
520 SuggestedPredefines += Existing.first.str();
521 SuggestedPredefines += '\n';
522 }
523 continue;
524 }
525
526 // If the macro was defined in one but undef'd in the other, we have a
527 // conflict.
528 if (Existing.second != Known->second.second) {
529 if (Diags) {
530 Diags->Report(diag::err_pch_macro_def_undef)
531 << MacroName << Known->second.second;
532 }
533 return true;
534 }
535
536 // If the macro was #undef'd in both, or if the macro bodies are identical,
537 // it's fine.
538 if (Existing.second || Existing.first == Known->second.first)
539 continue;
540
541 // The macro bodies differ; complain.
542 if (Diags) {
543 Diags->Report(diag::err_pch_macro_def_conflict)
544 << MacroName << Known->second.first << Existing.first;
545 }
546 return true;
547 }
548
549 // Check whether we're using predefines.
550 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
551 if (Diags) {
552 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
553 }
554 return true;
555 }
556
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000557 // Detailed record is important since it is used for the module cache hash.
558 if (LangOpts.Modules &&
559 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
560 if (Diags) {
561 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
562 }
563 return true;
564 }
565
Guy Benyei11169dd2012-12-18 14:30:41 +0000566 // Compute the #include and #include_macros lines we need.
567 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
568 StringRef File = ExistingPPOpts.Includes[I];
569 if (File == ExistingPPOpts.ImplicitPCHInclude)
570 continue;
571
572 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
573 != PPOpts.Includes.end())
574 continue;
575
576 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000577 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000578 SuggestedPredefines += "\"\n";
579 }
580
581 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
582 StringRef File = ExistingPPOpts.MacroIncludes[I];
583 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
584 File)
585 != PPOpts.MacroIncludes.end())
586 continue;
587
588 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000589 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000590 SuggestedPredefines += "\"\n##\n";
591 }
592
593 return false;
594}
595
596bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
597 bool Complain,
598 std::string &SuggestedPredefines) {
599 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
600
601 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000602 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000603 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000604 SuggestedPredefines,
605 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000606}
607
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000608/// Check the header search options deserialized from the control block
609/// against the header search options in an existing preprocessor.
610///
611/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
612static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
613 StringRef SpecificModuleCachePath,
614 StringRef ExistingModuleCachePath,
615 DiagnosticsEngine *Diags,
616 const LangOptions &LangOpts) {
617 if (LangOpts.Modules) {
618 if (SpecificModuleCachePath != ExistingModuleCachePath) {
619 if (Diags)
620 Diags->Report(diag::err_pch_modulecache_mismatch)
621 << SpecificModuleCachePath << ExistingModuleCachePath;
622 return true;
623 }
624 }
625
626 return false;
627}
628
629bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
630 StringRef SpecificModuleCachePath,
631 bool Complain) {
632 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
633 PP.getHeaderSearchInfo().getModuleCachePath(),
634 Complain ? &Reader.Diags : nullptr,
635 PP.getLangOpts());
636}
637
Guy Benyei11169dd2012-12-18 14:30:41 +0000638void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
639 PP.setCounterValue(Value);
640}
641
642//===----------------------------------------------------------------------===//
643// AST reader implementation
644//===----------------------------------------------------------------------===//
645
Nico Weber824285e2014-05-08 04:26:47 +0000646void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
647 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000648 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000649 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000650}
651
652
653
654unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
655 return serialization::ComputeHash(Sel);
656}
657
658
659std::pair<unsigned, unsigned>
660ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000661 using namespace llvm::support;
662 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
663 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000664 return std::make_pair(KeyLen, DataLen);
665}
666
667ASTSelectorLookupTrait::internal_key_type
668ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000669 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000670 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000671 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
672 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
673 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000674 if (N == 0)
675 return SelTable.getNullarySelector(FirstII);
676 else if (N == 1)
677 return SelTable.getUnarySelector(FirstII);
678
679 SmallVector<IdentifierInfo *, 16> Args;
680 Args.push_back(FirstII);
681 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000682 Args.push_back(Reader.getLocalIdentifier(
683 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000684
685 return SelTable.getSelector(N, Args.data());
686}
687
688ASTSelectorLookupTrait::data_type
689ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
690 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000691 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000692
693 data_type Result;
694
Justin Bogner57ba0b22014-03-28 22:03:24 +0000695 Result.ID = Reader.getGlobalSelectorID(
696 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000697 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
698 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
699 Result.InstanceBits = FullInstanceBits & 0x3;
700 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
701 Result.FactoryBits = FullFactoryBits & 0x3;
702 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
703 unsigned NumInstanceMethods = FullInstanceBits >> 3;
704 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000705
706 // Load instance methods
707 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000708 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
709 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000710 Result.Instance.push_back(Method);
711 }
712
713 // Load factory methods
714 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000715 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
716 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000717 Result.Factory.push_back(Method);
718 }
719
720 return Result;
721}
722
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000723unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
724 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000725}
726
727std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000728ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000729 using namespace llvm::support;
730 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
731 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 return std::make_pair(KeyLen, DataLen);
733}
734
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000735ASTIdentifierLookupTraitBase::internal_key_type
736ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000737 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000738 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000739}
740
Douglas Gregordcf25082013-02-11 18:16:18 +0000741/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000742static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
743 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000744 return II.hadMacroDefinition() ||
745 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000746 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000747 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000748 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
749 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000750}
751
Richard Smith76c2f2c2015-07-17 20:09:43 +0000752static bool readBit(unsigned &Bits) {
753 bool Value = Bits & 0x1;
754 Bits >>= 1;
755 return Value;
756}
757
Richard Smith79bf9202015-08-24 03:33:22 +0000758IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
759 using namespace llvm::support;
760 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
761 return Reader.getGlobalIdentifierID(F, RawID >> 1);
762}
763
Guy Benyei11169dd2012-12-18 14:30:41 +0000764IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
765 const unsigned char* d,
766 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000767 using namespace llvm::support;
768 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000769 bool IsInteresting = RawID & 0x01;
770
771 // Wipe out the "is interesting" bit.
772 RawID = RawID >> 1;
773
Richard Smith76c2f2c2015-07-17 20:09:43 +0000774 // Build the IdentifierInfo and link the identifier ID with it.
775 IdentifierInfo *II = KnownII;
776 if (!II) {
777 II = &Reader.getIdentifierTable().getOwn(k);
778 KnownII = II;
779 }
780 if (!II->isFromAST()) {
781 II->setIsFromAST();
Richard Smitha534a312015-07-21 23:54:07 +0000782 if (isInterestingIdentifier(Reader, *II, F.isModule()))
Richard Smith76c2f2c2015-07-17 20:09:43 +0000783 II->setChangedSinceDeserialization();
784 }
785 Reader.markIdentifierUpToDate(II);
786
Guy Benyei11169dd2012-12-18 14:30:41 +0000787 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
788 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000789 // For uninteresting identifiers, there's nothing else to do. Just notify
790 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000791 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000792 return II;
793 }
794
Justin Bogner57ba0b22014-03-28 22:03:24 +0000795 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
796 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000797 bool CPlusPlusOperatorKeyword = readBit(Bits);
798 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000799 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000800 bool Poisoned = readBit(Bits);
801 bool ExtensionToken = readBit(Bits);
802 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000803
804 assert(Bits == 0 && "Extra bits in the identifier?");
805 DataLen -= 8;
806
Guy Benyei11169dd2012-12-18 14:30:41 +0000807 // Set or check the various bits in the IdentifierInfo structure.
808 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000809 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000810 II->revertTokenIDToIdentifier();
811 if (!F.isModule())
812 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
813 else if (HasRevertedBuiltin && II->getBuiltinID()) {
814 II->revertBuiltin();
815 assert((II->hasRevertedBuiltin() ||
816 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
817 "Incorrect ObjC keyword or builtin ID");
818 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000819 assert(II->isExtensionToken() == ExtensionToken &&
820 "Incorrect extension token flag");
821 (void)ExtensionToken;
822 if (Poisoned)
823 II->setIsPoisoned(true);
824 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
825 "Incorrect C++ operator keyword flag");
826 (void)CPlusPlusOperatorKeyword;
827
828 // If this identifier is a macro, deserialize the macro
829 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000830 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000831 uint32_t MacroDirectivesOffset =
832 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000833 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000834
Richard Smithd7329392015-04-21 21:46:32 +0000835 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000836 }
837
838 Reader.SetIdentifierInfo(ID, II);
839
840 // Read all of the declarations visible at global scope with this
841 // name.
842 if (DataLen > 0) {
843 SmallVector<uint32_t, 4> DeclIDs;
844 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000845 DeclIDs.push_back(Reader.getGlobalDeclID(
846 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000847 Reader.SetGloballyVisibleDecls(II, DeclIDs);
848 }
849
850 return II;
851}
852
853unsigned
Richard Smith3b637412015-07-14 18:42:41 +0000854ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000855 llvm::FoldingSetNodeID ID;
856 ID.AddInteger(Key.Kind);
857
858 switch (Key.Kind) {
859 case DeclarationName::Identifier:
860 case DeclarationName::CXXLiteralOperatorName:
861 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
862 break;
863 case DeclarationName::ObjCZeroArgSelector:
864 case DeclarationName::ObjCOneArgSelector:
865 case DeclarationName::ObjCMultiArgSelector:
866 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
867 break;
868 case DeclarationName::CXXOperatorName:
869 ID.AddInteger((OverloadedOperatorKind)Key.Data);
870 break;
871 case DeclarationName::CXXConstructorName:
872 case DeclarationName::CXXDestructorName:
873 case DeclarationName::CXXConversionFunctionName:
874 case DeclarationName::CXXUsingDirective:
875 break;
876 }
877
878 return ID.ComputeHash();
879}
880
881ASTDeclContextNameLookupTrait::internal_key_type
882ASTDeclContextNameLookupTrait::GetInternalKey(
Richard Smith3b637412015-07-14 18:42:41 +0000883 const external_key_type& Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000884 DeclNameKey Key;
885 Key.Kind = Name.getNameKind();
886 switch (Name.getNameKind()) {
887 case DeclarationName::Identifier:
888 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
889 break;
890 case DeclarationName::ObjCZeroArgSelector:
891 case DeclarationName::ObjCOneArgSelector:
892 case DeclarationName::ObjCMultiArgSelector:
893 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
894 break;
895 case DeclarationName::CXXOperatorName:
896 Key.Data = Name.getCXXOverloadedOperator();
897 break;
898 case DeclarationName::CXXLiteralOperatorName:
899 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
900 break;
901 case DeclarationName::CXXConstructorName:
902 case DeclarationName::CXXDestructorName:
903 case DeclarationName::CXXConversionFunctionName:
904 case DeclarationName::CXXUsingDirective:
905 Key.Data = 0;
906 break;
907 }
908
909 return Key;
910}
911
912std::pair<unsigned, unsigned>
913ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000914 using namespace llvm::support;
915 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
916 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000917 return std::make_pair(KeyLen, DataLen);
918}
919
920ASTDeclContextNameLookupTrait::internal_key_type
921ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000922 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000923
924 DeclNameKey Key;
925 Key.Kind = (DeclarationName::NameKind)*d++;
926 switch (Key.Kind) {
927 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000928 Key.Data = (uint64_t)Reader.getLocalIdentifier(
929 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000930 break;
931 case DeclarationName::ObjCZeroArgSelector:
932 case DeclarationName::ObjCOneArgSelector:
933 case DeclarationName::ObjCMultiArgSelector:
934 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000935 (uint64_t)Reader.getLocalSelector(
936 F, endian::readNext<uint32_t, little, unaligned>(
937 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000938 break;
939 case DeclarationName::CXXOperatorName:
940 Key.Data = *d++; // OverloadedOperatorKind
941 break;
942 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000943 Key.Data = (uint64_t)Reader.getLocalIdentifier(
944 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 break;
946 case DeclarationName::CXXConstructorName:
947 case DeclarationName::CXXDestructorName:
948 case DeclarationName::CXXConversionFunctionName:
949 case DeclarationName::CXXUsingDirective:
950 Key.Data = 0;
951 break;
952 }
953
954 return Key;
955}
956
Richard Smithf02662d2015-07-30 03:17:16 +0000957ASTDeclContextNameLookupTrait::data_type
958ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
959 const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000960 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000961 using namespace llvm::support;
Richard Smithf02662d2015-07-30 03:17:16 +0000962 unsigned NumDecls = DataLen / 4;
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000963 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
964 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000965 return std::make_pair(Start, Start + NumDecls);
966}
967
Richard Smith0f4e2c42015-08-06 04:23:48 +0000968bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
969 BitstreamCursor &Cursor,
970 uint64_t Offset,
971 DeclContext *DC) {
972 assert(Offset != 0);
973
Guy Benyei11169dd2012-12-18 14:30:41 +0000974 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +0000975 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000976
Richard Smith0f4e2c42015-08-06 04:23:48 +0000977 RecordData Record;
978 StringRef Blob;
979 unsigned Code = Cursor.ReadCode();
980 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
981 if (RecCode != DECL_CONTEXT_LEXICAL) {
982 Error("Expected lexical block");
983 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000984 }
985
Richard Smith82f8fcd2015-08-06 22:07:25 +0000986 assert(!isa<TranslationUnitDecl>(DC) &&
987 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +0000988 // If we are handling a C++ class template instantiation, we can see multiple
989 // lexical updates for the same record. It's important that we select only one
990 // of them, so that field numbering works properly. Just pick the first one we
991 // see.
992 auto &Lex = LexicalDecls[DC];
993 if (!Lex.first) {
994 Lex = std::make_pair(
995 &M, llvm::makeArrayRef(
996 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
997 Blob.data()),
998 Blob.size() / 4));
999 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001000 DC->setHasExternalLexicalStorage(true);
1001 return false;
1002}
Guy Benyei11169dd2012-12-18 14:30:41 +00001003
Richard Smith0f4e2c42015-08-06 04:23:48 +00001004bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1005 BitstreamCursor &Cursor,
1006 uint64_t Offset,
1007 DeclID ID) {
1008 assert(Offset != 0);
1009
1010 SavedStreamPosition SavedPosition(Cursor);
1011 Cursor.JumpToBit(Offset);
1012
1013 RecordData Record;
1014 StringRef Blob;
1015 unsigned Code = Cursor.ReadCode();
1016 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1017 if (RecCode != DECL_CONTEXT_VISIBLE) {
1018 Error("Expected visible lookup table block");
1019 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001020 }
1021
Richard Smith0f4e2c42015-08-06 04:23:48 +00001022 // We can't safely determine the primary context yet, so delay attaching the
1023 // lookup table until we're done with recursive deserialization.
1024 unsigned BucketOffset = Record[0];
1025 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{
1026 &M, (const unsigned char *)Blob.data(), BucketOffset});
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 return false;
1028}
1029
1030void ASTReader::Error(StringRef Msg) {
1031 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001032 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1033 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001034 Diag(diag::note_module_cache_path)
1035 << PP.getHeaderSearchInfo().getModuleCachePath();
1036 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001037}
1038
1039void ASTReader::Error(unsigned DiagID,
1040 StringRef Arg1, StringRef Arg2) {
1041 if (Diags.isDiagnosticInFlight())
1042 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1043 else
1044 Diag(DiagID) << Arg1 << Arg2;
1045}
1046
1047//===----------------------------------------------------------------------===//
1048// Source Manager Deserialization
1049//===----------------------------------------------------------------------===//
1050
1051/// \brief Read the line table in the source manager block.
1052/// \returns true if there was an error.
1053bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001054 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001055 unsigned Idx = 0;
1056 LineTableInfo &LineTable = SourceMgr.getLineTable();
1057
1058 // Parse the file names
1059 std::map<int, int> FileIDs;
1060 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1061 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001062 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001063 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1064 }
1065
1066 // Parse the line entries
1067 std::vector<LineEntry> Entries;
1068 while (Idx < Record.size()) {
1069 int FID = Record[Idx++];
1070 assert(FID >= 0 && "Serialized line entries for non-local file.");
1071 // Remap FileID from 1-based old view.
1072 FID += F.SLocEntryBaseID - 1;
1073
1074 // Extract the line entries
1075 unsigned NumEntries = Record[Idx++];
1076 assert(NumEntries && "Numentries is 00000");
1077 Entries.clear();
1078 Entries.reserve(NumEntries);
1079 for (unsigned I = 0; I != NumEntries; ++I) {
1080 unsigned FileOffset = Record[Idx++];
1081 unsigned LineNo = Record[Idx++];
1082 int FilenameID = FileIDs[Record[Idx++]];
1083 SrcMgr::CharacteristicKind FileKind
1084 = (SrcMgr::CharacteristicKind)Record[Idx++];
1085 unsigned IncludeOffset = Record[Idx++];
1086 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1087 FileKind, IncludeOffset));
1088 }
1089 LineTable.AddEntry(FileID::get(FID), Entries);
1090 }
1091
1092 return false;
1093}
1094
1095/// \brief Read a source manager block
1096bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1097 using namespace SrcMgr;
1098
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001099 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001100
1101 // Set the source-location entry cursor to the current position in
1102 // the stream. This cursor will be used to read the contents of the
1103 // source manager block initially, and then lazily read
1104 // source-location entries as needed.
1105 SLocEntryCursor = F.Stream;
1106
1107 // The stream itself is going to skip over the source manager block.
1108 if (F.Stream.SkipBlock()) {
1109 Error("malformed block record in AST file");
1110 return true;
1111 }
1112
1113 // Enter the source manager block.
1114 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1115 Error("malformed source manager block record in AST file");
1116 return true;
1117 }
1118
1119 RecordData Record;
1120 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001121 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1122
1123 switch (E.Kind) {
1124 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1125 case llvm::BitstreamEntry::Error:
1126 Error("malformed block record in AST file");
1127 return true;
1128 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001129 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001130 case llvm::BitstreamEntry::Record:
1131 // The interesting case.
1132 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001133 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001134
Guy Benyei11169dd2012-12-18 14:30:41 +00001135 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001136 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001137 StringRef Blob;
1138 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001139 default: // Default behavior: ignore.
1140 break;
1141
1142 case SM_SLOC_FILE_ENTRY:
1143 case SM_SLOC_BUFFER_ENTRY:
1144 case SM_SLOC_EXPANSION_ENTRY:
1145 // Once we hit one of the source location entries, we're done.
1146 return false;
1147 }
1148 }
1149}
1150
1151/// \brief If a header file is not found at the path that we expect it to be
1152/// and the PCH file was moved from its original location, try to resolve the
1153/// file by assuming that header+PCH were moved together and the header is in
1154/// the same place relative to the PCH.
1155static std::string
1156resolveFileRelativeToOriginalDir(const std::string &Filename,
1157 const std::string &OriginalDir,
1158 const std::string &CurrDir) {
1159 assert(OriginalDir != CurrDir &&
1160 "No point trying to resolve the file if the PCH dir didn't change");
1161 using namespace llvm::sys;
1162 SmallString<128> filePath(Filename);
1163 fs::make_absolute(filePath);
1164 assert(path::is_absolute(OriginalDir));
1165 SmallString<128> currPCHPath(CurrDir);
1166
1167 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1168 fileDirE = path::end(path::parent_path(filePath));
1169 path::const_iterator origDirI = path::begin(OriginalDir),
1170 origDirE = path::end(OriginalDir);
1171 // Skip the common path components from filePath and OriginalDir.
1172 while (fileDirI != fileDirE && origDirI != origDirE &&
1173 *fileDirI == *origDirI) {
1174 ++fileDirI;
1175 ++origDirI;
1176 }
1177 for (; origDirI != origDirE; ++origDirI)
1178 path::append(currPCHPath, "..");
1179 path::append(currPCHPath, fileDirI, fileDirE);
1180 path::append(currPCHPath, path::filename(Filename));
1181 return currPCHPath.str();
1182}
1183
1184bool ASTReader::ReadSLocEntry(int ID) {
1185 if (ID == 0)
1186 return false;
1187
1188 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1189 Error("source location entry ID out-of-range for AST file");
1190 return true;
1191 }
1192
1193 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1194 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001195 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001196 unsigned BaseOffset = F->SLocEntryBaseOffset;
1197
1198 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001199 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1200 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001201 Error("incorrectly-formatted source location entry in AST file");
1202 return true;
1203 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001204
Guy Benyei11169dd2012-12-18 14:30:41 +00001205 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001206 StringRef Blob;
1207 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001208 default:
1209 Error("incorrectly-formatted source location entry in AST file");
1210 return true;
1211
1212 case SM_SLOC_FILE_ENTRY: {
1213 // We will detect whether a file changed and return 'Failure' for it, but
1214 // we will also try to fail gracefully by setting up the SLocEntry.
1215 unsigned InputID = Record[4];
1216 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001217 const FileEntry *File = IF.getFile();
1218 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001219
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001220 // Note that we only check if a File was returned. If it was out-of-date
1221 // we have complained but we will continue creating a FileID to recover
1222 // gracefully.
1223 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001224 return true;
1225
1226 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1227 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1228 // This is the module's main file.
1229 IncludeLoc = getImportLocation(F);
1230 }
1231 SrcMgr::CharacteristicKind
1232 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1233 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1234 ID, BaseOffset + Record[0]);
1235 SrcMgr::FileInfo &FileInfo =
1236 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1237 FileInfo.NumCreatedFIDs = Record[5];
1238 if (Record[3])
1239 FileInfo.setHasLineDirectives();
1240
1241 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1242 unsigned NumFileDecls = Record[7];
1243 if (NumFileDecls) {
1244 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1245 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1246 NumFileDecls));
1247 }
1248
1249 const SrcMgr::ContentCache *ContentCache
1250 = SourceMgr.getOrCreateContentCache(File,
1251 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1252 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1253 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1254 unsigned Code = SLocEntryCursor.ReadCode();
1255 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001256 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001257
1258 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1259 Error("AST record has invalid code");
1260 return true;
1261 }
1262
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001263 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001264 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001265 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001266 }
1267
1268 break;
1269 }
1270
1271 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001272 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001273 unsigned Offset = Record[0];
1274 SrcMgr::CharacteristicKind
1275 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1276 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001277 if (IncludeLoc.isInvalid() &&
1278 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001279 IncludeLoc = getImportLocation(F);
1280 }
1281 unsigned Code = SLocEntryCursor.ReadCode();
1282 Record.clear();
1283 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001284 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001285
1286 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1287 Error("AST record has invalid code");
1288 return true;
1289 }
1290
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001291 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1292 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001293 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001294 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001295 break;
1296 }
1297
1298 case SM_SLOC_EXPANSION_ENTRY: {
1299 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1300 SourceMgr.createExpansionLoc(SpellingLoc,
1301 ReadSourceLocation(*F, Record[2]),
1302 ReadSourceLocation(*F, Record[3]),
1303 Record[4],
1304 ID,
1305 BaseOffset + Record[0]);
1306 break;
1307 }
1308 }
1309
1310 return false;
1311}
1312
1313std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1314 if (ID == 0)
1315 return std::make_pair(SourceLocation(), "");
1316
1317 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1318 Error("source location entry ID out-of-range for AST file");
1319 return std::make_pair(SourceLocation(), "");
1320 }
1321
1322 // Find which module file this entry lands in.
1323 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001324 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001325 return std::make_pair(SourceLocation(), "");
1326
1327 // FIXME: Can we map this down to a particular submodule? That would be
1328 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001329 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001330}
1331
1332/// \brief Find the location where the module F is imported.
1333SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1334 if (F->ImportLoc.isValid())
1335 return F->ImportLoc;
1336
1337 // Otherwise we have a PCH. It's considered to be "imported" at the first
1338 // location of its includer.
1339 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001340 // Main file is the importer.
1341 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1342 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001343 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001344 return F->ImportedBy[0]->FirstLoc;
1345}
1346
1347/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1348/// specified cursor. Read the abbreviations that are at the top of the block
1349/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001350bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001351 if (Cursor.EnterSubBlock(BlockID)) {
1352 Error("malformed block record in AST file");
1353 return Failure;
1354 }
1355
1356 while (true) {
1357 uint64_t Offset = Cursor.GetCurrentBitNo();
1358 unsigned Code = Cursor.ReadCode();
1359
1360 // We expect all abbrevs to be at the start of the block.
1361 if (Code != llvm::bitc::DEFINE_ABBREV) {
1362 Cursor.JumpToBit(Offset);
1363 return false;
1364 }
1365 Cursor.ReadAbbrevRecord();
1366 }
1367}
1368
Richard Smithe40f2ba2013-08-07 21:41:30 +00001369Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001370 unsigned &Idx) {
1371 Token Tok;
1372 Tok.startToken();
1373 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1374 Tok.setLength(Record[Idx++]);
1375 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1376 Tok.setIdentifierInfo(II);
1377 Tok.setKind((tok::TokenKind)Record[Idx++]);
1378 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1379 return Tok;
1380}
1381
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001382MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001383 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001384
1385 // Keep track of where we are in the stream, then jump back there
1386 // after reading this macro.
1387 SavedStreamPosition SavedPosition(Stream);
1388
1389 Stream.JumpToBit(Offset);
1390 RecordData Record;
1391 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001392 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001393
Guy Benyei11169dd2012-12-18 14:30:41 +00001394 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001395 // Advance to the next record, but if we get to the end of the block, don't
1396 // pop it (removing all the abbreviations from the cursor) since we want to
1397 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001398 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001399 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1400
1401 switch (Entry.Kind) {
1402 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1403 case llvm::BitstreamEntry::Error:
1404 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001405 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001406 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001407 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001408 case llvm::BitstreamEntry::Record:
1409 // The interesting case.
1410 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001411 }
1412
1413 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001414 Record.clear();
1415 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001416 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001418 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001419 case PP_MACRO_DIRECTIVE_HISTORY:
1420 return Macro;
1421
Guy Benyei11169dd2012-12-18 14:30:41 +00001422 case PP_MACRO_OBJECT_LIKE:
1423 case PP_MACRO_FUNCTION_LIKE: {
1424 // If we already have a macro, that means that we've hit the end
1425 // of the definition of the macro we were looking for. We're
1426 // done.
1427 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001428 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001429
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001430 unsigned NextIndex = 1; // Skip identifier ID.
1431 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001432 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001433 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001434 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001435 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001436 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001437
Guy Benyei11169dd2012-12-18 14:30:41 +00001438 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1439 // Decode function-like macro info.
1440 bool isC99VarArgs = Record[NextIndex++];
1441 bool isGNUVarArgs = Record[NextIndex++];
1442 bool hasCommaPasting = Record[NextIndex++];
1443 MacroArgs.clear();
1444 unsigned NumArgs = Record[NextIndex++];
1445 for (unsigned i = 0; i != NumArgs; ++i)
1446 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1447
1448 // Install function-like macro info.
1449 MI->setIsFunctionLike();
1450 if (isC99VarArgs) MI->setIsC99Varargs();
1451 if (isGNUVarArgs) MI->setIsGNUVarargs();
1452 if (hasCommaPasting) MI->setHasCommaPasting();
1453 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1454 PP.getPreprocessorAllocator());
1455 }
1456
Guy Benyei11169dd2012-12-18 14:30:41 +00001457 // Remember that we saw this macro last so that we add the tokens that
1458 // form its body to it.
1459 Macro = MI;
1460
1461 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1462 Record[NextIndex]) {
1463 // We have a macro definition. Register the association
1464 PreprocessedEntityID
1465 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1466 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001467 PreprocessingRecord::PPEntityID PPID =
1468 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1469 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1470 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001471 if (PPDef)
1472 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001473 }
1474
1475 ++NumMacrosRead;
1476 break;
1477 }
1478
1479 case PP_TOKEN: {
1480 // If we see a TOKEN before a PP_MACRO_*, then the file is
1481 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001482 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001483
John McCallf413f5e2013-05-03 00:10:13 +00001484 unsigned Idx = 0;
1485 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001486 Macro->AddTokenToBody(Tok);
1487 break;
1488 }
1489 }
1490 }
1491}
1492
1493PreprocessedEntityID
1494ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1495 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1496 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1497 assert(I != M.PreprocessedEntityRemap.end()
1498 && "Invalid index into preprocessed entity index remap");
1499
1500 return LocalID + I->second;
1501}
1502
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001503unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1504 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001505}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001506
Guy Benyei11169dd2012-12-18 14:30:41 +00001507HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001508HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001509 internal_key_type ikey = {FE->getSize(),
1510 M.HasTimestamps ? FE->getModificationTime() : 0,
1511 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001512 return ikey;
1513}
Guy Benyei11169dd2012-12-18 14:30:41 +00001514
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001515bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001516 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 return false;
1518
Richard Smith7ed1bc92014-12-05 22:42:13 +00001519 if (llvm::sys::path::is_absolute(a.Filename) &&
1520 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001521 return true;
1522
Guy Benyei11169dd2012-12-18 14:30:41 +00001523 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001524 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001525 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1526 if (!Key.Imported)
1527 return FileMgr.getFile(Key.Filename);
1528
1529 std::string Resolved = Key.Filename;
1530 Reader.ResolveImportedPath(M, Resolved);
1531 return FileMgr.getFile(Resolved);
1532 };
1533
1534 const FileEntry *FEA = GetFile(a);
1535 const FileEntry *FEB = GetFile(b);
1536 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001537}
1538
1539std::pair<unsigned, unsigned>
1540HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001541 using namespace llvm::support;
1542 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001543 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001544 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001545}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001546
1547HeaderFileInfoTrait::internal_key_type
1548HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001549 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001550 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001551 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1552 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001553 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001554 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001555 return ikey;
1556}
1557
Guy Benyei11169dd2012-12-18 14:30:41 +00001558HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001559HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001560 unsigned DataLen) {
1561 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001562 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001563 HeaderFileInfo HFI;
1564 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001565 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1566 HFI.isImport |= (Flags >> 4) & 0x01;
1567 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1568 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001569 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001570 // FIXME: Find a better way to handle this. Maybe just store a
1571 // "has been included" flag?
1572 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1573 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001574 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1575 M, endian::readNext<uint32_t, little, unaligned>(d));
1576 if (unsigned FrameworkOffset =
1577 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001578 // The framework offset is 1 greater than the actual offset,
1579 // since 0 is used as an indicator for "no framework name".
1580 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1581 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1582 }
Richard Smith386bb072015-08-18 23:42:23 +00001583
1584 assert((End - d) % 4 == 0 &&
1585 "Wrong data length in HeaderFileInfo deserialization");
1586 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001587 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001588 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1589 LocalSMID >>= 2;
1590
1591 // This header is part of a module. Associate it with the module to enable
1592 // implicit module import.
1593 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1594 Module *Mod = Reader.getSubmodule(GlobalSMID);
1595 FileManager &FileMgr = Reader.getFileManager();
1596 ModuleMap &ModMap =
1597 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1598
1599 std::string Filename = key.Filename;
1600 if (key.Imported)
1601 Reader.ResolveImportedPath(M, Filename);
1602 // FIXME: This is not always the right filename-as-written, but we're not
1603 // going to use this information to rebuild the module, so it doesn't make
1604 // a lot of difference.
1605 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
1606 ModMap.addHeader(Mod, H, HeaderRole);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001607 }
1608
Guy Benyei11169dd2012-12-18 14:30:41 +00001609 // This HeaderFileInfo was externally loaded.
1610 HFI.External = true;
1611 return HFI;
1612}
1613
Richard Smithd7329392015-04-21 21:46:32 +00001614void ASTReader::addPendingMacro(IdentifierInfo *II,
1615 ModuleFile *M,
1616 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001617 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1618 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001619}
1620
1621void ASTReader::ReadDefinedMacros() {
1622 // Note that we are loading defined macros.
1623 Deserializing Macros(this);
1624
Pete Cooper57d3f142015-07-30 17:22:52 +00001625 for (auto &I : llvm::reverse(ModuleMgr)) {
1626 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001627
1628 // If there was no preprocessor block, skip this file.
1629 if (!MacroCursor.getBitStreamReader())
1630 continue;
1631
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001632 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001633 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001634
1635 RecordData Record;
1636 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001637 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1638
1639 switch (E.Kind) {
1640 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1641 case llvm::BitstreamEntry::Error:
1642 Error("malformed block record in AST file");
1643 return;
1644 case llvm::BitstreamEntry::EndBlock:
1645 goto NextCursor;
1646
1647 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001648 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001649 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001650 default: // Default behavior: ignore.
1651 break;
1652
1653 case PP_MACRO_OBJECT_LIKE:
1654 case PP_MACRO_FUNCTION_LIKE:
Pete Cooper57d3f142015-07-30 17:22:52 +00001655 getLocalIdentifier(*I, Record[0]);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001656 break;
1657
1658 case PP_TOKEN:
1659 // Ignore tokens.
1660 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001661 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001662 break;
1663 }
1664 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001665 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001666 }
1667}
1668
1669namespace {
1670 /// \brief Visitor class used to look up identifirs in an AST file.
1671 class IdentifierLookupVisitor {
1672 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001673 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001674 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001675 unsigned &NumIdentifierLookups;
1676 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001677 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001678
Guy Benyei11169dd2012-12-18 14:30:41 +00001679 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001680 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1681 unsigned &NumIdentifierLookups,
1682 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001683 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1684 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001685 NumIdentifierLookups(NumIdentifierLookups),
1686 NumIdentifierLookupHits(NumIdentifierLookupHits),
1687 Found()
1688 {
1689 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001690
1691 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001692 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001693 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001694 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001695
Guy Benyei11169dd2012-12-18 14:30:41 +00001696 ASTIdentifierLookupTable *IdTable
1697 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1698 if (!IdTable)
1699 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001700
1701 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001702 Found);
1703 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001704 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001705 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001706 if (Pos == IdTable->end())
1707 return false;
1708
1709 // Dereferencing the iterator has the effect of building the
1710 // IdentifierInfo node and populating it with the various
1711 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001712 ++NumIdentifierLookupHits;
1713 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001714 return true;
1715 }
1716
1717 // \brief Retrieve the identifier info found within the module
1718 // files.
1719 IdentifierInfo *getIdentifierInfo() const { return Found; }
1720 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001721}
Guy Benyei11169dd2012-12-18 14:30:41 +00001722
1723void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1724 // Note that we are loading an identifier.
1725 Deserializing AnIdentifier(this);
1726
1727 unsigned PriorGeneration = 0;
1728 if (getContext().getLangOpts().Modules)
1729 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001730
1731 // If there is a global index, look there first to determine which modules
1732 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001733 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001734 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001735 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001736 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1737 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001738 }
1739 }
1740
Douglas Gregor7211ac12013-01-25 23:32:03 +00001741 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001742 NumIdentifierLookups,
1743 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001744 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001745 markIdentifierUpToDate(&II);
1746}
1747
1748void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1749 if (!II)
1750 return;
1751
1752 II->setOutOfDate(false);
1753
1754 // Update the generation for this identifier.
1755 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001756 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001757}
1758
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001759void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1760 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001761 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001762
1763 BitstreamCursor &Cursor = M.MacroCursor;
1764 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001765 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001766
Richard Smith713369b2015-04-23 20:40:50 +00001767 struct ModuleMacroRecord {
1768 SubmoduleID SubModID;
1769 MacroInfo *MI;
1770 SmallVector<SubmoduleID, 8> Overrides;
1771 };
1772 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001773
Richard Smithd7329392015-04-21 21:46:32 +00001774 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1775 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1776 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001777 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001778 while (true) {
1779 llvm::BitstreamEntry Entry =
1780 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1781 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1782 Error("malformed block record in AST file");
1783 return;
1784 }
1785
1786 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001787 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001788 case PP_MACRO_DIRECTIVE_HISTORY:
1789 break;
1790
1791 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001792 ModuleMacros.push_back(ModuleMacroRecord());
1793 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001794 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1795 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001796 for (int I = 2, N = Record.size(); I != N; ++I)
1797 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001798 continue;
1799 }
1800
1801 default:
1802 Error("malformed block record in AST file");
1803 return;
1804 }
1805
1806 // We found the macro directive history; that's the last record
1807 // for this macro.
1808 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001809 }
1810
Richard Smithd7329392015-04-21 21:46:32 +00001811 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001812 {
1813 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001814 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001815 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001816 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001817 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001818 Module *Mod = getSubmodule(ModID);
1819 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001820 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001821 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001822 }
1823
1824 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001825 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001826 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001827 }
1828 }
1829
1830 // Don't read the directive history for a module; we don't have anywhere
1831 // to put it.
1832 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1833 return;
1834
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001835 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001836 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001837 unsigned Idx = 0, N = Record.size();
1838 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001839 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001840 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001841 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1842 switch (K) {
1843 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001844 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001845 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001846 break;
1847 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001848 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001849 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001850 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001851 }
1852 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001853 bool isPublic = Record[Idx++];
1854 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1855 break;
1856 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001857
1858 if (!Latest)
1859 Latest = MD;
1860 if (Earliest)
1861 Earliest->setPrevious(MD);
1862 Earliest = MD;
1863 }
1864
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001865 if (Latest)
1866 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001867}
1868
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001869ASTReader::InputFileInfo
1870ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001871 // Go find this input file.
1872 BitstreamCursor &Cursor = F.InputFilesCursor;
1873 SavedStreamPosition SavedPosition(Cursor);
1874 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1875
1876 unsigned Code = Cursor.ReadCode();
1877 RecordData Record;
1878 StringRef Blob;
1879
1880 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1881 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1882 "invalid record type for input file");
1883 (void)Result;
1884
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001885 std::string Filename;
1886 off_t StoredSize;
1887 time_t StoredTime;
1888 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001889
Ben Langmuir198c1682014-03-07 07:27:49 +00001890 assert(Record[0] == ID && "Bogus stored ID or offset");
1891 StoredSize = static_cast<off_t>(Record[1]);
1892 StoredTime = static_cast<time_t>(Record[2]);
1893 Overridden = static_cast<bool>(Record[3]);
1894 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001895 ResolveImportedPath(F, Filename);
1896
Hans Wennborg73945142014-03-14 17:45:06 +00001897 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1898 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001899}
1900
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001901InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001902 // If this ID is bogus, just return an empty input file.
1903 if (ID == 0 || ID > F.InputFilesLoaded.size())
1904 return InputFile();
1905
1906 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001907 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001908 return F.InputFilesLoaded[ID-1];
1909
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001910 if (F.InputFilesLoaded[ID-1].isNotFound())
1911 return InputFile();
1912
Guy Benyei11169dd2012-12-18 14:30:41 +00001913 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001914 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001915 SavedStreamPosition SavedPosition(Cursor);
1916 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1917
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001918 InputFileInfo FI = readInputFileInfo(F, ID);
1919 off_t StoredSize = FI.StoredSize;
1920 time_t StoredTime = FI.StoredTime;
1921 bool Overridden = FI.Overridden;
1922 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001923
Ben Langmuir198c1682014-03-07 07:27:49 +00001924 const FileEntry *File
1925 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1926 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1927
1928 // If we didn't find the file, resolve it relative to the
1929 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001930 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001931 F.OriginalDir != CurrentDir) {
1932 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1933 F.OriginalDir,
1934 CurrentDir);
1935 if (!Resolved.empty())
1936 File = FileMgr.getFile(Resolved);
1937 }
1938
1939 // For an overridden file, create a virtual file with the stored
1940 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001941 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001942 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1943 }
1944
Craig Toppera13603a2014-05-22 05:54:18 +00001945 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001946 if (Complain) {
1947 std::string ErrorStr = "could not find file '";
1948 ErrorStr += Filename;
1949 ErrorStr += "' referenced by AST file";
1950 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001951 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001952 // Record that we didn't find the file.
1953 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1954 return InputFile();
1955 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001956
Ben Langmuir198c1682014-03-07 07:27:49 +00001957 // Check if there was a request to override the contents of the file
1958 // that was part of the precompiled header. Overridding such a file
1959 // can lead to problems when lexing using the source locations from the
1960 // PCH.
1961 SourceManager &SM = getSourceManager();
1962 if (!Overridden && SM.isFileOverridden(File)) {
1963 if (Complain)
1964 Error(diag::err_fe_pch_file_overridden, Filename);
1965 // After emitting the diagnostic, recover by disabling the override so
1966 // that the original file will be used.
1967 SM.disableFileContentsOverride(File);
1968 // The FileEntry is a virtual file entry with the size of the contents
1969 // that would override the original contents. Set it to the original's
1970 // size/time.
1971 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1972 StoredSize, StoredTime);
1973 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001974
Ben Langmuir198c1682014-03-07 07:27:49 +00001975 bool IsOutOfDate = false;
1976
1977 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001978 if (!Overridden && //
1979 (StoredSize != File->getSize() ||
1980#if defined(LLVM_ON_WIN32)
1981 false
1982#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001983 // In our regression testing, the Windows file system seems to
1984 // have inconsistent modification times that sometimes
1985 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001986 //
Richard Smithe75ee0f2015-08-17 07:13:32 +00001987 // FIXME: This probably also breaks HeaderFileInfo lookups on Windows.
1988 (StoredTime && StoredTime != File->getModificationTime() &&
1989 !DisableValidation)
Guy Benyei11169dd2012-12-18 14:30:41 +00001990#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001991 )) {
1992 if (Complain) {
1993 // Build a list of the PCH imports that got us here (in reverse).
1994 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1995 while (ImportStack.back()->ImportedBy.size() > 0)
1996 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001997
Ben Langmuir198c1682014-03-07 07:27:49 +00001998 // The top-level PCH is stale.
1999 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2000 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002001
Ben Langmuir198c1682014-03-07 07:27:49 +00002002 // Print the import stack.
2003 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2004 Diag(diag::note_pch_required_by)
2005 << Filename << ImportStack[0]->FileName;
2006 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002007 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002008 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002009 }
2010
Ben Langmuir198c1682014-03-07 07:27:49 +00002011 if (!Diags.isDiagnosticInFlight())
2012 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002013 }
2014
Ben Langmuir198c1682014-03-07 07:27:49 +00002015 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002016 }
2017
Ben Langmuir198c1682014-03-07 07:27:49 +00002018 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2019
2020 // Note that we've loaded this input file.
2021 F.InputFilesLoaded[ID-1] = IF;
2022 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002023}
2024
Richard Smith7ed1bc92014-12-05 22:42:13 +00002025/// \brief If we are loading a relocatable PCH or module file, and the filename
2026/// is not an absolute path, add the system or module root to the beginning of
2027/// the file name.
2028void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2029 // Resolve relative to the base directory, if we have one.
2030 if (!M.BaseDirectory.empty())
2031 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002032}
2033
Richard Smith7ed1bc92014-12-05 22:42:13 +00002034void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002035 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2036 return;
2037
Richard Smith7ed1bc92014-12-05 22:42:13 +00002038 SmallString<128> Buffer;
2039 llvm::sys::path::append(Buffer, Prefix, Filename);
2040 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002041}
2042
Richard Smith0f99d6a2015-08-09 08:48:41 +00002043static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2044 switch (ARR) {
2045 case ASTReader::Failure: return true;
2046 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2047 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2048 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2049 case ASTReader::ConfigurationMismatch:
2050 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2051 case ASTReader::HadErrors: return true;
2052 case ASTReader::Success: return false;
2053 }
2054
2055 llvm_unreachable("unknown ASTReadResult");
2056}
2057
Guy Benyei11169dd2012-12-18 14:30:41 +00002058ASTReader::ASTReadResult
2059ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002060 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002061 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002062 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002063 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002064
2065 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2066 Error("malformed block record in AST file");
2067 return Failure;
2068 }
2069
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002070 // Should we allow the configuration of the module file to differ from the
2071 // configuration of the current translation unit in a compatible way?
2072 //
2073 // FIXME: Allow this for files explicitly specified with -include-pch too.
2074 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2075
Guy Benyei11169dd2012-12-18 14:30:41 +00002076 // Read all of the records and blocks in the control block.
2077 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002078 unsigned NumInputs = 0;
2079 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002080 while (1) {
2081 llvm::BitstreamEntry Entry = Stream.advance();
2082
2083 switch (Entry.Kind) {
2084 case llvm::BitstreamEntry::Error:
2085 Error("malformed block record in AST file");
2086 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002087 case llvm::BitstreamEntry::EndBlock: {
2088 // Validate input files.
2089 const HeaderSearchOptions &HSOpts =
2090 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002091
Richard Smitha1825302014-10-23 22:18:29 +00002092 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002093 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2094 // loaded module files, ignore missing inputs.
2095 if (!DisableValidation && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002096 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002097
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002098 // If we are reading a module, we will create a verification timestamp,
2099 // so we verify all input files. Otherwise, verify only user input
2100 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002101
2102 unsigned N = NumUserInputs;
2103 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002104 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002105 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002106 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002107 N = NumInputs;
2108
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002109 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002110 InputFile IF = getInputFile(F, I+1, Complain);
2111 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002112 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002113 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002114 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002115
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002116 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002117 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002118
Ben Langmuircb69b572014-03-07 06:40:32 +00002119 if (Listener && Listener->needsInputFileVisitation()) {
2120 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2121 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002122 for (unsigned I = 0; I < N; ++I) {
2123 bool IsSystem = I >= NumUserInputs;
2124 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002125 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2126 F.Kind == MK_ExplicitModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002127 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002128 }
2129
Guy Benyei11169dd2012-12-18 14:30:41 +00002130 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002131 }
2132
Chris Lattnere7b154b2013-01-19 21:39:22 +00002133 case llvm::BitstreamEntry::SubBlock:
2134 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002135 case INPUT_FILES_BLOCK_ID:
2136 F.InputFilesCursor = Stream;
2137 if (Stream.SkipBlock() || // Skip with the main cursor
2138 // Read the abbreviations
2139 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2140 Error("malformed block record in AST file");
2141 return Failure;
2142 }
2143 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002144
Guy Benyei11169dd2012-12-18 14:30:41 +00002145 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002146 if (Stream.SkipBlock()) {
2147 Error("malformed block record in AST file");
2148 return Failure;
2149 }
2150 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002151 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002152
2153 case llvm::BitstreamEntry::Record:
2154 // The interesting case.
2155 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002156 }
2157
2158 // Read and process a record.
2159 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002160 StringRef Blob;
2161 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002162 case METADATA: {
2163 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2164 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002165 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2166 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002167 return VersionMismatch;
2168 }
2169
Richard Smithe75ee0f2015-08-17 07:13:32 +00002170 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002171 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2172 Diag(diag::err_pch_with_compiler_errors);
2173 return HadErrors;
2174 }
2175
2176 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002177 // Relative paths in a relocatable PCH are relative to our sysroot.
2178 if (F.RelocatablePCH)
2179 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002180
Richard Smithe75ee0f2015-08-17 07:13:32 +00002181 F.HasTimestamps = Record[5];
2182
Guy Benyei11169dd2012-12-18 14:30:41 +00002183 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002184 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002185 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2186 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002187 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002188 return VersionMismatch;
2189 }
2190 break;
2191 }
2192
Ben Langmuir487ea142014-10-23 18:05:36 +00002193 case SIGNATURE:
2194 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2195 F.Signature = Record[0];
2196 break;
2197
Guy Benyei11169dd2012-12-18 14:30:41 +00002198 case IMPORTS: {
2199 // Load each of the imported PCH files.
2200 unsigned Idx = 0, N = Record.size();
2201 while (Idx < N) {
2202 // Read information about the AST file.
2203 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2204 // The import location will be the local one for now; we will adjust
2205 // all import locations of module imports after the global source
2206 // location info are setup.
2207 SourceLocation ImportLoc =
2208 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002209 off_t StoredSize = (off_t)Record[Idx++];
2210 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002211 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002212 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002213
Richard Smith0f99d6a2015-08-09 08:48:41 +00002214 // If our client can't cope with us being out of date, we can't cope with
2215 // our dependency being missing.
2216 unsigned Capabilities = ClientLoadCapabilities;
2217 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2218 Capabilities &= ~ARR_Missing;
2219
Guy Benyei11169dd2012-12-18 14:30:41 +00002220 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002221 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2222 Loaded, StoredSize, StoredModTime,
2223 StoredSignature, Capabilities);
2224
2225 // If we diagnosed a problem, produce a backtrace.
2226 if (isDiagnosedResult(Result, Capabilities))
2227 Diag(diag::note_module_file_imported_by)
2228 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2229
2230 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002231 case Failure: return Failure;
2232 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002233 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002234 case OutOfDate: return OutOfDate;
2235 case VersionMismatch: return VersionMismatch;
2236 case ConfigurationMismatch: return ConfigurationMismatch;
2237 case HadErrors: return HadErrors;
2238 case Success: break;
2239 }
2240 }
2241 break;
2242 }
2243
2244 case LANGUAGE_OPTIONS: {
2245 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002246 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002247 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002248 ParseLanguageOptions(Record, Complain, *Listener,
2249 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002250 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002251 return ConfigurationMismatch;
2252 break;
2253 }
2254
2255 case TARGET_OPTIONS: {
2256 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2257 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002258 ParseTargetOptions(Record, Complain, *Listener,
2259 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002260 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002261 return ConfigurationMismatch;
2262 break;
2263 }
2264
2265 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002266 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002267 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002268 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002269 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002270 !DisableValidation)
2271 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002272 break;
2273 }
2274
2275 case FILE_SYSTEM_OPTIONS: {
2276 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2277 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002278 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002279 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002280 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002281 return ConfigurationMismatch;
2282 break;
2283 }
2284
2285 case HEADER_SEARCH_OPTIONS: {
2286 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2287 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002288 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002289 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
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 PREPROCESSOR_OPTIONS: {
2296 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2297 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002298 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002299 ParsePreprocessorOptions(Record, Complain, *Listener,
2300 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002301 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002302 return ConfigurationMismatch;
2303 break;
2304 }
2305
2306 case ORIGINAL_FILE:
2307 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002308 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002309 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002310 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002311 break;
2312
2313 case ORIGINAL_FILE_ID:
2314 F.OriginalSourceFileID = FileID::get(Record[0]);
2315 break;
2316
2317 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002318 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002319 break;
2320
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002321 case MODULE_NAME:
2322 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002323 if (Listener)
2324 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002325 break;
2326
Richard Smith223d3f22014-12-06 03:21:08 +00002327 case MODULE_DIRECTORY: {
2328 assert(!F.ModuleName.empty() &&
2329 "MODULE_DIRECTORY found before MODULE_NAME");
2330 // If we've already loaded a module map file covering this module, we may
2331 // have a better path for it (relative to the current build).
2332 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2333 if (M && M->Directory) {
2334 // If we're implicitly loading a module, the base directory can't
2335 // change between the build and use.
2336 if (F.Kind != MK_ExplicitModule) {
2337 const DirectoryEntry *BuildDir =
2338 PP.getFileManager().getDirectory(Blob);
2339 if (!BuildDir || BuildDir != M->Directory) {
2340 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2341 Diag(diag::err_imported_module_relocated)
2342 << F.ModuleName << Blob << M->Directory->getName();
2343 return OutOfDate;
2344 }
2345 }
2346 F.BaseDirectory = M->Directory->getName();
2347 } else {
2348 F.BaseDirectory = Blob;
2349 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002350 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002351 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002352
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002353 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002354 if (ASTReadResult Result =
2355 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2356 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002357 break;
2358
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002359 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002360 NumInputs = Record[0];
2361 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002362 F.InputFileOffsets =
2363 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002364 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002365 break;
2366 }
2367 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002368}
2369
Ben Langmuir2c9af442014-04-10 17:57:43 +00002370ASTReader::ASTReadResult
2371ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002372 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002373
2374 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2375 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002376 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002377 }
2378
2379 // Read all of the records and blocks for the AST file.
2380 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002381 while (1) {
2382 llvm::BitstreamEntry Entry = Stream.advance();
2383
2384 switch (Entry.Kind) {
2385 case llvm::BitstreamEntry::Error:
2386 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002387 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002388 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002389 // Outside of C++, we do not store a lookup map for the translation unit.
2390 // Instead, mark it as needing a lookup map to be built if this module
2391 // contains any declarations lexically within it (which it always does!).
2392 // This usually has no cost, since we very rarely need the lookup map for
2393 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002394 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002395 if (DC->hasExternalLexicalStorage() &&
2396 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002397 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002398
Ben Langmuir2c9af442014-04-10 17:57:43 +00002399 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002400 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002401 case llvm::BitstreamEntry::SubBlock:
2402 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 case DECLTYPES_BLOCK_ID:
2404 // We lazily load the decls block, but we want to set up the
2405 // DeclsCursor cursor to point into it. Clone our current bitcode
2406 // cursor to it, enter the block and read the abbrevs in that block.
2407 // With the main cursor, we just skip over it.
2408 F.DeclsCursor = Stream;
2409 if (Stream.SkipBlock() || // Skip with the main cursor.
2410 // Read the abbrevs.
2411 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2412 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002413 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 }
2415 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002416
Guy Benyei11169dd2012-12-18 14:30:41 +00002417 case PREPROCESSOR_BLOCK_ID:
2418 F.MacroCursor = Stream;
2419 if (!PP.getExternalSource())
2420 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002421
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 if (Stream.SkipBlock() ||
2423 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2424 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002425 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002426 }
2427 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2428 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002429
Guy Benyei11169dd2012-12-18 14:30:41 +00002430 case PREPROCESSOR_DETAIL_BLOCK_ID:
2431 F.PreprocessorDetailCursor = Stream;
2432 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002433 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002435 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002436 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002437 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002438 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002439 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2440
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 if (!PP.getPreprocessingRecord())
2442 PP.createPreprocessingRecord();
2443 if (!PP.getPreprocessingRecord()->getExternalSource())
2444 PP.getPreprocessingRecord()->SetExternalSource(*this);
2445 break;
2446
2447 case SOURCE_MANAGER_BLOCK_ID:
2448 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002449 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002450 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002451
Guy Benyei11169dd2012-12-18 14:30:41 +00002452 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002453 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2454 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002456
Guy Benyei11169dd2012-12-18 14:30:41 +00002457 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002458 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002459 if (Stream.SkipBlock() ||
2460 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2461 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002462 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 }
2464 CommentsCursors.push_back(std::make_pair(C, &F));
2465 break;
2466 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002467
Guy Benyei11169dd2012-12-18 14:30:41 +00002468 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002469 if (Stream.SkipBlock()) {
2470 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002471 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002472 }
2473 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002474 }
2475 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002476
2477 case llvm::BitstreamEntry::Record:
2478 // The interesting case.
2479 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 }
2481
2482 // Read and process a record.
2483 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002484 StringRef Blob;
2485 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 default: // Default behavior: ignore.
2487 break;
2488
2489 case TYPE_OFFSET: {
2490 if (F.LocalNumTypes != 0) {
2491 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002492 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002494 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 F.LocalNumTypes = Record[0];
2496 unsigned LocalBaseTypeIndex = Record[1];
2497 F.BaseTypeIndex = getTotalNumTypes();
2498
2499 if (F.LocalNumTypes > 0) {
2500 // Introduce the global -> local mapping for types within this module.
2501 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2502
2503 // Introduce the local -> global mapping for types within this module.
2504 F.TypeRemap.insertOrReplace(
2505 std::make_pair(LocalBaseTypeIndex,
2506 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002507
2508 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 }
2510 break;
2511 }
2512
2513 case DECL_OFFSET: {
2514 if (F.LocalNumDecls != 0) {
2515 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002516 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002517 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002518 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 F.LocalNumDecls = Record[0];
2520 unsigned LocalBaseDeclID = Record[1];
2521 F.BaseDeclID = getTotalNumDecls();
2522
2523 if (F.LocalNumDecls > 0) {
2524 // Introduce the global -> local mapping for declarations within this
2525 // module.
2526 GlobalDeclMap.insert(
2527 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2528
2529 // Introduce the local -> global mapping for declarations within this
2530 // module.
2531 F.DeclRemap.insertOrReplace(
2532 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2533
2534 // Introduce the global -> local mapping for declarations within this
2535 // module.
2536 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002537
Ben Langmuir52ca6782014-10-20 16:27:32 +00002538 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2539 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002540 break;
2541 }
2542
2543 case TU_UPDATE_LEXICAL: {
2544 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002545 LexicalContents Contents(
2546 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2547 Blob.data()),
2548 static_cast<unsigned int>(Blob.size() / 4));
2549 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002550 TU->setHasExternalLexicalStorage(true);
2551 break;
2552 }
2553
2554 case UPDATE_VISIBLE: {
2555 unsigned Idx = 0;
2556 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002557 auto *Data = (const unsigned char*)Blob.data();
2558 unsigned BucketOffset = Record[Idx++];
2559 PendingVisibleUpdates[ID].push_back(
2560 PendingVisibleUpdate{&F, Data, BucketOffset});
2561 // If we've already loaded the decl, perform the updates when we finish
2562 // loading this block.
2563 if (Decl *D = GetExistingDecl(ID))
2564 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 break;
2566 }
2567
2568 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002569 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002571 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2572 (const unsigned char *)F.IdentifierTableData + Record[0],
2573 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2574 (const unsigned char *)F.IdentifierTableData,
2575 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002576
2577 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2578 }
2579 break;
2580
2581 case IDENTIFIER_OFFSET: {
2582 if (F.LocalNumIdentifiers != 0) {
2583 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002584 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002586 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 F.LocalNumIdentifiers = Record[0];
2588 unsigned LocalBaseIdentifierID = Record[1];
2589 F.BaseIdentifierID = getTotalNumIdentifiers();
2590
2591 if (F.LocalNumIdentifiers > 0) {
2592 // Introduce the global -> local mapping for identifiers within this
2593 // module.
2594 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2595 &F));
2596
2597 // Introduce the local -> global mapping for identifiers within this
2598 // module.
2599 F.IdentifierRemap.insertOrReplace(
2600 std::make_pair(LocalBaseIdentifierID,
2601 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002602
Ben Langmuir52ca6782014-10-20 16:27:32 +00002603 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2604 + F.LocalNumIdentifiers);
2605 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002606 break;
2607 }
2608
Richard Smith33e0f7e2015-07-22 02:08:40 +00002609 case INTERESTING_IDENTIFIERS:
2610 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2611 break;
2612
Ben Langmuir332aafe2014-01-31 01:06:56 +00002613 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002614 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2615 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002617 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 break;
2619
2620 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002621 if (SpecialTypes.empty()) {
2622 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2623 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2624 break;
2625 }
2626
2627 if (SpecialTypes.size() != Record.size()) {
2628 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002629 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002630 }
2631
2632 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2633 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2634 if (!SpecialTypes[I])
2635 SpecialTypes[I] = ID;
2636 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2637 // merge step?
2638 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002639 break;
2640
2641 case STATISTICS:
2642 TotalNumStatements += Record[0];
2643 TotalNumMacros += Record[1];
2644 TotalLexicalDeclContexts += Record[2];
2645 TotalVisibleDeclContexts += Record[3];
2646 break;
2647
2648 case UNUSED_FILESCOPED_DECLS:
2649 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2650 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2651 break;
2652
2653 case DELEGATING_CTORS:
2654 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2655 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2656 break;
2657
2658 case WEAK_UNDECLARED_IDENTIFIERS:
2659 if (Record.size() % 4 != 0) {
2660 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002661 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002662 }
2663
2664 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2665 // files. This isn't the way to do it :)
2666 WeakUndeclaredIdentifiers.clear();
2667
2668 // Translate the weak, undeclared identifiers into global IDs.
2669 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2670 WeakUndeclaredIdentifiers.push_back(
2671 getGlobalIdentifierID(F, Record[I++]));
2672 WeakUndeclaredIdentifiers.push_back(
2673 getGlobalIdentifierID(F, Record[I++]));
2674 WeakUndeclaredIdentifiers.push_back(
2675 ReadSourceLocation(F, Record, I).getRawEncoding());
2676 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2677 }
2678 break;
2679
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002681 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002682 F.LocalNumSelectors = Record[0];
2683 unsigned LocalBaseSelectorID = Record[1];
2684 F.BaseSelectorID = getTotalNumSelectors();
2685
2686 if (F.LocalNumSelectors > 0) {
2687 // Introduce the global -> local mapping for selectors within this
2688 // module.
2689 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2690
2691 // Introduce the local -> global mapping for selectors within this
2692 // module.
2693 F.SelectorRemap.insertOrReplace(
2694 std::make_pair(LocalBaseSelectorID,
2695 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002696
2697 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 }
2699 break;
2700 }
2701
2702 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002703 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 if (Record[0])
2705 F.SelectorLookupTable
2706 = ASTSelectorLookupTable::Create(
2707 F.SelectorLookupTableData + Record[0],
2708 F.SelectorLookupTableData,
2709 ASTSelectorLookupTrait(*this, F));
2710 TotalNumMethodPoolEntries += Record[1];
2711 break;
2712
2713 case REFERENCED_SELECTOR_POOL:
2714 if (!Record.empty()) {
2715 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2716 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2717 Record[Idx++]));
2718 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2719 getRawEncoding());
2720 }
2721 }
2722 break;
2723
2724 case PP_COUNTER_VALUE:
2725 if (!Record.empty() && Listener)
2726 Listener->ReadCounter(F, Record[0]);
2727 break;
2728
2729 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002730 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002731 F.NumFileSortedDecls = Record[0];
2732 break;
2733
2734 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002735 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002736 F.LocalNumSLocEntries = Record[0];
2737 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002738 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002739 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002741 if (!F.SLocEntryBaseID) {
2742 Error("ran out of source locations");
2743 break;
2744 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002745 // Make our entry in the range map. BaseID is negative and growing, so
2746 // we invert it. Because we invert it, though, we need the other end of
2747 // the range.
2748 unsigned RangeStart =
2749 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2750 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2751 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2752
2753 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2754 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2755 GlobalSLocOffsetMap.insert(
2756 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2757 - SLocSpaceSize,&F));
2758
2759 // Initialize the remapping table.
2760 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002761 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002762 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002763 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002764 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2765
2766 TotalNumSLocEntries += F.LocalNumSLocEntries;
2767 break;
2768 }
2769
2770 case MODULE_OFFSET_MAP: {
2771 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002772 const unsigned char *Data = (const unsigned char*)Blob.data();
2773 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002774
2775 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2776 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2777 F.SLocRemap.insert(std::make_pair(0U, 0));
2778 F.SLocRemap.insert(std::make_pair(2U, 1));
2779 }
2780
Guy Benyei11169dd2012-12-18 14:30:41 +00002781 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002782 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2783 RemapBuilder;
2784 RemapBuilder SLocRemap(F.SLocRemap);
2785 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2786 RemapBuilder MacroRemap(F.MacroRemap);
2787 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2788 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2789 RemapBuilder SelectorRemap(F.SelectorRemap);
2790 RemapBuilder DeclRemap(F.DeclRemap);
2791 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002792
2793 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002794 using namespace llvm::support;
2795 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002796 StringRef Name = StringRef((const char*)Data, Len);
2797 Data += Len;
2798 ModuleFile *OM = ModuleMgr.lookup(Name);
2799 if (!OM) {
2800 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002801 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002802 }
2803
Justin Bogner57ba0b22014-03-28 22:03:24 +00002804 uint32_t SLocOffset =
2805 endian::readNext<uint32_t, little, unaligned>(Data);
2806 uint32_t IdentifierIDOffset =
2807 endian::readNext<uint32_t, little, unaligned>(Data);
2808 uint32_t MacroIDOffset =
2809 endian::readNext<uint32_t, little, unaligned>(Data);
2810 uint32_t PreprocessedEntityIDOffset =
2811 endian::readNext<uint32_t, little, unaligned>(Data);
2812 uint32_t SubmoduleIDOffset =
2813 endian::readNext<uint32_t, little, unaligned>(Data);
2814 uint32_t SelectorIDOffset =
2815 endian::readNext<uint32_t, little, unaligned>(Data);
2816 uint32_t DeclIDOffset =
2817 endian::readNext<uint32_t, little, unaligned>(Data);
2818 uint32_t TypeIndexOffset =
2819 endian::readNext<uint32_t, little, unaligned>(Data);
2820
Ben Langmuir785180e2014-10-20 16:27:30 +00002821 uint32_t None = std::numeric_limits<uint32_t>::max();
2822
2823 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2824 RemapBuilder &Remap) {
2825 if (Offset != None)
2826 Remap.insert(std::make_pair(Offset,
2827 static_cast<int>(BaseOffset - Offset)));
2828 };
2829 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2830 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2831 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2832 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2833 PreprocessedEntityRemap);
2834 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2835 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2836 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2837 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002838
2839 // Global -> local mappings.
2840 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2841 }
2842 break;
2843 }
2844
2845 case SOURCE_MANAGER_LINE_TABLE:
2846 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002847 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002848 break;
2849
2850 case SOURCE_LOCATION_PRELOADS: {
2851 // Need to transform from the local view (1-based IDs) to the global view,
2852 // which is based off F.SLocEntryBaseID.
2853 if (!F.PreloadSLocEntries.empty()) {
2854 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002855 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002856 }
2857
2858 F.PreloadSLocEntries.swap(Record);
2859 break;
2860 }
2861
2862 case EXT_VECTOR_DECLS:
2863 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2864 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2865 break;
2866
2867 case VTABLE_USES:
2868 if (Record.size() % 3 != 0) {
2869 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002870 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002871 }
2872
2873 // Later tables overwrite earlier ones.
2874 // FIXME: Modules will have some trouble with this. This is clearly not
2875 // the right way to do this.
2876 VTableUses.clear();
2877
2878 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2879 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2880 VTableUses.push_back(
2881 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2882 VTableUses.push_back(Record[Idx++]);
2883 }
2884 break;
2885
Guy Benyei11169dd2012-12-18 14:30:41 +00002886 case PENDING_IMPLICIT_INSTANTIATIONS:
2887 if (PendingInstantiations.size() % 2 != 0) {
2888 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002889 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002890 }
2891
2892 if (Record.size() % 2 != 0) {
2893 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002894 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002895 }
2896
2897 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2898 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2899 PendingInstantiations.push_back(
2900 ReadSourceLocation(F, Record, I).getRawEncoding());
2901 }
2902 break;
2903
2904 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002905 if (Record.size() != 2) {
2906 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002907 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002908 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002909 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2910 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2911 break;
2912
2913 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002914 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2915 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2916 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002917
2918 unsigned LocalBasePreprocessedEntityID = Record[0];
2919
2920 unsigned StartingID;
2921 if (!PP.getPreprocessingRecord())
2922 PP.createPreprocessingRecord();
2923 if (!PP.getPreprocessingRecord()->getExternalSource())
2924 PP.getPreprocessingRecord()->SetExternalSource(*this);
2925 StartingID
2926 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002927 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002928 F.BasePreprocessedEntityID = StartingID;
2929
2930 if (F.NumPreprocessedEntities > 0) {
2931 // Introduce the global -> local mapping for preprocessed entities in
2932 // this module.
2933 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2934
2935 // Introduce the local -> global mapping for preprocessed entities in
2936 // this module.
2937 F.PreprocessedEntityRemap.insertOrReplace(
2938 std::make_pair(LocalBasePreprocessedEntityID,
2939 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2940 }
2941
2942 break;
2943 }
2944
2945 case DECL_UPDATE_OFFSETS: {
2946 if (Record.size() % 2 != 0) {
2947 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002948 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002949 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002950 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2951 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2952 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2953
2954 // If we've already loaded the decl, perform the updates when we finish
2955 // loading this block.
2956 if (Decl *D = GetExistingDecl(ID))
2957 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2958 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002959 break;
2960 }
2961
2962 case DECL_REPLACEMENTS: {
2963 if (Record.size() % 3 != 0) {
2964 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002965 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002966 }
2967 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2968 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2969 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2970 break;
2971 }
2972
2973 case OBJC_CATEGORIES_MAP: {
2974 if (F.LocalNumObjCCategoriesInMap != 0) {
2975 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002976 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002977 }
2978
2979 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002980 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 break;
2982 }
2983
2984 case OBJC_CATEGORIES:
2985 F.ObjCCategories.swap(Record);
2986 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00002987
Guy Benyei11169dd2012-12-18 14:30:41 +00002988 case CXX_BASE_SPECIFIER_OFFSETS: {
2989 if (F.LocalNumCXXBaseSpecifiers != 0) {
2990 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002991 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002992 }
Richard Smithc2bb8182015-03-24 06:36:48 +00002993
Guy Benyei11169dd2012-12-18 14:30:41 +00002994 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002995 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00002996 break;
2997 }
2998
2999 case CXX_CTOR_INITIALIZERS_OFFSETS: {
3000 if (F.LocalNumCXXCtorInitializers != 0) {
3001 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
3002 return Failure;
3003 }
3004
3005 F.LocalNumCXXCtorInitializers = Record[0];
3006 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003007 break;
3008 }
3009
3010 case DIAG_PRAGMA_MAPPINGS:
3011 if (F.PragmaDiagMappings.empty())
3012 F.PragmaDiagMappings.swap(Record);
3013 else
3014 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3015 Record.begin(), Record.end());
3016 break;
3017
3018 case CUDA_SPECIAL_DECL_REFS:
3019 // Later tables overwrite earlier ones.
3020 // FIXME: Modules will have trouble with this.
3021 CUDASpecialDeclRefs.clear();
3022 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3023 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3024 break;
3025
3026 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003027 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003028 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003029 if (Record[0]) {
3030 F.HeaderFileInfoTable
3031 = HeaderFileInfoLookupTable::Create(
3032 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3033 (const unsigned char *)F.HeaderFileInfoTableData,
3034 HeaderFileInfoTrait(*this, F,
3035 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003036 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003037
3038 PP.getHeaderSearchInfo().SetExternalSource(this);
3039 if (!PP.getHeaderSearchInfo().getExternalLookup())
3040 PP.getHeaderSearchInfo().SetExternalLookup(this);
3041 }
3042 break;
3043 }
3044
3045 case FP_PRAGMA_OPTIONS:
3046 // Later tables overwrite earlier ones.
3047 FPPragmaOptions.swap(Record);
3048 break;
3049
3050 case OPENCL_EXTENSIONS:
3051 // Later tables overwrite earlier ones.
3052 OpenCLExtensions.swap(Record);
3053 break;
3054
3055 case TENTATIVE_DEFINITIONS:
3056 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3057 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3058 break;
3059
3060 case KNOWN_NAMESPACES:
3061 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3062 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3063 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003064
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003065 case UNDEFINED_BUT_USED:
3066 if (UndefinedButUsed.size() % 2 != 0) {
3067 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003068 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003069 }
3070
3071 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003072 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003073 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003074 }
3075 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003076 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3077 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003078 ReadSourceLocation(F, Record, I).getRawEncoding());
3079 }
3080 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003081 case DELETE_EXPRS_TO_ANALYZE:
3082 for (unsigned I = 0, N = Record.size(); I != N;) {
3083 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3084 const uint64_t Count = Record[I++];
3085 DelayedDeleteExprs.push_back(Count);
3086 for (uint64_t C = 0; C < Count; ++C) {
3087 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3088 bool IsArrayForm = Record[I++] == 1;
3089 DelayedDeleteExprs.push_back(IsArrayForm);
3090 }
3091 }
3092 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003093
Guy Benyei11169dd2012-12-18 14:30:41 +00003094 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003095 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003096 // If we aren't loading a module (which has its own exports), make
3097 // all of the imported modules visible.
3098 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003099 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3100 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3101 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3102 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003103 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003104 }
3105 }
3106 break;
3107 }
3108
Guy Benyei11169dd2012-12-18 14:30:41 +00003109 case MACRO_OFFSET: {
3110 if (F.LocalNumMacros != 0) {
3111 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003112 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003113 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003114 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003115 F.LocalNumMacros = Record[0];
3116 unsigned LocalBaseMacroID = Record[1];
3117 F.BaseMacroID = getTotalNumMacros();
3118
3119 if (F.LocalNumMacros > 0) {
3120 // Introduce the global -> local mapping for macros within this module.
3121 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3122
3123 // Introduce the local -> global mapping for macros within this module.
3124 F.MacroRemap.insertOrReplace(
3125 std::make_pair(LocalBaseMacroID,
3126 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003127
3128 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003129 }
3130 break;
3131 }
3132
Richard Smithe40f2ba2013-08-07 21:41:30 +00003133 case LATE_PARSED_TEMPLATE: {
3134 LateParsedTemplates.append(Record.begin(), Record.end());
3135 break;
3136 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003137
3138 case OPTIMIZE_PRAGMA_OPTIONS:
3139 if (Record.size() != 1) {
3140 Error("invalid pragma optimize record");
3141 return Failure;
3142 }
3143 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3144 break;
Nico Weber72889432014-09-06 01:25:55 +00003145
3146 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3147 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3148 UnusedLocalTypedefNameCandidates.push_back(
3149 getGlobalDeclID(F, Record[I]));
3150 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 }
3152 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003153}
3154
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003155ASTReader::ASTReadResult
3156ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3157 const ModuleFile *ImportedBy,
3158 unsigned ClientLoadCapabilities) {
3159 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003160 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003161
Richard Smithe842a472014-10-22 02:05:46 +00003162 if (F.Kind == MK_ExplicitModule) {
3163 // For an explicitly-loaded module, we don't care whether the original
3164 // module map file exists or matches.
3165 return Success;
3166 }
3167
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003168 // Try to resolve ModuleName in the current header search context and
3169 // verify that it is found in the same module map file as we saved. If the
3170 // top-level AST file is a main file, skip this check because there is no
3171 // usable header search context.
3172 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003173 "MODULE_NAME should come before MODULE_MAP_FILE");
3174 if (F.Kind == MK_ImplicitModule &&
3175 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3176 // An implicitly-loaded module file should have its module listed in some
3177 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003178 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003179 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3180 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3181 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003182 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003183 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3184 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3185 // This module was defined by an imported (explicit) module.
3186 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3187 << ASTFE->getName();
3188 else
3189 // This module was built with a different module map.
3190 Diag(diag::err_imported_module_not_found)
3191 << F.ModuleName << F.FileName << ImportedBy->FileName
3192 << F.ModuleMapPath;
3193 }
3194 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003195 }
3196
Richard Smithe842a472014-10-22 02:05:46 +00003197 assert(M->Name == F.ModuleName && "found module with different name");
3198
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003199 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003200 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003201 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3202 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003203 assert(ImportedBy && "top-level import should be verified");
3204 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3205 Diag(diag::err_imported_module_modmap_changed)
3206 << F.ModuleName << ImportedBy->FileName
3207 << ModMap->getName() << F.ModuleMapPath;
3208 return OutOfDate;
3209 }
3210
3211 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3212 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3213 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003214 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003215 const FileEntry *F =
3216 FileMgr.getFile(Filename, false, false);
3217 if (F == nullptr) {
3218 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3219 Error("could not find file '" + Filename +"' referenced by AST file");
3220 return OutOfDate;
3221 }
3222 AdditionalStoredMaps.insert(F);
3223 }
3224
3225 // Check any additional module map files (e.g. module.private.modulemap)
3226 // that are not in the pcm.
3227 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3228 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3229 // Remove files that match
3230 // Note: SmallPtrSet::erase is really remove
3231 if (!AdditionalStoredMaps.erase(ModMap)) {
3232 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3233 Diag(diag::err_module_different_modmap)
3234 << F.ModuleName << /*new*/0 << ModMap->getName();
3235 return OutOfDate;
3236 }
3237 }
3238 }
3239
3240 // Check any additional module map files that are in the pcm, but not
3241 // found in header search. Cases that match are already removed.
3242 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3243 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3244 Diag(diag::err_module_different_modmap)
3245 << F.ModuleName << /*not new*/1 << ModMap->getName();
3246 return OutOfDate;
3247 }
3248 }
3249
3250 if (Listener)
3251 Listener->ReadModuleMapFile(F.ModuleMapPath);
3252 return Success;
3253}
3254
3255
Douglas Gregorc1489562013-02-12 23:36:21 +00003256/// \brief Move the given method to the back of the global list of methods.
3257static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3258 // Find the entry for this selector in the method pool.
3259 Sema::GlobalMethodPool::iterator Known
3260 = S.MethodPool.find(Method->getSelector());
3261 if (Known == S.MethodPool.end())
3262 return;
3263
3264 // Retrieve the appropriate method list.
3265 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3266 : Known->second.second;
3267 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003268 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003269 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003270 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003271 Found = true;
3272 } else {
3273 // Keep searching.
3274 continue;
3275 }
3276 }
3277
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003278 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003279 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003280 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003281 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003282 }
3283}
3284
Richard Smithde711422015-04-23 21:20:19 +00003285void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003286 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003287 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003288 bool wasHidden = D->Hidden;
3289 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003290
Richard Smith49f906a2014-03-01 00:08:04 +00003291 if (wasHidden && SemaObj) {
3292 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3293 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003294 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003295 }
3296 }
3297}
3298
Richard Smith49f906a2014-03-01 00:08:04 +00003299void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003300 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003301 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003302 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003303 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003304 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003305 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003306 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003307
3308 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003309 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003310 // there is nothing more to do.
3311 continue;
3312 }
Richard Smith49f906a2014-03-01 00:08:04 +00003313
Guy Benyei11169dd2012-12-18 14:30:41 +00003314 if (!Mod->isAvailable()) {
3315 // Modules that aren't available cannot be made visible.
3316 continue;
3317 }
3318
3319 // Update the module's name visibility.
3320 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003321
Guy Benyei11169dd2012-12-18 14:30:41 +00003322 // If we've already deserialized any names from this module,
3323 // mark them as visible.
3324 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3325 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003326 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003327 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003328 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003329 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3330 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003331 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003332
Guy Benyei11169dd2012-12-18 14:30:41 +00003333 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003334 SmallVector<Module *, 16> Exports;
3335 Mod->getExportedModules(Exports);
3336 for (SmallVectorImpl<Module *>::iterator
3337 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3338 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003339 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003340 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003341 }
3342 }
3343}
3344
Douglas Gregore060e572013-01-25 01:03:03 +00003345bool ASTReader::loadGlobalIndex() {
3346 if (GlobalIndex)
3347 return false;
3348
3349 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3350 !Context.getLangOpts().Modules)
3351 return true;
3352
3353 // Try to load the global index.
3354 TriedLoadingGlobalIndex = true;
3355 StringRef ModuleCachePath
3356 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3357 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003358 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003359 if (!Result.first)
3360 return true;
3361
3362 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003363 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003364 return false;
3365}
3366
3367bool ASTReader::isGlobalIndexUnavailable() const {
3368 return Context.getLangOpts().Modules && UseGlobalIndex &&
3369 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3370}
3371
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003372static void updateModuleTimestamp(ModuleFile &MF) {
3373 // Overwrite the timestamp file contents so that file's mtime changes.
3374 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003375 std::error_code EC;
3376 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3377 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003378 return;
3379 OS << "Timestamp file\n";
3380}
3381
Guy Benyei11169dd2012-12-18 14:30:41 +00003382ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3383 ModuleKind Type,
3384 SourceLocation ImportLoc,
3385 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003386 llvm::SaveAndRestore<SourceLocation>
3387 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3388
Richard Smithd1c46742014-04-30 02:24:17 +00003389 // Defer any pending actions until we get to the end of reading the AST file.
3390 Deserializing AnASTFile(this);
3391
Guy Benyei11169dd2012-12-18 14:30:41 +00003392 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003393 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003394
3395 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003396 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003397 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003398 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003399 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003400 ClientLoadCapabilities)) {
3401 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003402 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003403 case OutOfDate:
3404 case VersionMismatch:
3405 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003406 case HadErrors: {
3407 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3408 for (const ImportedModule &IM : Loaded)
3409 LoadedSet.insert(IM.Mod);
3410
Douglas Gregor7029ce12013-03-19 00:28:20 +00003411 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003412 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003413 Context.getLangOpts().Modules
3414 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003415 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003416
3417 // If we find that any modules are unusable, the global index is going
3418 // to be out-of-date. Just remove it.
3419 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003420 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003421 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003422 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003423 case Success:
3424 break;
3425 }
3426
3427 // Here comes stuff that we only do once the entire chain is loaded.
3428
3429 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003430 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3431 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003432 M != MEnd; ++M) {
3433 ModuleFile &F = *M->Mod;
3434
3435 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003436 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3437 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003438
3439 // Once read, set the ModuleFile bit base offset and update the size in
3440 // bits of all files we've seen.
3441 F.GlobalBitOffset = TotalModulesSizeInBits;
3442 TotalModulesSizeInBits += F.SizeInBits;
3443 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3444
3445 // Preload SLocEntries.
3446 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3447 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3448 // Load it through the SourceManager and don't call ReadSLocEntry()
3449 // directly because the entry may have already been loaded in which case
3450 // calling ReadSLocEntry() directly would trigger an assertion in
3451 // SourceManager.
3452 SourceMgr.getLoadedSLocEntryByID(Index);
3453 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003454
3455 // Preload all the pending interesting identifiers by marking them out of
3456 // date.
3457 for (auto Offset : F.PreloadIdentifierOffsets) {
3458 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3459 F.IdentifierTableData + Offset);
3460
3461 ASTIdentifierLookupTrait Trait(*this, F);
3462 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3463 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003464 auto &II = PP.getIdentifierTable().getOwn(Key);
3465 II.setOutOfDate(true);
3466
3467 // Mark this identifier as being from an AST file so that we can track
3468 // whether we need to serialize it.
3469 if (!II.isFromAST()) {
3470 II.setIsFromAST();
3471 if (isInterestingIdentifier(*this, II, F.isModule()))
3472 II.setChangedSinceDeserialization();
3473 }
3474
3475 // Associate the ID with the identifier so that the writer can reuse it.
3476 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3477 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003478 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003479 }
3480
Douglas Gregor603cd862013-03-22 18:50:14 +00003481 // Setup the import locations and notify the module manager that we've
3482 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003483 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3484 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003485 M != MEnd; ++M) {
3486 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003487
3488 ModuleMgr.moduleFileAccepted(&F);
3489
3490 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003491 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003492 if (!M->ImportedBy)
3493 F.ImportLoc = M->ImportLoc;
3494 else
3495 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3496 M->ImportLoc.getRawEncoding());
3497 }
3498
Richard Smith33e0f7e2015-07-22 02:08:40 +00003499 if (!Context.getLangOpts().CPlusPlus ||
3500 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3501 // Mark all of the identifiers in the identifier table as being out of date,
3502 // so that various accessors know to check the loaded modules when the
3503 // identifier is used.
3504 //
3505 // For C++ modules, we don't need information on many identifiers (just
3506 // those that provide macros or are poisoned), so we mark all of
3507 // the interesting ones via PreloadIdentifierOffsets.
3508 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3509 IdEnd = PP.getIdentifierTable().end();
3510 Id != IdEnd; ++Id)
3511 Id->second->setOutOfDate(true);
3512 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003513
3514 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003515 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3516 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003517 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3518 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003519
3520 switch (Unresolved.Kind) {
3521 case UnresolvedModuleRef::Conflict:
3522 if (ResolvedMod) {
3523 Module::Conflict Conflict;
3524 Conflict.Other = ResolvedMod;
3525 Conflict.Message = Unresolved.String.str();
3526 Unresolved.Mod->Conflicts.push_back(Conflict);
3527 }
3528 continue;
3529
3530 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003531 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003532 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003533 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003534
Douglas Gregorfb912652013-03-20 21:10:35 +00003535 case UnresolvedModuleRef::Export:
3536 if (ResolvedMod || Unresolved.IsWildcard)
3537 Unresolved.Mod->Exports.push_back(
3538 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3539 continue;
3540 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003541 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003542 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003543
3544 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3545 // Might be unnecessary as use declarations are only used to build the
3546 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003547
3548 InitializeContext();
3549
Richard Smith3d8e97e2013-10-18 06:54:39 +00003550 if (SemaObj)
3551 UpdateSema();
3552
Guy Benyei11169dd2012-12-18 14:30:41 +00003553 if (DeserializationListener)
3554 DeserializationListener->ReaderInitialized(this);
3555
3556 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3557 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3558 PrimaryModule.OriginalSourceFileID
3559 = FileID::get(PrimaryModule.SLocEntryBaseID
3560 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3561
3562 // If this AST file is a precompiled preamble, then set the
3563 // preamble file ID of the source manager to the file source file
3564 // from which the preamble was built.
3565 if (Type == MK_Preamble) {
3566 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3567 } else if (Type == MK_MainFile) {
3568 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3569 }
3570 }
3571
3572 // For any Objective-C class definitions we have already loaded, make sure
3573 // that we load any additional categories.
3574 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3575 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3576 ObjCClassesLoaded[I],
3577 PreviousGeneration);
3578 }
Douglas Gregore060e572013-01-25 01:03:03 +00003579
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003580 if (PP.getHeaderSearchInfo()
3581 .getHeaderSearchOpts()
3582 .ModulesValidateOncePerBuildSession) {
3583 // Now we are certain that the module and all modules it depends on are
3584 // up to date. Create or update timestamp files for modules that are
3585 // located in the module cache (not for PCH files that could be anywhere
3586 // in the filesystem).
3587 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3588 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003589 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003590 updateModuleTimestamp(*M.Mod);
3591 }
3592 }
3593 }
3594
Guy Benyei11169dd2012-12-18 14:30:41 +00003595 return Success;
3596}
3597
Ben Langmuir487ea142014-10-23 18:05:36 +00003598static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3599
Ben Langmuir70a1b812015-03-24 04:43:52 +00003600/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3601static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3602 return Stream.Read(8) == 'C' &&
3603 Stream.Read(8) == 'P' &&
3604 Stream.Read(8) == 'C' &&
3605 Stream.Read(8) == 'H';
3606}
3607
Richard Smith0f99d6a2015-08-09 08:48:41 +00003608static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3609 switch (Kind) {
3610 case MK_PCH:
3611 return 0; // PCH
3612 case MK_ImplicitModule:
3613 case MK_ExplicitModule:
3614 return 1; // module
3615 case MK_MainFile:
3616 case MK_Preamble:
3617 return 2; // main source file
3618 }
3619 llvm_unreachable("unknown module kind");
3620}
3621
Guy Benyei11169dd2012-12-18 14:30:41 +00003622ASTReader::ASTReadResult
3623ASTReader::ReadASTCore(StringRef FileName,
3624 ModuleKind Type,
3625 SourceLocation ImportLoc,
3626 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003627 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003628 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003629 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003630 unsigned ClientLoadCapabilities) {
3631 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003632 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003633 ModuleManager::AddModuleResult AddResult
3634 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003635 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003636 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003637 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003638
Douglas Gregor7029ce12013-03-19 00:28:20 +00003639 switch (AddResult) {
3640 case ModuleManager::AlreadyLoaded:
3641 return Success;
3642
3643 case ModuleManager::NewlyLoaded:
3644 // Load module file below.
3645 break;
3646
3647 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003648 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003649 // it.
3650 if (ClientLoadCapabilities & ARR_Missing)
3651 return Missing;
3652
3653 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003654 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3655 << FileName << ErrorStr.empty()
3656 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003657 return Failure;
3658
3659 case ModuleManager::OutOfDate:
3660 // We couldn't load the module file because it is out-of-date. If the
3661 // client can handle out-of-date, return it.
3662 if (ClientLoadCapabilities & ARR_OutOfDate)
3663 return OutOfDate;
3664
3665 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003666 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3667 << FileName << ErrorStr.empty()
3668 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003669 return Failure;
3670 }
3671
Douglas Gregor7029ce12013-03-19 00:28:20 +00003672 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003673
3674 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3675 // module?
3676 if (FileName != "-") {
3677 CurrentDir = llvm::sys::path::parent_path(FileName);
3678 if (CurrentDir.empty()) CurrentDir = ".";
3679 }
3680
3681 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003682 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003683 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003684 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003685 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3686
Guy Benyei11169dd2012-12-18 14:30:41 +00003687 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003688 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003689 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3690 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003691 return Failure;
3692 }
3693
3694 // This is used for compatibility with older PCH formats.
3695 bool HaveReadControlBlock = false;
3696
Chris Lattnerefa77172013-01-20 00:00:22 +00003697 while (1) {
3698 llvm::BitstreamEntry Entry = Stream.advance();
3699
3700 switch (Entry.Kind) {
3701 case llvm::BitstreamEntry::Error:
3702 case llvm::BitstreamEntry::EndBlock:
3703 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003704 Error("invalid record at top-level of AST file");
3705 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003706
3707 case llvm::BitstreamEntry::SubBlock:
3708 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003709 }
3710
Guy Benyei11169dd2012-12-18 14:30:41 +00003711 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003712 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003713 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3714 if (Stream.ReadBlockInfoBlock()) {
3715 Error("malformed BlockInfoBlock in AST file");
3716 return Failure;
3717 }
3718 break;
3719 case CONTROL_BLOCK_ID:
3720 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003721 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003722 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003723 // Check that we didn't try to load a non-module AST file as a module.
3724 //
3725 // FIXME: Should we also perform the converse check? Loading a module as
3726 // a PCH file sort of works, but it's a bit wonky.
3727 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule) &&
3728 F.ModuleName.empty()) {
3729 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3730 if (Result != OutOfDate ||
3731 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3732 Diag(diag::err_module_file_not_module) << FileName;
3733 return Result;
3734 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003735 break;
3736
3737 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003738 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003739 case OutOfDate: return OutOfDate;
3740 case VersionMismatch: return VersionMismatch;
3741 case ConfigurationMismatch: return ConfigurationMismatch;
3742 case HadErrors: return HadErrors;
3743 }
3744 break;
3745 case AST_BLOCK_ID:
3746 if (!HaveReadControlBlock) {
3747 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003748 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003749 return VersionMismatch;
3750 }
3751
3752 // Record that we've loaded this module.
3753 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3754 return Success;
3755
3756 default:
3757 if (Stream.SkipBlock()) {
3758 Error("malformed block record in AST file");
3759 return Failure;
3760 }
3761 break;
3762 }
3763 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003764}
3765
Richard Smitha7e2cc62015-05-01 01:53:09 +00003766void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003767 // If there's a listener, notify them that we "read" the translation unit.
3768 if (DeserializationListener)
3769 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3770 Context.getTranslationUnitDecl());
3771
Guy Benyei11169dd2012-12-18 14:30:41 +00003772 // FIXME: Find a better way to deal with collisions between these
3773 // built-in types. Right now, we just ignore the problem.
3774
3775 // Load the special types.
3776 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3777 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3778 if (!Context.CFConstantStringTypeDecl)
3779 Context.setCFConstantStringType(GetType(String));
3780 }
3781
3782 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3783 QualType FileType = GetType(File);
3784 if (FileType.isNull()) {
3785 Error("FILE type is NULL");
3786 return;
3787 }
3788
3789 if (!Context.FILEDecl) {
3790 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3791 Context.setFILEDecl(Typedef->getDecl());
3792 else {
3793 const TagType *Tag = FileType->getAs<TagType>();
3794 if (!Tag) {
3795 Error("Invalid FILE type in AST file");
3796 return;
3797 }
3798 Context.setFILEDecl(Tag->getDecl());
3799 }
3800 }
3801 }
3802
3803 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3804 QualType Jmp_bufType = GetType(Jmp_buf);
3805 if (Jmp_bufType.isNull()) {
3806 Error("jmp_buf type is NULL");
3807 return;
3808 }
3809
3810 if (!Context.jmp_bufDecl) {
3811 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3812 Context.setjmp_bufDecl(Typedef->getDecl());
3813 else {
3814 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3815 if (!Tag) {
3816 Error("Invalid jmp_buf type in AST file");
3817 return;
3818 }
3819 Context.setjmp_bufDecl(Tag->getDecl());
3820 }
3821 }
3822 }
3823
3824 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3825 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3826 if (Sigjmp_bufType.isNull()) {
3827 Error("sigjmp_buf type is NULL");
3828 return;
3829 }
3830
3831 if (!Context.sigjmp_bufDecl) {
3832 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3833 Context.setsigjmp_bufDecl(Typedef->getDecl());
3834 else {
3835 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3836 assert(Tag && "Invalid sigjmp_buf type in AST file");
3837 Context.setsigjmp_bufDecl(Tag->getDecl());
3838 }
3839 }
3840 }
3841
3842 if (unsigned ObjCIdRedef
3843 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3844 if (Context.ObjCIdRedefinitionType.isNull())
3845 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3846 }
3847
3848 if (unsigned ObjCClassRedef
3849 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3850 if (Context.ObjCClassRedefinitionType.isNull())
3851 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3852 }
3853
3854 if (unsigned ObjCSelRedef
3855 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3856 if (Context.ObjCSelRedefinitionType.isNull())
3857 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3858 }
3859
3860 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3861 QualType Ucontext_tType = GetType(Ucontext_t);
3862 if (Ucontext_tType.isNull()) {
3863 Error("ucontext_t type is NULL");
3864 return;
3865 }
3866
3867 if (!Context.ucontext_tDecl) {
3868 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3869 Context.setucontext_tDecl(Typedef->getDecl());
3870 else {
3871 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3872 assert(Tag && "Invalid ucontext_t type in AST file");
3873 Context.setucontext_tDecl(Tag->getDecl());
3874 }
3875 }
3876 }
3877 }
3878
3879 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3880
3881 // If there were any CUDA special declarations, deserialize them.
3882 if (!CUDASpecialDeclRefs.empty()) {
3883 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3884 Context.setcudaConfigureCallDecl(
3885 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3886 }
Richard Smith56be7542014-03-21 00:33:59 +00003887
Guy Benyei11169dd2012-12-18 14:30:41 +00003888 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003889 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003890 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003891 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003892 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003893 /*ImportLoc=*/Import.ImportLoc);
3894 PP.makeModuleVisible(Imported, Import.ImportLoc);
3895 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003896 }
3897 ImportedModules.clear();
3898}
3899
3900void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003901 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003902}
3903
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003904/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3905/// cursor into the start of the given block ID, returning false on success and
3906/// true on failure.
3907static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003908 while (1) {
3909 llvm::BitstreamEntry Entry = Cursor.advance();
3910 switch (Entry.Kind) {
3911 case llvm::BitstreamEntry::Error:
3912 case llvm::BitstreamEntry::EndBlock:
3913 return true;
3914
3915 case llvm::BitstreamEntry::Record:
3916 // Ignore top-level records.
3917 Cursor.skipRecord(Entry.ID);
3918 break;
3919
3920 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003921 if (Entry.ID == BlockID) {
3922 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003923 return true;
3924 // Found it!
3925 return false;
3926 }
3927
3928 if (Cursor.SkipBlock())
3929 return true;
3930 }
3931 }
3932}
3933
Ben Langmuir70a1b812015-03-24 04:43:52 +00003934/// \brief Reads and return the signature record from \p StreamFile's control
3935/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003936static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3937 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003938 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003939 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003940
3941 // Scan for the CONTROL_BLOCK_ID block.
3942 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3943 return 0;
3944
3945 // Scan for SIGNATURE inside the control block.
3946 ASTReader::RecordData Record;
3947 while (1) {
3948 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3949 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3950 Entry.Kind != llvm::BitstreamEntry::Record)
3951 return 0;
3952
3953 Record.clear();
3954 StringRef Blob;
3955 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3956 return Record[0];
3957 }
3958}
3959
Guy Benyei11169dd2012-12-18 14:30:41 +00003960/// \brief Retrieve the name of the original source file name
3961/// directly from the AST file, without actually loading the AST
3962/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003963std::string ASTReader::getOriginalSourceFile(
3964 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003965 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003966 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00003967 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00003968 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00003969 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3970 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00003971 return std::string();
3972 }
3973
3974 // Initialize the stream
3975 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003976 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003977 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003978
3979 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003980 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003981 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3982 return std::string();
3983 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003984
Chris Lattnere7b154b2013-01-19 21:39:22 +00003985 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003986 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003987 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3988 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003989 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003990
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003991 // Scan for ORIGINAL_FILE inside the control block.
3992 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003993 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003994 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003995 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3996 return std::string();
3997
3998 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3999 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4000 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004001 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004002
Guy Benyei11169dd2012-12-18 14:30:41 +00004003 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004004 StringRef Blob;
4005 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4006 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004007 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004008}
4009
4010namespace {
4011 class SimplePCHValidator : public ASTReaderListener {
4012 const LangOptions &ExistingLangOpts;
4013 const TargetOptions &ExistingTargetOpts;
4014 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004015 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004016 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004017
Guy Benyei11169dd2012-12-18 14:30:41 +00004018 public:
4019 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4020 const TargetOptions &ExistingTargetOpts,
4021 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004022 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004023 FileManager &FileMgr)
4024 : ExistingLangOpts(ExistingLangOpts),
4025 ExistingTargetOpts(ExistingTargetOpts),
4026 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004027 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004028 FileMgr(FileMgr)
4029 {
4030 }
4031
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004032 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4033 bool AllowCompatibleDifferences) override {
4034 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4035 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004036 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004037 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4038 bool AllowCompatibleDifferences) override {
4039 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4040 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004041 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004042 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4043 StringRef SpecificModuleCachePath,
4044 bool Complain) override {
4045 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4046 ExistingModuleCachePath,
4047 nullptr, ExistingLangOpts);
4048 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004049 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4050 bool Complain,
4051 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004052 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004053 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004054 }
4055 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004056}
Guy Benyei11169dd2012-12-18 14:30:41 +00004057
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004058bool ASTReader::readASTFileControlBlock(
4059 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004060 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004061 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004062 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004063 // FIXME: This allows use of the VFS; we do not allow use of the
4064 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004065 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004066 if (!Buffer) {
4067 return true;
4068 }
4069
4070 // Initialize the stream
4071 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004072 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004073 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004074
4075 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004076 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004077 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004078
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004079 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004080 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004081 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004082
4083 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004084 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004085 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004086 BitstreamCursor InputFilesCursor;
4087 if (NeedsInputFiles) {
4088 InputFilesCursor = Stream;
4089 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4090 return true;
4091
4092 // Read the abbreviations
4093 while (true) {
4094 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4095 unsigned Code = InputFilesCursor.ReadCode();
4096
4097 // We expect all abbrevs to be at the start of the block.
4098 if (Code != llvm::bitc::DEFINE_ABBREV) {
4099 InputFilesCursor.JumpToBit(Offset);
4100 break;
4101 }
4102 InputFilesCursor.ReadAbbrevRecord();
4103 }
4104 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004105
4106 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004107 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004108 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004109 while (1) {
4110 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4111 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4112 return false;
4113
4114 if (Entry.Kind != llvm::BitstreamEntry::Record)
4115 return true;
4116
Guy Benyei11169dd2012-12-18 14:30:41 +00004117 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004118 StringRef Blob;
4119 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004120 switch ((ControlRecordTypes)RecCode) {
4121 case METADATA: {
4122 if (Record[0] != VERSION_MAJOR)
4123 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004124
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004125 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004126 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004127
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004128 break;
4129 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004130 case MODULE_NAME:
4131 Listener.ReadModuleName(Blob);
4132 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004133 case MODULE_DIRECTORY:
4134 ModuleDir = Blob;
4135 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004136 case MODULE_MAP_FILE: {
4137 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004138 auto Path = ReadString(Record, Idx);
4139 ResolveImportedPath(Path, ModuleDir);
4140 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004141 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004142 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004143 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004144 if (ParseLanguageOptions(Record, false, Listener,
4145 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004146 return true;
4147 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004148
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004149 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004150 if (ParseTargetOptions(Record, false, Listener,
4151 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004152 return true;
4153 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004154
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004155 case DIAGNOSTIC_OPTIONS:
4156 if (ParseDiagnosticOptions(Record, false, Listener))
4157 return true;
4158 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004159
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004160 case FILE_SYSTEM_OPTIONS:
4161 if (ParseFileSystemOptions(Record, false, Listener))
4162 return true;
4163 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004164
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004165 case HEADER_SEARCH_OPTIONS:
4166 if (ParseHeaderSearchOptions(Record, false, Listener))
4167 return true;
4168 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004169
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004170 case PREPROCESSOR_OPTIONS: {
4171 std::string IgnoredSuggestedPredefines;
4172 if (ParsePreprocessorOptions(Record, false, Listener,
4173 IgnoredSuggestedPredefines))
4174 return true;
4175 break;
4176 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004177
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004178 case INPUT_FILE_OFFSETS: {
4179 if (!NeedsInputFiles)
4180 break;
4181
4182 unsigned NumInputFiles = Record[0];
4183 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004184 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004185 for (unsigned I = 0; I != NumInputFiles; ++I) {
4186 // Go find this input file.
4187 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004188
4189 if (isSystemFile && !NeedsSystemInputFiles)
4190 break; // the rest are system input files
4191
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004192 BitstreamCursor &Cursor = InputFilesCursor;
4193 SavedStreamPosition SavedPosition(Cursor);
4194 Cursor.JumpToBit(InputFileOffs[I]);
4195
4196 unsigned Code = Cursor.ReadCode();
4197 RecordData Record;
4198 StringRef Blob;
4199 bool shouldContinue = false;
4200 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4201 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004202 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004203 std::string Filename = Blob;
4204 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004205 shouldContinue = Listener.visitInputFile(
4206 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004207 break;
4208 }
4209 if (!shouldContinue)
4210 break;
4211 }
4212 break;
4213 }
4214
Richard Smithd4b230b2014-10-27 23:01:16 +00004215 case IMPORTS: {
4216 if (!NeedsImports)
4217 break;
4218
4219 unsigned Idx = 0, N = Record.size();
4220 while (Idx < N) {
4221 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004222 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004223 std::string Filename = ReadString(Record, Idx);
4224 ResolveImportedPath(Filename, ModuleDir);
4225 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004226 }
4227 break;
4228 }
4229
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004230 default:
4231 // No other validation to perform.
4232 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004233 }
4234 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004235}
4236
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004237bool ASTReader::isAcceptableASTFile(
4238 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004239 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004240 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4241 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004242 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4243 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004244 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004245 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004246}
4247
Ben Langmuir2c9af442014-04-10 17:57:43 +00004248ASTReader::ASTReadResult
4249ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004250 // Enter the submodule block.
4251 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4252 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004253 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004254 }
4255
4256 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4257 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004258 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004259 RecordData Record;
4260 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004261 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4262
4263 switch (Entry.Kind) {
4264 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4265 case llvm::BitstreamEntry::Error:
4266 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004267 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004268 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004269 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004270 case llvm::BitstreamEntry::Record:
4271 // The interesting case.
4272 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004273 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004274
Guy Benyei11169dd2012-12-18 14:30:41 +00004275 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004276 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004277 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004278 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4279
4280 if ((Kind == SUBMODULE_METADATA) != First) {
4281 Error("submodule metadata record should be at beginning of block");
4282 return Failure;
4283 }
4284 First = false;
4285
4286 // Submodule information is only valid if we have a current module.
4287 // FIXME: Should we error on these cases?
4288 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4289 Kind != SUBMODULE_DEFINITION)
4290 continue;
4291
4292 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004293 default: // Default behavior: ignore.
4294 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004295
Richard Smith03478d92014-10-23 22:12:14 +00004296 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004297 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004298 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004299 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004300 }
Richard Smith03478d92014-10-23 22:12:14 +00004301
Chris Lattner0e6c9402013-01-20 02:38:54 +00004302 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004303 unsigned Idx = 0;
4304 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4305 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4306 bool IsFramework = Record[Idx++];
4307 bool IsExplicit = Record[Idx++];
4308 bool IsSystem = Record[Idx++];
4309 bool IsExternC = Record[Idx++];
4310 bool InferSubmodules = Record[Idx++];
4311 bool InferExplicitSubmodules = Record[Idx++];
4312 bool InferExportWildcard = Record[Idx++];
4313 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004314
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004315 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004316 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004318
Guy Benyei11169dd2012-12-18 14:30:41 +00004319 // Retrieve this (sub)module from the module map, creating it if
4320 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004321 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004323
4324 // FIXME: set the definition loc for CurrentModule, or call
4325 // ModMap.setInferredModuleAllowedBy()
4326
Guy Benyei11169dd2012-12-18 14:30:41 +00004327 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4328 if (GlobalIndex >= SubmodulesLoaded.size() ||
4329 SubmodulesLoaded[GlobalIndex]) {
4330 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004331 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004332 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004333
Douglas Gregor7029ce12013-03-19 00:28:20 +00004334 if (!ParentModule) {
4335 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4336 if (CurFile != F.File) {
4337 if (!Diags.isDiagnosticInFlight()) {
4338 Diag(diag::err_module_file_conflict)
4339 << CurrentModule->getTopLevelModuleName()
4340 << CurFile->getName()
4341 << F.File->getName();
4342 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004343 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004344 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004345 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004346
4347 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004348 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004349
Adrian Prantl15bcf702015-06-30 17:39:43 +00004350 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004351 CurrentModule->IsFromModuleFile = true;
4352 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004353 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004354 CurrentModule->InferSubmodules = InferSubmodules;
4355 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4356 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004357 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004358 if (DeserializationListener)
4359 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4360
4361 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004362
Douglas Gregorfb912652013-03-20 21:10:35 +00004363 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004364 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004365 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004366 CurrentModule->UnresolvedConflicts.clear();
4367 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004368 break;
4369 }
4370
4371 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004372 std::string Filename = Blob;
4373 ResolveImportedPath(F, Filename);
4374 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004375 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004376 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4377 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004378 // This can be a spurious difference caused by changing the VFS to
4379 // point to a different copy of the file, and it is too late to
4380 // to rebuild safely.
4381 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4382 // after input file validation only real problems would remain and we
4383 // could just error. For now, assume it's okay.
4384 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004385 }
4386 }
4387 break;
4388 }
4389
Richard Smith202210b2014-10-24 20:23:01 +00004390 case SUBMODULE_HEADER:
4391 case SUBMODULE_EXCLUDED_HEADER:
4392 case SUBMODULE_PRIVATE_HEADER:
4393 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004394 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4395 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004396 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004397
Richard Smith202210b2014-10-24 20:23:01 +00004398 case SUBMODULE_TEXTUAL_HEADER:
4399 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4400 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4401 // them here.
4402 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004403
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004405 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004406 break;
4407 }
4408
4409 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004410 std::string Dirname = Blob;
4411 ResolveImportedPath(F, Dirname);
4412 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004413 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004414 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4415 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004416 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4417 Error("mismatched umbrella directories in submodule");
4418 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004419 }
4420 }
4421 break;
4422 }
4423
4424 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004425 F.BaseSubmoduleID = getTotalNumSubmodules();
4426 F.LocalNumSubmodules = Record[0];
4427 unsigned LocalBaseSubmoduleID = Record[1];
4428 if (F.LocalNumSubmodules > 0) {
4429 // Introduce the global -> local mapping for submodules within this
4430 // module.
4431 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4432
4433 // Introduce the local -> global mapping for submodules within this
4434 // module.
4435 F.SubmoduleRemap.insertOrReplace(
4436 std::make_pair(LocalBaseSubmoduleID,
4437 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004438
Ben Langmuir52ca6782014-10-20 16:27:32 +00004439 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4440 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 break;
4442 }
4443
4444 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004446 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004447 Unresolved.File = &F;
4448 Unresolved.Mod = CurrentModule;
4449 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004450 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004452 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 }
4454 break;
4455 }
4456
4457 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004459 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 Unresolved.File = &F;
4461 Unresolved.Mod = CurrentModule;
4462 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004463 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004465 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 }
4467
4468 // Once we've loaded the set of exports, there's no reason to keep
4469 // the parsed, unresolved exports around.
4470 CurrentModule->UnresolvedExports.clear();
4471 break;
4472 }
4473 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004474 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004475 Context.getTargetInfo());
4476 break;
4477 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004478
4479 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004480 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004481 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004482 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004483
4484 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004485 CurrentModule->ConfigMacros.push_back(Blob.str());
4486 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004487
4488 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004489 UnresolvedModuleRef Unresolved;
4490 Unresolved.File = &F;
4491 Unresolved.Mod = CurrentModule;
4492 Unresolved.ID = Record[0];
4493 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4494 Unresolved.IsWildcard = false;
4495 Unresolved.String = Blob;
4496 UnresolvedModuleRefs.push_back(Unresolved);
4497 break;
4498 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 }
4500 }
4501}
4502
4503/// \brief Parse the record that corresponds to a LangOptions data
4504/// structure.
4505///
4506/// This routine parses the language options from the AST file and then gives
4507/// them to the AST listener if one is set.
4508///
4509/// \returns true if the listener deems the file unacceptable, false otherwise.
4510bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4511 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004512 ASTReaderListener &Listener,
4513 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004514 LangOptions LangOpts;
4515 unsigned Idx = 0;
4516#define LANGOPT(Name, Bits, Default, Description) \
4517 LangOpts.Name = Record[Idx++];
4518#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4519 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4520#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004521#define SANITIZER(NAME, ID) \
4522 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004523#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004524
Ben Langmuircd98cb72015-06-23 18:20:18 +00004525 for (unsigned N = Record[Idx++]; N; --N)
4526 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4527
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4529 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4530 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004531
Ben Langmuird4a667a2015-06-23 18:20:23 +00004532 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004533
4534 // Comment options.
4535 for (unsigned N = Record[Idx++]; N; --N) {
4536 LangOpts.CommentOpts.BlockCommandNames.push_back(
4537 ReadString(Record, Idx));
4538 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004539 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004540
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004541 return Listener.ReadLanguageOptions(LangOpts, Complain,
4542 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004543}
4544
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004545bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4546 ASTReaderListener &Listener,
4547 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004548 unsigned Idx = 0;
4549 TargetOptions TargetOpts;
4550 TargetOpts.Triple = ReadString(Record, Idx);
4551 TargetOpts.CPU = ReadString(Record, Idx);
4552 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 for (unsigned N = Record[Idx++]; N; --N) {
4554 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4555 }
4556 for (unsigned N = Record[Idx++]; N; --N) {
4557 TargetOpts.Features.push_back(ReadString(Record, Idx));
4558 }
4559
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004560 return Listener.ReadTargetOptions(TargetOpts, Complain,
4561 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004562}
4563
4564bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4565 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004566 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004567 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004568#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004569#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004570 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004571#include "clang/Basic/DiagnosticOptions.def"
4572
Richard Smith3be1cb22014-08-07 00:24:21 +00004573 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004574 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004575 for (unsigned N = Record[Idx++]; N; --N)
4576 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004577
4578 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4579}
4580
4581bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4582 ASTReaderListener &Listener) {
4583 FileSystemOptions FSOpts;
4584 unsigned Idx = 0;
4585 FSOpts.WorkingDir = ReadString(Record, Idx);
4586 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4587}
4588
4589bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4590 bool Complain,
4591 ASTReaderListener &Listener) {
4592 HeaderSearchOptions HSOpts;
4593 unsigned Idx = 0;
4594 HSOpts.Sysroot = ReadString(Record, Idx);
4595
4596 // Include entries.
4597 for (unsigned N = Record[Idx++]; N; --N) {
4598 std::string Path = ReadString(Record, Idx);
4599 frontend::IncludeDirGroup Group
4600 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 bool IsFramework = Record[Idx++];
4602 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004603 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4604 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 }
4606
4607 // System header prefixes.
4608 for (unsigned N = Record[Idx++]; N; --N) {
4609 std::string Prefix = ReadString(Record, Idx);
4610 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004611 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004612 }
4613
4614 HSOpts.ResourceDir = ReadString(Record, Idx);
4615 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004616 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 HSOpts.DisableModuleHash = Record[Idx++];
4618 HSOpts.UseBuiltinIncludes = Record[Idx++];
4619 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4620 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4621 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004622 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004623
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004624 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4625 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004626}
4627
4628bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4629 bool Complain,
4630 ASTReaderListener &Listener,
4631 std::string &SuggestedPredefines) {
4632 PreprocessorOptions PPOpts;
4633 unsigned Idx = 0;
4634
4635 // Macro definitions/undefs
4636 for (unsigned N = Record[Idx++]; N; --N) {
4637 std::string Macro = ReadString(Record, Idx);
4638 bool IsUndef = Record[Idx++];
4639 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4640 }
4641
4642 // Includes
4643 for (unsigned N = Record[Idx++]; N; --N) {
4644 PPOpts.Includes.push_back(ReadString(Record, Idx));
4645 }
4646
4647 // Macro Includes
4648 for (unsigned N = Record[Idx++]; N; --N) {
4649 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4650 }
4651
4652 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004653 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004654 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4655 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4656 PPOpts.ObjCXXARCStandardLibrary =
4657 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4658 SuggestedPredefines.clear();
4659 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4660 SuggestedPredefines);
4661}
4662
4663std::pair<ModuleFile *, unsigned>
4664ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4665 GlobalPreprocessedEntityMapType::iterator
4666 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4667 assert(I != GlobalPreprocessedEntityMap.end() &&
4668 "Corrupted global preprocessed entity map");
4669 ModuleFile *M = I->second;
4670 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4671 return std::make_pair(M, LocalIndex);
4672}
4673
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004674llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004675ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4676 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4677 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4678 Mod.NumPreprocessedEntities);
4679
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004680 return llvm::make_range(PreprocessingRecord::iterator(),
4681 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004682}
4683
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004684llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004685ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004686 return llvm::make_range(
4687 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4688 ModuleDeclIterator(this, &Mod,
4689 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004690}
4691
4692PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4693 PreprocessedEntityID PPID = Index+1;
4694 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4695 ModuleFile &M = *PPInfo.first;
4696 unsigned LocalIndex = PPInfo.second;
4697 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4698
Guy Benyei11169dd2012-12-18 14:30:41 +00004699 if (!PP.getPreprocessingRecord()) {
4700 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004701 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004702 }
4703
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004704 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4705 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4706
4707 llvm::BitstreamEntry Entry =
4708 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4709 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004710 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004711
Guy Benyei11169dd2012-12-18 14:30:41 +00004712 // Read the record.
4713 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4714 ReadSourceLocation(M, PPOffs.End));
4715 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004716 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004717 RecordData Record;
4718 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004719 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4720 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004721 switch (RecType) {
4722 case PPD_MACRO_EXPANSION: {
4723 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004724 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004725 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004726 if (isBuiltin)
4727 Name = getLocalIdentifier(M, Record[1]);
4728 else {
Richard Smith66a81862015-05-04 02:25:31 +00004729 PreprocessedEntityID GlobalID =
4730 getGlobalPreprocessedEntityID(M, Record[1]);
4731 Def = cast<MacroDefinitionRecord>(
4732 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004733 }
4734
4735 MacroExpansion *ME;
4736 if (isBuiltin)
4737 ME = new (PPRec) MacroExpansion(Name, Range);
4738 else
4739 ME = new (PPRec) MacroExpansion(Def, Range);
4740
4741 return ME;
4742 }
4743
4744 case PPD_MACRO_DEFINITION: {
4745 // Decode the identifier info and then check again; if the macro is
4746 // still defined and associated with the identifier,
4747 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004748 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004749
4750 if (DeserializationListener)
4751 DeserializationListener->MacroDefinitionRead(PPID, MD);
4752
4753 return MD;
4754 }
4755
4756 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004757 const char *FullFileNameStart = Blob.data() + Record[0];
4758 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004759 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004760 if (!FullFileName.empty())
4761 File = PP.getFileManager().getFile(FullFileName);
4762
4763 // FIXME: Stable encoding
4764 InclusionDirective::InclusionKind Kind
4765 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4766 InclusionDirective *ID
4767 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004768 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 Record[1], Record[3],
4770 File,
4771 Range);
4772 return ID;
4773 }
4774 }
4775
4776 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4777}
4778
4779/// \brief \arg SLocMapI points at a chunk of a module that contains no
4780/// preprocessed entities or the entities it contains are not the ones we are
4781/// looking for. Find the next module that contains entities and return the ID
4782/// of the first entry.
4783PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4784 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4785 ++SLocMapI;
4786 for (GlobalSLocOffsetMapType::const_iterator
4787 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4788 ModuleFile &M = *SLocMapI->second;
4789 if (M.NumPreprocessedEntities)
4790 return M.BasePreprocessedEntityID;
4791 }
4792
4793 return getTotalNumPreprocessedEntities();
4794}
4795
4796namespace {
4797
4798template <unsigned PPEntityOffset::*PPLoc>
4799struct PPEntityComp {
4800 const ASTReader &Reader;
4801 ModuleFile &M;
4802
4803 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4804
4805 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4806 SourceLocation LHS = getLoc(L);
4807 SourceLocation RHS = getLoc(R);
4808 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4809 }
4810
4811 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4812 SourceLocation LHS = getLoc(L);
4813 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4814 }
4815
4816 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4817 SourceLocation RHS = getLoc(R);
4818 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4819 }
4820
4821 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4822 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4823 }
4824};
4825
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004826}
Guy Benyei11169dd2012-12-18 14:30:41 +00004827
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004828PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4829 bool EndsAfter) const {
4830 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004831 return getTotalNumPreprocessedEntities();
4832
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004833 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4834 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004835 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4836 "Corrupted global sloc offset map");
4837
4838 if (SLocMapI->second->NumPreprocessedEntities == 0)
4839 return findNextPreprocessedEntity(SLocMapI);
4840
4841 ModuleFile &M = *SLocMapI->second;
4842 typedef const PPEntityOffset *pp_iterator;
4843 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4844 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4845
4846 size_t Count = M.NumPreprocessedEntities;
4847 size_t Half;
4848 pp_iterator First = pp_begin;
4849 pp_iterator PPI;
4850
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004851 if (EndsAfter) {
4852 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4853 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4854 } else {
4855 // Do a binary search manually instead of using std::lower_bound because
4856 // The end locations of entities may be unordered (when a macro expansion
4857 // is inside another macro argument), but for this case it is not important
4858 // whether we get the first macro expansion or its containing macro.
4859 while (Count > 0) {
4860 Half = Count / 2;
4861 PPI = First;
4862 std::advance(PPI, Half);
4863 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4864 Loc)) {
4865 First = PPI;
4866 ++First;
4867 Count = Count - Half - 1;
4868 } else
4869 Count = Half;
4870 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004871 }
4872
4873 if (PPI == pp_end)
4874 return findNextPreprocessedEntity(SLocMapI);
4875
4876 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4877}
4878
Guy Benyei11169dd2012-12-18 14:30:41 +00004879/// \brief Returns a pair of [Begin, End) indices of preallocated
4880/// preprocessed entities that \arg Range encompasses.
4881std::pair<unsigned, unsigned>
4882 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4883 if (Range.isInvalid())
4884 return std::make_pair(0,0);
4885 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4886
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004887 PreprocessedEntityID BeginID =
4888 findPreprocessedEntity(Range.getBegin(), false);
4889 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004890 return std::make_pair(BeginID, EndID);
4891}
4892
4893/// \brief Optionally returns true or false if the preallocated preprocessed
4894/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004895Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004896 FileID FID) {
4897 if (FID.isInvalid())
4898 return false;
4899
4900 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4901 ModuleFile &M = *PPInfo.first;
4902 unsigned LocalIndex = PPInfo.second;
4903 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4904
4905 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4906 if (Loc.isInvalid())
4907 return false;
4908
4909 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4910 return true;
4911 else
4912 return false;
4913}
4914
4915namespace {
4916 /// \brief Visitor used to search for information about a header file.
4917 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004918 const FileEntry *FE;
4919
David Blaikie05785d12013-02-20 22:23:23 +00004920 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004921
4922 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004923 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4924 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004925
4926 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004927 HeaderFileInfoLookupTable *Table
4928 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4929 if (!Table)
4930 return false;
4931
4932 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00004933 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004934 if (Pos == Table->end())
4935 return false;
4936
Richard Smithbdf2d932015-07-30 03:37:16 +00004937 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00004938 return true;
4939 }
4940
David Blaikie05785d12013-02-20 22:23:23 +00004941 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004942 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004943}
Guy Benyei11169dd2012-12-18 14:30:41 +00004944
4945HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004946 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004947 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004948 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004949 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004950
4951 return HeaderFileInfo();
4952}
4953
4954void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4955 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004956 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004957 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4958 ModuleFile &F = *(*I);
4959 unsigned Idx = 0;
4960 DiagStates.clear();
4961 assert(!Diag.DiagStates.empty());
4962 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4963 while (Idx < F.PragmaDiagMappings.size()) {
4964 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4965 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4966 if (DiagStateID != 0) {
4967 Diag.DiagStatePoints.push_back(
4968 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4969 FullSourceLoc(Loc, SourceMgr)));
4970 continue;
4971 }
4972
4973 assert(DiagStateID == 0);
4974 // A new DiagState was created here.
4975 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4976 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4977 DiagStates.push_back(NewState);
4978 Diag.DiagStatePoints.push_back(
4979 DiagnosticsEngine::DiagStatePoint(NewState,
4980 FullSourceLoc(Loc, SourceMgr)));
4981 while (1) {
4982 assert(Idx < F.PragmaDiagMappings.size() &&
4983 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4984 if (Idx >= F.PragmaDiagMappings.size()) {
4985 break; // Something is messed up but at least avoid infinite loop in
4986 // release build.
4987 }
4988 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4989 if (DiagID == (unsigned)-1) {
4990 break; // no more diag/map pairs for this location.
4991 }
Alp Tokerc726c362014-06-10 09:31:37 +00004992 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4993 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4994 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00004995 }
4996 }
4997 }
4998}
4999
5000/// \brief Get the correct cursor and offset for loading a type.
5001ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5002 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5003 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5004 ModuleFile *M = I->second;
5005 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5006}
5007
5008/// \brief Read and return the type with the given index..
5009///
5010/// The index is the type ID, shifted and minus the number of predefs. This
5011/// routine actually reads the record corresponding to the type at the given
5012/// location. It is a helper routine for GetType, which deals with reading type
5013/// IDs.
5014QualType ASTReader::readTypeRecord(unsigned Index) {
5015 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005016 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005017
5018 // Keep track of where we are in the stream, then jump back there
5019 // after reading this type.
5020 SavedStreamPosition SavedPosition(DeclsCursor);
5021
5022 ReadingKindTracker ReadingKind(Read_Type, *this);
5023
5024 // Note that we are loading a type record.
5025 Deserializing AType(this);
5026
5027 unsigned Idx = 0;
5028 DeclsCursor.JumpToBit(Loc.Offset);
5029 RecordData Record;
5030 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005031 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005032 case TYPE_EXT_QUAL: {
5033 if (Record.size() != 2) {
5034 Error("Incorrect encoding of extended qualifier type");
5035 return QualType();
5036 }
5037 QualType Base = readType(*Loc.F, Record, Idx);
5038 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5039 return Context.getQualifiedType(Base, Quals);
5040 }
5041
5042 case TYPE_COMPLEX: {
5043 if (Record.size() != 1) {
5044 Error("Incorrect encoding of complex type");
5045 return QualType();
5046 }
5047 QualType ElemType = readType(*Loc.F, Record, Idx);
5048 return Context.getComplexType(ElemType);
5049 }
5050
5051 case TYPE_POINTER: {
5052 if (Record.size() != 1) {
5053 Error("Incorrect encoding of pointer type");
5054 return QualType();
5055 }
5056 QualType PointeeType = readType(*Loc.F, Record, Idx);
5057 return Context.getPointerType(PointeeType);
5058 }
5059
Reid Kleckner8a365022013-06-24 17:51:48 +00005060 case TYPE_DECAYED: {
5061 if (Record.size() != 1) {
5062 Error("Incorrect encoding of decayed type");
5063 return QualType();
5064 }
5065 QualType OriginalType = readType(*Loc.F, Record, Idx);
5066 QualType DT = Context.getAdjustedParameterType(OriginalType);
5067 if (!isa<DecayedType>(DT))
5068 Error("Decayed type does not decay");
5069 return DT;
5070 }
5071
Reid Kleckner0503a872013-12-05 01:23:43 +00005072 case TYPE_ADJUSTED: {
5073 if (Record.size() != 2) {
5074 Error("Incorrect encoding of adjusted type");
5075 return QualType();
5076 }
5077 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5078 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5079 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5080 }
5081
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 case TYPE_BLOCK_POINTER: {
5083 if (Record.size() != 1) {
5084 Error("Incorrect encoding of block pointer type");
5085 return QualType();
5086 }
5087 QualType PointeeType = readType(*Loc.F, Record, Idx);
5088 return Context.getBlockPointerType(PointeeType);
5089 }
5090
5091 case TYPE_LVALUE_REFERENCE: {
5092 if (Record.size() != 2) {
5093 Error("Incorrect encoding of lvalue reference type");
5094 return QualType();
5095 }
5096 QualType PointeeType = readType(*Loc.F, Record, Idx);
5097 return Context.getLValueReferenceType(PointeeType, Record[1]);
5098 }
5099
5100 case TYPE_RVALUE_REFERENCE: {
5101 if (Record.size() != 1) {
5102 Error("Incorrect encoding of rvalue reference type");
5103 return QualType();
5104 }
5105 QualType PointeeType = readType(*Loc.F, Record, Idx);
5106 return Context.getRValueReferenceType(PointeeType);
5107 }
5108
5109 case TYPE_MEMBER_POINTER: {
5110 if (Record.size() != 2) {
5111 Error("Incorrect encoding of member pointer type");
5112 return QualType();
5113 }
5114 QualType PointeeType = readType(*Loc.F, Record, Idx);
5115 QualType ClassType = readType(*Loc.F, Record, Idx);
5116 if (PointeeType.isNull() || ClassType.isNull())
5117 return QualType();
5118
5119 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5120 }
5121
5122 case TYPE_CONSTANT_ARRAY: {
5123 QualType ElementType = readType(*Loc.F, Record, Idx);
5124 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5125 unsigned IndexTypeQuals = Record[2];
5126 unsigned Idx = 3;
5127 llvm::APInt Size = ReadAPInt(Record, Idx);
5128 return Context.getConstantArrayType(ElementType, Size,
5129 ASM, IndexTypeQuals);
5130 }
5131
5132 case TYPE_INCOMPLETE_ARRAY: {
5133 QualType ElementType = readType(*Loc.F, Record, Idx);
5134 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5135 unsigned IndexTypeQuals = Record[2];
5136 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5137 }
5138
5139 case TYPE_VARIABLE_ARRAY: {
5140 QualType ElementType = readType(*Loc.F, Record, Idx);
5141 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5142 unsigned IndexTypeQuals = Record[2];
5143 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5144 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5145 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5146 ASM, IndexTypeQuals,
5147 SourceRange(LBLoc, RBLoc));
5148 }
5149
5150 case TYPE_VECTOR: {
5151 if (Record.size() != 3) {
5152 Error("incorrect encoding of vector type in AST file");
5153 return QualType();
5154 }
5155
5156 QualType ElementType = readType(*Loc.F, Record, Idx);
5157 unsigned NumElements = Record[1];
5158 unsigned VecKind = Record[2];
5159 return Context.getVectorType(ElementType, NumElements,
5160 (VectorType::VectorKind)VecKind);
5161 }
5162
5163 case TYPE_EXT_VECTOR: {
5164 if (Record.size() != 3) {
5165 Error("incorrect encoding of extended vector type in AST file");
5166 return QualType();
5167 }
5168
5169 QualType ElementType = readType(*Loc.F, Record, Idx);
5170 unsigned NumElements = Record[1];
5171 return Context.getExtVectorType(ElementType, NumElements);
5172 }
5173
5174 case TYPE_FUNCTION_NO_PROTO: {
5175 if (Record.size() != 6) {
5176 Error("incorrect encoding of no-proto function type");
5177 return QualType();
5178 }
5179 QualType ResultType = readType(*Loc.F, Record, Idx);
5180 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5181 (CallingConv)Record[4], Record[5]);
5182 return Context.getFunctionNoProtoType(ResultType, Info);
5183 }
5184
5185 case TYPE_FUNCTION_PROTO: {
5186 QualType ResultType = readType(*Loc.F, Record, Idx);
5187
5188 FunctionProtoType::ExtProtoInfo EPI;
5189 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5190 /*hasregparm*/ Record[2],
5191 /*regparm*/ Record[3],
5192 static_cast<CallingConv>(Record[4]),
5193 /*produces*/ Record[5]);
5194
5195 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005196
5197 EPI.Variadic = Record[Idx++];
5198 EPI.HasTrailingReturn = Record[Idx++];
5199 EPI.TypeQuals = Record[Idx++];
5200 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005201 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005202 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005203
5204 unsigned NumParams = Record[Idx++];
5205 SmallVector<QualType, 16> ParamTypes;
5206 for (unsigned I = 0; I != NumParams; ++I)
5207 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5208
Jordan Rose5c382722013-03-08 21:51:21 +00005209 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005210 }
5211
5212 case TYPE_UNRESOLVED_USING: {
5213 unsigned Idx = 0;
5214 return Context.getTypeDeclType(
5215 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5216 }
5217
5218 case TYPE_TYPEDEF: {
5219 if (Record.size() != 2) {
5220 Error("incorrect encoding of typedef type");
5221 return QualType();
5222 }
5223 unsigned Idx = 0;
5224 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5225 QualType Canonical = readType(*Loc.F, Record, Idx);
5226 if (!Canonical.isNull())
5227 Canonical = Context.getCanonicalType(Canonical);
5228 return Context.getTypedefType(Decl, Canonical);
5229 }
5230
5231 case TYPE_TYPEOF_EXPR:
5232 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5233
5234 case TYPE_TYPEOF: {
5235 if (Record.size() != 1) {
5236 Error("incorrect encoding of typeof(type) in AST file");
5237 return QualType();
5238 }
5239 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5240 return Context.getTypeOfType(UnderlyingType);
5241 }
5242
5243 case TYPE_DECLTYPE: {
5244 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5245 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5246 }
5247
5248 case TYPE_UNARY_TRANSFORM: {
5249 QualType BaseType = readType(*Loc.F, Record, Idx);
5250 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5251 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5252 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5253 }
5254
Richard Smith74aeef52013-04-26 16:15:35 +00005255 case TYPE_AUTO: {
5256 QualType Deduced = readType(*Loc.F, Record, Idx);
5257 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005258 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005259 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005260 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005261
5262 case TYPE_RECORD: {
5263 if (Record.size() != 2) {
5264 Error("incorrect encoding of record type");
5265 return QualType();
5266 }
5267 unsigned Idx = 0;
5268 bool IsDependent = Record[Idx++];
5269 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5270 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5271 QualType T = Context.getRecordType(RD);
5272 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5273 return T;
5274 }
5275
5276 case TYPE_ENUM: {
5277 if (Record.size() != 2) {
5278 Error("incorrect encoding of enum type");
5279 return QualType();
5280 }
5281 unsigned Idx = 0;
5282 bool IsDependent = Record[Idx++];
5283 QualType T
5284 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5285 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5286 return T;
5287 }
5288
5289 case TYPE_ATTRIBUTED: {
5290 if (Record.size() != 3) {
5291 Error("incorrect encoding of attributed type");
5292 return QualType();
5293 }
5294 QualType modifiedType = readType(*Loc.F, Record, Idx);
5295 QualType equivalentType = readType(*Loc.F, Record, Idx);
5296 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5297 return Context.getAttributedType(kind, modifiedType, equivalentType);
5298 }
5299
5300 case TYPE_PAREN: {
5301 if (Record.size() != 1) {
5302 Error("incorrect encoding of paren type");
5303 return QualType();
5304 }
5305 QualType InnerType = readType(*Loc.F, Record, Idx);
5306 return Context.getParenType(InnerType);
5307 }
5308
5309 case TYPE_PACK_EXPANSION: {
5310 if (Record.size() != 2) {
5311 Error("incorrect encoding of pack expansion type");
5312 return QualType();
5313 }
5314 QualType Pattern = readType(*Loc.F, Record, Idx);
5315 if (Pattern.isNull())
5316 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005317 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005318 if (Record[1])
5319 NumExpansions = Record[1] - 1;
5320 return Context.getPackExpansionType(Pattern, NumExpansions);
5321 }
5322
5323 case TYPE_ELABORATED: {
5324 unsigned Idx = 0;
5325 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5326 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5327 QualType NamedType = readType(*Loc.F, Record, Idx);
5328 return Context.getElaboratedType(Keyword, NNS, NamedType);
5329 }
5330
5331 case TYPE_OBJC_INTERFACE: {
5332 unsigned Idx = 0;
5333 ObjCInterfaceDecl *ItfD
5334 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5335 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5336 }
5337
5338 case TYPE_OBJC_OBJECT: {
5339 unsigned Idx = 0;
5340 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005341 unsigned NumTypeArgs = Record[Idx++];
5342 SmallVector<QualType, 4> TypeArgs;
5343 for (unsigned I = 0; I != NumTypeArgs; ++I)
5344 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005345 unsigned NumProtos = Record[Idx++];
5346 SmallVector<ObjCProtocolDecl*, 4> Protos;
5347 for (unsigned I = 0; I != NumProtos; ++I)
5348 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005349 bool IsKindOf = Record[Idx++];
5350 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005351 }
5352
5353 case TYPE_OBJC_OBJECT_POINTER: {
5354 unsigned Idx = 0;
5355 QualType Pointee = readType(*Loc.F, Record, Idx);
5356 return Context.getObjCObjectPointerType(Pointee);
5357 }
5358
5359 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5360 unsigned Idx = 0;
5361 QualType Parm = readType(*Loc.F, Record, Idx);
5362 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005363 return Context.getSubstTemplateTypeParmType(
5364 cast<TemplateTypeParmType>(Parm),
5365 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005366 }
5367
5368 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5369 unsigned Idx = 0;
5370 QualType Parm = readType(*Loc.F, Record, Idx);
5371 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5372 return Context.getSubstTemplateTypeParmPackType(
5373 cast<TemplateTypeParmType>(Parm),
5374 ArgPack);
5375 }
5376
5377 case TYPE_INJECTED_CLASS_NAME: {
5378 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5379 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5380 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5381 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005382 const Type *T = nullptr;
5383 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5384 if (const Type *Existing = DI->getTypeForDecl()) {
5385 T = Existing;
5386 break;
5387 }
5388 }
5389 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005390 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005391 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5392 DI->setTypeForDecl(T);
5393 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005394 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005395 }
5396
5397 case TYPE_TEMPLATE_TYPE_PARM: {
5398 unsigned Idx = 0;
5399 unsigned Depth = Record[Idx++];
5400 unsigned Index = Record[Idx++];
5401 bool Pack = Record[Idx++];
5402 TemplateTypeParmDecl *D
5403 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5404 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5405 }
5406
5407 case TYPE_DEPENDENT_NAME: {
5408 unsigned Idx = 0;
5409 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5410 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005411 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005412 QualType Canon = readType(*Loc.F, Record, Idx);
5413 if (!Canon.isNull())
5414 Canon = Context.getCanonicalType(Canon);
5415 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5416 }
5417
5418 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5419 unsigned Idx = 0;
5420 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5421 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005422 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005423 unsigned NumArgs = Record[Idx++];
5424 SmallVector<TemplateArgument, 8> Args;
5425 Args.reserve(NumArgs);
5426 while (NumArgs--)
5427 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5428 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5429 Args.size(), Args.data());
5430 }
5431
5432 case TYPE_DEPENDENT_SIZED_ARRAY: {
5433 unsigned Idx = 0;
5434
5435 // ArrayType
5436 QualType ElementType = readType(*Loc.F, Record, Idx);
5437 ArrayType::ArraySizeModifier ASM
5438 = (ArrayType::ArraySizeModifier)Record[Idx++];
5439 unsigned IndexTypeQuals = Record[Idx++];
5440
5441 // DependentSizedArrayType
5442 Expr *NumElts = ReadExpr(*Loc.F);
5443 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5444
5445 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5446 IndexTypeQuals, Brackets);
5447 }
5448
5449 case TYPE_TEMPLATE_SPECIALIZATION: {
5450 unsigned Idx = 0;
5451 bool IsDependent = Record[Idx++];
5452 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5453 SmallVector<TemplateArgument, 8> Args;
5454 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5455 QualType Underlying = readType(*Loc.F, Record, Idx);
5456 QualType T;
5457 if (Underlying.isNull())
5458 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5459 Args.size());
5460 else
5461 T = Context.getTemplateSpecializationType(Name, Args.data(),
5462 Args.size(), Underlying);
5463 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5464 return T;
5465 }
5466
5467 case TYPE_ATOMIC: {
5468 if (Record.size() != 1) {
5469 Error("Incorrect encoding of atomic type");
5470 return QualType();
5471 }
5472 QualType ValueType = readType(*Loc.F, Record, Idx);
5473 return Context.getAtomicType(ValueType);
5474 }
5475 }
5476 llvm_unreachable("Invalid TypeCode!");
5477}
5478
Richard Smith564417a2014-03-20 21:47:22 +00005479void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5480 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005481 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005482 const RecordData &Record, unsigned &Idx) {
5483 ExceptionSpecificationType EST =
5484 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005485 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005486 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005487 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005488 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005489 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005490 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005491 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005492 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005493 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5494 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005495 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005496 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005497 }
5498}
5499
Guy Benyei11169dd2012-12-18 14:30:41 +00005500class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5501 ASTReader &Reader;
5502 ModuleFile &F;
5503 const ASTReader::RecordData &Record;
5504 unsigned &Idx;
5505
5506 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5507 unsigned &I) {
5508 return Reader.ReadSourceLocation(F, R, I);
5509 }
5510
5511 template<typename T>
5512 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5513 return Reader.ReadDeclAs<T>(F, Record, Idx);
5514 }
5515
5516public:
5517 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5518 const ASTReader::RecordData &Record, unsigned &Idx)
5519 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5520 { }
5521
5522 // We want compile-time assurance that we've enumerated all of
5523 // these, so unfortunately we have to declare them first, then
5524 // define them out-of-line.
5525#define ABSTRACT_TYPELOC(CLASS, PARENT)
5526#define TYPELOC(CLASS, PARENT) \
5527 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5528#include "clang/AST/TypeLocNodes.def"
5529
5530 void VisitFunctionTypeLoc(FunctionTypeLoc);
5531 void VisitArrayTypeLoc(ArrayTypeLoc);
5532};
5533
5534void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5535 // nothing to do
5536}
5537void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5538 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5539 if (TL.needsExtraLocalData()) {
5540 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5541 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5542 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5543 TL.setModeAttr(Record[Idx++]);
5544 }
5545}
5546void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5547 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5548}
5549void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5550 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5551}
Reid Kleckner8a365022013-06-24 17:51:48 +00005552void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5553 // nothing to do
5554}
Reid Kleckner0503a872013-12-05 01:23:43 +00005555void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5556 // nothing to do
5557}
Guy Benyei11169dd2012-12-18 14:30:41 +00005558void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5559 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5560}
5561void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5562 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5563}
5564void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5565 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5566}
5567void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5568 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5569 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5570}
5571void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5572 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5573 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5574 if (Record[Idx++])
5575 TL.setSizeExpr(Reader.ReadExpr(F));
5576 else
Craig Toppera13603a2014-05-22 05:54:18 +00005577 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005578}
5579void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5580 VisitArrayTypeLoc(TL);
5581}
5582void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5583 VisitArrayTypeLoc(TL);
5584}
5585void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5586 VisitArrayTypeLoc(TL);
5587}
5588void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5589 DependentSizedArrayTypeLoc TL) {
5590 VisitArrayTypeLoc(TL);
5591}
5592void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5593 DependentSizedExtVectorTypeLoc TL) {
5594 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5595}
5596void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5597 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5598}
5599void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5600 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5601}
5602void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5603 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5604 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5605 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5606 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005607 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5608 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005609 }
5610}
5611void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5612 VisitFunctionTypeLoc(TL);
5613}
5614void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5615 VisitFunctionTypeLoc(TL);
5616}
5617void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5618 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5619}
5620void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5621 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5622}
5623void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5624 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5625 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5626 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5627}
5628void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5629 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5630 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5631 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5632 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5633}
5634void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5635 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5636}
5637void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5638 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5639 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5640 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5641 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5642}
5643void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5644 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5645}
5646void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5647 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5648}
5649void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5650 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5651}
5652void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5653 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5654 if (TL.hasAttrOperand()) {
5655 SourceRange range;
5656 range.setBegin(ReadSourceLocation(Record, Idx));
5657 range.setEnd(ReadSourceLocation(Record, Idx));
5658 TL.setAttrOperandParensRange(range);
5659 }
5660 if (TL.hasAttrExprOperand()) {
5661 if (Record[Idx++])
5662 TL.setAttrExprOperand(Reader.ReadExpr(F));
5663 else
Craig Toppera13603a2014-05-22 05:54:18 +00005664 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005665 } else if (TL.hasAttrEnumOperand())
5666 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5667}
5668void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5669 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5670}
5671void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5672 SubstTemplateTypeParmTypeLoc TL) {
5673 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5674}
5675void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5676 SubstTemplateTypeParmPackTypeLoc TL) {
5677 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5678}
5679void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5680 TemplateSpecializationTypeLoc TL) {
5681 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5682 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5683 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5684 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5685 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5686 TL.setArgLocInfo(i,
5687 Reader.GetTemplateArgumentLocInfo(F,
5688 TL.getTypePtr()->getArg(i).getKind(),
5689 Record, Idx));
5690}
5691void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5692 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5693 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5694}
5695void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5696 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5697 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5698}
5699void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5700 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5701}
5702void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5703 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5704 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5705 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5706}
5707void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5708 DependentTemplateSpecializationTypeLoc TL) {
5709 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5710 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5711 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5712 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5713 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5714 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5715 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5716 TL.setArgLocInfo(I,
5717 Reader.GetTemplateArgumentLocInfo(F,
5718 TL.getTypePtr()->getArg(I).getKind(),
5719 Record, Idx));
5720}
5721void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5722 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5723}
5724void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5725 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5726}
5727void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5728 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005729 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5730 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5731 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5732 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5733 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5734 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005735 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5736 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5737}
5738void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5739 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5740}
5741void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5742 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5743 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5744 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5745}
5746
5747TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5748 const RecordData &Record,
5749 unsigned &Idx) {
5750 QualType InfoTy = readType(F, Record, Idx);
5751 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005752 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005753
5754 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5755 TypeLocReader TLR(*this, F, Record, Idx);
5756 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5757 TLR.Visit(TL);
5758 return TInfo;
5759}
5760
5761QualType ASTReader::GetType(TypeID ID) {
5762 unsigned FastQuals = ID & Qualifiers::FastMask;
5763 unsigned Index = ID >> Qualifiers::FastWidth;
5764
5765 if (Index < NUM_PREDEF_TYPE_IDS) {
5766 QualType T;
5767 switch ((PredefinedTypeIDs)Index) {
5768 case PREDEF_TYPE_NULL_ID: return QualType();
5769 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5770 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5771
5772 case PREDEF_TYPE_CHAR_U_ID:
5773 case PREDEF_TYPE_CHAR_S_ID:
5774 // FIXME: Check that the signedness of CharTy is correct!
5775 T = Context.CharTy;
5776 break;
5777
5778 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5779 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5780 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5781 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5782 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5783 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5784 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5785 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5786 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5787 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5788 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5789 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5790 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5791 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5792 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5793 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5794 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5795 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5796 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5797 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5798 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5799 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5800 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5801 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5802 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5803 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5804 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5805 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005806 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5807 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5808 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5809 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5810 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5811 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005812 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005813 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005814 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5815
5816 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5817 T = Context.getAutoRRefDeductType();
5818 break;
5819
5820 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5821 T = Context.ARCUnbridgedCastTy;
5822 break;
5823
Guy Benyei11169dd2012-12-18 14:30:41 +00005824 case PREDEF_TYPE_BUILTIN_FN:
5825 T = Context.BuiltinFnTy;
5826 break;
5827 }
5828
5829 assert(!T.isNull() && "Unknown predefined type");
5830 return T.withFastQualifiers(FastQuals);
5831 }
5832
5833 Index -= NUM_PREDEF_TYPE_IDS;
5834 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5835 if (TypesLoaded[Index].isNull()) {
5836 TypesLoaded[Index] = readTypeRecord(Index);
5837 if (TypesLoaded[Index].isNull())
5838 return QualType();
5839
5840 TypesLoaded[Index]->setFromAST();
5841 if (DeserializationListener)
5842 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5843 TypesLoaded[Index]);
5844 }
5845
5846 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5847}
5848
5849QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5850 return GetType(getGlobalTypeID(F, LocalID));
5851}
5852
5853serialization::TypeID
5854ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5855 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5856 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5857
5858 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5859 return LocalID;
5860
5861 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5862 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5863 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5864
5865 unsigned GlobalIndex = LocalIndex + I->second;
5866 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5867}
5868
5869TemplateArgumentLocInfo
5870ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5871 TemplateArgument::ArgKind Kind,
5872 const RecordData &Record,
5873 unsigned &Index) {
5874 switch (Kind) {
5875 case TemplateArgument::Expression:
5876 return ReadExpr(F);
5877 case TemplateArgument::Type:
5878 return GetTypeSourceInfo(F, Record, Index);
5879 case TemplateArgument::Template: {
5880 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5881 Index);
5882 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5883 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5884 SourceLocation());
5885 }
5886 case TemplateArgument::TemplateExpansion: {
5887 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5888 Index);
5889 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5890 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5891 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5892 EllipsisLoc);
5893 }
5894 case TemplateArgument::Null:
5895 case TemplateArgument::Integral:
5896 case TemplateArgument::Declaration:
5897 case TemplateArgument::NullPtr:
5898 case TemplateArgument::Pack:
5899 // FIXME: Is this right?
5900 return TemplateArgumentLocInfo();
5901 }
5902 llvm_unreachable("unexpected template argument loc");
5903}
5904
5905TemplateArgumentLoc
5906ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5907 const RecordData &Record, unsigned &Index) {
5908 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5909
5910 if (Arg.getKind() == TemplateArgument::Expression) {
5911 if (Record[Index++]) // bool InfoHasSameExpr.
5912 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5913 }
5914 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5915 Record, Index));
5916}
5917
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005918const ASTTemplateArgumentListInfo*
5919ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5920 const RecordData &Record,
5921 unsigned &Index) {
5922 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5923 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5924 unsigned NumArgsAsWritten = Record[Index++];
5925 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5926 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5927 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5928 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5929}
5930
Guy Benyei11169dd2012-12-18 14:30:41 +00005931Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5932 return GetDecl(ID);
5933}
5934
Richard Smith50895422015-01-31 03:04:55 +00005935template<typename TemplateSpecializationDecl>
5936static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5937 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5938 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5939}
5940
Richard Smith053f6c62014-05-16 23:01:30 +00005941void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005942 if (NumCurrentElementsDeserializing) {
5943 // We arrange to not care about the complete redeclaration chain while we're
5944 // deserializing. Just remember that the AST has marked this one as complete
5945 // but that it's not actually complete yet, so we know we still need to
5946 // complete it later.
5947 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5948 return;
5949 }
5950
Richard Smith053f6c62014-05-16 23:01:30 +00005951 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5952
Richard Smith053f6c62014-05-16 23:01:30 +00005953 // If this is a named declaration, complete it by looking it up
5954 // within its context.
5955 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005956 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005957 // all mergeable entities within it.
5958 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5959 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5960 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00005961 if (!getContext().getLangOpts().CPlusPlus &&
5962 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00005963 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00005964 // the identifier instead. (For C++ modules, we don't store decls
5965 // in the serialized identifier table, so we do the lookup in the TU.)
5966 auto *II = Name.getAsIdentifierInfo();
5967 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00005968 if (II->isOutOfDate())
5969 updateOutOfDateIdentifier(*II);
5970 } else
5971 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005972 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00005973 // Find all declarations of this kind from the relevant context.
5974 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
5975 auto *DC = cast<DeclContext>(DCDecl);
5976 SmallVector<Decl*, 8> Decls;
5977 FindExternalLexicalDecls(
5978 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
5979 }
Richard Smith053f6c62014-05-16 23:01:30 +00005980 }
5981 }
Richard Smith50895422015-01-31 03:04:55 +00005982
5983 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5984 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5985 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5986 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5987 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5988 if (auto *Template = FD->getPrimaryTemplate())
5989 Template->LoadLazySpecializations();
5990 }
Richard Smith053f6c62014-05-16 23:01:30 +00005991}
5992
Richard Smithc2bb8182015-03-24 06:36:48 +00005993uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5994 const RecordData &Record,
5995 unsigned &Idx) {
5996 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5997 Error("malformed AST file: missing C++ ctor initializers");
5998 return 0;
5999 }
6000
6001 unsigned LocalID = Record[Idx++];
6002 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6003}
6004
6005CXXCtorInitializer **
6006ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6007 RecordLocation Loc = getLocalBitOffset(Offset);
6008 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6009 SavedStreamPosition SavedPosition(Cursor);
6010 Cursor.JumpToBit(Loc.Offset);
6011 ReadingKindTracker ReadingKind(Read_Decl, *this);
6012
6013 RecordData Record;
6014 unsigned Code = Cursor.ReadCode();
6015 unsigned RecCode = Cursor.readRecord(Code, Record);
6016 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6017 Error("malformed AST file: missing C++ ctor initializers");
6018 return nullptr;
6019 }
6020
6021 unsigned Idx = 0;
6022 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6023}
6024
Richard Smithcd45dbc2014-04-19 03:48:30 +00006025uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6026 const RecordData &Record,
6027 unsigned &Idx) {
6028 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6029 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006030 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006031 }
6032
Guy Benyei11169dd2012-12-18 14:30:41 +00006033 unsigned LocalID = Record[Idx++];
6034 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6035}
6036
6037CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6038 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006039 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006040 SavedStreamPosition SavedPosition(Cursor);
6041 Cursor.JumpToBit(Loc.Offset);
6042 ReadingKindTracker ReadingKind(Read_Decl, *this);
6043 RecordData Record;
6044 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006045 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006046 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006047 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006048 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006049 }
6050
6051 unsigned Idx = 0;
6052 unsigned NumBases = Record[Idx++];
6053 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6054 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6055 for (unsigned I = 0; I != NumBases; ++I)
6056 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6057 return Bases;
6058}
6059
6060serialization::DeclID
6061ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6062 if (LocalID < NUM_PREDEF_DECL_IDS)
6063 return LocalID;
6064
6065 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6066 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6067 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6068
6069 return LocalID + I->second;
6070}
6071
6072bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6073 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006074 // Predefined decls aren't from any module.
6075 if (ID < NUM_PREDEF_DECL_IDS)
6076 return false;
6077
Richard Smithbcda1a92015-07-12 23:51:20 +00006078 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6079 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006080}
6081
Douglas Gregor9f782892013-01-21 15:25:38 +00006082ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006083 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006084 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006085 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6086 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6087 return I->second;
6088}
6089
6090SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6091 if (ID < NUM_PREDEF_DECL_IDS)
6092 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006093
Guy Benyei11169dd2012-12-18 14:30:41 +00006094 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6095
6096 if (Index > DeclsLoaded.size()) {
6097 Error("declaration ID out-of-range for AST file");
6098 return SourceLocation();
6099 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006100
Guy Benyei11169dd2012-12-18 14:30:41 +00006101 if (Decl *D = DeclsLoaded[Index])
6102 return D->getLocation();
6103
6104 unsigned RawLocation = 0;
6105 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6106 return ReadSourceLocation(*Rec.F, RawLocation);
6107}
6108
Richard Smithfe620d22015-03-05 23:24:12 +00006109static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6110 switch (ID) {
6111 case PREDEF_DECL_NULL_ID:
6112 return nullptr;
6113
6114 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6115 return Context.getTranslationUnitDecl();
6116
6117 case PREDEF_DECL_OBJC_ID_ID:
6118 return Context.getObjCIdDecl();
6119
6120 case PREDEF_DECL_OBJC_SEL_ID:
6121 return Context.getObjCSelDecl();
6122
6123 case PREDEF_DECL_OBJC_CLASS_ID:
6124 return Context.getObjCClassDecl();
6125
6126 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6127 return Context.getObjCProtocolDecl();
6128
6129 case PREDEF_DECL_INT_128_ID:
6130 return Context.getInt128Decl();
6131
6132 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6133 return Context.getUInt128Decl();
6134
6135 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6136 return Context.getObjCInstanceTypeDecl();
6137
6138 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6139 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006140
Richard Smith9b88a4c2015-07-27 05:40:23 +00006141 case PREDEF_DECL_VA_LIST_TAG:
6142 return Context.getVaListTagDecl();
6143
Richard Smithf19e1272015-03-07 00:04:49 +00006144 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6145 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006146 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006147 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006148}
6149
Richard Smithcd45dbc2014-04-19 03:48:30 +00006150Decl *ASTReader::GetExistingDecl(DeclID ID) {
6151 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006152 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6153 if (D) {
6154 // Track that we have merged the declaration with ID \p ID into the
6155 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006156 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006157 if (Merged.empty())
6158 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006159 }
Richard Smithfe620d22015-03-05 23:24:12 +00006160 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006161 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006162
Guy Benyei11169dd2012-12-18 14:30:41 +00006163 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6164
6165 if (Index >= DeclsLoaded.size()) {
6166 assert(0 && "declaration ID out-of-range for AST file");
6167 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006168 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006169 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006170
6171 return DeclsLoaded[Index];
6172}
6173
6174Decl *ASTReader::GetDecl(DeclID ID) {
6175 if (ID < NUM_PREDEF_DECL_IDS)
6176 return GetExistingDecl(ID);
6177
6178 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6179
6180 if (Index >= DeclsLoaded.size()) {
6181 assert(0 && "declaration ID out-of-range for AST file");
6182 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006183 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006184 }
6185
Guy Benyei11169dd2012-12-18 14:30:41 +00006186 if (!DeclsLoaded[Index]) {
6187 ReadDeclRecord(ID);
6188 if (DeserializationListener)
6189 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6190 }
6191
6192 return DeclsLoaded[Index];
6193}
6194
6195DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6196 DeclID GlobalID) {
6197 if (GlobalID < NUM_PREDEF_DECL_IDS)
6198 return GlobalID;
6199
6200 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6201 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6202 ModuleFile *Owner = I->second;
6203
6204 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6205 = M.GlobalToLocalDeclIDs.find(Owner);
6206 if (Pos == M.GlobalToLocalDeclIDs.end())
6207 return 0;
6208
6209 return GlobalID - Owner->BaseDeclID + Pos->second;
6210}
6211
6212serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6213 const RecordData &Record,
6214 unsigned &Idx) {
6215 if (Idx >= Record.size()) {
6216 Error("Corrupted AST file");
6217 return 0;
6218 }
6219
6220 return getGlobalDeclID(F, Record[Idx++]);
6221}
6222
6223/// \brief Resolve the offset of a statement into a statement.
6224///
6225/// This operation will read a new statement from the external
6226/// source each time it is called, and is meant to be used via a
6227/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6228Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6229 // Switch case IDs are per Decl.
6230 ClearSwitchCaseIDs();
6231
6232 // Offset here is a global offset across the entire chain.
6233 RecordLocation Loc = getLocalBitOffset(Offset);
6234 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6235 return ReadStmtFromStream(*Loc.F);
6236}
6237
Richard Smith3cb15722015-08-05 22:41:45 +00006238void ASTReader::FindExternalLexicalDecls(
6239 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6240 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006241 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6242
Richard Smith9ccdd932015-08-06 22:14:12 +00006243 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006244 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6245 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6246 auto K = (Decl::Kind)+LexicalDecls[I];
6247 if (!IsKindWeWant(K))
6248 continue;
6249
6250 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6251
6252 // Don't add predefined declarations to the lexical context more
6253 // than once.
6254 if (ID < NUM_PREDEF_DECL_IDS) {
6255 if (PredefsVisited[ID])
6256 continue;
6257
6258 PredefsVisited[ID] = true;
6259 }
6260
6261 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006262 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006263 if (!DC->isDeclInLexicalTraversal(D))
6264 Decls.push_back(D);
6265 }
6266 }
6267 };
6268
6269 if (isa<TranslationUnitDecl>(DC)) {
6270 for (auto Lexical : TULexicalDecls)
6271 Visit(Lexical.first, Lexical.second);
6272 } else {
6273 auto I = LexicalDecls.find(DC);
6274 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006275 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006276 }
6277
Guy Benyei11169dd2012-12-18 14:30:41 +00006278 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006279}
6280
6281namespace {
6282
6283class DeclIDComp {
6284 ASTReader &Reader;
6285 ModuleFile &Mod;
6286
6287public:
6288 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6289
6290 bool operator()(LocalDeclID L, LocalDeclID R) const {
6291 SourceLocation LHS = getLocation(L);
6292 SourceLocation RHS = getLocation(R);
6293 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6294 }
6295
6296 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6297 SourceLocation RHS = getLocation(R);
6298 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6299 }
6300
6301 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6302 SourceLocation LHS = getLocation(L);
6303 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6304 }
6305
6306 SourceLocation getLocation(LocalDeclID ID) const {
6307 return Reader.getSourceManager().getFileLoc(
6308 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6309 }
6310};
6311
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006312}
Guy Benyei11169dd2012-12-18 14:30:41 +00006313
6314void ASTReader::FindFileRegionDecls(FileID File,
6315 unsigned Offset, unsigned Length,
6316 SmallVectorImpl<Decl *> &Decls) {
6317 SourceManager &SM = getSourceManager();
6318
6319 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6320 if (I == FileDeclIDs.end())
6321 return;
6322
6323 FileDeclsInfo &DInfo = I->second;
6324 if (DInfo.Decls.empty())
6325 return;
6326
6327 SourceLocation
6328 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6329 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6330
6331 DeclIDComp DIDComp(*this, *DInfo.Mod);
6332 ArrayRef<serialization::LocalDeclID>::iterator
6333 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6334 BeginLoc, DIDComp);
6335 if (BeginIt != DInfo.Decls.begin())
6336 --BeginIt;
6337
6338 // If we are pointing at a top-level decl inside an objc container, we need
6339 // to backtrack until we find it otherwise we will fail to report that the
6340 // region overlaps with an objc container.
6341 while (BeginIt != DInfo.Decls.begin() &&
6342 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6343 ->isTopLevelDeclInObjCContainer())
6344 --BeginIt;
6345
6346 ArrayRef<serialization::LocalDeclID>::iterator
6347 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6348 EndLoc, DIDComp);
6349 if (EndIt != DInfo.Decls.end())
6350 ++EndIt;
6351
6352 for (ArrayRef<serialization::LocalDeclID>::iterator
6353 DIt = BeginIt; DIt != EndIt; ++DIt)
6354 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6355}
6356
Richard Smith3b637412015-07-14 18:42:41 +00006357/// \brief Retrieve the "definitive" module file for the definition of the
6358/// given declaration context, if there is one.
6359///
6360/// The "definitive" module file is the only place where we need to look to
6361/// find information about the declarations within the given declaration
6362/// context. For example, C++ and Objective-C classes, C structs/unions, and
6363/// Objective-C protocols, categories, and extensions are all defined in a
6364/// single place in the source code, so they have definitive module files
6365/// associated with them. C++ namespaces, on the other hand, can have
6366/// definitions in multiple different module files.
6367///
6368/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6369/// NDEBUG checking.
6370static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6371 ASTReader &Reader) {
6372 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6373 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6374
6375 return nullptr;
6376}
6377
Guy Benyei11169dd2012-12-18 14:30:41 +00006378namespace {
6379 /// \brief ModuleFile visitor used to perform name lookup into a
6380 /// declaration context.
6381 class DeclContextNameLookupVisitor {
6382 ASTReader &Reader;
Richard Smithf13c68d2015-08-06 21:05:21 +00006383 const DeclContext *Context;
Guy Benyei11169dd2012-12-18 14:30:41 +00006384 DeclarationName Name;
Richard Smith3b637412015-07-14 18:42:41 +00006385 ASTDeclContextNameLookupTrait::DeclNameKey NameKey;
6386 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00006387 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006388 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006389
6390 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006391 DeclContextNameLookupVisitor(ASTReader &Reader,
Richard Smithf13c68d2015-08-06 21:05:21 +00006392 const DeclContext *Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00006393 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006394 SmallVectorImpl<NamedDecl *> &Decls,
6395 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
Richard Smithf13c68d2015-08-06 21:05:21 +00006396 : Reader(Reader), Context(Context), Name(Name),
Richard Smith3b637412015-07-14 18:42:41 +00006397 NameKey(ASTDeclContextNameLookupTrait::GetInternalKey(Name)),
6398 NameHash(ASTDeclContextNameLookupTrait::ComputeHash(NameKey)),
6399 Decls(Decls), DeclSet(DeclSet) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006400
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006401 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006402 // Check whether we have any visible declaration information for
6403 // this context in this module.
Richard Smithf13c68d2015-08-06 21:05:21 +00006404 auto Info = M.DeclContextInfos.find(Context);
6405 if (Info == M.DeclContextInfos.end() || !Info->second.NameLookupTableData)
Guy Benyei11169dd2012-12-18 14:30:41 +00006406 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006407
Guy Benyei11169dd2012-12-18 14:30:41 +00006408 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006409 ASTDeclContextNameLookupTable *LookupTable =
Richard Smithf13c68d2015-08-06 21:05:21 +00006410 Info->second.NameLookupTableData;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006411 ASTDeclContextNameLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00006412 LookupTable->find_hashed(NameKey, NameHash);
Guy Benyei11169dd2012-12-18 14:30:41 +00006413 if (Pos == LookupTable->end())
6414 return false;
6415
6416 bool FoundAnything = false;
6417 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6418 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006419 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006420 if (!ND)
6421 continue;
6422
Richard Smithbdf2d932015-07-30 03:37:16 +00006423 if (ND->getDeclName() != Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006424 // A name might be null because the decl's redeclarable part is
6425 // currently read before reading its name. The lookup is triggered by
6426 // building that decl (likely indirectly), and so it is later in the
6427 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006428 // FIXME: This should not happen; deserializing declarations should
6429 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006430 continue;
6431 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006432
Guy Benyei11169dd2012-12-18 14:30:41 +00006433 // Record this declaration.
6434 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006435 if (DeclSet.insert(ND).second)
6436 Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006437 }
6438
6439 return FoundAnything;
6440 }
6441 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006442}
Guy Benyei11169dd2012-12-18 14:30:41 +00006443
Richard Smith9ce12e32013-02-07 03:30:24 +00006444bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006445ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6446 DeclarationName Name) {
6447 assert(DC->hasExternalVisibleStorage() &&
6448 "DeclContext has no visible decls in storage");
6449 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006450 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006451
Richard Smith8c913ec2014-08-14 02:21:01 +00006452 Deserializing LookupResults(this);
6453
Guy Benyei11169dd2012-12-18 14:30:41 +00006454 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006455 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006456
Richard Smithf13c68d2015-08-06 21:05:21 +00006457 DeclContextNameLookupVisitor Visitor(*this, DC, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006458
Richard Smithf13c68d2015-08-06 21:05:21 +00006459 // If we can definitively determine which module file to look into,
6460 // only look there. Otherwise, look in all module files.
6461 if (ModuleFile *Definitive = getDefinitiveModuleFileFor(DC, *this))
6462 Visitor(*Definitive);
6463 else
6464 ModuleMgr.visit(Visitor);
Richard Smithcd45dbc2014-04-19 03:48:30 +00006465
Guy Benyei11169dd2012-12-18 14:30:41 +00006466 ++NumVisibleDeclContextsRead;
6467 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006468 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006469}
6470
6471namespace {
6472 /// \brief ModuleFile visitor used to retrieve all visible names in a
6473 /// declaration context.
6474 class DeclContextAllNamesVisitor {
6475 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006476 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006477 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006478 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006479 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006480
6481 public:
6482 DeclContextAllNamesVisitor(ASTReader &Reader,
6483 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006484 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006485 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006486
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006487 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006488 // Check whether we have any visible declaration information for
6489 // this context in this module.
6490 ModuleFile::DeclContextInfosMap::iterator Info;
6491 bool FoundInfo = false;
Richard Smithbdf2d932015-07-30 03:37:16 +00006492 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
6493 Info = M.DeclContextInfos.find(Contexts[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006494 if (Info != M.DeclContextInfos.end() &&
6495 Info->second.NameLookupTableData) {
6496 FoundInfo = true;
6497 break;
6498 }
6499 }
6500
6501 if (!FoundInfo)
6502 return false;
6503
Richard Smith52e3fba2014-03-11 07:17:35 +00006504 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006505 Info->second.NameLookupTableData;
6506 bool FoundAnything = false;
6507 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006508 I = LookupTable->data_begin(), E = LookupTable->data_end();
6509 I != E;
6510 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006511 ASTDeclContextNameLookupTrait::data_type Data = *I;
6512 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006513 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006514 if (!ND)
6515 continue;
6516
6517 // Record this declaration.
6518 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006519 if (DeclSet.insert(ND).second)
6520 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006521 }
6522 }
6523
Richard Smithbdf2d932015-07-30 03:37:16 +00006524 return FoundAnything && !VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006525 }
6526 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006527}
Guy Benyei11169dd2012-12-18 14:30:41 +00006528
6529void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6530 if (!DC->hasExternalVisibleStorage())
6531 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006532 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006533
6534 // Compute the declaration contexts we need to look into. Multiple such
6535 // declaration contexts occur when two declaration contexts from disjoint
6536 // modules get merged, e.g., when two namespaces with the same name are
6537 // independently defined in separate modules.
6538 SmallVector<const DeclContext *, 2> Contexts;
6539 Contexts.push_back(DC);
6540
6541 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006542 KeyDeclsMap::iterator Key =
6543 KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6544 if (Key != KeyDecls.end()) {
6545 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6546 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006547 }
6548 }
6549
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006550 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6551 /*VisitAll=*/DC->isFileContext());
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006552 ModuleMgr.visit(Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006553 ++NumVisibleDeclContextsRead;
6554
Craig Topper79be4cd2013-07-05 04:33:53 +00006555 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006556 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6557 }
6558 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6559}
6560
6561/// \brief Under non-PCH compilation the consumer receives the objc methods
6562/// before receiving the implementation, and codegen depends on this.
6563/// We simulate this by deserializing and passing to consumer the methods of the
6564/// implementation before passing the deserialized implementation decl.
6565static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6566 ASTConsumer *Consumer) {
6567 assert(ImplD && Consumer);
6568
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006569 for (auto *I : ImplD->methods())
6570 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006571
6572 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6573}
6574
6575void ASTReader::PassInterestingDeclsToConsumer() {
6576 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006577
6578 if (PassingDeclsToConsumer)
6579 return;
6580
6581 // Guard variable to avoid recursively redoing the process of passing
6582 // decls to consumer.
6583 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6584 true);
6585
Richard Smith9e2341d2015-03-23 03:25:59 +00006586 // Ensure that we've loaded all potentially-interesting declarations
6587 // that need to be eagerly loaded.
6588 for (auto ID : EagerlyDeserializedDecls)
6589 GetDecl(ID);
6590 EagerlyDeserializedDecls.clear();
6591
Guy Benyei11169dd2012-12-18 14:30:41 +00006592 while (!InterestingDecls.empty()) {
6593 Decl *D = InterestingDecls.front();
6594 InterestingDecls.pop_front();
6595
6596 PassInterestingDeclToConsumer(D);
6597 }
6598}
6599
6600void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6601 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6602 PassObjCImplDeclToConsumer(ImplD, Consumer);
6603 else
6604 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6605}
6606
6607void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6608 this->Consumer = Consumer;
6609
Richard Smith9e2341d2015-03-23 03:25:59 +00006610 if (Consumer)
6611 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006612
6613 if (DeserializationListener)
6614 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006615}
6616
6617void ASTReader::PrintStats() {
6618 std::fprintf(stderr, "*** AST File Statistics:\n");
6619
6620 unsigned NumTypesLoaded
6621 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6622 QualType());
6623 unsigned NumDeclsLoaded
6624 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006625 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006626 unsigned NumIdentifiersLoaded
6627 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6628 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006629 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006630 unsigned NumMacrosLoaded
6631 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6632 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006633 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006634 unsigned NumSelectorsLoaded
6635 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6636 SelectorsLoaded.end(),
6637 Selector());
6638
6639 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6640 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6641 NumSLocEntriesRead, TotalNumSLocEntries,
6642 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6643 if (!TypesLoaded.empty())
6644 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6645 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6646 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6647 if (!DeclsLoaded.empty())
6648 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6649 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6650 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6651 if (!IdentifiersLoaded.empty())
6652 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6653 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6654 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6655 if (!MacrosLoaded.empty())
6656 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6657 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6658 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6659 if (!SelectorsLoaded.empty())
6660 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6661 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6662 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6663 if (TotalNumStatements)
6664 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6665 NumStatementsRead, TotalNumStatements,
6666 ((float)NumStatementsRead/TotalNumStatements * 100));
6667 if (TotalNumMacros)
6668 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6669 NumMacrosRead, TotalNumMacros,
6670 ((float)NumMacrosRead/TotalNumMacros * 100));
6671 if (TotalLexicalDeclContexts)
6672 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6673 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6674 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6675 * 100));
6676 if (TotalVisibleDeclContexts)
6677 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6678 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6679 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6680 * 100));
6681 if (TotalNumMethodPoolEntries) {
6682 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6683 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6684 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6685 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006686 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006687 if (NumMethodPoolLookups) {
6688 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6689 NumMethodPoolHits, NumMethodPoolLookups,
6690 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6691 }
6692 if (NumMethodPoolTableLookups) {
6693 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6694 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6695 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6696 * 100.0));
6697 }
6698
Douglas Gregor00a50f72013-01-25 00:38:33 +00006699 if (NumIdentifierLookupHits) {
6700 std::fprintf(stderr,
6701 " %u / %u identifier table lookups succeeded (%f%%)\n",
6702 NumIdentifierLookupHits, NumIdentifierLookups,
6703 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6704 }
6705
Douglas Gregore060e572013-01-25 01:03:03 +00006706 if (GlobalIndex) {
6707 std::fprintf(stderr, "\n");
6708 GlobalIndex->printStats();
6709 }
6710
Guy Benyei11169dd2012-12-18 14:30:41 +00006711 std::fprintf(stderr, "\n");
6712 dump();
6713 std::fprintf(stderr, "\n");
6714}
6715
6716template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6717static void
6718dumpModuleIDMap(StringRef Name,
6719 const ContinuousRangeMap<Key, ModuleFile *,
6720 InitialCapacity> &Map) {
6721 if (Map.begin() == Map.end())
6722 return;
6723
6724 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6725 llvm::errs() << Name << ":\n";
6726 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6727 I != IEnd; ++I) {
6728 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6729 << "\n";
6730 }
6731}
6732
6733void ASTReader::dump() {
6734 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6735 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6736 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6737 dumpModuleIDMap("Global type map", GlobalTypeMap);
6738 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6739 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6740 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6741 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6742 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6743 dumpModuleIDMap("Global preprocessed entity map",
6744 GlobalPreprocessedEntityMap);
6745
6746 llvm::errs() << "\n*** PCH/Modules Loaded:";
6747 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6748 MEnd = ModuleMgr.end();
6749 M != MEnd; ++M)
6750 (*M)->dump();
6751}
6752
6753/// Return the amount of memory used by memory buffers, breaking down
6754/// by heap-backed versus mmap'ed memory.
6755void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6756 for (ModuleConstIterator I = ModuleMgr.begin(),
6757 E = ModuleMgr.end(); I != E; ++I) {
6758 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6759 size_t bytes = buf->getBufferSize();
6760 switch (buf->getBufferKind()) {
6761 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6762 sizes.malloc_bytes += bytes;
6763 break;
6764 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6765 sizes.mmap_bytes += bytes;
6766 break;
6767 }
6768 }
6769 }
6770}
6771
6772void ASTReader::InitializeSema(Sema &S) {
6773 SemaObj = &S;
6774 S.addExternalSource(this);
6775
6776 // Makes sure any declarations that were deserialized "too early"
6777 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006778 for (uint64_t ID : PreloadedDeclIDs) {
6779 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6780 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006781 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006782 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006783
Richard Smith3d8e97e2013-10-18 06:54:39 +00006784 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006785 if (!FPPragmaOptions.empty()) {
6786 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6787 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6788 }
6789
Richard Smith3d8e97e2013-10-18 06:54:39 +00006790 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006791 if (!OpenCLExtensions.empty()) {
6792 unsigned I = 0;
6793#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6794#include "clang/Basic/OpenCLExtensions.def"
6795
6796 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6797 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006798
6799 UpdateSema();
6800}
6801
6802void ASTReader::UpdateSema() {
6803 assert(SemaObj && "no Sema to update");
6804
6805 // Load the offsets of the declarations that Sema references.
6806 // They will be lazily deserialized when needed.
6807 if (!SemaDeclRefs.empty()) {
6808 assert(SemaDeclRefs.size() % 2 == 0);
6809 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6810 if (!SemaObj->StdNamespace)
6811 SemaObj->StdNamespace = SemaDeclRefs[I];
6812 if (!SemaObj->StdBadAlloc)
6813 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6814 }
6815 SemaDeclRefs.clear();
6816 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006817
6818 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6819 // encountered the pragma in the source.
6820 if(OptimizeOffPragmaLocation.isValid())
6821 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006822}
6823
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006824IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006825 // Note that we are loading an identifier.
6826 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006827
Douglas Gregor7211ac12013-01-25 23:32:03 +00006828 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006829 NumIdentifierLookups,
6830 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006831
6832 // We don't need to do identifier table lookups in C++ modules (we preload
6833 // all interesting declarations, and don't need to use the scope for name
6834 // lookups). Perform the lookup in PCH files, though, since we don't build
6835 // a complete initial identifier table if we're carrying on from a PCH.
6836 if (Context.getLangOpts().CPlusPlus) {
6837 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006838 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006839 break;
6840 } else {
6841 // If there is a global index, look there first to determine which modules
6842 // provably do not have any results for this identifier.
6843 GlobalModuleIndex::HitSet Hits;
6844 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6845 if (!loadGlobalIndex()) {
6846 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6847 HitsPtr = &Hits;
6848 }
6849 }
6850
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006851 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006852 }
6853
Guy Benyei11169dd2012-12-18 14:30:41 +00006854 IdentifierInfo *II = Visitor.getIdentifierInfo();
6855 markIdentifierUpToDate(II);
6856 return II;
6857}
6858
6859namespace clang {
6860 /// \brief An identifier-lookup iterator that enumerates all of the
6861 /// identifiers stored within a set of AST files.
6862 class ASTIdentifierIterator : public IdentifierIterator {
6863 /// \brief The AST reader whose identifiers are being enumerated.
6864 const ASTReader &Reader;
6865
6866 /// \brief The current index into the chain of AST files stored in
6867 /// the AST reader.
6868 unsigned Index;
6869
6870 /// \brief The current position within the identifier lookup table
6871 /// of the current AST file.
6872 ASTIdentifierLookupTable::key_iterator Current;
6873
6874 /// \brief The end position within the identifier lookup table of
6875 /// the current AST file.
6876 ASTIdentifierLookupTable::key_iterator End;
6877
6878 public:
6879 explicit ASTIdentifierIterator(const ASTReader &Reader);
6880
Craig Topper3e89dfe2014-03-13 02:13:41 +00006881 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006882 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006883}
Guy Benyei11169dd2012-12-18 14:30:41 +00006884
6885ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6886 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6887 ASTIdentifierLookupTable *IdTable
6888 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6889 Current = IdTable->key_begin();
6890 End = IdTable->key_end();
6891}
6892
6893StringRef ASTIdentifierIterator::Next() {
6894 while (Current == End) {
6895 // If we have exhausted all of our AST files, we're done.
6896 if (Index == 0)
6897 return StringRef();
6898
6899 --Index;
6900 ASTIdentifierLookupTable *IdTable
6901 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6902 IdentifierLookupTable;
6903 Current = IdTable->key_begin();
6904 End = IdTable->key_end();
6905 }
6906
6907 // We have any identifiers remaining in the current AST file; return
6908 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006909 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006910 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006911 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006912}
6913
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006914IdentifierIterator *ASTReader::getIdentifiers() {
6915 if (!loadGlobalIndex())
6916 return GlobalIndex->createIdentifierIterator();
6917
Guy Benyei11169dd2012-12-18 14:30:41 +00006918 return new ASTIdentifierIterator(*this);
6919}
6920
6921namespace clang { namespace serialization {
6922 class ReadMethodPoolVisitor {
6923 ASTReader &Reader;
6924 Selector Sel;
6925 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006926 unsigned InstanceBits;
6927 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006928 bool InstanceHasMoreThanOneDecl;
6929 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006930 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6931 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006932
6933 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006934 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006935 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006936 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006937 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6938 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006939
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006940 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006941 if (!M.SelectorLookupTable)
6942 return false;
6943
6944 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00006945 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00006946 return true;
6947
Richard Smithbdf2d932015-07-30 03:37:16 +00006948 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006949 ASTSelectorLookupTable *PoolTable
6950 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00006951 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00006952 if (Pos == PoolTable->end())
6953 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006954
Richard Smithbdf2d932015-07-30 03:37:16 +00006955 ++Reader.NumMethodPoolTableHits;
6956 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006957 // FIXME: Not quite happy with the statistics here. We probably should
6958 // disable this tracking when called via LoadSelector.
6959 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00006960 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006961 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00006962 if (Reader.DeserializationListener)
6963 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006964
Richard Smithbdf2d932015-07-30 03:37:16 +00006965 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6966 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6967 InstanceBits = Data.InstanceBits;
6968 FactoryBits = Data.FactoryBits;
6969 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6970 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006971 return true;
6972 }
6973
6974 /// \brief Retrieve the instance methods found by this visitor.
6975 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6976 return InstanceMethods;
6977 }
6978
6979 /// \brief Retrieve the instance methods found by this visitor.
6980 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6981 return FactoryMethods;
6982 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006983
6984 unsigned getInstanceBits() const { return InstanceBits; }
6985 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006986 bool instanceHasMoreThanOneDecl() const {
6987 return InstanceHasMoreThanOneDecl;
6988 }
6989 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006990 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006991} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00006992
6993/// \brief Add the given set of methods to the method list.
6994static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6995 ObjCMethodList &List) {
6996 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6997 S.addMethodToGlobalList(&List, Methods[I]);
6998 }
6999}
7000
7001void ASTReader::ReadMethodPool(Selector Sel) {
7002 // Get the selector generation and update it to the current generation.
7003 unsigned &Generation = SelectorGeneration[Sel];
7004 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007005 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007006
7007 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007008 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007009 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007010 ModuleMgr.visit(Visitor);
7011
Guy Benyei11169dd2012-12-18 14:30:41 +00007012 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007013 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007014 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007015
7016 ++NumMethodPoolHits;
7017
Guy Benyei11169dd2012-12-18 14:30:41 +00007018 if (!getSema())
7019 return;
7020
7021 Sema &S = *getSema();
7022 Sema::GlobalMethodPool::iterator Pos
7023 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007024
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007025 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007026 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007027 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007028 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007029
7030 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7031 // when building a module we keep every method individually and may need to
7032 // update hasMoreThanOneDecl as we add the methods.
7033 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7034 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007035}
7036
7037void ASTReader::ReadKnownNamespaces(
7038 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7039 Namespaces.clear();
7040
7041 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7042 if (NamespaceDecl *Namespace
7043 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7044 Namespaces.push_back(Namespace);
7045 }
7046}
7047
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007048void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007049 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007050 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7051 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007052 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007053 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007054 Undefined.insert(std::make_pair(D, Loc));
7055 }
7056}
Nick Lewycky8334af82013-01-26 00:35:08 +00007057
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007058void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7059 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7060 Exprs) {
7061 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7062 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7063 uint64_t Count = DelayedDeleteExprs[Idx++];
7064 for (uint64_t C = 0; C < Count; ++C) {
7065 SourceLocation DeleteLoc =
7066 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7067 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7068 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7069 }
7070 }
7071}
7072
Guy Benyei11169dd2012-12-18 14:30:41 +00007073void ASTReader::ReadTentativeDefinitions(
7074 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7075 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7076 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7077 if (Var)
7078 TentativeDefs.push_back(Var);
7079 }
7080 TentativeDefinitions.clear();
7081}
7082
7083void ASTReader::ReadUnusedFileScopedDecls(
7084 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7085 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7086 DeclaratorDecl *D
7087 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7088 if (D)
7089 Decls.push_back(D);
7090 }
7091 UnusedFileScopedDecls.clear();
7092}
7093
7094void ASTReader::ReadDelegatingConstructors(
7095 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7096 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7097 CXXConstructorDecl *D
7098 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7099 if (D)
7100 Decls.push_back(D);
7101 }
7102 DelegatingCtorDecls.clear();
7103}
7104
7105void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7106 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7107 TypedefNameDecl *D
7108 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7109 if (D)
7110 Decls.push_back(D);
7111 }
7112 ExtVectorDecls.clear();
7113}
7114
Nico Weber72889432014-09-06 01:25:55 +00007115void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7116 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7117 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7118 ++I) {
7119 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7120 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7121 if (D)
7122 Decls.insert(D);
7123 }
7124 UnusedLocalTypedefNameCandidates.clear();
7125}
7126
Guy Benyei11169dd2012-12-18 14:30:41 +00007127void ASTReader::ReadReferencedSelectors(
7128 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7129 if (ReferencedSelectorsData.empty())
7130 return;
7131
7132 // If there are @selector references added them to its pool. This is for
7133 // implementation of -Wselector.
7134 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7135 unsigned I = 0;
7136 while (I < DataSize) {
7137 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7138 SourceLocation SelLoc
7139 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7140 Sels.push_back(std::make_pair(Sel, SelLoc));
7141 }
7142 ReferencedSelectorsData.clear();
7143}
7144
7145void ASTReader::ReadWeakUndeclaredIdentifiers(
7146 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7147 if (WeakUndeclaredIdentifiers.empty())
7148 return;
7149
7150 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7151 IdentifierInfo *WeakId
7152 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7153 IdentifierInfo *AliasId
7154 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7155 SourceLocation Loc
7156 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7157 bool Used = WeakUndeclaredIdentifiers[I++];
7158 WeakInfo WI(AliasId, Loc);
7159 WI.setUsed(Used);
7160 WeakIDs.push_back(std::make_pair(WeakId, WI));
7161 }
7162 WeakUndeclaredIdentifiers.clear();
7163}
7164
7165void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7166 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7167 ExternalVTableUse VT;
7168 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7169 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7170 VT.DefinitionRequired = VTableUses[Idx++];
7171 VTables.push_back(VT);
7172 }
7173
7174 VTableUses.clear();
7175}
7176
7177void ASTReader::ReadPendingInstantiations(
7178 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7179 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7180 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7181 SourceLocation Loc
7182 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7183
7184 Pending.push_back(std::make_pair(D, Loc));
7185 }
7186 PendingInstantiations.clear();
7187}
7188
Richard Smithe40f2ba2013-08-07 21:41:30 +00007189void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007190 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007191 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7192 /* In loop */) {
7193 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7194
7195 LateParsedTemplate *LT = new LateParsedTemplate;
7196 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7197
7198 ModuleFile *F = getOwningModuleFile(LT->D);
7199 assert(F && "No module");
7200
7201 unsigned TokN = LateParsedTemplates[Idx++];
7202 LT->Toks.reserve(TokN);
7203 for (unsigned T = 0; T < TokN; ++T)
7204 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7205
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007206 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007207 }
7208
7209 LateParsedTemplates.clear();
7210}
7211
Guy Benyei11169dd2012-12-18 14:30:41 +00007212void ASTReader::LoadSelector(Selector Sel) {
7213 // It would be complicated to avoid reading the methods anyway. So don't.
7214 ReadMethodPool(Sel);
7215}
7216
7217void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7218 assert(ID && "Non-zero identifier ID required");
7219 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7220 IdentifiersLoaded[ID - 1] = II;
7221 if (DeserializationListener)
7222 DeserializationListener->IdentifierRead(ID, II);
7223}
7224
7225/// \brief Set the globally-visible declarations associated with the given
7226/// identifier.
7227///
7228/// If the AST reader is currently in a state where the given declaration IDs
7229/// cannot safely be resolved, they are queued until it is safe to resolve
7230/// them.
7231///
7232/// \param II an IdentifierInfo that refers to one or more globally-visible
7233/// declarations.
7234///
7235/// \param DeclIDs the set of declaration IDs with the name @p II that are
7236/// visible at global scope.
7237///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007238/// \param Decls if non-null, this vector will be populated with the set of
7239/// deserialized declarations. These declarations will not be pushed into
7240/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007241void
7242ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7243 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007244 SmallVectorImpl<Decl *> *Decls) {
7245 if (NumCurrentElementsDeserializing && !Decls) {
7246 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007247 return;
7248 }
7249
7250 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007251 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007252 // Queue this declaration so that it will be added to the
7253 // translation unit scope and identifier's declaration chain
7254 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007255 PreloadedDeclIDs.push_back(DeclIDs[I]);
7256 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007257 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007258
7259 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7260
7261 // If we're simply supposed to record the declarations, do so now.
7262 if (Decls) {
7263 Decls->push_back(D);
7264 continue;
7265 }
7266
7267 // Introduce this declaration into the translation-unit scope
7268 // and add it to the declaration chain for this identifier, so
7269 // that (unqualified) name lookup will find it.
7270 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007271 }
7272}
7273
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007274IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007275 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007276 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007277
7278 if (IdentifiersLoaded.empty()) {
7279 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007280 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007281 }
7282
7283 ID -= 1;
7284 if (!IdentifiersLoaded[ID]) {
7285 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7286 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7287 ModuleFile *M = I->second;
7288 unsigned Index = ID - M->BaseIdentifierID;
7289 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7290
7291 // All of the strings in the AST file are preceded by a 16-bit length.
7292 // Extract that 16-bit length to avoid having to execute strlen().
7293 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7294 // unsigned integers. This is important to avoid integer overflow when
7295 // we cast them to 'unsigned'.
7296 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7297 unsigned StrLen = (((unsigned) StrLenPtr[0])
7298 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007299 IdentifiersLoaded[ID]
7300 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007301 if (DeserializationListener)
7302 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7303 }
7304
7305 return IdentifiersLoaded[ID];
7306}
7307
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007308IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7309 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007310}
7311
7312IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7313 if (LocalID < NUM_PREDEF_IDENT_IDS)
7314 return LocalID;
7315
7316 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7317 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7318 assert(I != M.IdentifierRemap.end()
7319 && "Invalid index into identifier index remap");
7320
7321 return LocalID + I->second;
7322}
7323
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007324MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007325 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007326 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007327
7328 if (MacrosLoaded.empty()) {
7329 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007330 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007331 }
7332
7333 ID -= NUM_PREDEF_MACRO_IDS;
7334 if (!MacrosLoaded[ID]) {
7335 GlobalMacroMapType::iterator I
7336 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7337 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7338 ModuleFile *M = I->second;
7339 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007340 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7341
7342 if (DeserializationListener)
7343 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7344 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007345 }
7346
7347 return MacrosLoaded[ID];
7348}
7349
7350MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7351 if (LocalID < NUM_PREDEF_MACRO_IDS)
7352 return LocalID;
7353
7354 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7355 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7356 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7357
7358 return LocalID + I->second;
7359}
7360
7361serialization::SubmoduleID
7362ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7363 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7364 return LocalID;
7365
7366 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7367 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7368 assert(I != M.SubmoduleRemap.end()
7369 && "Invalid index into submodule index remap");
7370
7371 return LocalID + I->second;
7372}
7373
7374Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7375 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7376 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007377 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007378 }
7379
7380 if (GlobalID > SubmodulesLoaded.size()) {
7381 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007382 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007383 }
7384
7385 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7386}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007387
7388Module *ASTReader::getModule(unsigned ID) {
7389 return getSubmodule(ID);
7390}
7391
Adrian Prantl15bcf702015-06-30 17:39:43 +00007392ExternalASTSource::ASTSourceDescriptor
7393ASTReader::getSourceDescriptor(const Module &M) {
7394 StringRef Dir, Filename;
7395 if (M.Directory)
7396 Dir = M.Directory->getName();
7397 if (auto *File = M.getASTFile())
7398 Filename = File->getName();
7399 return ASTReader::ASTSourceDescriptor{
7400 M.getFullModuleName(), Dir, Filename,
7401 M.Signature
7402 };
7403}
7404
7405llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7406ASTReader::getSourceDescriptor(unsigned ID) {
7407 if (const Module *M = getSubmodule(ID))
7408 return getSourceDescriptor(*M);
7409
7410 // If there is only a single PCH, return it instead.
7411 // Chained PCH are not suported.
7412 if (ModuleMgr.size() == 1) {
7413 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7414 return ASTReader::ASTSourceDescriptor{
7415 MF.OriginalSourceFileName, MF.OriginalDir,
7416 MF.FileName,
7417 MF.Signature
7418 };
7419 }
7420 return None;
7421}
7422
Guy Benyei11169dd2012-12-18 14:30:41 +00007423Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7424 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7425}
7426
7427Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7428 if (ID == 0)
7429 return Selector();
7430
7431 if (ID > SelectorsLoaded.size()) {
7432 Error("selector ID out of range in AST file");
7433 return Selector();
7434 }
7435
Craig Toppera13603a2014-05-22 05:54:18 +00007436 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007437 // Load this selector from the selector table.
7438 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7439 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7440 ModuleFile &M = *I->second;
7441 ASTSelectorLookupTrait Trait(*this, M);
7442 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7443 SelectorsLoaded[ID - 1] =
7444 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7445 if (DeserializationListener)
7446 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7447 }
7448
7449 return SelectorsLoaded[ID - 1];
7450}
7451
7452Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7453 return DecodeSelector(ID);
7454}
7455
7456uint32_t ASTReader::GetNumExternalSelectors() {
7457 // ID 0 (the null selector) is considered an external selector.
7458 return getTotalNumSelectors() + 1;
7459}
7460
7461serialization::SelectorID
7462ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7463 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7464 return LocalID;
7465
7466 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7467 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7468 assert(I != M.SelectorRemap.end()
7469 && "Invalid index into selector index remap");
7470
7471 return LocalID + I->second;
7472}
7473
7474DeclarationName
7475ASTReader::ReadDeclarationName(ModuleFile &F,
7476 const RecordData &Record, unsigned &Idx) {
7477 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7478 switch (Kind) {
7479 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007480 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007481
7482 case DeclarationName::ObjCZeroArgSelector:
7483 case DeclarationName::ObjCOneArgSelector:
7484 case DeclarationName::ObjCMultiArgSelector:
7485 return DeclarationName(ReadSelector(F, Record, Idx));
7486
7487 case DeclarationName::CXXConstructorName:
7488 return Context.DeclarationNames.getCXXConstructorName(
7489 Context.getCanonicalType(readType(F, Record, Idx)));
7490
7491 case DeclarationName::CXXDestructorName:
7492 return Context.DeclarationNames.getCXXDestructorName(
7493 Context.getCanonicalType(readType(F, Record, Idx)));
7494
7495 case DeclarationName::CXXConversionFunctionName:
7496 return Context.DeclarationNames.getCXXConversionFunctionName(
7497 Context.getCanonicalType(readType(F, Record, Idx)));
7498
7499 case DeclarationName::CXXOperatorName:
7500 return Context.DeclarationNames.getCXXOperatorName(
7501 (OverloadedOperatorKind)Record[Idx++]);
7502
7503 case DeclarationName::CXXLiteralOperatorName:
7504 return Context.DeclarationNames.getCXXLiteralOperatorName(
7505 GetIdentifierInfo(F, Record, Idx));
7506
7507 case DeclarationName::CXXUsingDirective:
7508 return DeclarationName::getUsingDirectiveName();
7509 }
7510
7511 llvm_unreachable("Invalid NameKind!");
7512}
7513
7514void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7515 DeclarationNameLoc &DNLoc,
7516 DeclarationName Name,
7517 const RecordData &Record, unsigned &Idx) {
7518 switch (Name.getNameKind()) {
7519 case DeclarationName::CXXConstructorName:
7520 case DeclarationName::CXXDestructorName:
7521 case DeclarationName::CXXConversionFunctionName:
7522 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7523 break;
7524
7525 case DeclarationName::CXXOperatorName:
7526 DNLoc.CXXOperatorName.BeginOpNameLoc
7527 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7528 DNLoc.CXXOperatorName.EndOpNameLoc
7529 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7530 break;
7531
7532 case DeclarationName::CXXLiteralOperatorName:
7533 DNLoc.CXXLiteralOperatorName.OpNameLoc
7534 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7535 break;
7536
7537 case DeclarationName::Identifier:
7538 case DeclarationName::ObjCZeroArgSelector:
7539 case DeclarationName::ObjCOneArgSelector:
7540 case DeclarationName::ObjCMultiArgSelector:
7541 case DeclarationName::CXXUsingDirective:
7542 break;
7543 }
7544}
7545
7546void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7547 DeclarationNameInfo &NameInfo,
7548 const RecordData &Record, unsigned &Idx) {
7549 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7550 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7551 DeclarationNameLoc DNLoc;
7552 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7553 NameInfo.setInfo(DNLoc);
7554}
7555
7556void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7557 const RecordData &Record, unsigned &Idx) {
7558 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7559 unsigned NumTPLists = Record[Idx++];
7560 Info.NumTemplParamLists = NumTPLists;
7561 if (NumTPLists) {
7562 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7563 for (unsigned i=0; i != NumTPLists; ++i)
7564 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7565 }
7566}
7567
7568TemplateName
7569ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7570 unsigned &Idx) {
7571 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7572 switch (Kind) {
7573 case TemplateName::Template:
7574 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7575
7576 case TemplateName::OverloadedTemplate: {
7577 unsigned size = Record[Idx++];
7578 UnresolvedSet<8> Decls;
7579 while (size--)
7580 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7581
7582 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7583 }
7584
7585 case TemplateName::QualifiedTemplate: {
7586 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7587 bool hasTemplKeyword = Record[Idx++];
7588 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7589 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7590 }
7591
7592 case TemplateName::DependentTemplate: {
7593 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7594 if (Record[Idx++]) // isIdentifier
7595 return Context.getDependentTemplateName(NNS,
7596 GetIdentifierInfo(F, Record,
7597 Idx));
7598 return Context.getDependentTemplateName(NNS,
7599 (OverloadedOperatorKind)Record[Idx++]);
7600 }
7601
7602 case TemplateName::SubstTemplateTemplateParm: {
7603 TemplateTemplateParmDecl *param
7604 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7605 if (!param) return TemplateName();
7606 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7607 return Context.getSubstTemplateTemplateParm(param, replacement);
7608 }
7609
7610 case TemplateName::SubstTemplateTemplateParmPack: {
7611 TemplateTemplateParmDecl *Param
7612 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7613 if (!Param)
7614 return TemplateName();
7615
7616 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7617 if (ArgPack.getKind() != TemplateArgument::Pack)
7618 return TemplateName();
7619
7620 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7621 }
7622 }
7623
7624 llvm_unreachable("Unhandled template name kind!");
7625}
7626
Richard Smith2bb3c342015-08-09 01:05:31 +00007627TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7628 const RecordData &Record,
7629 unsigned &Idx,
7630 bool Canonicalize) {
7631 if (Canonicalize) {
7632 // The caller wants a canonical template argument. Sometimes the AST only
7633 // wants template arguments in canonical form (particularly as the template
7634 // argument lists of template specializations) so ensure we preserve that
7635 // canonical form across serialization.
7636 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7637 return Context.getCanonicalTemplateArgument(Arg);
7638 }
7639
Guy Benyei11169dd2012-12-18 14:30:41 +00007640 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7641 switch (Kind) {
7642 case TemplateArgument::Null:
7643 return TemplateArgument();
7644 case TemplateArgument::Type:
7645 return TemplateArgument(readType(F, Record, Idx));
7646 case TemplateArgument::Declaration: {
7647 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007648 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007649 }
7650 case TemplateArgument::NullPtr:
7651 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7652 case TemplateArgument::Integral: {
7653 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7654 QualType T = readType(F, Record, Idx);
7655 return TemplateArgument(Context, Value, T);
7656 }
7657 case TemplateArgument::Template:
7658 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7659 case TemplateArgument::TemplateExpansion: {
7660 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007661 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007662 if (unsigned NumExpansions = Record[Idx++])
7663 NumTemplateExpansions = NumExpansions - 1;
7664 return TemplateArgument(Name, NumTemplateExpansions);
7665 }
7666 case TemplateArgument::Expression:
7667 return TemplateArgument(ReadExpr(F));
7668 case TemplateArgument::Pack: {
7669 unsigned NumArgs = Record[Idx++];
7670 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7671 for (unsigned I = 0; I != NumArgs; ++I)
7672 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007673 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007674 }
7675 }
7676
7677 llvm_unreachable("Unhandled template argument kind!");
7678}
7679
7680TemplateParameterList *
7681ASTReader::ReadTemplateParameterList(ModuleFile &F,
7682 const RecordData &Record, unsigned &Idx) {
7683 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7684 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7685 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7686
7687 unsigned NumParams = Record[Idx++];
7688 SmallVector<NamedDecl *, 16> Params;
7689 Params.reserve(NumParams);
7690 while (NumParams--)
7691 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7692
7693 TemplateParameterList* TemplateParams =
7694 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7695 Params.data(), Params.size(), RAngleLoc);
7696 return TemplateParams;
7697}
7698
7699void
7700ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007701ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007702 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007703 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007704 unsigned NumTemplateArgs = Record[Idx++];
7705 TemplArgs.reserve(NumTemplateArgs);
7706 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007707 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007708}
7709
7710/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007711void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007712 const RecordData &Record, unsigned &Idx) {
7713 unsigned NumDecls = Record[Idx++];
7714 Set.reserve(Context, NumDecls);
7715 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007716 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007717 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007718 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007719 }
7720}
7721
7722CXXBaseSpecifier
7723ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7724 const RecordData &Record, unsigned &Idx) {
7725 bool isVirtual = static_cast<bool>(Record[Idx++]);
7726 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7727 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7728 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7729 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7730 SourceRange Range = ReadSourceRange(F, Record, Idx);
7731 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7732 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7733 EllipsisLoc);
7734 Result.setInheritConstructors(inheritConstructors);
7735 return Result;
7736}
7737
Richard Smithc2bb8182015-03-24 06:36:48 +00007738CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007739ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7740 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007741 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007742 assert(NumInitializers && "wrote ctor initializers but have no inits");
7743 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7744 for (unsigned i = 0; i != NumInitializers; ++i) {
7745 TypeSourceInfo *TInfo = nullptr;
7746 bool IsBaseVirtual = false;
7747 FieldDecl *Member = nullptr;
7748 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007749
Richard Smithc2bb8182015-03-24 06:36:48 +00007750 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7751 switch (Type) {
7752 case CTOR_INITIALIZER_BASE:
7753 TInfo = GetTypeSourceInfo(F, Record, Idx);
7754 IsBaseVirtual = Record[Idx++];
7755 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007756
Richard Smithc2bb8182015-03-24 06:36:48 +00007757 case CTOR_INITIALIZER_DELEGATING:
7758 TInfo = GetTypeSourceInfo(F, Record, Idx);
7759 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007760
Richard Smithc2bb8182015-03-24 06:36:48 +00007761 case CTOR_INITIALIZER_MEMBER:
7762 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7763 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007764
Richard Smithc2bb8182015-03-24 06:36:48 +00007765 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7766 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7767 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007768 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007769
7770 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7771 Expr *Init = ReadExpr(F);
7772 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7773 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7774 bool IsWritten = Record[Idx++];
7775 unsigned SourceOrderOrNumArrayIndices;
7776 SmallVector<VarDecl *, 8> Indices;
7777 if (IsWritten) {
7778 SourceOrderOrNumArrayIndices = Record[Idx++];
7779 } else {
7780 SourceOrderOrNumArrayIndices = Record[Idx++];
7781 Indices.reserve(SourceOrderOrNumArrayIndices);
7782 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7783 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7784 }
7785
7786 CXXCtorInitializer *BOMInit;
7787 if (Type == CTOR_INITIALIZER_BASE) {
7788 BOMInit = new (Context)
7789 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7790 RParenLoc, MemberOrEllipsisLoc);
7791 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7792 BOMInit = new (Context)
7793 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7794 } else if (IsWritten) {
7795 if (Member)
7796 BOMInit = new (Context) CXXCtorInitializer(
7797 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7798 else
7799 BOMInit = new (Context)
7800 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7801 LParenLoc, Init, RParenLoc);
7802 } else {
7803 if (IndirectMember) {
7804 assert(Indices.empty() && "Indirect field improperly initialized");
7805 BOMInit = new (Context)
7806 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7807 LParenLoc, Init, RParenLoc);
7808 } else {
7809 BOMInit = CXXCtorInitializer::Create(
7810 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7811 Indices.data(), Indices.size());
7812 }
7813 }
7814
7815 if (IsWritten)
7816 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7817 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007818 }
7819
Richard Smithc2bb8182015-03-24 06:36:48 +00007820 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007821}
7822
7823NestedNameSpecifier *
7824ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7825 const RecordData &Record, unsigned &Idx) {
7826 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007827 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007828 for (unsigned I = 0; I != N; ++I) {
7829 NestedNameSpecifier::SpecifierKind Kind
7830 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7831 switch (Kind) {
7832 case NestedNameSpecifier::Identifier: {
7833 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7834 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7835 break;
7836 }
7837
7838 case NestedNameSpecifier::Namespace: {
7839 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7840 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7841 break;
7842 }
7843
7844 case NestedNameSpecifier::NamespaceAlias: {
7845 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7846 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7847 break;
7848 }
7849
7850 case NestedNameSpecifier::TypeSpec:
7851 case NestedNameSpecifier::TypeSpecWithTemplate: {
7852 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7853 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007854 return nullptr;
7855
Guy Benyei11169dd2012-12-18 14:30:41 +00007856 bool Template = Record[Idx++];
7857 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7858 break;
7859 }
7860
7861 case NestedNameSpecifier::Global: {
7862 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7863 // No associated value, and there can't be a prefix.
7864 break;
7865 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007866
7867 case NestedNameSpecifier::Super: {
7868 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7869 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7870 break;
7871 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007872 }
7873 Prev = NNS;
7874 }
7875 return NNS;
7876}
7877
7878NestedNameSpecifierLoc
7879ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7880 unsigned &Idx) {
7881 unsigned N = Record[Idx++];
7882 NestedNameSpecifierLocBuilder Builder;
7883 for (unsigned I = 0; I != N; ++I) {
7884 NestedNameSpecifier::SpecifierKind Kind
7885 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7886 switch (Kind) {
7887 case NestedNameSpecifier::Identifier: {
7888 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7889 SourceRange Range = ReadSourceRange(F, Record, Idx);
7890 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7891 break;
7892 }
7893
7894 case NestedNameSpecifier::Namespace: {
7895 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7896 SourceRange Range = ReadSourceRange(F, Record, Idx);
7897 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7898 break;
7899 }
7900
7901 case NestedNameSpecifier::NamespaceAlias: {
7902 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7903 SourceRange Range = ReadSourceRange(F, Record, Idx);
7904 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7905 break;
7906 }
7907
7908 case NestedNameSpecifier::TypeSpec:
7909 case NestedNameSpecifier::TypeSpecWithTemplate: {
7910 bool Template = Record[Idx++];
7911 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7912 if (!T)
7913 return NestedNameSpecifierLoc();
7914 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7915
7916 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7917 Builder.Extend(Context,
7918 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7919 T->getTypeLoc(), ColonColonLoc);
7920 break;
7921 }
7922
7923 case NestedNameSpecifier::Global: {
7924 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7925 Builder.MakeGlobal(Context, ColonColonLoc);
7926 break;
7927 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007928
7929 case NestedNameSpecifier::Super: {
7930 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7931 SourceRange Range = ReadSourceRange(F, Record, Idx);
7932 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7933 break;
7934 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007935 }
7936 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007937
Guy Benyei11169dd2012-12-18 14:30:41 +00007938 return Builder.getWithLocInContext(Context);
7939}
7940
7941SourceRange
7942ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7943 unsigned &Idx) {
7944 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7945 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7946 return SourceRange(beg, end);
7947}
7948
7949/// \brief Read an integral value
7950llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7951 unsigned BitWidth = Record[Idx++];
7952 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7953 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7954 Idx += NumWords;
7955 return Result;
7956}
7957
7958/// \brief Read a signed integral value
7959llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7960 bool isUnsigned = Record[Idx++];
7961 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7962}
7963
7964/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007965llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7966 const llvm::fltSemantics &Sem,
7967 unsigned &Idx) {
7968 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007969}
7970
7971// \brief Read a string
7972std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7973 unsigned Len = Record[Idx++];
7974 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7975 Idx += Len;
7976 return Result;
7977}
7978
Richard Smith7ed1bc92014-12-05 22:42:13 +00007979std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7980 unsigned &Idx) {
7981 std::string Filename = ReadString(Record, Idx);
7982 ResolveImportedPath(F, Filename);
7983 return Filename;
7984}
7985
Guy Benyei11169dd2012-12-18 14:30:41 +00007986VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7987 unsigned &Idx) {
7988 unsigned Major = Record[Idx++];
7989 unsigned Minor = Record[Idx++];
7990 unsigned Subminor = Record[Idx++];
7991 if (Minor == 0)
7992 return VersionTuple(Major);
7993 if (Subminor == 0)
7994 return VersionTuple(Major, Minor - 1);
7995 return VersionTuple(Major, Minor - 1, Subminor - 1);
7996}
7997
7998CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7999 const RecordData &Record,
8000 unsigned &Idx) {
8001 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8002 return CXXTemporary::Create(Context, Decl);
8003}
8004
8005DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008006 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008007}
8008
8009DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8010 return Diags.Report(Loc, DiagID);
8011}
8012
8013/// \brief Retrieve the identifier table associated with the
8014/// preprocessor.
8015IdentifierTable &ASTReader::getIdentifierTable() {
8016 return PP.getIdentifierTable();
8017}
8018
8019/// \brief Record that the given ID maps to the given switch-case
8020/// statement.
8021void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008022 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008023 "Already have a SwitchCase with this ID");
8024 (*CurrSwitchCaseStmts)[ID] = SC;
8025}
8026
8027/// \brief Retrieve the switch-case statement with the given ID.
8028SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008029 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008030 return (*CurrSwitchCaseStmts)[ID];
8031}
8032
8033void ASTReader::ClearSwitchCaseIDs() {
8034 CurrSwitchCaseStmts->clear();
8035}
8036
8037void ASTReader::ReadComments() {
8038 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008039 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008040 serialization::ModuleFile *> >::iterator
8041 I = CommentsCursors.begin(),
8042 E = CommentsCursors.end();
8043 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008044 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008045 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008046 serialization::ModuleFile &F = *I->second;
8047 SavedStreamPosition SavedPosition(Cursor);
8048
8049 RecordData Record;
8050 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008051 llvm::BitstreamEntry Entry =
8052 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008053
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008054 switch (Entry.Kind) {
8055 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8056 case llvm::BitstreamEntry::Error:
8057 Error("malformed block record in AST file");
8058 return;
8059 case llvm::BitstreamEntry::EndBlock:
8060 goto NextCursor;
8061 case llvm::BitstreamEntry::Record:
8062 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008063 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008064 }
8065
8066 // Read a record.
8067 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008068 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008069 case COMMENTS_RAW_COMMENT: {
8070 unsigned Idx = 0;
8071 SourceRange SR = ReadSourceRange(F, Record, Idx);
8072 RawComment::CommentKind Kind =
8073 (RawComment::CommentKind) Record[Idx++];
8074 bool IsTrailingComment = Record[Idx++];
8075 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008076 Comments.push_back(new (Context) RawComment(
8077 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8078 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008079 break;
8080 }
8081 }
8082 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008083 NextCursor:
8084 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008085 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008086}
8087
Richard Smithcd45dbc2014-04-19 03:48:30 +00008088std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8089 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008090 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008091 return M->getFullModuleName();
8092
8093 // Otherwise, use the name of the top-level module the decl is within.
8094 if (ModuleFile *M = getOwningModuleFile(D))
8095 return M->ModuleName;
8096
8097 // Not from a module.
8098 return "";
8099}
8100
Guy Benyei11169dd2012-12-18 14:30:41 +00008101void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008102 while (!PendingIdentifierInfos.empty() ||
8103 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008104 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008105 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008106 // If any identifiers with corresponding top-level declarations have
8107 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008108 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8109 TopLevelDeclsMap;
8110 TopLevelDeclsMap TopLevelDecls;
8111
Guy Benyei11169dd2012-12-18 14:30:41 +00008112 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008113 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008114 SmallVector<uint32_t, 4> DeclIDs =
8115 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008116 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008117
8118 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008119 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008120
Richard Smith851072e2014-05-19 20:59:20 +00008121 // For each decl chain that we wanted to complete while deserializing, mark
8122 // it as "still needs to be completed".
8123 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8124 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8125 }
8126 PendingIncompleteDeclChains.clear();
8127
Guy Benyei11169dd2012-12-18 14:30:41 +00008128 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008129 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008130 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008131 PendingDeclChains.clear();
8132
Douglas Gregor6168bd22013-02-18 15:53:43 +00008133 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008134 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8135 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008136 IdentifierInfo *II = TLD->first;
8137 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008138 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008139 }
8140 }
8141
Guy Benyei11169dd2012-12-18 14:30:41 +00008142 // Load any pending macro definitions.
8143 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008144 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8145 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8146 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8147 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008148 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008149 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008150 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008151 if (Info.M->Kind != MK_ImplicitModule &&
8152 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008153 resolvePendingMacro(II, Info);
8154 }
8155 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008156 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008157 ++IDIdx) {
8158 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008159 if (Info.M->Kind == MK_ImplicitModule ||
8160 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008161 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008162 }
8163 }
8164 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008165
8166 // Wire up the DeclContexts for Decls that we delayed setting until
8167 // recursive loading is completed.
8168 while (!PendingDeclContextInfos.empty()) {
8169 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8170 PendingDeclContextInfos.pop_front();
8171 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8172 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8173 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8174 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008175
Richard Smithd1c46742014-04-30 02:24:17 +00008176 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008177 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008178 auto Update = PendingUpdateRecords.pop_back_val();
8179 ReadingKindTracker ReadingKind(Read_Decl, *this);
8180 loadDeclUpdateRecords(Update.first, Update.second);
8181 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008182 }
Richard Smith8a639892015-01-24 01:07:20 +00008183
8184 // At this point, all update records for loaded decls are in place, so any
8185 // fake class definitions should have become real.
8186 assert(PendingFakeDefinitionData.empty() &&
8187 "faked up a class definition but never saw the real one");
8188
Guy Benyei11169dd2012-12-18 14:30:41 +00008189 // If we deserialized any C++ or Objective-C class definitions, any
8190 // Objective-C protocol definitions, or any redeclarable templates, make sure
8191 // that all redeclarations point to the definitions. Note that this can only
8192 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008193 for (Decl *D : PendingDefinitions) {
8194 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008195 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008196 // Make sure that the TagType points at the definition.
8197 const_cast<TagType*>(TagT)->decl = TD;
8198 }
Richard Smith8ce51082015-03-11 01:44:51 +00008199
Craig Topperc6914d02014-08-25 04:15:02 +00008200 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008201 for (auto *R = getMostRecentExistingDecl(RD); R;
8202 R = R->getPreviousDecl()) {
8203 assert((R == D) ==
8204 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008205 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008206 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008207 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008208 }
8209
8210 continue;
8211 }
Richard Smith8ce51082015-03-11 01:44:51 +00008212
Craig Topperc6914d02014-08-25 04:15:02 +00008213 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008214 // Make sure that the ObjCInterfaceType points at the definition.
8215 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8216 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008217
8218 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8219 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8220
Guy Benyei11169dd2012-12-18 14:30:41 +00008221 continue;
8222 }
Richard Smith8ce51082015-03-11 01:44:51 +00008223
Craig Topperc6914d02014-08-25 04:15:02 +00008224 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008225 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8226 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8227
Guy Benyei11169dd2012-12-18 14:30:41 +00008228 continue;
8229 }
Richard Smith8ce51082015-03-11 01:44:51 +00008230
Craig Topperc6914d02014-08-25 04:15:02 +00008231 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008232 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8233 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008234 }
8235 PendingDefinitions.clear();
8236
8237 // Load the bodies of any functions or methods we've encountered. We do
8238 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008239 // have been fully wired up (hasBody relies on this).
8240 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008241 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8242 PBEnd = PendingBodies.end();
8243 PB != PBEnd; ++PB) {
8244 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8245 // FIXME: Check for =delete/=default?
8246 // FIXME: Complain about ODR violations here?
8247 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8248 FD->setLazyBody(PB->second);
8249 continue;
8250 }
8251
8252 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8253 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8254 MD->setLazyBody(PB->second);
8255 }
8256 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008257
8258 // Do some cleanup.
8259 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8260 getContext().deduplicateMergedDefinitonsFor(ND);
8261 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008262}
8263
8264void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008265 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8266 return;
8267
Richard Smitha0ce9c42014-07-29 23:23:27 +00008268 // Trigger the import of the full definition of each class that had any
8269 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008270 // These updates may in turn find and diagnose some ODR failures, so take
8271 // ownership of the set first.
8272 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8273 PendingOdrMergeFailures.clear();
8274 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008275 Merge.first->buildLookup();
8276 Merge.first->decls_begin();
8277 Merge.first->bases_begin();
8278 Merge.first->vbases_begin();
8279 for (auto *RD : Merge.second) {
8280 RD->decls_begin();
8281 RD->bases_begin();
8282 RD->vbases_begin();
8283 }
8284 }
8285
8286 // For each declaration from a merged context, check that the canonical
8287 // definition of that context also contains a declaration of the same
8288 // entity.
8289 //
8290 // Caution: this loop does things that might invalidate iterators into
8291 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8292 while (!PendingOdrMergeChecks.empty()) {
8293 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8294
8295 // FIXME: Skip over implicit declarations for now. This matters for things
8296 // like implicitly-declared special member functions. This isn't entirely
8297 // correct; we can end up with multiple unmerged declarations of the same
8298 // implicit entity.
8299 if (D->isImplicit())
8300 continue;
8301
8302 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008303
8304 bool Found = false;
8305 const Decl *DCanon = D->getCanonicalDecl();
8306
Richard Smith01bdb7a2014-08-28 05:44:07 +00008307 for (auto RI : D->redecls()) {
8308 if (RI->getLexicalDeclContext() == CanonDef) {
8309 Found = true;
8310 break;
8311 }
8312 }
8313 if (Found)
8314 continue;
8315
Richard Smith0f4e2c42015-08-06 04:23:48 +00008316 // Quick check failed, time to do the slow thing. Note, we can't just
8317 // look up the name of D in CanonDef here, because the member that is
8318 // in CanonDef might not be found by name lookup (it might have been
8319 // replaced by a more recent declaration in the lookup table), and we
8320 // can't necessarily find it in the redeclaration chain because it might
8321 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008322 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008323 for (auto *CanonMember : CanonDef->decls()) {
8324 if (CanonMember->getCanonicalDecl() == DCanon) {
8325 // This can happen if the declaration is merely mergeable and not
8326 // actually redeclarable (we looked for redeclarations earlier).
8327 //
8328 // FIXME: We should be able to detect this more efficiently, without
8329 // pulling in all of the members of CanonDef.
8330 Found = true;
8331 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008332 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008333 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8334 if (ND->getDeclName() == D->getDeclName())
8335 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008336 }
8337
8338 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008339 // The AST doesn't like TagDecls becoming invalid after they've been
8340 // completed. We only really need to mark FieldDecls as invalid here.
8341 if (!isa<TagDecl>(D))
8342 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008343
8344 // Ensure we don't accidentally recursively enter deserialization while
8345 // we're producing our diagnostic.
8346 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008347
8348 std::string CanonDefModule =
8349 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8350 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8351 << D << getOwningModuleNameForDiagnostic(D)
8352 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8353
8354 if (Candidates.empty())
8355 Diag(cast<Decl>(CanonDef)->getLocation(),
8356 diag::note_module_odr_violation_no_possible_decls) << D;
8357 else {
8358 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8359 Diag(Candidates[I]->getLocation(),
8360 diag::note_module_odr_violation_possible_decl)
8361 << Candidates[I];
8362 }
8363
8364 DiagnosedOdrMergeFailures.insert(CanonDef);
8365 }
8366 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008367
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008368 if (OdrMergeFailures.empty())
8369 return;
8370
8371 // Ensure we don't accidentally recursively enter deserialization while
8372 // we're producing our diagnostics.
8373 Deserializing RecursionGuard(this);
8374
Richard Smithcd45dbc2014-04-19 03:48:30 +00008375 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008376 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008377 // If we've already pointed out a specific problem with this class, don't
8378 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008379 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008380 continue;
8381
8382 bool Diagnosed = false;
8383 for (auto *RD : Merge.second) {
8384 // Multiple different declarations got merged together; tell the user
8385 // where they came from.
8386 if (Merge.first != RD) {
8387 // FIXME: Walk the definition, figure out what's different,
8388 // and diagnose that.
8389 if (!Diagnosed) {
8390 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8391 Diag(Merge.first->getLocation(),
8392 diag::err_module_odr_violation_different_definitions)
8393 << Merge.first << Module.empty() << Module;
8394 Diagnosed = true;
8395 }
8396
8397 Diag(RD->getLocation(),
8398 diag::note_module_odr_violation_different_definitions)
8399 << getOwningModuleNameForDiagnostic(RD);
8400 }
8401 }
8402
8403 if (!Diagnosed) {
8404 // All definitions are updates to the same declaration. This happens if a
8405 // module instantiates the declaration of a class template specialization
8406 // and two or more other modules instantiate its definition.
8407 //
8408 // FIXME: Indicate which modules had instantiations of this definition.
8409 // FIXME: How can this even happen?
8410 Diag(Merge.first->getLocation(),
8411 diag::err_module_odr_violation_different_instantiations)
8412 << Merge.first;
8413 }
8414 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008415}
8416
Richard Smithce18a182015-07-14 00:26:00 +00008417void ASTReader::StartedDeserializing() {
8418 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8419 ReadTimer->startTimer();
8420}
8421
Guy Benyei11169dd2012-12-18 14:30:41 +00008422void ASTReader::FinishedDeserializing() {
8423 assert(NumCurrentElementsDeserializing &&
8424 "FinishedDeserializing not paired with StartedDeserializing");
8425 if (NumCurrentElementsDeserializing == 1) {
8426 // We decrease NumCurrentElementsDeserializing only after pending actions
8427 // are finished, to avoid recursively re-calling finishPendingActions().
8428 finishPendingActions();
8429 }
8430 --NumCurrentElementsDeserializing;
8431
Richard Smitha0ce9c42014-07-29 23:23:27 +00008432 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008433 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008434 while (!PendingExceptionSpecUpdates.empty()) {
8435 auto Updates = std::move(PendingExceptionSpecUpdates);
8436 PendingExceptionSpecUpdates.clear();
8437 for (auto Update : Updates) {
8438 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008439 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
8440 for (auto *Redecl : Update.second->redecls())
8441 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008442 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008443 }
8444
Richard Smithce18a182015-07-14 00:26:00 +00008445 if (ReadTimer)
8446 ReadTimer->stopTimer();
8447
Richard Smith0f4e2c42015-08-06 04:23:48 +00008448 diagnoseOdrViolations();
8449
Richard Smith04d05b52014-03-23 00:27:18 +00008450 // We are not in recursive loading, so it's safe to pass the "interesting"
8451 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008452 if (Consumer)
8453 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008454 }
8455}
8456
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008457void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008458 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8459 // Remove any fake results before adding any real ones.
8460 auto It = PendingFakeLookupResults.find(II);
8461 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008462 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008463 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008464 // FIXME: this works around module+PCH performance issue.
8465 // Rather than erase the result from the map, which is O(n), just clear
8466 // the vector of NamedDecls.
8467 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008468 }
8469 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008470
8471 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8472 SemaObj->TUScope->AddDecl(D);
8473 } else if (SemaObj->TUScope) {
8474 // Adding the decl to IdResolver may have failed because it was already in
8475 // (even though it was not added in scope). If it is already in, make sure
8476 // it gets in the scope as well.
8477 if (std::find(SemaObj->IdResolver.begin(Name),
8478 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8479 SemaObj->TUScope->AddDecl(D);
8480 }
8481}
8482
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008483ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008484 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008485 StringRef isysroot, bool DisableValidation,
8486 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008487 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Richard Smithce18a182015-07-14 00:26:00 +00008488 bool UseGlobalIndex,
8489 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008490 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008491 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008492 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008493 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008494 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008495 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008496 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008497 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8498 AllowConfigurationMismatch(AllowConfigurationMismatch),
8499 ValidateSystemInputs(ValidateSystemInputs),
8500 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008501 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8502 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8503 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8504 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008505 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8506 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8507 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8508 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8509 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8510 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008511 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008512 SourceMgr.setExternalSLocEntrySource(this);
8513}
8514
8515ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008516 if (OwnsDeserializationListener)
8517 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008518}