blob: dbfc5c31db133ce1f28ee012e2a5cbea7f9d8965 [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"
Richard Smithd88a7f12015-09-01 20:35:42 +000023#include "clang/AST/ASTMutationListener.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000024#include "clang/AST/NestedNameSpecifier.h"
25#include "clang/AST/Type.h"
26#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000027#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000029#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/SourceManagerInternals.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/TargetOptions.h"
33#include "clang/Basic/Version.h"
34#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000035#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/Lex/HeaderSearch.h"
37#include "clang/Lex/HeaderSearchOptions.h"
38#include "clang/Lex/MacroInfo.h"
39#include "clang/Lex/PreprocessingRecord.h"
40#include "clang/Lex/Preprocessor.h"
41#include "clang/Lex/PreprocessorOptions.h"
42#include "clang/Sema/Scope.h"
43#include "clang/Sema/Sema.h"
44#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000045#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000046#include "clang/Serialization/ModuleManager.h"
47#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000048#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000049#include "llvm/ADT/StringExtras.h"
50#include "llvm/Bitcode/BitstreamReader.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/FileSystem.h"
53#include "llvm/Support/MemoryBuffer.h"
54#include "llvm/Support/Path.h"
55#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000056#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000058#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000059#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000060#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000061
62using namespace clang;
63using namespace clang::serialization;
64using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000065using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000066
Ben Langmuircb69b572014-03-07 06:40:32 +000067
68//===----------------------------------------------------------------------===//
69// ChainedASTReaderListener implementation
70//===----------------------------------------------------------------------===//
71
72bool
73ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
74 return First->ReadFullVersionInformation(FullVersion) ||
75 Second->ReadFullVersionInformation(FullVersion);
76}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000077void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
78 First->ReadModuleName(ModuleName);
79 Second->ReadModuleName(ModuleName);
80}
81void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
82 First->ReadModuleMapFile(ModuleMapPath);
83 Second->ReadModuleMapFile(ModuleMapPath);
84}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000085bool
86ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
87 bool Complain,
88 bool AllowCompatibleDifferences) {
89 return First->ReadLanguageOptions(LangOpts, Complain,
90 AllowCompatibleDifferences) ||
91 Second->ReadLanguageOptions(LangOpts, Complain,
92 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000093}
Chandler Carruth0d745bc2015-03-14 04:47:43 +000094bool ChainedASTReaderListener::ReadTargetOptions(
95 const TargetOptions &TargetOpts, bool Complain,
96 bool AllowCompatibleDifferences) {
97 return First->ReadTargetOptions(TargetOpts, Complain,
98 AllowCompatibleDifferences) ||
99 Second->ReadTargetOptions(TargetOpts, Complain,
100 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000101}
102bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000103 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000104 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
105 Second->ReadDiagnosticOptions(DiagOpts, Complain);
106}
107bool
108ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
109 bool Complain) {
110 return First->ReadFileSystemOptions(FSOpts, Complain) ||
111 Second->ReadFileSystemOptions(FSOpts, Complain);
112}
113
114bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000115 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
116 bool Complain) {
117 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
118 Complain) ||
119 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
120 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000121}
122bool ChainedASTReaderListener::ReadPreprocessorOptions(
123 const PreprocessorOptions &PPOpts, bool Complain,
124 std::string &SuggestedPredefines) {
125 return First->ReadPreprocessorOptions(PPOpts, Complain,
126 SuggestedPredefines) ||
127 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
128}
129void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
130 unsigned Value) {
131 First->ReadCounter(M, Value);
132 Second->ReadCounter(M, Value);
133}
134bool ChainedASTReaderListener::needsInputFileVisitation() {
135 return First->needsInputFileVisitation() ||
136 Second->needsInputFileVisitation();
137}
138bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
139 return First->needsSystemInputFileVisitation() ||
140 Second->needsSystemInputFileVisitation();
141}
Richard Smith216a3bd2015-08-13 17:57:10 +0000142void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
143 ModuleKind Kind) {
144 First->visitModuleFile(Filename, Kind);
145 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000146}
Ben Langmuircb69b572014-03-07 06:40:32 +0000147bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000148 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000149 bool isOverridden,
150 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000151 bool Continue = false;
152 if (First->needsInputFileVisitation() &&
153 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000154 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
155 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000156 if (Second->needsInputFileVisitation() &&
157 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000158 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
159 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000160 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000161}
162
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000163void ChainedASTReaderListener::readModuleFileExtension(
164 const ModuleFileExtensionMetadata &Metadata) {
165 First->readModuleFileExtension(Metadata);
166 Second->readModuleFileExtension(Metadata);
167}
168
Guy Benyei11169dd2012-12-18 14:30:41 +0000169//===----------------------------------------------------------------------===//
170// PCH validator implementation
171//===----------------------------------------------------------------------===//
172
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000173ASTReaderListener::~ASTReaderListener() {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000174
175/// \brief Compare the given set of language options against an existing set of
176/// language options.
177///
178/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000179/// \param AllowCompatibleDifferences If true, differences between compatible
180/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000181///
182/// \returns true if the languagae options mis-match, false otherwise.
183static bool checkLanguageOptions(const LangOptions &LangOpts,
184 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000185 DiagnosticsEngine *Diags,
186 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000187#define LANGOPT(Name, Bits, Default, Description) \
188 if (ExistingLangOpts.Name != LangOpts.Name) { \
189 if (Diags) \
190 Diags->Report(diag::err_pch_langopt_mismatch) \
191 << Description << LangOpts.Name << ExistingLangOpts.Name; \
192 return true; \
193 }
194
195#define VALUE_LANGOPT(Name, Bits, Default, Description) \
196 if (ExistingLangOpts.Name != LangOpts.Name) { \
197 if (Diags) \
198 Diags->Report(diag::err_pch_langopt_value_mismatch) \
199 << Description; \
200 return true; \
201 }
202
203#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
204 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
205 if (Diags) \
206 Diags->Report(diag::err_pch_langopt_value_mismatch) \
207 << Description; \
208 return true; \
209 }
210
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000211#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
212 if (!AllowCompatibleDifferences) \
213 LANGOPT(Name, Bits, Default, Description)
214
215#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
216 if (!AllowCompatibleDifferences) \
217 ENUM_LANGOPT(Name, Bits, Default, Description)
218
Guy Benyei11169dd2012-12-18 14:30:41 +0000219#define BENIGN_LANGOPT(Name, Bits, Default, Description)
220#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
221#include "clang/Basic/LangOptions.def"
222
Ben Langmuircd98cb72015-06-23 18:20:18 +0000223 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
224 if (Diags)
225 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
226 return true;
227 }
228
Guy Benyei11169dd2012-12-18 14:30:41 +0000229 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
230 if (Diags)
231 Diags->Report(diag::err_pch_langopt_value_mismatch)
232 << "target Objective-C runtime";
233 return true;
234 }
235
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000236 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
237 LangOpts.CommentOpts.BlockCommandNames) {
238 if (Diags)
239 Diags->Report(diag::err_pch_langopt_value_mismatch)
240 << "block command names";
241 return true;
242 }
243
Guy Benyei11169dd2012-12-18 14:30:41 +0000244 return false;
245}
246
247/// \brief Compare the given set of target options against an existing set of
248/// target options.
249///
250/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
251///
252/// \returns true if the target options mis-match, false otherwise.
253static bool checkTargetOptions(const TargetOptions &TargetOpts,
254 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000255 DiagnosticsEngine *Diags,
256 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000257#define CHECK_TARGET_OPT(Field, Name) \
258 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
259 if (Diags) \
260 Diags->Report(diag::err_pch_targetopt_mismatch) \
261 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
262 return true; \
263 }
264
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000265 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000266 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000267 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000268
269 // We can tolerate different CPUs in many cases, notably when one CPU
270 // supports a strict superset of another. When allowing compatible
271 // differences skip this check.
272 if (!AllowCompatibleDifferences)
273 CHECK_TARGET_OPT(CPU, "target CPU");
274
Guy Benyei11169dd2012-12-18 14:30:41 +0000275#undef CHECK_TARGET_OPT
276
277 // Compare feature sets.
278 SmallVector<StringRef, 4> ExistingFeatures(
279 ExistingTargetOpts.FeaturesAsWritten.begin(),
280 ExistingTargetOpts.FeaturesAsWritten.end());
281 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
282 TargetOpts.FeaturesAsWritten.end());
283 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
284 std::sort(ReadFeatures.begin(), ReadFeatures.end());
285
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000286 // We compute the set difference in both directions explicitly so that we can
287 // diagnose the differences differently.
288 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
289 std::set_difference(
290 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
291 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
292 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
293 ExistingFeatures.begin(), ExistingFeatures.end(),
294 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000295
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000296 // If we are allowing compatible differences and the read feature set is
297 // a strict subset of the existing feature set, there is nothing to diagnose.
298 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
299 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000300
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000301 if (Diags) {
302 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000303 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000304 << /* is-existing-feature */ false << Feature;
305 for (StringRef Feature : UnmatchedExistingFeatures)
306 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
307 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000308 }
309
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000310 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000311}
312
313bool
314PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000315 bool Complain,
316 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000317 const LangOptions &ExistingLangOpts = PP.getLangOpts();
318 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000319 Complain ? &Reader.Diags : nullptr,
320 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000321}
322
323bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000324 bool Complain,
325 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000326 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
327 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000328 Complain ? &Reader.Diags : nullptr,
329 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000330}
331
332namespace {
333 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
334 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000335 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
336 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000337}
338
Ben Langmuirb92de022014-04-29 16:25:26 +0000339static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
340 DiagnosticsEngine &Diags,
341 bool Complain) {
342 typedef DiagnosticsEngine::Level Level;
343
344 // Check current mappings for new -Werror mappings, and the stored mappings
345 // for cases that were explicitly mapped to *not* be errors that are now
346 // errors because of options like -Werror.
347 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
348
349 for (DiagnosticsEngine *MappingSource : MappingSources) {
350 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
351 diag::kind DiagID = DiagIDMappingPair.first;
352 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
353 if (CurLevel < DiagnosticsEngine::Error)
354 continue; // not significant
355 Level StoredLevel =
356 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
357 if (StoredLevel < DiagnosticsEngine::Error) {
358 if (Complain)
359 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
360 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
361 return true;
362 }
363 }
364 }
365
366 return false;
367}
368
Alp Tokerac4e8e52014-06-22 21:58:33 +0000369static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
370 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
371 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
372 return true;
373 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000374}
375
376static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
377 DiagnosticsEngine &Diags,
378 bool IsSystem, bool Complain) {
379 // Top-level options
380 if (IsSystem) {
381 if (Diags.getSuppressSystemWarnings())
382 return false;
383 // If -Wsystem-headers was not enabled before, be conservative
384 if (StoredDiags.getSuppressSystemWarnings()) {
385 if (Complain)
386 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
387 return true;
388 }
389 }
390
391 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
392 if (Complain)
393 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
394 return true;
395 }
396
397 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
398 !StoredDiags.getEnableAllWarnings()) {
399 if (Complain)
400 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
401 return true;
402 }
403
404 if (isExtHandlingFromDiagsError(Diags) &&
405 !isExtHandlingFromDiagsError(StoredDiags)) {
406 if (Complain)
407 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
408 return true;
409 }
410
411 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
412}
413
414bool PCHValidator::ReadDiagnosticOptions(
415 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
416 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
417 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
418 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000419 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000420 // This should never fail, because we would have processed these options
421 // before writing them to an ASTFile.
422 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
423
424 ModuleManager &ModuleMgr = Reader.getModuleManager();
425 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
426
427 // If the original import came from a file explicitly generated by the user,
428 // don't check the diagnostic mappings.
429 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000430 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000431 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
432 // the transitive closure of its imports, since unrelated modules cannot be
433 // imported until after this module finishes validation.
434 ModuleFile *TopImport = *ModuleMgr.rbegin();
435 while (!TopImport->ImportedBy.empty())
436 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000437 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000438 return false;
439
440 StringRef ModuleName = TopImport->ModuleName;
441 assert(!ModuleName.empty() && "diagnostic options read before module name");
442
443 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
444 assert(M && "missing module");
445
446 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
447 // contains the union of their flags.
448 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
449}
450
Guy Benyei11169dd2012-12-18 14:30:41 +0000451/// \brief Collect the macro definitions provided by the given preprocessor
452/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000453static void
454collectMacroDefinitions(const PreprocessorOptions &PPOpts,
455 MacroDefinitionsMap &Macros,
456 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000457 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
458 StringRef Macro = PPOpts.Macros[I].first;
459 bool IsUndef = PPOpts.Macros[I].second;
460
461 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
462 StringRef MacroName = MacroPair.first;
463 StringRef MacroBody = MacroPair.second;
464
465 // For an #undef'd macro, we only care about the name.
466 if (IsUndef) {
467 if (MacroNames && !Macros.count(MacroName))
468 MacroNames->push_back(MacroName);
469
470 Macros[MacroName] = std::make_pair("", true);
471 continue;
472 }
473
474 // For a #define'd macro, figure out the actual definition.
475 if (MacroName.size() == Macro.size())
476 MacroBody = "1";
477 else {
478 // Note: GCC drops anything following an end-of-line character.
479 StringRef::size_type End = MacroBody.find_first_of("\n\r");
480 MacroBody = MacroBody.substr(0, End);
481 }
482
483 if (MacroNames && !Macros.count(MacroName))
484 MacroNames->push_back(MacroName);
485 Macros[MacroName] = std::make_pair(MacroBody, false);
486 }
487}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000488
Guy Benyei11169dd2012-12-18 14:30:41 +0000489/// \brief Check the preprocessor options deserialized from the control block
490/// against the preprocessor options in an existing preprocessor.
491///
492/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
493static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
494 const PreprocessorOptions &ExistingPPOpts,
495 DiagnosticsEngine *Diags,
496 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000497 std::string &SuggestedPredefines,
498 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000499 // Check macro definitions.
500 MacroDefinitionsMap ASTFileMacros;
501 collectMacroDefinitions(PPOpts, ASTFileMacros);
502 MacroDefinitionsMap ExistingMacros;
503 SmallVector<StringRef, 4> ExistingMacroNames;
504 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
505
506 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
507 // Dig out the macro definition in the existing preprocessor options.
508 StringRef MacroName = ExistingMacroNames[I];
509 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
510
511 // Check whether we know anything about this macro name or not.
512 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
513 = ASTFileMacros.find(MacroName);
514 if (Known == ASTFileMacros.end()) {
515 // FIXME: Check whether this identifier was referenced anywhere in the
516 // AST file. If so, we should reject the AST file. Unfortunately, this
517 // information isn't in the control block. What shall we do about it?
518
519 if (Existing.second) {
520 SuggestedPredefines += "#undef ";
521 SuggestedPredefines += MacroName.str();
522 SuggestedPredefines += '\n';
523 } else {
524 SuggestedPredefines += "#define ";
525 SuggestedPredefines += MacroName.str();
526 SuggestedPredefines += ' ';
527 SuggestedPredefines += Existing.first.str();
528 SuggestedPredefines += '\n';
529 }
530 continue;
531 }
532
533 // If the macro was defined in one but undef'd in the other, we have a
534 // conflict.
535 if (Existing.second != Known->second.second) {
536 if (Diags) {
537 Diags->Report(diag::err_pch_macro_def_undef)
538 << MacroName << Known->second.second;
539 }
540 return true;
541 }
542
543 // If the macro was #undef'd in both, or if the macro bodies are identical,
544 // it's fine.
545 if (Existing.second || Existing.first == Known->second.first)
546 continue;
547
548 // The macro bodies differ; complain.
549 if (Diags) {
550 Diags->Report(diag::err_pch_macro_def_conflict)
551 << MacroName << Known->second.first << Existing.first;
552 }
553 return true;
554 }
555
556 // Check whether we're using predefines.
557 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
558 if (Diags) {
559 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
560 }
561 return true;
562 }
563
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000564 // Detailed record is important since it is used for the module cache hash.
565 if (LangOpts.Modules &&
566 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
567 if (Diags) {
568 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
569 }
570 return true;
571 }
572
Guy Benyei11169dd2012-12-18 14:30:41 +0000573 // Compute the #include and #include_macros lines we need.
574 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
575 StringRef File = ExistingPPOpts.Includes[I];
576 if (File == ExistingPPOpts.ImplicitPCHInclude)
577 continue;
578
579 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
580 != PPOpts.Includes.end())
581 continue;
582
583 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000584 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000585 SuggestedPredefines += "\"\n";
586 }
587
588 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
589 StringRef File = ExistingPPOpts.MacroIncludes[I];
590 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
591 File)
592 != PPOpts.MacroIncludes.end())
593 continue;
594
595 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000596 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000597 SuggestedPredefines += "\"\n##\n";
598 }
599
600 return false;
601}
602
603bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
604 bool Complain,
605 std::string &SuggestedPredefines) {
606 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
607
608 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000609 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000610 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000611 SuggestedPredefines,
612 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000613}
614
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000615/// Check the header search options deserialized from the control block
616/// against the header search options in an existing preprocessor.
617///
618/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
619static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
620 StringRef SpecificModuleCachePath,
621 StringRef ExistingModuleCachePath,
622 DiagnosticsEngine *Diags,
623 const LangOptions &LangOpts) {
624 if (LangOpts.Modules) {
625 if (SpecificModuleCachePath != ExistingModuleCachePath) {
626 if (Diags)
627 Diags->Report(diag::err_pch_modulecache_mismatch)
628 << SpecificModuleCachePath << ExistingModuleCachePath;
629 return true;
630 }
631 }
632
633 return false;
634}
635
636bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
637 StringRef SpecificModuleCachePath,
638 bool Complain) {
639 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
640 PP.getHeaderSearchInfo().getModuleCachePath(),
641 Complain ? &Reader.Diags : nullptr,
642 PP.getLangOpts());
643}
644
Guy Benyei11169dd2012-12-18 14:30:41 +0000645void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
646 PP.setCounterValue(Value);
647}
648
649//===----------------------------------------------------------------------===//
650// AST reader implementation
651//===----------------------------------------------------------------------===//
652
Nico Weber824285e2014-05-08 04:26:47 +0000653void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
654 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000655 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000656 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000657}
658
659
660
661unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
662 return serialization::ComputeHash(Sel);
663}
664
665
666std::pair<unsigned, unsigned>
667ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000668 using namespace llvm::support;
669 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
670 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000671 return std::make_pair(KeyLen, DataLen);
672}
673
674ASTSelectorLookupTrait::internal_key_type
675ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000676 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000677 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000678 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
679 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
680 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000681 if (N == 0)
682 return SelTable.getNullarySelector(FirstII);
683 else if (N == 1)
684 return SelTable.getUnarySelector(FirstII);
685
686 SmallVector<IdentifierInfo *, 16> Args;
687 Args.push_back(FirstII);
688 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000689 Args.push_back(Reader.getLocalIdentifier(
690 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000691
692 return SelTable.getSelector(N, Args.data());
693}
694
695ASTSelectorLookupTrait::data_type
696ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
697 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000698 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000699
700 data_type Result;
701
Justin Bogner57ba0b22014-03-28 22:03:24 +0000702 Result.ID = Reader.getGlobalSelectorID(
703 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000704 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
705 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
706 Result.InstanceBits = FullInstanceBits & 0x3;
707 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
708 Result.FactoryBits = FullFactoryBits & 0x3;
709 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
710 unsigned NumInstanceMethods = FullInstanceBits >> 3;
711 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000712
713 // Load instance methods
714 for (unsigned I = 0; I != NumInstanceMethods; ++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.Instance.push_back(Method);
718 }
719
720 // Load factory methods
721 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000722 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
723 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000724 Result.Factory.push_back(Method);
725 }
726
727 return Result;
728}
729
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000730unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
731 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000732}
733
734std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000735ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000736 using namespace llvm::support;
737 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
738 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000739 return std::make_pair(KeyLen, DataLen);
740}
741
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000742ASTIdentifierLookupTraitBase::internal_key_type
743ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000744 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000745 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000746}
747
Douglas Gregordcf25082013-02-11 18:16:18 +0000748/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000749static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
750 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000751 return II.hadMacroDefinition() ||
752 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000753 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000754 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000755 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
756 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000757}
758
Richard Smith76c2f2c2015-07-17 20:09:43 +0000759static bool readBit(unsigned &Bits) {
760 bool Value = Bits & 0x1;
761 Bits >>= 1;
762 return Value;
763}
764
Richard Smith79bf9202015-08-24 03:33:22 +0000765IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
766 using namespace llvm::support;
767 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
768 return Reader.getGlobalIdentifierID(F, RawID >> 1);
769}
770
Richard Smitheb4b58f62016-02-05 01:40:54 +0000771static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
772 if (!II.isFromAST()) {
773 II.setIsFromAST();
774 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
775 if (isInterestingIdentifier(Reader, II, IsModule))
776 II.setChangedSinceDeserialization();
777 }
778}
779
Guy Benyei11169dd2012-12-18 14:30:41 +0000780IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
781 const unsigned char* d,
782 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000783 using namespace llvm::support;
784 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000785 bool IsInteresting = RawID & 0x01;
786
787 // Wipe out the "is interesting" bit.
788 RawID = RawID >> 1;
789
Richard Smith76c2f2c2015-07-17 20:09:43 +0000790 // Build the IdentifierInfo and link the identifier ID with it.
791 IdentifierInfo *II = KnownII;
792 if (!II) {
793 II = &Reader.getIdentifierTable().getOwn(k);
794 KnownII = II;
795 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000796 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000797 Reader.markIdentifierUpToDate(II);
798
Guy Benyei11169dd2012-12-18 14:30:41 +0000799 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
800 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000801 // For uninteresting identifiers, there's nothing else to do. Just notify
802 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000803 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000804 return II;
805 }
806
Justin Bogner57ba0b22014-03-28 22:03:24 +0000807 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
808 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000809 bool CPlusPlusOperatorKeyword = readBit(Bits);
810 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000811 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000812 bool Poisoned = readBit(Bits);
813 bool ExtensionToken = readBit(Bits);
814 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000815
816 assert(Bits == 0 && "Extra bits in the identifier?");
817 DataLen -= 8;
818
Guy Benyei11169dd2012-12-18 14:30:41 +0000819 // Set or check the various bits in the IdentifierInfo structure.
820 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000821 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000822 II->revertTokenIDToIdentifier();
823 if (!F.isModule())
824 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
825 else if (HasRevertedBuiltin && II->getBuiltinID()) {
826 II->revertBuiltin();
827 assert((II->hasRevertedBuiltin() ||
828 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
829 "Incorrect ObjC keyword or builtin ID");
830 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000831 assert(II->isExtensionToken() == ExtensionToken &&
832 "Incorrect extension token flag");
833 (void)ExtensionToken;
834 if (Poisoned)
835 II->setIsPoisoned(true);
836 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
837 "Incorrect C++ operator keyword flag");
838 (void)CPlusPlusOperatorKeyword;
839
840 // If this identifier is a macro, deserialize the macro
841 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000842 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000843 uint32_t MacroDirectivesOffset =
844 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000845 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000846
Richard Smithd7329392015-04-21 21:46:32 +0000847 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000848 }
849
850 Reader.SetIdentifierInfo(ID, II);
851
852 // Read all of the declarations visible at global scope with this
853 // name.
854 if (DataLen > 0) {
855 SmallVector<uint32_t, 4> DeclIDs;
856 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000857 DeclIDs.push_back(Reader.getGlobalDeclID(
858 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000859 Reader.SetGloballyVisibleDecls(II, DeclIDs);
860 }
861
862 return II;
863}
864
Richard Smitha06c7e62015-08-26 23:55:49 +0000865DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
866 : Kind(Name.getNameKind()) {
867 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000868 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000869 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000870 break;
871 case DeclarationName::ObjCZeroArgSelector:
872 case DeclarationName::ObjCOneArgSelector:
873 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000874 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000875 break;
876 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000877 Data = Name.getCXXOverloadedOperator();
878 break;
879 case DeclarationName::CXXLiteralOperatorName:
880 Data = (uint64_t)Name.getCXXLiteralIdentifier();
881 break;
882 case DeclarationName::CXXConstructorName:
883 case DeclarationName::CXXDestructorName:
884 case DeclarationName::CXXConversionFunctionName:
885 case DeclarationName::CXXUsingDirective:
886 Data = 0;
887 break;
888 }
889}
890
891unsigned DeclarationNameKey::getHash() const {
892 llvm::FoldingSetNodeID ID;
893 ID.AddInteger(Kind);
894
895 switch (Kind) {
896 case DeclarationName::Identifier:
897 case DeclarationName::CXXLiteralOperatorName:
898 ID.AddString(((IdentifierInfo*)Data)->getName());
899 break;
900 case DeclarationName::ObjCZeroArgSelector:
901 case DeclarationName::ObjCOneArgSelector:
902 case DeclarationName::ObjCMultiArgSelector:
903 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
904 break;
905 case DeclarationName::CXXOperatorName:
906 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000907 break;
908 case DeclarationName::CXXConstructorName:
909 case DeclarationName::CXXDestructorName:
910 case DeclarationName::CXXConversionFunctionName:
911 case DeclarationName::CXXUsingDirective:
912 break;
913 }
914
915 return ID.ComputeHash();
916}
917
Richard Smithd88a7f12015-09-01 20:35:42 +0000918ModuleFile *
919ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
920 using namespace llvm::support;
921 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
922 return Reader.getLocalModuleFile(F, ModuleFileID);
923}
924
Guy Benyei11169dd2012-12-18 14:30:41 +0000925std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000926ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000927 using namespace llvm::support;
928 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
929 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000930 return std::make_pair(KeyLen, DataLen);
931}
932
Richard Smitha06c7e62015-08-26 23:55:49 +0000933ASTDeclContextNameLookupTrait::internal_key_type
934ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000935 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000936
Richard Smitha06c7e62015-08-26 23:55:49 +0000937 auto Kind = (DeclarationName::NameKind)*d++;
938 uint64_t Data;
939 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000940 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000941 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000942 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000943 break;
944 case DeclarationName::ObjCZeroArgSelector:
945 case DeclarationName::ObjCOneArgSelector:
946 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000947 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000948 (uint64_t)Reader.getLocalSelector(
949 F, endian::readNext<uint32_t, little, unaligned>(
950 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000951 break;
952 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000953 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +0000954 break;
955 case DeclarationName::CXXLiteralOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000956 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000957 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000958 break;
959 case DeclarationName::CXXConstructorName:
960 case DeclarationName::CXXDestructorName:
961 case DeclarationName::CXXConversionFunctionName:
962 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +0000963 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000964 break;
965 }
966
Richard Smitha06c7e62015-08-26 23:55:49 +0000967 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000968}
969
Richard Smithd88a7f12015-09-01 20:35:42 +0000970void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
971 const unsigned char *d,
972 unsigned DataLen,
973 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000974 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +0000975 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
976 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
977 Val.insert(Reader.getGlobalDeclID(F, LocalID));
978 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000979}
980
Richard Smith0f4e2c42015-08-06 04:23:48 +0000981bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
982 BitstreamCursor &Cursor,
983 uint64_t Offset,
984 DeclContext *DC) {
985 assert(Offset != 0);
986
Guy Benyei11169dd2012-12-18 14:30:41 +0000987 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +0000988 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000989
Richard Smith0f4e2c42015-08-06 04:23:48 +0000990 RecordData Record;
991 StringRef Blob;
992 unsigned Code = Cursor.ReadCode();
993 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
994 if (RecCode != DECL_CONTEXT_LEXICAL) {
995 Error("Expected lexical block");
996 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000997 }
998
Richard Smith82f8fcd2015-08-06 22:07:25 +0000999 assert(!isa<TranslationUnitDecl>(DC) &&
1000 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001001 // If we are handling a C++ class template instantiation, we can see multiple
1002 // lexical updates for the same record. It's important that we select only one
1003 // of them, so that field numbering works properly. Just pick the first one we
1004 // see.
1005 auto &Lex = LexicalDecls[DC];
1006 if (!Lex.first) {
1007 Lex = std::make_pair(
1008 &M, llvm::makeArrayRef(
1009 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1010 Blob.data()),
1011 Blob.size() / 4));
1012 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001013 DC->setHasExternalLexicalStorage(true);
1014 return false;
1015}
Guy Benyei11169dd2012-12-18 14:30:41 +00001016
Richard Smith0f4e2c42015-08-06 04:23:48 +00001017bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1018 BitstreamCursor &Cursor,
1019 uint64_t Offset,
1020 DeclID ID) {
1021 assert(Offset != 0);
1022
1023 SavedStreamPosition SavedPosition(Cursor);
1024 Cursor.JumpToBit(Offset);
1025
1026 RecordData Record;
1027 StringRef Blob;
1028 unsigned Code = Cursor.ReadCode();
1029 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1030 if (RecCode != DECL_CONTEXT_VISIBLE) {
1031 Error("Expected visible lookup table block");
1032 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001033 }
1034
Richard Smith0f4e2c42015-08-06 04:23:48 +00001035 // We can't safely determine the primary context yet, so delay attaching the
1036 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001037 auto *Data = (const unsigned char*)Blob.data();
1038 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001039 return false;
1040}
1041
1042void ASTReader::Error(StringRef Msg) {
1043 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001044 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1045 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001046 Diag(diag::note_module_cache_path)
1047 << PP.getHeaderSearchInfo().getModuleCachePath();
1048 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001049}
1050
1051void ASTReader::Error(unsigned DiagID,
1052 StringRef Arg1, StringRef Arg2) {
1053 if (Diags.isDiagnosticInFlight())
1054 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1055 else
1056 Diag(DiagID) << Arg1 << Arg2;
1057}
1058
1059//===----------------------------------------------------------------------===//
1060// Source Manager Deserialization
1061//===----------------------------------------------------------------------===//
1062
1063/// \brief Read the line table in the source manager block.
1064/// \returns true if there was an error.
1065bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001066 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001067 unsigned Idx = 0;
1068 LineTableInfo &LineTable = SourceMgr.getLineTable();
1069
1070 // Parse the file names
1071 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001072 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001073 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001074 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001075 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1076 }
Richard Smith63078492015-09-01 07:41:55 +00001077 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001078
1079 // Parse the line entries
1080 std::vector<LineEntry> Entries;
1081 while (Idx < Record.size()) {
1082 int FID = Record[Idx++];
1083 assert(FID >= 0 && "Serialized line entries for non-local file.");
1084 // Remap FileID from 1-based old view.
1085 FID += F.SLocEntryBaseID - 1;
1086
1087 // Extract the line entries
1088 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001089 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001090 Entries.clear();
1091 Entries.reserve(NumEntries);
1092 for (unsigned I = 0; I != NumEntries; ++I) {
1093 unsigned FileOffset = Record[Idx++];
1094 unsigned LineNo = Record[Idx++];
1095 int FilenameID = FileIDs[Record[Idx++]];
1096 SrcMgr::CharacteristicKind FileKind
1097 = (SrcMgr::CharacteristicKind)Record[Idx++];
1098 unsigned IncludeOffset = Record[Idx++];
1099 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1100 FileKind, IncludeOffset));
1101 }
1102 LineTable.AddEntry(FileID::get(FID), Entries);
1103 }
1104
1105 return false;
1106}
1107
1108/// \brief Read a source manager block
1109bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1110 using namespace SrcMgr;
1111
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001112 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001113
1114 // Set the source-location entry cursor to the current position in
1115 // the stream. This cursor will be used to read the contents of the
1116 // source manager block initially, and then lazily read
1117 // source-location entries as needed.
1118 SLocEntryCursor = F.Stream;
1119
1120 // The stream itself is going to skip over the source manager block.
1121 if (F.Stream.SkipBlock()) {
1122 Error("malformed block record in AST file");
1123 return true;
1124 }
1125
1126 // Enter the source manager block.
1127 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1128 Error("malformed source manager block record in AST file");
1129 return true;
1130 }
1131
1132 RecordData Record;
1133 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001134 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1135
1136 switch (E.Kind) {
1137 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1138 case llvm::BitstreamEntry::Error:
1139 Error("malformed block record in AST file");
1140 return true;
1141 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001142 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001143 case llvm::BitstreamEntry::Record:
1144 // The interesting case.
1145 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001146 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001147
Guy Benyei11169dd2012-12-18 14:30:41 +00001148 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001149 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001150 StringRef Blob;
1151 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001152 default: // Default behavior: ignore.
1153 break;
1154
1155 case SM_SLOC_FILE_ENTRY:
1156 case SM_SLOC_BUFFER_ENTRY:
1157 case SM_SLOC_EXPANSION_ENTRY:
1158 // Once we hit one of the source location entries, we're done.
1159 return false;
1160 }
1161 }
1162}
1163
1164/// \brief If a header file is not found at the path that we expect it to be
1165/// and the PCH file was moved from its original location, try to resolve the
1166/// file by assuming that header+PCH were moved together and the header is in
1167/// the same place relative to the PCH.
1168static std::string
1169resolveFileRelativeToOriginalDir(const std::string &Filename,
1170 const std::string &OriginalDir,
1171 const std::string &CurrDir) {
1172 assert(OriginalDir != CurrDir &&
1173 "No point trying to resolve the file if the PCH dir didn't change");
1174 using namespace llvm::sys;
1175 SmallString<128> filePath(Filename);
1176 fs::make_absolute(filePath);
1177 assert(path::is_absolute(OriginalDir));
1178 SmallString<128> currPCHPath(CurrDir);
1179
1180 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1181 fileDirE = path::end(path::parent_path(filePath));
1182 path::const_iterator origDirI = path::begin(OriginalDir),
1183 origDirE = path::end(OriginalDir);
1184 // Skip the common path components from filePath and OriginalDir.
1185 while (fileDirI != fileDirE && origDirI != origDirE &&
1186 *fileDirI == *origDirI) {
1187 ++fileDirI;
1188 ++origDirI;
1189 }
1190 for (; origDirI != origDirE; ++origDirI)
1191 path::append(currPCHPath, "..");
1192 path::append(currPCHPath, fileDirI, fileDirE);
1193 path::append(currPCHPath, path::filename(Filename));
1194 return currPCHPath.str();
1195}
1196
1197bool ASTReader::ReadSLocEntry(int ID) {
1198 if (ID == 0)
1199 return false;
1200
1201 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1202 Error("source location entry ID out-of-range for AST file");
1203 return true;
1204 }
1205
1206 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1207 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001208 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001209 unsigned BaseOffset = F->SLocEntryBaseOffset;
1210
1211 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001212 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1213 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001214 Error("incorrectly-formatted source location entry in AST file");
1215 return true;
1216 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001217
Guy Benyei11169dd2012-12-18 14:30:41 +00001218 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001219 StringRef Blob;
1220 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001221 default:
1222 Error("incorrectly-formatted source location entry in AST file");
1223 return true;
1224
1225 case SM_SLOC_FILE_ENTRY: {
1226 // We will detect whether a file changed and return 'Failure' for it, but
1227 // we will also try to fail gracefully by setting up the SLocEntry.
1228 unsigned InputID = Record[4];
1229 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001230 const FileEntry *File = IF.getFile();
1231 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001232
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001233 // Note that we only check if a File was returned. If it was out-of-date
1234 // we have complained but we will continue creating a FileID to recover
1235 // gracefully.
1236 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001237 return true;
1238
1239 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1240 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1241 // This is the module's main file.
1242 IncludeLoc = getImportLocation(F);
1243 }
1244 SrcMgr::CharacteristicKind
1245 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1246 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1247 ID, BaseOffset + Record[0]);
1248 SrcMgr::FileInfo &FileInfo =
1249 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1250 FileInfo.NumCreatedFIDs = Record[5];
1251 if (Record[3])
1252 FileInfo.setHasLineDirectives();
1253
1254 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1255 unsigned NumFileDecls = Record[7];
1256 if (NumFileDecls) {
1257 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1258 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1259 NumFileDecls));
1260 }
1261
1262 const SrcMgr::ContentCache *ContentCache
1263 = SourceMgr.getOrCreateContentCache(File,
1264 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1265 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001266 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1267 !ContentCache->getRawBuffer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001268 unsigned Code = SLocEntryCursor.ReadCode();
1269 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001270 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001271
1272 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1273 Error("AST record has invalid code");
1274 return true;
1275 }
1276
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001277 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001278 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001279 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001280 }
1281
1282 break;
1283 }
1284
1285 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001286 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001287 unsigned Offset = Record[0];
1288 SrcMgr::CharacteristicKind
1289 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1290 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001291 if (IncludeLoc.isInvalid() &&
1292 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001293 IncludeLoc = getImportLocation(F);
1294 }
1295 unsigned Code = SLocEntryCursor.ReadCode();
1296 Record.clear();
1297 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001298 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001299
1300 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1301 Error("AST record has invalid code");
1302 return true;
1303 }
1304
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001305 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1306 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001307 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001308 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001309 break;
1310 }
1311
1312 case SM_SLOC_EXPANSION_ENTRY: {
1313 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1314 SourceMgr.createExpansionLoc(SpellingLoc,
1315 ReadSourceLocation(*F, Record[2]),
1316 ReadSourceLocation(*F, Record[3]),
1317 Record[4],
1318 ID,
1319 BaseOffset + Record[0]);
1320 break;
1321 }
1322 }
1323
1324 return false;
1325}
1326
1327std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1328 if (ID == 0)
1329 return std::make_pair(SourceLocation(), "");
1330
1331 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1332 Error("source location entry ID out-of-range for AST file");
1333 return std::make_pair(SourceLocation(), "");
1334 }
1335
1336 // Find which module file this entry lands in.
1337 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001338 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001339 return std::make_pair(SourceLocation(), "");
1340
1341 // FIXME: Can we map this down to a particular submodule? That would be
1342 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001343 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001344}
1345
1346/// \brief Find the location where the module F is imported.
1347SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1348 if (F->ImportLoc.isValid())
1349 return F->ImportLoc;
1350
1351 // Otherwise we have a PCH. It's considered to be "imported" at the first
1352 // location of its includer.
1353 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001354 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001355 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001356 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001357 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001358 return F->ImportedBy[0]->FirstLoc;
1359}
1360
1361/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1362/// specified cursor. Read the abbreviations that are at the top of the block
1363/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001364bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001365 if (Cursor.EnterSubBlock(BlockID))
1366 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001367
1368 while (true) {
1369 uint64_t Offset = Cursor.GetCurrentBitNo();
1370 unsigned Code = Cursor.ReadCode();
1371
1372 // We expect all abbrevs to be at the start of the block.
1373 if (Code != llvm::bitc::DEFINE_ABBREV) {
1374 Cursor.JumpToBit(Offset);
1375 return false;
1376 }
1377 Cursor.ReadAbbrevRecord();
1378 }
1379}
1380
Richard Smithe40f2ba2013-08-07 21:41:30 +00001381Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001382 unsigned &Idx) {
1383 Token Tok;
1384 Tok.startToken();
1385 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1386 Tok.setLength(Record[Idx++]);
1387 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1388 Tok.setIdentifierInfo(II);
1389 Tok.setKind((tok::TokenKind)Record[Idx++]);
1390 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1391 return Tok;
1392}
1393
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001394MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001395 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001396
1397 // Keep track of where we are in the stream, then jump back there
1398 // after reading this macro.
1399 SavedStreamPosition SavedPosition(Stream);
1400
1401 Stream.JumpToBit(Offset);
1402 RecordData Record;
1403 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001404 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001405
Guy Benyei11169dd2012-12-18 14:30:41 +00001406 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001407 // Advance to the next record, but if we get to the end of the block, don't
1408 // pop it (removing all the abbreviations from the cursor) since we want to
1409 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001410 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001411 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1412
1413 switch (Entry.Kind) {
1414 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1415 case llvm::BitstreamEntry::Error:
1416 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001417 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001418 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001419 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001420 case llvm::BitstreamEntry::Record:
1421 // The interesting case.
1422 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001423 }
1424
1425 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001426 Record.clear();
1427 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001428 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001429 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001430 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001431 case PP_MACRO_DIRECTIVE_HISTORY:
1432 return Macro;
1433
Guy Benyei11169dd2012-12-18 14:30:41 +00001434 case PP_MACRO_OBJECT_LIKE:
1435 case PP_MACRO_FUNCTION_LIKE: {
1436 // If we already have a macro, that means that we've hit the end
1437 // of the definition of the macro we were looking for. We're
1438 // done.
1439 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001440 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001441
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001442 unsigned NextIndex = 1; // Skip identifier ID.
1443 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001444 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001445 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001446 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001447 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001448 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001449
Guy Benyei11169dd2012-12-18 14:30:41 +00001450 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1451 // Decode function-like macro info.
1452 bool isC99VarArgs = Record[NextIndex++];
1453 bool isGNUVarArgs = Record[NextIndex++];
1454 bool hasCommaPasting = Record[NextIndex++];
1455 MacroArgs.clear();
1456 unsigned NumArgs = Record[NextIndex++];
1457 for (unsigned i = 0; i != NumArgs; ++i)
1458 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1459
1460 // Install function-like macro info.
1461 MI->setIsFunctionLike();
1462 if (isC99VarArgs) MI->setIsC99Varargs();
1463 if (isGNUVarArgs) MI->setIsGNUVarargs();
1464 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001465 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001466 }
1467
Guy Benyei11169dd2012-12-18 14:30:41 +00001468 // Remember that we saw this macro last so that we add the tokens that
1469 // form its body to it.
1470 Macro = MI;
1471
1472 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1473 Record[NextIndex]) {
1474 // We have a macro definition. Register the association
1475 PreprocessedEntityID
1476 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1477 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001478 PreprocessingRecord::PPEntityID PPID =
1479 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1480 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1481 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001482 if (PPDef)
1483 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001484 }
1485
1486 ++NumMacrosRead;
1487 break;
1488 }
1489
1490 case PP_TOKEN: {
1491 // If we see a TOKEN before a PP_MACRO_*, then the file is
1492 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001493 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001494
John McCallf413f5e2013-05-03 00:10:13 +00001495 unsigned Idx = 0;
1496 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001497 Macro->AddTokenToBody(Tok);
1498 break;
1499 }
1500 }
1501 }
1502}
1503
1504PreprocessedEntityID
1505ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1506 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1507 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1508 assert(I != M.PreprocessedEntityRemap.end()
1509 && "Invalid index into preprocessed entity index remap");
1510
1511 return LocalID + I->second;
1512}
1513
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001514unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1515 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001516}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001517
Guy Benyei11169dd2012-12-18 14:30:41 +00001518HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001519HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001520 internal_key_type ikey = {FE->getSize(),
1521 M.HasTimestamps ? FE->getModificationTime() : 0,
1522 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001523 return ikey;
1524}
Guy Benyei11169dd2012-12-18 14:30:41 +00001525
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001526bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001527 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001528 return false;
1529
Richard Smith7ed1bc92014-12-05 22:42:13 +00001530 if (llvm::sys::path::is_absolute(a.Filename) &&
1531 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001532 return true;
1533
Guy Benyei11169dd2012-12-18 14:30:41 +00001534 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001535 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001536 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1537 if (!Key.Imported)
1538 return FileMgr.getFile(Key.Filename);
1539
1540 std::string Resolved = Key.Filename;
1541 Reader.ResolveImportedPath(M, Resolved);
1542 return FileMgr.getFile(Resolved);
1543 };
1544
1545 const FileEntry *FEA = GetFile(a);
1546 const FileEntry *FEB = GetFile(b);
1547 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001548}
1549
1550std::pair<unsigned, unsigned>
1551HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001552 using namespace llvm::support;
1553 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001554 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001555 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001556}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001557
1558HeaderFileInfoTrait::internal_key_type
1559HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001560 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001561 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001562 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1563 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001564 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001565 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001566 return ikey;
1567}
1568
Guy Benyei11169dd2012-12-18 14:30:41 +00001569HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001570HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001571 unsigned DataLen) {
1572 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001573 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001574 HeaderFileInfo HFI;
1575 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001576 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1577 HFI.isImport |= (Flags >> 4) & 0x01;
1578 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1579 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001580 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001581 // FIXME: Find a better way to handle this. Maybe just store a
1582 // "has been included" flag?
1583 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1584 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001585 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1586 M, endian::readNext<uint32_t, little, unaligned>(d));
1587 if (unsigned FrameworkOffset =
1588 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001589 // The framework offset is 1 greater than the actual offset,
1590 // since 0 is used as an indicator for "no framework name".
1591 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1592 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1593 }
Richard Smith386bb072015-08-18 23:42:23 +00001594
1595 assert((End - d) % 4 == 0 &&
1596 "Wrong data length in HeaderFileInfo deserialization");
1597 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001598 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001599 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1600 LocalSMID >>= 2;
1601
1602 // This header is part of a module. Associate it with the module to enable
1603 // implicit module import.
1604 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1605 Module *Mod = Reader.getSubmodule(GlobalSMID);
1606 FileManager &FileMgr = Reader.getFileManager();
1607 ModuleMap &ModMap =
1608 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1609
1610 std::string Filename = key.Filename;
1611 if (key.Imported)
1612 Reader.ResolveImportedPath(M, Filename);
1613 // FIXME: This is not always the right filename-as-written, but we're not
1614 // going to use this information to rebuild the module, so it doesn't make
1615 // a lot of difference.
1616 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001617 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1618 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001619 }
1620
Guy Benyei11169dd2012-12-18 14:30:41 +00001621 // This HeaderFileInfo was externally loaded.
1622 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001623 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001624 return HFI;
1625}
1626
Richard Smithd7329392015-04-21 21:46:32 +00001627void ASTReader::addPendingMacro(IdentifierInfo *II,
1628 ModuleFile *M,
1629 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001630 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1631 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001632}
1633
1634void ASTReader::ReadDefinedMacros() {
1635 // Note that we are loading defined macros.
1636 Deserializing Macros(this);
1637
Pete Cooper57d3f142015-07-30 17:22:52 +00001638 for (auto &I : llvm::reverse(ModuleMgr)) {
1639 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001640
1641 // If there was no preprocessor block, skip this file.
1642 if (!MacroCursor.getBitStreamReader())
1643 continue;
1644
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001645 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001646 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001647
1648 RecordData Record;
1649 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001650 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1651
1652 switch (E.Kind) {
1653 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1654 case llvm::BitstreamEntry::Error:
1655 Error("malformed block record in AST file");
1656 return;
1657 case llvm::BitstreamEntry::EndBlock:
1658 goto NextCursor;
1659
1660 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001661 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001662 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001663 default: // Default behavior: ignore.
1664 break;
1665
1666 case PP_MACRO_OBJECT_LIKE:
1667 case PP_MACRO_FUNCTION_LIKE:
Pete Cooper57d3f142015-07-30 17:22:52 +00001668 getLocalIdentifier(*I, Record[0]);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001669 break;
1670
1671 case PP_TOKEN:
1672 // Ignore tokens.
1673 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001674 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001675 break;
1676 }
1677 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001678 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001679 }
1680}
1681
1682namespace {
1683 /// \brief Visitor class used to look up identifirs in an AST file.
1684 class IdentifierLookupVisitor {
1685 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001686 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001687 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001688 unsigned &NumIdentifierLookups;
1689 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001690 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001691
Guy Benyei11169dd2012-12-18 14:30:41 +00001692 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001693 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1694 unsigned &NumIdentifierLookups,
1695 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001696 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1697 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001698 NumIdentifierLookups(NumIdentifierLookups),
1699 NumIdentifierLookupHits(NumIdentifierLookupHits),
1700 Found()
1701 {
1702 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001703
1704 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001705 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001706 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001707 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001708
Guy Benyei11169dd2012-12-18 14:30:41 +00001709 ASTIdentifierLookupTable *IdTable
1710 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1711 if (!IdTable)
1712 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001713
1714 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001715 Found);
1716 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001717 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001718 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001719 if (Pos == IdTable->end())
1720 return false;
1721
1722 // Dereferencing the iterator has the effect of building the
1723 // IdentifierInfo node and populating it with the various
1724 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001725 ++NumIdentifierLookupHits;
1726 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001727 return true;
1728 }
1729
1730 // \brief Retrieve the identifier info found within the module
1731 // files.
1732 IdentifierInfo *getIdentifierInfo() const { return Found; }
1733 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001734}
Guy Benyei11169dd2012-12-18 14:30:41 +00001735
1736void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1737 // Note that we are loading an identifier.
1738 Deserializing AnIdentifier(this);
1739
1740 unsigned PriorGeneration = 0;
1741 if (getContext().getLangOpts().Modules)
1742 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001743
1744 // If there is a global index, look there first to determine which modules
1745 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001746 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001747 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001748 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001749 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1750 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001751 }
1752 }
1753
Douglas Gregor7211ac12013-01-25 23:32:03 +00001754 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001755 NumIdentifierLookups,
1756 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001757 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001758 markIdentifierUpToDate(&II);
1759}
1760
1761void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1762 if (!II)
1763 return;
1764
1765 II->setOutOfDate(false);
1766
1767 // Update the generation for this identifier.
1768 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001769 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001770}
1771
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001772void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1773 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001774 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001775
1776 BitstreamCursor &Cursor = M.MacroCursor;
1777 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001778 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001779
Richard Smith713369b2015-04-23 20:40:50 +00001780 struct ModuleMacroRecord {
1781 SubmoduleID SubModID;
1782 MacroInfo *MI;
1783 SmallVector<SubmoduleID, 8> Overrides;
1784 };
1785 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001786
Richard Smithd7329392015-04-21 21:46:32 +00001787 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1788 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1789 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001790 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001791 while (true) {
1792 llvm::BitstreamEntry Entry =
1793 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1794 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1795 Error("malformed block record in AST file");
1796 return;
1797 }
1798
1799 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001800 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001801 case PP_MACRO_DIRECTIVE_HISTORY:
1802 break;
1803
1804 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001805 ModuleMacros.push_back(ModuleMacroRecord());
1806 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001807 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1808 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001809 for (int I = 2, N = Record.size(); I != N; ++I)
1810 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001811 continue;
1812 }
1813
1814 default:
1815 Error("malformed block record in AST file");
1816 return;
1817 }
1818
1819 // We found the macro directive history; that's the last record
1820 // for this macro.
1821 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001822 }
1823
Richard Smithd7329392015-04-21 21:46:32 +00001824 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001825 {
1826 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001827 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001828 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001829 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001830 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001831 Module *Mod = getSubmodule(ModID);
1832 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001833 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001834 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001835 }
1836
1837 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001838 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001839 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001840 }
1841 }
1842
1843 // Don't read the directive history for a module; we don't have anywhere
1844 // to put it.
1845 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1846 return;
1847
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001848 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001849 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001850 unsigned Idx = 0, N = Record.size();
1851 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001852 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001853 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001854 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1855 switch (K) {
1856 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001857 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001858 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001859 break;
1860 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001861 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001862 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001863 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001864 }
1865 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001866 bool isPublic = Record[Idx++];
1867 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1868 break;
1869 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001870
1871 if (!Latest)
1872 Latest = MD;
1873 if (Earliest)
1874 Earliest->setPrevious(MD);
1875 Earliest = MD;
1876 }
1877
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001878 if (Latest)
1879 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001880}
1881
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001882ASTReader::InputFileInfo
1883ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001884 // Go find this input file.
1885 BitstreamCursor &Cursor = F.InputFilesCursor;
1886 SavedStreamPosition SavedPosition(Cursor);
1887 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1888
1889 unsigned Code = Cursor.ReadCode();
1890 RecordData Record;
1891 StringRef Blob;
1892
1893 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1894 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1895 "invalid record type for input file");
1896 (void)Result;
1897
1898 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00001899 InputFileInfo R;
1900 R.StoredSize = static_cast<off_t>(Record[1]);
1901 R.StoredTime = static_cast<time_t>(Record[2]);
1902 R.Overridden = static_cast<bool>(Record[3]);
1903 R.Transient = static_cast<bool>(Record[4]);
1904 R.Filename = Blob;
1905 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00001906 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001907}
1908
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001909InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001910 // If this ID is bogus, just return an empty input file.
1911 if (ID == 0 || ID > F.InputFilesLoaded.size())
1912 return InputFile();
1913
1914 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001915 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001916 return F.InputFilesLoaded[ID-1];
1917
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001918 if (F.InputFilesLoaded[ID-1].isNotFound())
1919 return InputFile();
1920
Guy Benyei11169dd2012-12-18 14:30:41 +00001921 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001922 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001923 SavedStreamPosition SavedPosition(Cursor);
1924 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1925
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001926 InputFileInfo FI = readInputFileInfo(F, ID);
1927 off_t StoredSize = FI.StoredSize;
1928 time_t StoredTime = FI.StoredTime;
1929 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001930 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001931 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001932
Richard Smitha8cfffa2015-11-26 02:04:16 +00001933 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00001934
1935 // If we didn't find the file, resolve it relative to the
1936 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001937 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001938 F.OriginalDir != CurrentDir) {
1939 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1940 F.OriginalDir,
1941 CurrentDir);
1942 if (!Resolved.empty())
1943 File = FileMgr.getFile(Resolved);
1944 }
1945
1946 // For an overridden file, create a virtual file with the stored
1947 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00001948 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00001949 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00001950
Craig Toppera13603a2014-05-22 05:54:18 +00001951 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001952 if (Complain) {
1953 std::string ErrorStr = "could not find file '";
1954 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00001955 ErrorStr += "' referenced by AST file '";
1956 ErrorStr += F.FileName;
1957 ErrorStr += "'";
Ben Langmuir198c1682014-03-07 07:27:49 +00001958 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001959 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001960 // Record that we didn't find the file.
1961 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1962 return InputFile();
1963 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001964
Ben Langmuir198c1682014-03-07 07:27:49 +00001965 // Check if there was a request to override the contents of the file
1966 // that was part of the precompiled header. Overridding such a file
1967 // can lead to problems when lexing using the source locations from the
1968 // PCH.
1969 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00001970 // FIXME: Reject if the overrides are different.
1971 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001972 if (Complain)
1973 Error(diag::err_fe_pch_file_overridden, Filename);
1974 // After emitting the diagnostic, recover by disabling the override so
1975 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00001976 //
1977 // FIXME: This recovery is just as broken as the original state; there may
1978 // be another precompiled module that's using the overridden contents, or
1979 // we might be half way through parsing it. Instead, we should treat the
1980 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00001981 SM.disableFileContentsOverride(File);
1982 // The FileEntry is a virtual file entry with the size of the contents
1983 // that would override the original contents. Set it to the original's
1984 // size/time.
1985 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1986 StoredSize, StoredTime);
1987 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001988
Ben Langmuir198c1682014-03-07 07:27:49 +00001989 bool IsOutOfDate = false;
1990
1991 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001992 if (!Overridden && //
1993 (StoredSize != File->getSize() ||
1994#if defined(LLVM_ON_WIN32)
1995 false
1996#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001997 // In our regression testing, the Windows file system seems to
1998 // have inconsistent modification times that sometimes
1999 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00002000 //
Richard Smithe75ee0f2015-08-17 07:13:32 +00002001 // FIXME: This probably also breaks HeaderFileInfo lookups on Windows.
2002 (StoredTime && StoredTime != File->getModificationTime() &&
2003 !DisableValidation)
Guy Benyei11169dd2012-12-18 14:30:41 +00002004#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002005 )) {
2006 if (Complain) {
2007 // Build a list of the PCH imports that got us here (in reverse).
2008 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2009 while (ImportStack.back()->ImportedBy.size() > 0)
2010 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002011
Ben Langmuir198c1682014-03-07 07:27:49 +00002012 // The top-level PCH is stale.
2013 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2014 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002015
Ben Langmuir198c1682014-03-07 07:27:49 +00002016 // Print the import stack.
2017 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2018 Diag(diag::note_pch_required_by)
2019 << Filename << ImportStack[0]->FileName;
2020 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002021 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002022 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002023 }
2024
Ben Langmuir198c1682014-03-07 07:27:49 +00002025 if (!Diags.isDiagnosticInFlight())
2026 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002027 }
2028
Ben Langmuir198c1682014-03-07 07:27:49 +00002029 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002030 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002031 // FIXME: If the file is overridden and we've already opened it,
2032 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002033
Richard Smitha8cfffa2015-11-26 02:04:16 +00002034 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002035
2036 // Note that we've loaded this input file.
2037 F.InputFilesLoaded[ID-1] = IF;
2038 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002039}
2040
Richard Smith7ed1bc92014-12-05 22:42:13 +00002041/// \brief If we are loading a relocatable PCH or module file, and the filename
2042/// is not an absolute path, add the system or module root to the beginning of
2043/// the file name.
2044void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2045 // Resolve relative to the base directory, if we have one.
2046 if (!M.BaseDirectory.empty())
2047 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002048}
2049
Richard Smith7ed1bc92014-12-05 22:42:13 +00002050void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002051 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2052 return;
2053
Richard Smith7ed1bc92014-12-05 22:42:13 +00002054 SmallString<128> Buffer;
2055 llvm::sys::path::append(Buffer, Prefix, Filename);
2056 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002057}
2058
Richard Smith0f99d6a2015-08-09 08:48:41 +00002059static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2060 switch (ARR) {
2061 case ASTReader::Failure: return true;
2062 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2063 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2064 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2065 case ASTReader::ConfigurationMismatch:
2066 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2067 case ASTReader::HadErrors: return true;
2068 case ASTReader::Success: return false;
2069 }
2070
2071 llvm_unreachable("unknown ASTReadResult");
2072}
2073
Richard Smith0516b182015-09-08 19:40:14 +00002074ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2075 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2076 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2077 std::string &SuggestedPredefines) {
2078 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2079 return Failure;
2080
2081 // Read all of the records in the options block.
2082 RecordData Record;
2083 ASTReadResult Result = Success;
2084 while (1) {
2085 llvm::BitstreamEntry Entry = Stream.advance();
2086
2087 switch (Entry.Kind) {
2088 case llvm::BitstreamEntry::Error:
2089 case llvm::BitstreamEntry::SubBlock:
2090 return Failure;
2091
2092 case llvm::BitstreamEntry::EndBlock:
2093 return Result;
2094
2095 case llvm::BitstreamEntry::Record:
2096 // The interesting case.
2097 break;
2098 }
2099
2100 // Read and process a record.
2101 Record.clear();
2102 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2103 case LANGUAGE_OPTIONS: {
2104 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2105 if (ParseLanguageOptions(Record, Complain, Listener,
2106 AllowCompatibleConfigurationMismatch))
2107 Result = ConfigurationMismatch;
2108 break;
2109 }
2110
2111 case TARGET_OPTIONS: {
2112 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2113 if (ParseTargetOptions(Record, Complain, Listener,
2114 AllowCompatibleConfigurationMismatch))
2115 Result = ConfigurationMismatch;
2116 break;
2117 }
2118
2119 case DIAGNOSTIC_OPTIONS: {
2120 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2121 if (!AllowCompatibleConfigurationMismatch &&
2122 ParseDiagnosticOptions(Record, Complain, Listener))
2123 return OutOfDate;
2124 break;
2125 }
2126
2127 case FILE_SYSTEM_OPTIONS: {
2128 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2129 if (!AllowCompatibleConfigurationMismatch &&
2130 ParseFileSystemOptions(Record, Complain, Listener))
2131 Result = ConfigurationMismatch;
2132 break;
2133 }
2134
2135 case HEADER_SEARCH_OPTIONS: {
2136 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2137 if (!AllowCompatibleConfigurationMismatch &&
2138 ParseHeaderSearchOptions(Record, Complain, Listener))
2139 Result = ConfigurationMismatch;
2140 break;
2141 }
2142
2143 case PREPROCESSOR_OPTIONS:
2144 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2145 if (!AllowCompatibleConfigurationMismatch &&
2146 ParsePreprocessorOptions(Record, Complain, Listener,
2147 SuggestedPredefines))
2148 Result = ConfigurationMismatch;
2149 break;
2150 }
2151 }
2152}
2153
Guy Benyei11169dd2012-12-18 14:30:41 +00002154ASTReader::ASTReadResult
2155ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002156 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002157 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002158 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002159 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002160 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002161
2162 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2163 Error("malformed block record in AST file");
2164 return Failure;
2165 }
2166
2167 // Read all of the records and blocks in the control block.
2168 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002169 unsigned NumInputs = 0;
2170 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002171 while (1) {
2172 llvm::BitstreamEntry Entry = Stream.advance();
2173
2174 switch (Entry.Kind) {
2175 case llvm::BitstreamEntry::Error:
2176 Error("malformed block record in AST file");
2177 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002178 case llvm::BitstreamEntry::EndBlock: {
2179 // Validate input files.
2180 const HeaderSearchOptions &HSOpts =
2181 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002182
Richard Smitha1825302014-10-23 22:18:29 +00002183 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002184 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2185 // loaded module files, ignore missing inputs.
2186 if (!DisableValidation && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002187 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002188
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002189 // If we are reading a module, we will create a verification timestamp,
2190 // so we verify all input files. Otherwise, verify only user input
2191 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002192
2193 unsigned N = NumUserInputs;
2194 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002195 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002196 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002197 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002198 N = NumInputs;
2199
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002200 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002201 InputFile IF = getInputFile(F, I+1, Complain);
2202 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002203 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002204 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002205 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002206
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002207 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002208 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002209
Ben Langmuircb69b572014-03-07 06:40:32 +00002210 if (Listener && Listener->needsInputFileVisitation()) {
2211 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2212 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002213 for (unsigned I = 0; I < N; ++I) {
2214 bool IsSystem = I >= NumUserInputs;
2215 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002216 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2217 F.Kind == MK_ExplicitModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002218 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002219 }
2220
Richard Smith8a308ec2015-11-05 00:54:55 +00002221 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002222 }
2223
Chris Lattnere7b154b2013-01-19 21:39:22 +00002224 case llvm::BitstreamEntry::SubBlock:
2225 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002226 case INPUT_FILES_BLOCK_ID:
2227 F.InputFilesCursor = Stream;
2228 if (Stream.SkipBlock() || // Skip with the main cursor
2229 // Read the abbreviations
2230 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2231 Error("malformed block record in AST file");
2232 return Failure;
2233 }
2234 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002235
2236 case OPTIONS_BLOCK_ID:
2237 // If we're reading the first module for this group, check its options
2238 // are compatible with ours. For modules it imports, no further checking
2239 // is required, because we checked them when we built it.
2240 if (Listener && !ImportedBy) {
2241 // Should we allow the configuration of the module file to differ from
2242 // the configuration of the current translation unit in a compatible
2243 // way?
2244 //
2245 // FIXME: Allow this for files explicitly specified with -include-pch.
2246 bool AllowCompatibleConfigurationMismatch =
2247 F.Kind == MK_ExplicitModule;
2248
Richard Smith8a308ec2015-11-05 00:54:55 +00002249 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2250 AllowCompatibleConfigurationMismatch,
2251 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002252 if (Result == Failure) {
2253 Error("malformed block record in AST file");
2254 return Result;
2255 }
2256
Richard Smith8a308ec2015-11-05 00:54:55 +00002257 if (DisableValidation ||
2258 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2259 Result = Success;
2260
2261 // If we've diagnosed a problem, we're done.
2262 if (Result != Success &&
2263 isDiagnosedResult(Result, ClientLoadCapabilities))
Richard Smith0516b182015-09-08 19:40:14 +00002264 return Result;
2265 } else if (Stream.SkipBlock()) {
2266 Error("malformed block record in AST file");
2267 return Failure;
2268 }
2269 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002270
Guy Benyei11169dd2012-12-18 14:30:41 +00002271 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002272 if (Stream.SkipBlock()) {
2273 Error("malformed block record in AST file");
2274 return Failure;
2275 }
2276 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002277 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002278
2279 case llvm::BitstreamEntry::Record:
2280 // The interesting case.
2281 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002282 }
2283
2284 // Read and process a record.
2285 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002286 StringRef Blob;
2287 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 case METADATA: {
2289 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2290 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002291 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2292 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002293 return VersionMismatch;
2294 }
2295
Richard Smithe75ee0f2015-08-17 07:13:32 +00002296 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002297 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2298 Diag(diag::err_pch_with_compiler_errors);
2299 return HadErrors;
2300 }
2301
2302 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002303 // Relative paths in a relocatable PCH are relative to our sysroot.
2304 if (F.RelocatablePCH)
2305 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002306
Richard Smithe75ee0f2015-08-17 07:13:32 +00002307 F.HasTimestamps = Record[5];
2308
Guy Benyei11169dd2012-12-18 14:30:41 +00002309 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002310 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002311 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2312 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002313 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002314 return VersionMismatch;
2315 }
2316 break;
2317 }
2318
Ben Langmuir487ea142014-10-23 18:05:36 +00002319 case SIGNATURE:
2320 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2321 F.Signature = Record[0];
2322 break;
2323
Guy Benyei11169dd2012-12-18 14:30:41 +00002324 case IMPORTS: {
2325 // Load each of the imported PCH files.
2326 unsigned Idx = 0, N = Record.size();
2327 while (Idx < N) {
2328 // Read information about the AST file.
2329 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2330 // The import location will be the local one for now; we will adjust
2331 // all import locations of module imports after the global source
2332 // location info are setup.
2333 SourceLocation ImportLoc =
2334 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002335 off_t StoredSize = (off_t)Record[Idx++];
2336 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002337 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002338 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002339
Richard Smith0f99d6a2015-08-09 08:48:41 +00002340 // If our client can't cope with us being out of date, we can't cope with
2341 // our dependency being missing.
2342 unsigned Capabilities = ClientLoadCapabilities;
2343 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2344 Capabilities &= ~ARR_Missing;
2345
Guy Benyei11169dd2012-12-18 14:30:41 +00002346 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002347 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2348 Loaded, StoredSize, StoredModTime,
2349 StoredSignature, Capabilities);
2350
2351 // If we diagnosed a problem, produce a backtrace.
2352 if (isDiagnosedResult(Result, Capabilities))
2353 Diag(diag::note_module_file_imported_by)
2354 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2355
2356 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002357 case Failure: return Failure;
2358 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002359 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002360 case OutOfDate: return OutOfDate;
2361 case VersionMismatch: return VersionMismatch;
2362 case ConfigurationMismatch: return ConfigurationMismatch;
2363 case HadErrors: return HadErrors;
2364 case Success: break;
2365 }
2366 }
2367 break;
2368 }
2369
Guy Benyei11169dd2012-12-18 14:30:41 +00002370 case ORIGINAL_FILE:
2371 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002372 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002373 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002374 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002375 break;
2376
2377 case ORIGINAL_FILE_ID:
2378 F.OriginalSourceFileID = FileID::get(Record[0]);
2379 break;
2380
2381 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002382 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002383 break;
2384
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002385 case MODULE_NAME:
2386 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002387 if (Listener)
2388 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002389 break;
2390
Richard Smith223d3f22014-12-06 03:21:08 +00002391 case MODULE_DIRECTORY: {
2392 assert(!F.ModuleName.empty() &&
2393 "MODULE_DIRECTORY found before MODULE_NAME");
2394 // If we've already loaded a module map file covering this module, we may
2395 // have a better path for it (relative to the current build).
2396 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2397 if (M && M->Directory) {
2398 // If we're implicitly loading a module, the base directory can't
2399 // change between the build and use.
2400 if (F.Kind != MK_ExplicitModule) {
2401 const DirectoryEntry *BuildDir =
2402 PP.getFileManager().getDirectory(Blob);
2403 if (!BuildDir || BuildDir != M->Directory) {
2404 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2405 Diag(diag::err_imported_module_relocated)
2406 << F.ModuleName << Blob << M->Directory->getName();
2407 return OutOfDate;
2408 }
2409 }
2410 F.BaseDirectory = M->Directory->getName();
2411 } else {
2412 F.BaseDirectory = Blob;
2413 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002414 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002415 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002416
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002417 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002418 if (ASTReadResult Result =
2419 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2420 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002421 break;
2422
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002423 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002424 NumInputs = Record[0];
2425 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002426 F.InputFileOffsets =
2427 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002428 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 break;
2430 }
2431 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002432}
2433
Ben Langmuir2c9af442014-04-10 17:57:43 +00002434ASTReader::ASTReadResult
2435ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002436 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002437
2438 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2439 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002440 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 }
2442
2443 // Read all of the records and blocks for the AST file.
2444 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002445 while (1) {
2446 llvm::BitstreamEntry Entry = Stream.advance();
2447
2448 switch (Entry.Kind) {
2449 case llvm::BitstreamEntry::Error:
2450 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002451 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002452 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002453 // Outside of C++, we do not store a lookup map for the translation unit.
2454 // Instead, mark it as needing a lookup map to be built if this module
2455 // contains any declarations lexically within it (which it always does!).
2456 // This usually has no cost, since we very rarely need the lookup map for
2457 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002458 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002459 if (DC->hasExternalLexicalStorage() &&
2460 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002461 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002462
Ben Langmuir2c9af442014-04-10 17:57:43 +00002463 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002465 case llvm::BitstreamEntry::SubBlock:
2466 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002467 case DECLTYPES_BLOCK_ID:
2468 // We lazily load the decls block, but we want to set up the
2469 // DeclsCursor cursor to point into it. Clone our current bitcode
2470 // cursor to it, enter the block and read the abbrevs in that block.
2471 // With the main cursor, we just skip over it.
2472 F.DeclsCursor = Stream;
2473 if (Stream.SkipBlock() || // Skip with the main cursor.
2474 // Read the abbrevs.
2475 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2476 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002477 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002478 }
2479 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002480
Guy Benyei11169dd2012-12-18 14:30:41 +00002481 case PREPROCESSOR_BLOCK_ID:
2482 F.MacroCursor = Stream;
2483 if (!PP.getExternalSource())
2484 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002485
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 if (Stream.SkipBlock() ||
2487 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2488 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002489 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 }
2491 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2492 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002493
Guy Benyei11169dd2012-12-18 14:30:41 +00002494 case PREPROCESSOR_DETAIL_BLOCK_ID:
2495 F.PreprocessorDetailCursor = Stream;
2496 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002497 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002499 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002500 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002501 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002503 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2504
Guy Benyei11169dd2012-12-18 14:30:41 +00002505 if (!PP.getPreprocessingRecord())
2506 PP.createPreprocessingRecord();
2507 if (!PP.getPreprocessingRecord()->getExternalSource())
2508 PP.getPreprocessingRecord()->SetExternalSource(*this);
2509 break;
2510
2511 case SOURCE_MANAGER_BLOCK_ID:
2512 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002513 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002514 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002515
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002517 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2518 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002520
Guy Benyei11169dd2012-12-18 14:30:41 +00002521 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002522 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 if (Stream.SkipBlock() ||
2524 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2525 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002526 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002527 }
2528 CommentsCursors.push_back(std::make_pair(C, &F));
2529 break;
2530 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002531
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002533 if (Stream.SkipBlock()) {
2534 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002535 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002536 }
2537 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 }
2539 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002540
2541 case llvm::BitstreamEntry::Record:
2542 // The interesting case.
2543 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002544 }
2545
2546 // Read and process a record.
2547 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002548 StringRef Blob;
2549 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002550 default: // Default behavior: ignore.
2551 break;
2552
2553 case TYPE_OFFSET: {
2554 if (F.LocalNumTypes != 0) {
2555 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002556 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002557 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002558 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 F.LocalNumTypes = Record[0];
2560 unsigned LocalBaseTypeIndex = Record[1];
2561 F.BaseTypeIndex = getTotalNumTypes();
2562
2563 if (F.LocalNumTypes > 0) {
2564 // Introduce the global -> local mapping for types within this module.
2565 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2566
2567 // Introduce the local -> global mapping for types within this module.
2568 F.TypeRemap.insertOrReplace(
2569 std::make_pair(LocalBaseTypeIndex,
2570 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002571
2572 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 }
2574 break;
2575 }
2576
2577 case DECL_OFFSET: {
2578 if (F.LocalNumDecls != 0) {
2579 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002580 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002582 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 F.LocalNumDecls = Record[0];
2584 unsigned LocalBaseDeclID = Record[1];
2585 F.BaseDeclID = getTotalNumDecls();
2586
2587 if (F.LocalNumDecls > 0) {
2588 // Introduce the global -> local mapping for declarations within this
2589 // module.
2590 GlobalDeclMap.insert(
2591 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2592
2593 // Introduce the local -> global mapping for declarations within this
2594 // module.
2595 F.DeclRemap.insertOrReplace(
2596 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2597
2598 // Introduce the global -> local mapping for declarations within this
2599 // module.
2600 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002601
Ben Langmuir52ca6782014-10-20 16:27:32 +00002602 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2603 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 break;
2605 }
2606
2607 case TU_UPDATE_LEXICAL: {
2608 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002609 LexicalContents Contents(
2610 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2611 Blob.data()),
2612 static_cast<unsigned int>(Blob.size() / 4));
2613 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 TU->setHasExternalLexicalStorage(true);
2615 break;
2616 }
2617
2618 case UPDATE_VISIBLE: {
2619 unsigned Idx = 0;
2620 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002621 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002622 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002623 // If we've already loaded the decl, perform the updates when we finish
2624 // loading this block.
2625 if (Decl *D = GetExistingDecl(ID))
2626 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002627 break;
2628 }
2629
2630 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002631 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002632 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002633 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2634 (const unsigned char *)F.IdentifierTableData + Record[0],
2635 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2636 (const unsigned char *)F.IdentifierTableData,
2637 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002638
2639 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2640 }
2641 break;
2642
2643 case IDENTIFIER_OFFSET: {
2644 if (F.LocalNumIdentifiers != 0) {
2645 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002646 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002647 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002648 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002649 F.LocalNumIdentifiers = Record[0];
2650 unsigned LocalBaseIdentifierID = Record[1];
2651 F.BaseIdentifierID = getTotalNumIdentifiers();
2652
2653 if (F.LocalNumIdentifiers > 0) {
2654 // Introduce the global -> local mapping for identifiers within this
2655 // module.
2656 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2657 &F));
2658
2659 // Introduce the local -> global mapping for identifiers within this
2660 // module.
2661 F.IdentifierRemap.insertOrReplace(
2662 std::make_pair(LocalBaseIdentifierID,
2663 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002664
Ben Langmuir52ca6782014-10-20 16:27:32 +00002665 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2666 + F.LocalNumIdentifiers);
2667 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002668 break;
2669 }
2670
Richard Smith33e0f7e2015-07-22 02:08:40 +00002671 case INTERESTING_IDENTIFIERS:
2672 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2673 break;
2674
Ben Langmuir332aafe2014-01-31 01:06:56 +00002675 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002676 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2677 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002678 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002679 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 break;
2681
2682 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002683 if (SpecialTypes.empty()) {
2684 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2685 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2686 break;
2687 }
2688
2689 if (SpecialTypes.size() != Record.size()) {
2690 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002691 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002692 }
2693
2694 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2695 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2696 if (!SpecialTypes[I])
2697 SpecialTypes[I] = ID;
2698 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2699 // merge step?
2700 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002701 break;
2702
2703 case STATISTICS:
2704 TotalNumStatements += Record[0];
2705 TotalNumMacros += Record[1];
2706 TotalLexicalDeclContexts += Record[2];
2707 TotalVisibleDeclContexts += Record[3];
2708 break;
2709
2710 case UNUSED_FILESCOPED_DECLS:
2711 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2712 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2713 break;
2714
2715 case DELEGATING_CTORS:
2716 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2717 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2718 break;
2719
2720 case WEAK_UNDECLARED_IDENTIFIERS:
2721 if (Record.size() % 4 != 0) {
2722 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002723 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002724 }
2725
2726 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2727 // files. This isn't the way to do it :)
2728 WeakUndeclaredIdentifiers.clear();
2729
2730 // Translate the weak, undeclared identifiers into global IDs.
2731 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2732 WeakUndeclaredIdentifiers.push_back(
2733 getGlobalIdentifierID(F, Record[I++]));
2734 WeakUndeclaredIdentifiers.push_back(
2735 getGlobalIdentifierID(F, Record[I++]));
2736 WeakUndeclaredIdentifiers.push_back(
2737 ReadSourceLocation(F, Record, I).getRawEncoding());
2738 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2739 }
2740 break;
2741
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002743 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002744 F.LocalNumSelectors = Record[0];
2745 unsigned LocalBaseSelectorID = Record[1];
2746 F.BaseSelectorID = getTotalNumSelectors();
2747
2748 if (F.LocalNumSelectors > 0) {
2749 // Introduce the global -> local mapping for selectors within this
2750 // module.
2751 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2752
2753 // Introduce the local -> global mapping for selectors within this
2754 // module.
2755 F.SelectorRemap.insertOrReplace(
2756 std::make_pair(LocalBaseSelectorID,
2757 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002758
2759 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002760 }
2761 break;
2762 }
2763
2764 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002765 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 if (Record[0])
2767 F.SelectorLookupTable
2768 = ASTSelectorLookupTable::Create(
2769 F.SelectorLookupTableData + Record[0],
2770 F.SelectorLookupTableData,
2771 ASTSelectorLookupTrait(*this, F));
2772 TotalNumMethodPoolEntries += Record[1];
2773 break;
2774
2775 case REFERENCED_SELECTOR_POOL:
2776 if (!Record.empty()) {
2777 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2778 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2779 Record[Idx++]));
2780 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2781 getRawEncoding());
2782 }
2783 }
2784 break;
2785
2786 case PP_COUNTER_VALUE:
2787 if (!Record.empty() && Listener)
2788 Listener->ReadCounter(F, Record[0]);
2789 break;
2790
2791 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002792 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002793 F.NumFileSortedDecls = Record[0];
2794 break;
2795
2796 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002797 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002798 F.LocalNumSLocEntries = Record[0];
2799 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002800 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002801 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002802 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002803 if (!F.SLocEntryBaseID) {
2804 Error("ran out of source locations");
2805 break;
2806 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002807 // Make our entry in the range map. BaseID is negative and growing, so
2808 // we invert it. Because we invert it, though, we need the other end of
2809 // the range.
2810 unsigned RangeStart =
2811 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2812 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2813 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2814
2815 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2816 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2817 GlobalSLocOffsetMap.insert(
2818 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2819 - SLocSpaceSize,&F));
2820
2821 // Initialize the remapping table.
2822 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002823 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002824 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002825 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002826 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2827
2828 TotalNumSLocEntries += F.LocalNumSLocEntries;
2829 break;
2830 }
2831
2832 case MODULE_OFFSET_MAP: {
2833 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002834 const unsigned char *Data = (const unsigned char*)Blob.data();
2835 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002836
2837 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2838 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2839 F.SLocRemap.insert(std::make_pair(0U, 0));
2840 F.SLocRemap.insert(std::make_pair(2U, 1));
2841 }
2842
Guy Benyei11169dd2012-12-18 14:30:41 +00002843 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002844 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2845 RemapBuilder;
2846 RemapBuilder SLocRemap(F.SLocRemap);
2847 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2848 RemapBuilder MacroRemap(F.MacroRemap);
2849 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2850 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2851 RemapBuilder SelectorRemap(F.SelectorRemap);
2852 RemapBuilder DeclRemap(F.DeclRemap);
2853 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002854
Richard Smithd8879c82015-08-24 21:59:32 +00002855 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002856 using namespace llvm::support;
2857 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002858 StringRef Name = StringRef((const char*)Data, Len);
2859 Data += Len;
2860 ModuleFile *OM = ModuleMgr.lookup(Name);
2861 if (!OM) {
2862 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002863 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002864 }
2865
Justin Bogner57ba0b22014-03-28 22:03:24 +00002866 uint32_t SLocOffset =
2867 endian::readNext<uint32_t, little, unaligned>(Data);
2868 uint32_t IdentifierIDOffset =
2869 endian::readNext<uint32_t, little, unaligned>(Data);
2870 uint32_t MacroIDOffset =
2871 endian::readNext<uint32_t, little, unaligned>(Data);
2872 uint32_t PreprocessedEntityIDOffset =
2873 endian::readNext<uint32_t, little, unaligned>(Data);
2874 uint32_t SubmoduleIDOffset =
2875 endian::readNext<uint32_t, little, unaligned>(Data);
2876 uint32_t SelectorIDOffset =
2877 endian::readNext<uint32_t, little, unaligned>(Data);
2878 uint32_t DeclIDOffset =
2879 endian::readNext<uint32_t, little, unaligned>(Data);
2880 uint32_t TypeIndexOffset =
2881 endian::readNext<uint32_t, little, unaligned>(Data);
2882
Ben Langmuir785180e2014-10-20 16:27:30 +00002883 uint32_t None = std::numeric_limits<uint32_t>::max();
2884
2885 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2886 RemapBuilder &Remap) {
2887 if (Offset != None)
2888 Remap.insert(std::make_pair(Offset,
2889 static_cast<int>(BaseOffset - Offset)));
2890 };
2891 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2892 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2893 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2894 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2895 PreprocessedEntityRemap);
2896 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2897 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2898 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2899 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002900
2901 // Global -> local mappings.
2902 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2903 }
2904 break;
2905 }
2906
2907 case SOURCE_MANAGER_LINE_TABLE:
2908 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002909 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002910 break;
2911
2912 case SOURCE_LOCATION_PRELOADS: {
2913 // Need to transform from the local view (1-based IDs) to the global view,
2914 // which is based off F.SLocEntryBaseID.
2915 if (!F.PreloadSLocEntries.empty()) {
2916 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002917 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002918 }
2919
2920 F.PreloadSLocEntries.swap(Record);
2921 break;
2922 }
2923
2924 case EXT_VECTOR_DECLS:
2925 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2926 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2927 break;
2928
2929 case VTABLE_USES:
2930 if (Record.size() % 3 != 0) {
2931 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002932 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 }
2934
2935 // Later tables overwrite earlier ones.
2936 // FIXME: Modules will have some trouble with this. This is clearly not
2937 // the right way to do this.
2938 VTableUses.clear();
2939
2940 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2941 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2942 VTableUses.push_back(
2943 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2944 VTableUses.push_back(Record[Idx++]);
2945 }
2946 break;
2947
Guy Benyei11169dd2012-12-18 14:30:41 +00002948 case PENDING_IMPLICIT_INSTANTIATIONS:
2949 if (PendingInstantiations.size() % 2 != 0) {
2950 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002951 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002952 }
2953
2954 if (Record.size() % 2 != 0) {
2955 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002956 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002957 }
2958
2959 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2960 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2961 PendingInstantiations.push_back(
2962 ReadSourceLocation(F, Record, I).getRawEncoding());
2963 }
2964 break;
2965
2966 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002967 if (Record.size() != 2) {
2968 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002969 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002970 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002971 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2972 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2973 break;
2974
2975 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002976 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2977 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2978 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002979
2980 unsigned LocalBasePreprocessedEntityID = Record[0];
2981
2982 unsigned StartingID;
2983 if (!PP.getPreprocessingRecord())
2984 PP.createPreprocessingRecord();
2985 if (!PP.getPreprocessingRecord()->getExternalSource())
2986 PP.getPreprocessingRecord()->SetExternalSource(*this);
2987 StartingID
2988 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002989 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002990 F.BasePreprocessedEntityID = StartingID;
2991
2992 if (F.NumPreprocessedEntities > 0) {
2993 // Introduce the global -> local mapping for preprocessed entities in
2994 // this module.
2995 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2996
2997 // Introduce the local -> global mapping for preprocessed entities in
2998 // this module.
2999 F.PreprocessedEntityRemap.insertOrReplace(
3000 std::make_pair(LocalBasePreprocessedEntityID,
3001 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3002 }
3003
3004 break;
3005 }
3006
3007 case DECL_UPDATE_OFFSETS: {
3008 if (Record.size() % 2 != 0) {
3009 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003010 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003012 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3013 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3014 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3015
3016 // If we've already loaded the decl, perform the updates when we finish
3017 // loading this block.
3018 if (Decl *D = GetExistingDecl(ID))
3019 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3020 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003021 break;
3022 }
3023
3024 case DECL_REPLACEMENTS: {
3025 if (Record.size() % 3 != 0) {
3026 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003027 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003028 }
3029 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3030 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3031 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3032 break;
3033 }
3034
3035 case OBJC_CATEGORIES_MAP: {
3036 if (F.LocalNumObjCCategoriesInMap != 0) {
3037 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003038 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003039 }
3040
3041 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003042 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003043 break;
3044 }
3045
3046 case OBJC_CATEGORIES:
3047 F.ObjCCategories.swap(Record);
3048 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003049
Guy Benyei11169dd2012-12-18 14:30:41 +00003050 case CXX_BASE_SPECIFIER_OFFSETS: {
3051 if (F.LocalNumCXXBaseSpecifiers != 0) {
3052 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003053 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003054 }
Richard Smithc2bb8182015-03-24 06:36:48 +00003055
Guy Benyei11169dd2012-12-18 14:30:41 +00003056 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003057 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00003058 break;
3059 }
3060
3061 case CXX_CTOR_INITIALIZERS_OFFSETS: {
3062 if (F.LocalNumCXXCtorInitializers != 0) {
3063 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
3064 return Failure;
3065 }
3066
3067 F.LocalNumCXXCtorInitializers = Record[0];
3068 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003069 break;
3070 }
3071
3072 case DIAG_PRAGMA_MAPPINGS:
3073 if (F.PragmaDiagMappings.empty())
3074 F.PragmaDiagMappings.swap(Record);
3075 else
3076 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3077 Record.begin(), Record.end());
3078 break;
3079
3080 case CUDA_SPECIAL_DECL_REFS:
3081 // Later tables overwrite earlier ones.
3082 // FIXME: Modules will have trouble with this.
3083 CUDASpecialDeclRefs.clear();
3084 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3085 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3086 break;
3087
3088 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003089 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003090 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003091 if (Record[0]) {
3092 F.HeaderFileInfoTable
3093 = HeaderFileInfoLookupTable::Create(
3094 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3095 (const unsigned char *)F.HeaderFileInfoTableData,
3096 HeaderFileInfoTrait(*this, F,
3097 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003098 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003099
3100 PP.getHeaderSearchInfo().SetExternalSource(this);
3101 if (!PP.getHeaderSearchInfo().getExternalLookup())
3102 PP.getHeaderSearchInfo().SetExternalLookup(this);
3103 }
3104 break;
3105 }
3106
3107 case FP_PRAGMA_OPTIONS:
3108 // Later tables overwrite earlier ones.
3109 FPPragmaOptions.swap(Record);
3110 break;
3111
3112 case OPENCL_EXTENSIONS:
3113 // Later tables overwrite earlier ones.
3114 OpenCLExtensions.swap(Record);
3115 break;
3116
3117 case TENTATIVE_DEFINITIONS:
3118 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3119 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3120 break;
3121
3122 case KNOWN_NAMESPACES:
3123 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3124 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3125 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003126
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003127 case UNDEFINED_BUT_USED:
3128 if (UndefinedButUsed.size() % 2 != 0) {
3129 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003130 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003131 }
3132
3133 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003134 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003135 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003136 }
3137 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003138 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3139 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003140 ReadSourceLocation(F, Record, I).getRawEncoding());
3141 }
3142 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003143 case DELETE_EXPRS_TO_ANALYZE:
3144 for (unsigned I = 0, N = Record.size(); I != N;) {
3145 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3146 const uint64_t Count = Record[I++];
3147 DelayedDeleteExprs.push_back(Count);
3148 for (uint64_t C = 0; C < Count; ++C) {
3149 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3150 bool IsArrayForm = Record[I++] == 1;
3151 DelayedDeleteExprs.push_back(IsArrayForm);
3152 }
3153 }
3154 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003155
Guy Benyei11169dd2012-12-18 14:30:41 +00003156 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003157 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003158 // If we aren't loading a module (which has its own exports), make
3159 // all of the imported modules visible.
3160 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003161 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3162 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3163 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3164 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003165 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003166 }
3167 }
3168 break;
3169 }
3170
Guy Benyei11169dd2012-12-18 14:30:41 +00003171 case MACRO_OFFSET: {
3172 if (F.LocalNumMacros != 0) {
3173 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003174 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003175 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003176 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003177 F.LocalNumMacros = Record[0];
3178 unsigned LocalBaseMacroID = Record[1];
3179 F.BaseMacroID = getTotalNumMacros();
3180
3181 if (F.LocalNumMacros > 0) {
3182 // Introduce the global -> local mapping for macros within this module.
3183 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3184
3185 // Introduce the local -> global mapping for macros within this module.
3186 F.MacroRemap.insertOrReplace(
3187 std::make_pair(LocalBaseMacroID,
3188 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003189
3190 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003191 }
3192 break;
3193 }
3194
Richard Smithe40f2ba2013-08-07 21:41:30 +00003195 case LATE_PARSED_TEMPLATE: {
3196 LateParsedTemplates.append(Record.begin(), Record.end());
3197 break;
3198 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003199
3200 case OPTIMIZE_PRAGMA_OPTIONS:
3201 if (Record.size() != 1) {
3202 Error("invalid pragma optimize record");
3203 return Failure;
3204 }
3205 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3206 break;
Nico Weber72889432014-09-06 01:25:55 +00003207
3208 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3209 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3210 UnusedLocalTypedefNameCandidates.push_back(
3211 getGlobalDeclID(F, Record[I]));
3212 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003213 }
3214 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003215}
3216
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003217ASTReader::ASTReadResult
3218ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3219 const ModuleFile *ImportedBy,
3220 unsigned ClientLoadCapabilities) {
3221 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003222 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003223
Richard Smithe842a472014-10-22 02:05:46 +00003224 if (F.Kind == MK_ExplicitModule) {
3225 // For an explicitly-loaded module, we don't care whether the original
3226 // module map file exists or matches.
3227 return Success;
3228 }
3229
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003230 // Try to resolve ModuleName in the current header search context and
3231 // verify that it is found in the same module map file as we saved. If the
3232 // top-level AST file is a main file, skip this check because there is no
3233 // usable header search context.
3234 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003235 "MODULE_NAME should come before MODULE_MAP_FILE");
3236 if (F.Kind == MK_ImplicitModule &&
3237 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3238 // An implicitly-loaded module file should have its module listed in some
3239 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003240 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003241 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3242 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3243 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003244 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003245 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3246 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3247 // This module was defined by an imported (explicit) module.
3248 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3249 << ASTFE->getName();
3250 else
3251 // This module was built with a different module map.
3252 Diag(diag::err_imported_module_not_found)
3253 << F.ModuleName << F.FileName << ImportedBy->FileName
3254 << F.ModuleMapPath;
3255 }
3256 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003257 }
3258
Richard Smithe842a472014-10-22 02:05:46 +00003259 assert(M->Name == F.ModuleName && "found module with different name");
3260
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003261 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003262 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003263 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3264 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003265 assert(ImportedBy && "top-level import should be verified");
3266 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3267 Diag(diag::err_imported_module_modmap_changed)
3268 << F.ModuleName << ImportedBy->FileName
3269 << ModMap->getName() << F.ModuleMapPath;
3270 return OutOfDate;
3271 }
3272
3273 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3274 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3275 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003276 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003277 const FileEntry *F =
3278 FileMgr.getFile(Filename, false, false);
3279 if (F == nullptr) {
3280 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3281 Error("could not find file '" + Filename +"' referenced by AST file");
3282 return OutOfDate;
3283 }
3284 AdditionalStoredMaps.insert(F);
3285 }
3286
3287 // Check any additional module map files (e.g. module.private.modulemap)
3288 // that are not in the pcm.
3289 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3290 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3291 // Remove files that match
3292 // Note: SmallPtrSet::erase is really remove
3293 if (!AdditionalStoredMaps.erase(ModMap)) {
3294 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3295 Diag(diag::err_module_different_modmap)
3296 << F.ModuleName << /*new*/0 << ModMap->getName();
3297 return OutOfDate;
3298 }
3299 }
3300 }
3301
3302 // Check any additional module map files that are in the pcm, but not
3303 // found in header search. Cases that match are already removed.
3304 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3305 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3306 Diag(diag::err_module_different_modmap)
3307 << F.ModuleName << /*not new*/1 << ModMap->getName();
3308 return OutOfDate;
3309 }
3310 }
3311
3312 if (Listener)
3313 Listener->ReadModuleMapFile(F.ModuleMapPath);
3314 return Success;
3315}
3316
3317
Douglas Gregorc1489562013-02-12 23:36:21 +00003318/// \brief Move the given method to the back of the global list of methods.
3319static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3320 // Find the entry for this selector in the method pool.
3321 Sema::GlobalMethodPool::iterator Known
3322 = S.MethodPool.find(Method->getSelector());
3323 if (Known == S.MethodPool.end())
3324 return;
3325
3326 // Retrieve the appropriate method list.
3327 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3328 : Known->second.second;
3329 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003330 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003331 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003332 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003333 Found = true;
3334 } else {
3335 // Keep searching.
3336 continue;
3337 }
3338 }
3339
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003340 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003341 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003342 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003343 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003344 }
3345}
3346
Richard Smithde711422015-04-23 21:20:19 +00003347void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003348 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003349 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003350 bool wasHidden = D->Hidden;
3351 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003352
Richard Smith49f906a2014-03-01 00:08:04 +00003353 if (wasHidden && SemaObj) {
3354 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3355 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003356 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003357 }
3358 }
3359}
3360
Richard Smith49f906a2014-03-01 00:08:04 +00003361void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003362 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003363 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003364 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003365 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003366 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003367 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003368 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003369
3370 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003371 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003372 // there is nothing more to do.
3373 continue;
3374 }
Richard Smith49f906a2014-03-01 00:08:04 +00003375
Guy Benyei11169dd2012-12-18 14:30:41 +00003376 if (!Mod->isAvailable()) {
3377 // Modules that aren't available cannot be made visible.
3378 continue;
3379 }
3380
3381 // Update the module's name visibility.
3382 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003383
Guy Benyei11169dd2012-12-18 14:30:41 +00003384 // If we've already deserialized any names from this module,
3385 // mark them as visible.
3386 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3387 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003388 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003389 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003390 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003391 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3392 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003393 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003394
Guy Benyei11169dd2012-12-18 14:30:41 +00003395 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003396 SmallVector<Module *, 16> Exports;
3397 Mod->getExportedModules(Exports);
3398 for (SmallVectorImpl<Module *>::iterator
3399 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3400 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003401 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003402 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003403 }
3404 }
3405}
3406
Douglas Gregore060e572013-01-25 01:03:03 +00003407bool ASTReader::loadGlobalIndex() {
3408 if (GlobalIndex)
3409 return false;
3410
3411 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3412 !Context.getLangOpts().Modules)
3413 return true;
3414
3415 // Try to load the global index.
3416 TriedLoadingGlobalIndex = true;
3417 StringRef ModuleCachePath
3418 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3419 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003420 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003421 if (!Result.first)
3422 return true;
3423
3424 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003425 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003426 return false;
3427}
3428
3429bool ASTReader::isGlobalIndexUnavailable() const {
3430 return Context.getLangOpts().Modules && UseGlobalIndex &&
3431 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3432}
3433
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003434static void updateModuleTimestamp(ModuleFile &MF) {
3435 // Overwrite the timestamp file contents so that file's mtime changes.
3436 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003437 std::error_code EC;
3438 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3439 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003440 return;
3441 OS << "Timestamp file\n";
3442}
3443
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003444/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3445/// cursor into the start of the given block ID, returning false on success and
3446/// true on failure.
3447static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3448 while (1) {
3449 llvm::BitstreamEntry Entry = Cursor.advance();
3450 switch (Entry.Kind) {
3451 case llvm::BitstreamEntry::Error:
3452 case llvm::BitstreamEntry::EndBlock:
3453 return true;
3454
3455 case llvm::BitstreamEntry::Record:
3456 // Ignore top-level records.
3457 Cursor.skipRecord(Entry.ID);
3458 break;
3459
3460 case llvm::BitstreamEntry::SubBlock:
3461 if (Entry.ID == BlockID) {
3462 if (Cursor.EnterSubBlock(BlockID))
3463 return true;
3464 // Found it!
3465 return false;
3466 }
3467
3468 if (Cursor.SkipBlock())
3469 return true;
3470 }
3471 }
3472}
3473
Guy Benyei11169dd2012-12-18 14:30:41 +00003474ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3475 ModuleKind Type,
3476 SourceLocation ImportLoc,
3477 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003478 llvm::SaveAndRestore<SourceLocation>
3479 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3480
Richard Smithd1c46742014-04-30 02:24:17 +00003481 // Defer any pending actions until we get to the end of reading the AST file.
3482 Deserializing AnASTFile(this);
3483
Guy Benyei11169dd2012-12-18 14:30:41 +00003484 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003485 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003486
3487 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003488 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003489 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003490 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003491 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003492 ClientLoadCapabilities)) {
3493 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003494 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003495 case OutOfDate:
3496 case VersionMismatch:
3497 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003498 case HadErrors: {
3499 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3500 for (const ImportedModule &IM : Loaded)
3501 LoadedSet.insert(IM.Mod);
3502
Douglas Gregor7029ce12013-03-19 00:28:20 +00003503 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003504 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003505 Context.getLangOpts().Modules
3506 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003507 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003508
3509 // If we find that any modules are unusable, the global index is going
3510 // to be out-of-date. Just remove it.
3511 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003512 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003513 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003514 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003515 case Success:
3516 break;
3517 }
3518
3519 // Here comes stuff that we only do once the entire chain is loaded.
3520
3521 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003522 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3523 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003524 M != MEnd; ++M) {
3525 ModuleFile &F = *M->Mod;
3526
3527 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003528 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3529 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003530
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003531 // Read the extension blocks.
3532 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3533 if (ASTReadResult Result = ReadExtensionBlock(F))
3534 return Result;
3535 }
3536
Guy Benyei11169dd2012-12-18 14:30:41 +00003537 // Once read, set the ModuleFile bit base offset and update the size in
3538 // bits of all files we've seen.
3539 F.GlobalBitOffset = TotalModulesSizeInBits;
3540 TotalModulesSizeInBits += F.SizeInBits;
3541 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3542
3543 // Preload SLocEntries.
3544 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3545 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3546 // Load it through the SourceManager and don't call ReadSLocEntry()
3547 // directly because the entry may have already been loaded in which case
3548 // calling ReadSLocEntry() directly would trigger an assertion in
3549 // SourceManager.
3550 SourceMgr.getLoadedSLocEntryByID(Index);
3551 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003552
3553 // Preload all the pending interesting identifiers by marking them out of
3554 // date.
3555 for (auto Offset : F.PreloadIdentifierOffsets) {
3556 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3557 F.IdentifierTableData + Offset);
3558
3559 ASTIdentifierLookupTrait Trait(*this, F);
3560 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3561 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003562 auto &II = PP.getIdentifierTable().getOwn(Key);
3563 II.setOutOfDate(true);
3564
3565 // Mark this identifier as being from an AST file so that we can track
3566 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003567 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003568
3569 // Associate the ID with the identifier so that the writer can reuse it.
3570 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3571 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003572 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003573 }
3574
Douglas Gregor603cd862013-03-22 18:50:14 +00003575 // Setup the import locations and notify the module manager that we've
3576 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003577 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3578 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003579 M != MEnd; ++M) {
3580 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003581
3582 ModuleMgr.moduleFileAccepted(&F);
3583
3584 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003585 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003586 if (!M->ImportedBy)
3587 F.ImportLoc = M->ImportLoc;
3588 else
3589 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3590 M->ImportLoc.getRawEncoding());
3591 }
3592
Richard Smith33e0f7e2015-07-22 02:08:40 +00003593 if (!Context.getLangOpts().CPlusPlus ||
3594 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3595 // Mark all of the identifiers in the identifier table as being out of date,
3596 // so that various accessors know to check the loaded modules when the
3597 // identifier is used.
3598 //
3599 // For C++ modules, we don't need information on many identifiers (just
3600 // those that provide macros or are poisoned), so we mark all of
3601 // the interesting ones via PreloadIdentifierOffsets.
3602 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3603 IdEnd = PP.getIdentifierTable().end();
3604 Id != IdEnd; ++Id)
3605 Id->second->setOutOfDate(true);
3606 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003607
3608 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003609 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3610 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003611 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3612 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003613
3614 switch (Unresolved.Kind) {
3615 case UnresolvedModuleRef::Conflict:
3616 if (ResolvedMod) {
3617 Module::Conflict Conflict;
3618 Conflict.Other = ResolvedMod;
3619 Conflict.Message = Unresolved.String.str();
3620 Unresolved.Mod->Conflicts.push_back(Conflict);
3621 }
3622 continue;
3623
3624 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003625 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003626 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003628
Douglas Gregorfb912652013-03-20 21:10:35 +00003629 case UnresolvedModuleRef::Export:
3630 if (ResolvedMod || Unresolved.IsWildcard)
3631 Unresolved.Mod->Exports.push_back(
3632 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3633 continue;
3634 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003635 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003636 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003637
3638 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3639 // Might be unnecessary as use declarations are only used to build the
3640 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003641
3642 InitializeContext();
3643
Richard Smith3d8e97e2013-10-18 06:54:39 +00003644 if (SemaObj)
3645 UpdateSema();
3646
Guy Benyei11169dd2012-12-18 14:30:41 +00003647 if (DeserializationListener)
3648 DeserializationListener->ReaderInitialized(this);
3649
3650 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003651 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003652 PrimaryModule.OriginalSourceFileID
3653 = FileID::get(PrimaryModule.SLocEntryBaseID
3654 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3655
3656 // If this AST file is a precompiled preamble, then set the
3657 // preamble file ID of the source manager to the file source file
3658 // from which the preamble was built.
3659 if (Type == MK_Preamble) {
3660 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3661 } else if (Type == MK_MainFile) {
3662 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3663 }
3664 }
3665
3666 // For any Objective-C class definitions we have already loaded, make sure
3667 // that we load any additional categories.
3668 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3669 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3670 ObjCClassesLoaded[I],
3671 PreviousGeneration);
3672 }
Douglas Gregore060e572013-01-25 01:03:03 +00003673
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003674 if (PP.getHeaderSearchInfo()
3675 .getHeaderSearchOpts()
3676 .ModulesValidateOncePerBuildSession) {
3677 // Now we are certain that the module and all modules it depends on are
3678 // up to date. Create or update timestamp files for modules that are
3679 // located in the module cache (not for PCH files that could be anywhere
3680 // in the filesystem).
3681 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3682 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003683 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003684 updateModuleTimestamp(*M.Mod);
3685 }
3686 }
3687 }
3688
Guy Benyei11169dd2012-12-18 14:30:41 +00003689 return Success;
3690}
3691
Ben Langmuir487ea142014-10-23 18:05:36 +00003692static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3693
Ben Langmuir70a1b812015-03-24 04:43:52 +00003694/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3695static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3696 return Stream.Read(8) == 'C' &&
3697 Stream.Read(8) == 'P' &&
3698 Stream.Read(8) == 'C' &&
3699 Stream.Read(8) == 'H';
3700}
3701
Richard Smith0f99d6a2015-08-09 08:48:41 +00003702static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3703 switch (Kind) {
3704 case MK_PCH:
3705 return 0; // PCH
3706 case MK_ImplicitModule:
3707 case MK_ExplicitModule:
3708 return 1; // module
3709 case MK_MainFile:
3710 case MK_Preamble:
3711 return 2; // main source file
3712 }
3713 llvm_unreachable("unknown module kind");
3714}
3715
Guy Benyei11169dd2012-12-18 14:30:41 +00003716ASTReader::ASTReadResult
3717ASTReader::ReadASTCore(StringRef FileName,
3718 ModuleKind Type,
3719 SourceLocation ImportLoc,
3720 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003721 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003722 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003723 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003724 unsigned ClientLoadCapabilities) {
3725 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003726 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003727 ModuleManager::AddModuleResult AddResult
3728 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003729 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003730 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003731 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003732
Douglas Gregor7029ce12013-03-19 00:28:20 +00003733 switch (AddResult) {
3734 case ModuleManager::AlreadyLoaded:
3735 return Success;
3736
3737 case ModuleManager::NewlyLoaded:
3738 // Load module file below.
3739 break;
3740
3741 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003742 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003743 // it.
3744 if (ClientLoadCapabilities & ARR_Missing)
3745 return Missing;
3746
3747 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003748 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3749 << FileName << ErrorStr.empty()
3750 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003751 return Failure;
3752
3753 case ModuleManager::OutOfDate:
3754 // We couldn't load the module file because it is out-of-date. If the
3755 // client can handle out-of-date, return it.
3756 if (ClientLoadCapabilities & ARR_OutOfDate)
3757 return OutOfDate;
3758
3759 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003760 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3761 << FileName << ErrorStr.empty()
3762 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003763 return Failure;
3764 }
3765
Douglas Gregor7029ce12013-03-19 00:28:20 +00003766 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003767
3768 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3769 // module?
3770 if (FileName != "-") {
3771 CurrentDir = llvm::sys::path::parent_path(FileName);
3772 if (CurrentDir.empty()) CurrentDir = ".";
3773 }
3774
3775 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003776 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003777 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003778 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003779 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3780
Guy Benyei11169dd2012-12-18 14:30:41 +00003781 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003782 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003783 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3784 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003785 return Failure;
3786 }
3787
3788 // This is used for compatibility with older PCH formats.
3789 bool HaveReadControlBlock = false;
Chris Lattnerefa77172013-01-20 00:00:22 +00003790 while (1) {
3791 llvm::BitstreamEntry Entry = Stream.advance();
3792
3793 switch (Entry.Kind) {
3794 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003795 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003796 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003797 Error("invalid record at top-level of AST file");
3798 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003799
3800 case llvm::BitstreamEntry::SubBlock:
3801 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003802 }
3803
Chris Lattnerefa77172013-01-20 00:00:22 +00003804 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003805 case CONTROL_BLOCK_ID:
3806 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003807 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003808 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003809 // Check that we didn't try to load a non-module AST file as a module.
3810 //
3811 // FIXME: Should we also perform the converse check? Loading a module as
3812 // a PCH file sort of works, but it's a bit wonky.
3813 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule) &&
3814 F.ModuleName.empty()) {
3815 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3816 if (Result != OutOfDate ||
3817 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3818 Diag(diag::err_module_file_not_module) << FileName;
3819 return Result;
3820 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003821 break;
3822
3823 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003824 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003825 case OutOfDate: return OutOfDate;
3826 case VersionMismatch: return VersionMismatch;
3827 case ConfigurationMismatch: return ConfigurationMismatch;
3828 case HadErrors: return HadErrors;
3829 }
3830 break;
Richard Smithf8c32552015-09-02 17:45:54 +00003831
Guy Benyei11169dd2012-12-18 14:30:41 +00003832 case AST_BLOCK_ID:
3833 if (!HaveReadControlBlock) {
3834 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003835 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003836 return VersionMismatch;
3837 }
3838
3839 // Record that we've loaded this module.
3840 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3841 return Success;
3842
3843 default:
3844 if (Stream.SkipBlock()) {
3845 Error("malformed block record in AST file");
3846 return Failure;
3847 }
3848 break;
3849 }
3850 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003851
3852 return Success;
3853}
3854
3855/// Parse a record and blob containing module file extension metadata.
3856static bool parseModuleFileExtensionMetadata(
3857 const SmallVectorImpl<uint64_t> &Record,
3858 StringRef Blob,
3859 ModuleFileExtensionMetadata &Metadata) {
3860 if (Record.size() < 4) return true;
3861
3862 Metadata.MajorVersion = Record[0];
3863 Metadata.MinorVersion = Record[1];
3864
3865 unsigned BlockNameLen = Record[2];
3866 unsigned UserInfoLen = Record[3];
3867
3868 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
3869
3870 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
3871 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
3872 Blob.data() + BlockNameLen + UserInfoLen);
3873 return false;
3874}
3875
3876ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
3877 BitstreamCursor &Stream = F.Stream;
3878
3879 RecordData Record;
3880 while (true) {
3881 llvm::BitstreamEntry Entry = Stream.advance();
3882 switch (Entry.Kind) {
3883 case llvm::BitstreamEntry::SubBlock:
3884 if (Stream.SkipBlock())
3885 return Failure;
3886
3887 continue;
3888
3889 case llvm::BitstreamEntry::EndBlock:
3890 return Success;
3891
3892 case llvm::BitstreamEntry::Error:
3893 return HadErrors;
3894
3895 case llvm::BitstreamEntry::Record:
3896 break;
3897 }
3898
3899 Record.clear();
3900 StringRef Blob;
3901 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
3902 switch (RecCode) {
3903 case EXTENSION_METADATA: {
3904 ModuleFileExtensionMetadata Metadata;
3905 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
3906 return Failure;
3907
3908 // Find a module file extension with this block name.
3909 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
3910 if (Known == ModuleFileExtensions.end()) break;
3911
3912 // Form a reader.
3913 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
3914 F, Stream)) {
3915 F.ExtensionReaders.push_back(std::move(Reader));
3916 }
3917
3918 break;
3919 }
3920 }
3921 }
3922
3923 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00003924}
3925
Richard Smitha7e2cc62015-05-01 01:53:09 +00003926void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003927 // If there's a listener, notify them that we "read" the translation unit.
3928 if (DeserializationListener)
3929 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3930 Context.getTranslationUnitDecl());
3931
Guy Benyei11169dd2012-12-18 14:30:41 +00003932 // FIXME: Find a better way to deal with collisions between these
3933 // built-in types. Right now, we just ignore the problem.
3934
3935 // Load the special types.
3936 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3937 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3938 if (!Context.CFConstantStringTypeDecl)
3939 Context.setCFConstantStringType(GetType(String));
3940 }
3941
3942 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3943 QualType FileType = GetType(File);
3944 if (FileType.isNull()) {
3945 Error("FILE type is NULL");
3946 return;
3947 }
3948
3949 if (!Context.FILEDecl) {
3950 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3951 Context.setFILEDecl(Typedef->getDecl());
3952 else {
3953 const TagType *Tag = FileType->getAs<TagType>();
3954 if (!Tag) {
3955 Error("Invalid FILE type in AST file");
3956 return;
3957 }
3958 Context.setFILEDecl(Tag->getDecl());
3959 }
3960 }
3961 }
3962
3963 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3964 QualType Jmp_bufType = GetType(Jmp_buf);
3965 if (Jmp_bufType.isNull()) {
3966 Error("jmp_buf type is NULL");
3967 return;
3968 }
3969
3970 if (!Context.jmp_bufDecl) {
3971 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3972 Context.setjmp_bufDecl(Typedef->getDecl());
3973 else {
3974 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3975 if (!Tag) {
3976 Error("Invalid jmp_buf type in AST file");
3977 return;
3978 }
3979 Context.setjmp_bufDecl(Tag->getDecl());
3980 }
3981 }
3982 }
3983
3984 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3985 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3986 if (Sigjmp_bufType.isNull()) {
3987 Error("sigjmp_buf type is NULL");
3988 return;
3989 }
3990
3991 if (!Context.sigjmp_bufDecl) {
3992 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3993 Context.setsigjmp_bufDecl(Typedef->getDecl());
3994 else {
3995 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3996 assert(Tag && "Invalid sigjmp_buf type in AST file");
3997 Context.setsigjmp_bufDecl(Tag->getDecl());
3998 }
3999 }
4000 }
4001
4002 if (unsigned ObjCIdRedef
4003 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4004 if (Context.ObjCIdRedefinitionType.isNull())
4005 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4006 }
4007
4008 if (unsigned ObjCClassRedef
4009 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4010 if (Context.ObjCClassRedefinitionType.isNull())
4011 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4012 }
4013
4014 if (unsigned ObjCSelRedef
4015 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4016 if (Context.ObjCSelRedefinitionType.isNull())
4017 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4018 }
4019
4020 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4021 QualType Ucontext_tType = GetType(Ucontext_t);
4022 if (Ucontext_tType.isNull()) {
4023 Error("ucontext_t type is NULL");
4024 return;
4025 }
4026
4027 if (!Context.ucontext_tDecl) {
4028 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4029 Context.setucontext_tDecl(Typedef->getDecl());
4030 else {
4031 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4032 assert(Tag && "Invalid ucontext_t type in AST file");
4033 Context.setucontext_tDecl(Tag->getDecl());
4034 }
4035 }
4036 }
4037 }
4038
4039 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4040
4041 // If there were any CUDA special declarations, deserialize them.
4042 if (!CUDASpecialDeclRefs.empty()) {
4043 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4044 Context.setcudaConfigureCallDecl(
4045 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4046 }
Richard Smith56be7542014-03-21 00:33:59 +00004047
Guy Benyei11169dd2012-12-18 14:30:41 +00004048 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004049 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004050 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004051 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004052 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004053 /*ImportLoc=*/Import.ImportLoc);
4054 PP.makeModuleVisible(Imported, Import.ImportLoc);
4055 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004056 }
4057 ImportedModules.clear();
4058}
4059
4060void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004061 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004062}
4063
Ben Langmuir70a1b812015-03-24 04:43:52 +00004064/// \brief Reads and return the signature record from \p StreamFile's control
4065/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00004066static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4067 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004068 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004069 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004070
4071 // Scan for the CONTROL_BLOCK_ID block.
4072 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4073 return 0;
4074
4075 // Scan for SIGNATURE inside the control block.
4076 ASTReader::RecordData Record;
4077 while (1) {
4078 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4079 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4080 Entry.Kind != llvm::BitstreamEntry::Record)
4081 return 0;
4082
4083 Record.clear();
4084 StringRef Blob;
4085 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4086 return Record[0];
4087 }
4088}
4089
Guy Benyei11169dd2012-12-18 14:30:41 +00004090/// \brief Retrieve the name of the original source file name
4091/// directly from the AST file, without actually loading the AST
4092/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004093std::string ASTReader::getOriginalSourceFile(
4094 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004095 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004096 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004097 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004098 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004099 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4100 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004101 return std::string();
4102 }
4103
4104 // Initialize the stream
4105 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004106 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004107 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004108
4109 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004110 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004111 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4112 return std::string();
4113 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004114
Chris Lattnere7b154b2013-01-19 21:39:22 +00004115 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004116 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004117 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4118 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004119 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004120
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004121 // Scan for ORIGINAL_FILE inside the control block.
4122 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004123 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004124 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004125 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4126 return std::string();
4127
4128 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4129 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4130 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004131 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004132
Guy Benyei11169dd2012-12-18 14:30:41 +00004133 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004134 StringRef Blob;
4135 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4136 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004137 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004138}
4139
4140namespace {
4141 class SimplePCHValidator : public ASTReaderListener {
4142 const LangOptions &ExistingLangOpts;
4143 const TargetOptions &ExistingTargetOpts;
4144 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004145 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004146 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004147
Guy Benyei11169dd2012-12-18 14:30:41 +00004148 public:
4149 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4150 const TargetOptions &ExistingTargetOpts,
4151 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004152 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004153 FileManager &FileMgr)
4154 : ExistingLangOpts(ExistingLangOpts),
4155 ExistingTargetOpts(ExistingTargetOpts),
4156 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004157 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004158 FileMgr(FileMgr)
4159 {
4160 }
4161
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004162 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4163 bool AllowCompatibleDifferences) override {
4164 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4165 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004166 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004167 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4168 bool AllowCompatibleDifferences) override {
4169 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4170 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004171 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004172 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4173 StringRef SpecificModuleCachePath,
4174 bool Complain) override {
4175 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4176 ExistingModuleCachePath,
4177 nullptr, ExistingLangOpts);
4178 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004179 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4180 bool Complain,
4181 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004182 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004183 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004184 }
4185 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004186}
Guy Benyei11169dd2012-12-18 14:30:41 +00004187
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004188bool ASTReader::readASTFileControlBlock(
4189 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004190 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004191 bool FindModuleFileExtensions,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004192 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004193 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004194 // FIXME: This allows use of the VFS; we do not allow use of the
4195 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004196 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004197 if (!Buffer) {
4198 return true;
4199 }
4200
4201 // Initialize the stream
4202 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004203 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004204 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004205
4206 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004207 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004208 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004209
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004210 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004211 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004212 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004213
4214 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004215 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004216 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004217 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004218
Guy Benyei11169dd2012-12-18 14:30:41 +00004219 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004220 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004221 bool DoneWithControlBlock = false;
4222 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004223 llvm::BitstreamEntry Entry = Stream.advance();
4224
4225 switch (Entry.Kind) {
4226 case llvm::BitstreamEntry::SubBlock: {
4227 switch (Entry.ID) {
4228 case OPTIONS_BLOCK_ID: {
4229 std::string IgnoredSuggestedPredefines;
4230 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4231 /*AllowCompatibleConfigurationMismatch*/ false,
4232 Listener, IgnoredSuggestedPredefines) != Success)
4233 return true;
4234 break;
4235 }
4236
4237 case INPUT_FILES_BLOCK_ID:
4238 InputFilesCursor = Stream;
4239 if (Stream.SkipBlock() ||
4240 (NeedsInputFiles &&
4241 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4242 return true;
4243 break;
4244
4245 default:
4246 if (Stream.SkipBlock())
4247 return true;
4248 break;
4249 }
4250
4251 continue;
4252 }
4253
4254 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004255 DoneWithControlBlock = true;
4256 break;
Richard Smith0516b182015-09-08 19:40:14 +00004257
4258 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004259 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004260
4261 case llvm::BitstreamEntry::Record:
4262 break;
4263 }
4264
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004265 if (DoneWithControlBlock) break;
4266
Guy Benyei11169dd2012-12-18 14:30:41 +00004267 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004268 StringRef Blob;
4269 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004270 switch ((ControlRecordTypes)RecCode) {
4271 case METADATA: {
4272 if (Record[0] != VERSION_MAJOR)
4273 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004274
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004275 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004276 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004277
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004278 break;
4279 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004280 case MODULE_NAME:
4281 Listener.ReadModuleName(Blob);
4282 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004283 case MODULE_DIRECTORY:
4284 ModuleDir = Blob;
4285 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004286 case MODULE_MAP_FILE: {
4287 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004288 auto Path = ReadString(Record, Idx);
4289 ResolveImportedPath(Path, ModuleDir);
4290 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004291 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004292 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004293 case INPUT_FILE_OFFSETS: {
4294 if (!NeedsInputFiles)
4295 break;
4296
4297 unsigned NumInputFiles = Record[0];
4298 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004299 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004300 for (unsigned I = 0; I != NumInputFiles; ++I) {
4301 // Go find this input file.
4302 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004303
4304 if (isSystemFile && !NeedsSystemInputFiles)
4305 break; // the rest are system input files
4306
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004307 BitstreamCursor &Cursor = InputFilesCursor;
4308 SavedStreamPosition SavedPosition(Cursor);
4309 Cursor.JumpToBit(InputFileOffs[I]);
4310
4311 unsigned Code = Cursor.ReadCode();
4312 RecordData Record;
4313 StringRef Blob;
4314 bool shouldContinue = false;
4315 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4316 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004317 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004318 std::string Filename = Blob;
4319 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004320 shouldContinue = Listener.visitInputFile(
4321 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004322 break;
4323 }
4324 if (!shouldContinue)
4325 break;
4326 }
4327 break;
4328 }
4329
Richard Smithd4b230b2014-10-27 23:01:16 +00004330 case IMPORTS: {
4331 if (!NeedsImports)
4332 break;
4333
4334 unsigned Idx = 0, N = Record.size();
4335 while (Idx < N) {
4336 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004337 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004338 std::string Filename = ReadString(Record, Idx);
4339 ResolveImportedPath(Filename, ModuleDir);
4340 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004341 }
4342 break;
4343 }
4344
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004345 default:
4346 // No other validation to perform.
4347 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004348 }
4349 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004350
4351 // Look for module file extension blocks, if requested.
4352 if (FindModuleFileExtensions) {
4353 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4354 bool DoneWithExtensionBlock = false;
4355 while (!DoneWithExtensionBlock) {
4356 llvm::BitstreamEntry Entry = Stream.advance();
4357
4358 switch (Entry.Kind) {
4359 case llvm::BitstreamEntry::SubBlock:
4360 if (Stream.SkipBlock())
4361 return true;
4362
4363 continue;
4364
4365 case llvm::BitstreamEntry::EndBlock:
4366 DoneWithExtensionBlock = true;
4367 continue;
4368
4369 case llvm::BitstreamEntry::Error:
4370 return true;
4371
4372 case llvm::BitstreamEntry::Record:
4373 break;
4374 }
4375
4376 Record.clear();
4377 StringRef Blob;
4378 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4379 switch (RecCode) {
4380 case EXTENSION_METADATA: {
4381 ModuleFileExtensionMetadata Metadata;
4382 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4383 return true;
4384
4385 Listener.readModuleFileExtension(Metadata);
4386 break;
4387 }
4388 }
4389 }
4390 }
4391 }
4392
4393 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004394}
4395
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004396bool ASTReader::isAcceptableASTFile(
4397 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004398 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004399 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4400 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004401 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4402 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004403 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004404 /*FindModuleFileExtensions=*/false,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004405 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004406}
4407
Ben Langmuir2c9af442014-04-10 17:57:43 +00004408ASTReader::ASTReadResult
4409ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004410 // Enter the submodule block.
4411 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4412 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004413 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004414 }
4415
4416 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4417 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004418 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004419 RecordData Record;
4420 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004421 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4422
4423 switch (Entry.Kind) {
4424 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4425 case llvm::BitstreamEntry::Error:
4426 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004427 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004428 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004429 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004430 case llvm::BitstreamEntry::Record:
4431 // The interesting case.
4432 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004434
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004436 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004437 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004438 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4439
4440 if ((Kind == SUBMODULE_METADATA) != First) {
4441 Error("submodule metadata record should be at beginning of block");
4442 return Failure;
4443 }
4444 First = false;
4445
4446 // Submodule information is only valid if we have a current module.
4447 // FIXME: Should we error on these cases?
4448 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4449 Kind != SUBMODULE_DEFINITION)
4450 continue;
4451
4452 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 default: // Default behavior: ignore.
4454 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004455
Richard Smith03478d92014-10-23 22:12:14 +00004456 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004457 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004459 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 }
Richard Smith03478d92014-10-23 22:12:14 +00004461
Chris Lattner0e6c9402013-01-20 02:38:54 +00004462 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004463 unsigned Idx = 0;
4464 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4465 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4466 bool IsFramework = Record[Idx++];
4467 bool IsExplicit = Record[Idx++];
4468 bool IsSystem = Record[Idx++];
4469 bool IsExternC = Record[Idx++];
4470 bool InferSubmodules = Record[Idx++];
4471 bool InferExplicitSubmodules = Record[Idx++];
4472 bool InferExportWildcard = Record[Idx++];
4473 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004474
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004475 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004476 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004478
Guy Benyei11169dd2012-12-18 14:30:41 +00004479 // Retrieve this (sub)module from the module map, creating it if
4480 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004481 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004482 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004483
4484 // FIXME: set the definition loc for CurrentModule, or call
4485 // ModMap.setInferredModuleAllowedBy()
4486
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4488 if (GlobalIndex >= SubmodulesLoaded.size() ||
4489 SubmodulesLoaded[GlobalIndex]) {
4490 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004491 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004493
Douglas Gregor7029ce12013-03-19 00:28:20 +00004494 if (!ParentModule) {
4495 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4496 if (CurFile != F.File) {
4497 if (!Diags.isDiagnosticInFlight()) {
4498 Diag(diag::err_module_file_conflict)
4499 << CurrentModule->getTopLevelModuleName()
4500 << CurFile->getName()
4501 << F.File->getName();
4502 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004503 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004504 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004505 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004506
4507 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004508 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004509
Adrian Prantl15bcf702015-06-30 17:39:43 +00004510 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004511 CurrentModule->IsFromModuleFile = true;
4512 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004513 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004514 CurrentModule->InferSubmodules = InferSubmodules;
4515 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4516 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004517 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004518 if (DeserializationListener)
4519 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4520
4521 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004522
Douglas Gregorfb912652013-03-20 21:10:35 +00004523 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004524 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004525 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004526 CurrentModule->UnresolvedConflicts.clear();
4527 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 break;
4529 }
4530
4531 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004532 std::string Filename = Blob;
4533 ResolveImportedPath(F, Filename);
4534 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004535 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004536 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4537 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004538 // This can be a spurious difference caused by changing the VFS to
4539 // point to a different copy of the file, and it is too late to
4540 // to rebuild safely.
4541 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4542 // after input file validation only real problems would remain and we
4543 // could just error. For now, assume it's okay.
4544 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 }
4546 }
4547 break;
4548 }
4549
Richard Smith202210b2014-10-24 20:23:01 +00004550 case SUBMODULE_HEADER:
4551 case SUBMODULE_EXCLUDED_HEADER:
4552 case SUBMODULE_PRIVATE_HEADER:
4553 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004554 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4555 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004556 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004557
Richard Smith202210b2014-10-24 20:23:01 +00004558 case SUBMODULE_TEXTUAL_HEADER:
4559 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4560 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4561 // them here.
4562 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004563
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004565 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 break;
4567 }
4568
4569 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004570 std::string Dirname = Blob;
4571 ResolveImportedPath(F, Dirname);
4572 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004573 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004574 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4575 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004576 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4577 Error("mismatched umbrella directories in submodule");
4578 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 }
4580 }
4581 break;
4582 }
4583
4584 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004585 F.BaseSubmoduleID = getTotalNumSubmodules();
4586 F.LocalNumSubmodules = Record[0];
4587 unsigned LocalBaseSubmoduleID = Record[1];
4588 if (F.LocalNumSubmodules > 0) {
4589 // Introduce the global -> local mapping for submodules within this
4590 // module.
4591 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4592
4593 // Introduce the local -> global mapping for submodules within this
4594 // module.
4595 F.SubmoduleRemap.insertOrReplace(
4596 std::make_pair(LocalBaseSubmoduleID,
4597 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004598
Ben Langmuir52ca6782014-10-20 16:27:32 +00004599 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4600 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 break;
4602 }
4603
4604 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004606 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004607 Unresolved.File = &F;
4608 Unresolved.Mod = CurrentModule;
4609 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004610 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004611 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004612 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 }
4614 break;
4615 }
4616
4617 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004618 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004619 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 Unresolved.File = &F;
4621 Unresolved.Mod = CurrentModule;
4622 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004623 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004624 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004625 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004626 }
4627
4628 // Once we've loaded the set of exports, there's no reason to keep
4629 // the parsed, unresolved exports around.
4630 CurrentModule->UnresolvedExports.clear();
4631 break;
4632 }
4633 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004634 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 Context.getTargetInfo());
4636 break;
4637 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004638
4639 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004640 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004641 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004642 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004643
4644 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004645 CurrentModule->ConfigMacros.push_back(Blob.str());
4646 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004647
4648 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004649 UnresolvedModuleRef Unresolved;
4650 Unresolved.File = &F;
4651 Unresolved.Mod = CurrentModule;
4652 Unresolved.ID = Record[0];
4653 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4654 Unresolved.IsWildcard = false;
4655 Unresolved.String = Blob;
4656 UnresolvedModuleRefs.push_back(Unresolved);
4657 break;
4658 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004659 }
4660 }
4661}
4662
4663/// \brief Parse the record that corresponds to a LangOptions data
4664/// structure.
4665///
4666/// This routine parses the language options from the AST file and then gives
4667/// them to the AST listener if one is set.
4668///
4669/// \returns true if the listener deems the file unacceptable, false otherwise.
4670bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4671 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004672 ASTReaderListener &Listener,
4673 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004674 LangOptions LangOpts;
4675 unsigned Idx = 0;
4676#define LANGOPT(Name, Bits, Default, Description) \
4677 LangOpts.Name = Record[Idx++];
4678#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4679 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4680#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004681#define SANITIZER(NAME, ID) \
4682 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004683#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004684
Ben Langmuircd98cb72015-06-23 18:20:18 +00004685 for (unsigned N = Record[Idx++]; N; --N)
4686 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4687
Guy Benyei11169dd2012-12-18 14:30:41 +00004688 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4689 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4690 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004691
Ben Langmuird4a667a2015-06-23 18:20:23 +00004692 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004693
4694 // Comment options.
4695 for (unsigned N = Record[Idx++]; N; --N) {
4696 LangOpts.CommentOpts.BlockCommandNames.push_back(
4697 ReadString(Record, Idx));
4698 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004699 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004700
Samuel Antaoee8fb302016-01-06 13:42:12 +00004701 // OpenMP offloading options.
4702 for (unsigned N = Record[Idx++]; N; --N) {
4703 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
4704 }
4705
4706 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
4707
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004708 return Listener.ReadLanguageOptions(LangOpts, Complain,
4709 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004710}
4711
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004712bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4713 ASTReaderListener &Listener,
4714 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 unsigned Idx = 0;
4716 TargetOptions TargetOpts;
4717 TargetOpts.Triple = ReadString(Record, Idx);
4718 TargetOpts.CPU = ReadString(Record, Idx);
4719 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004720 for (unsigned N = Record[Idx++]; N; --N) {
4721 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4722 }
4723 for (unsigned N = Record[Idx++]; N; --N) {
4724 TargetOpts.Features.push_back(ReadString(Record, Idx));
4725 }
4726
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004727 return Listener.ReadTargetOptions(TargetOpts, Complain,
4728 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004729}
4730
4731bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4732 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004733 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004734 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004735#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004736#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004737 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004738#include "clang/Basic/DiagnosticOptions.def"
4739
Richard Smith3be1cb22014-08-07 00:24:21 +00004740 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004741 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004742 for (unsigned N = Record[Idx++]; N; --N)
4743 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004744
4745 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4746}
4747
4748bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4749 ASTReaderListener &Listener) {
4750 FileSystemOptions FSOpts;
4751 unsigned Idx = 0;
4752 FSOpts.WorkingDir = ReadString(Record, Idx);
4753 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4754}
4755
4756bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4757 bool Complain,
4758 ASTReaderListener &Listener) {
4759 HeaderSearchOptions HSOpts;
4760 unsigned Idx = 0;
4761 HSOpts.Sysroot = ReadString(Record, Idx);
4762
4763 // Include entries.
4764 for (unsigned N = Record[Idx++]; N; --N) {
4765 std::string Path = ReadString(Record, Idx);
4766 frontend::IncludeDirGroup Group
4767 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004768 bool IsFramework = Record[Idx++];
4769 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004770 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4771 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004772 }
4773
4774 // System header prefixes.
4775 for (unsigned N = Record[Idx++]; N; --N) {
4776 std::string Prefix = ReadString(Record, Idx);
4777 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004778 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004779 }
4780
4781 HSOpts.ResourceDir = ReadString(Record, Idx);
4782 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004783 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004784 HSOpts.DisableModuleHash = Record[Idx++];
4785 HSOpts.UseBuiltinIncludes = Record[Idx++];
4786 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4787 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4788 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004789 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004790
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004791 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4792 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004793}
4794
4795bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4796 bool Complain,
4797 ASTReaderListener &Listener,
4798 std::string &SuggestedPredefines) {
4799 PreprocessorOptions PPOpts;
4800 unsigned Idx = 0;
4801
4802 // Macro definitions/undefs
4803 for (unsigned N = Record[Idx++]; N; --N) {
4804 std::string Macro = ReadString(Record, Idx);
4805 bool IsUndef = Record[Idx++];
4806 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4807 }
4808
4809 // Includes
4810 for (unsigned N = Record[Idx++]; N; --N) {
4811 PPOpts.Includes.push_back(ReadString(Record, Idx));
4812 }
4813
4814 // Macro Includes
4815 for (unsigned N = Record[Idx++]; N; --N) {
4816 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4817 }
4818
4819 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004820 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004821 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4822 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4823 PPOpts.ObjCXXARCStandardLibrary =
4824 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4825 SuggestedPredefines.clear();
4826 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4827 SuggestedPredefines);
4828}
4829
4830std::pair<ModuleFile *, unsigned>
4831ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4832 GlobalPreprocessedEntityMapType::iterator
4833 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4834 assert(I != GlobalPreprocessedEntityMap.end() &&
4835 "Corrupted global preprocessed entity map");
4836 ModuleFile *M = I->second;
4837 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4838 return std::make_pair(M, LocalIndex);
4839}
4840
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004841llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004842ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4843 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4844 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4845 Mod.NumPreprocessedEntities);
4846
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004847 return llvm::make_range(PreprocessingRecord::iterator(),
4848 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004849}
4850
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004851llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004852ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004853 return llvm::make_range(
4854 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4855 ModuleDeclIterator(this, &Mod,
4856 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004857}
4858
4859PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4860 PreprocessedEntityID PPID = Index+1;
4861 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4862 ModuleFile &M = *PPInfo.first;
4863 unsigned LocalIndex = PPInfo.second;
4864 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4865
Guy Benyei11169dd2012-12-18 14:30:41 +00004866 if (!PP.getPreprocessingRecord()) {
4867 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004868 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004869 }
4870
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004871 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4872 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4873
4874 llvm::BitstreamEntry Entry =
4875 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4876 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004877 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004878
Guy Benyei11169dd2012-12-18 14:30:41 +00004879 // Read the record.
4880 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4881 ReadSourceLocation(M, PPOffs.End));
4882 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004883 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004884 RecordData Record;
4885 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004886 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4887 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004888 switch (RecType) {
4889 case PPD_MACRO_EXPANSION: {
4890 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004891 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004892 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004893 if (isBuiltin)
4894 Name = getLocalIdentifier(M, Record[1]);
4895 else {
Richard Smith66a81862015-05-04 02:25:31 +00004896 PreprocessedEntityID GlobalID =
4897 getGlobalPreprocessedEntityID(M, Record[1]);
4898 Def = cast<MacroDefinitionRecord>(
4899 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004900 }
4901
4902 MacroExpansion *ME;
4903 if (isBuiltin)
4904 ME = new (PPRec) MacroExpansion(Name, Range);
4905 else
4906 ME = new (PPRec) MacroExpansion(Def, Range);
4907
4908 return ME;
4909 }
4910
4911 case PPD_MACRO_DEFINITION: {
4912 // Decode the identifier info and then check again; if the macro is
4913 // still defined and associated with the identifier,
4914 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004915 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004916
4917 if (DeserializationListener)
4918 DeserializationListener->MacroDefinitionRead(PPID, MD);
4919
4920 return MD;
4921 }
4922
4923 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004924 const char *FullFileNameStart = Blob.data() + Record[0];
4925 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004926 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004927 if (!FullFileName.empty())
4928 File = PP.getFileManager().getFile(FullFileName);
4929
4930 // FIXME: Stable encoding
4931 InclusionDirective::InclusionKind Kind
4932 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4933 InclusionDirective *ID
4934 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004935 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004936 Record[1], Record[3],
4937 File,
4938 Range);
4939 return ID;
4940 }
4941 }
4942
4943 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4944}
4945
4946/// \brief \arg SLocMapI points at a chunk of a module that contains no
4947/// preprocessed entities or the entities it contains are not the ones we are
4948/// looking for. Find the next module that contains entities and return the ID
4949/// of the first entry.
4950PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4951 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4952 ++SLocMapI;
4953 for (GlobalSLocOffsetMapType::const_iterator
4954 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4955 ModuleFile &M = *SLocMapI->second;
4956 if (M.NumPreprocessedEntities)
4957 return M.BasePreprocessedEntityID;
4958 }
4959
4960 return getTotalNumPreprocessedEntities();
4961}
4962
4963namespace {
4964
4965template <unsigned PPEntityOffset::*PPLoc>
4966struct PPEntityComp {
4967 const ASTReader &Reader;
4968 ModuleFile &M;
4969
4970 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4971
4972 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4973 SourceLocation LHS = getLoc(L);
4974 SourceLocation RHS = getLoc(R);
4975 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4976 }
4977
4978 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4979 SourceLocation LHS = getLoc(L);
4980 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4981 }
4982
4983 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4984 SourceLocation RHS = getLoc(R);
4985 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4986 }
4987
4988 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4989 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4990 }
4991};
4992
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004993}
Guy Benyei11169dd2012-12-18 14:30:41 +00004994
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004995PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4996 bool EndsAfter) const {
4997 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004998 return getTotalNumPreprocessedEntities();
4999
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005000 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5001 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005002 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5003 "Corrupted global sloc offset map");
5004
5005 if (SLocMapI->second->NumPreprocessedEntities == 0)
5006 return findNextPreprocessedEntity(SLocMapI);
5007
5008 ModuleFile &M = *SLocMapI->second;
5009 typedef const PPEntityOffset *pp_iterator;
5010 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5011 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5012
5013 size_t Count = M.NumPreprocessedEntities;
5014 size_t Half;
5015 pp_iterator First = pp_begin;
5016 pp_iterator PPI;
5017
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005018 if (EndsAfter) {
5019 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5020 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
5021 } else {
5022 // Do a binary search manually instead of using std::lower_bound because
5023 // The end locations of entities may be unordered (when a macro expansion
5024 // is inside another macro argument), but for this case it is not important
5025 // whether we get the first macro expansion or its containing macro.
5026 while (Count > 0) {
5027 Half = Count / 2;
5028 PPI = First;
5029 std::advance(PPI, Half);
5030 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
5031 Loc)) {
5032 First = PPI;
5033 ++First;
5034 Count = Count - Half - 1;
5035 } else
5036 Count = Half;
5037 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005038 }
5039
5040 if (PPI == pp_end)
5041 return findNextPreprocessedEntity(SLocMapI);
5042
5043 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5044}
5045
Guy Benyei11169dd2012-12-18 14:30:41 +00005046/// \brief Returns a pair of [Begin, End) indices of preallocated
5047/// preprocessed entities that \arg Range encompasses.
5048std::pair<unsigned, unsigned>
5049 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5050 if (Range.isInvalid())
5051 return std::make_pair(0,0);
5052 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5053
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005054 PreprocessedEntityID BeginID =
5055 findPreprocessedEntity(Range.getBegin(), false);
5056 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 return std::make_pair(BeginID, EndID);
5058}
5059
5060/// \brief Optionally returns true or false if the preallocated preprocessed
5061/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005062Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 FileID FID) {
5064 if (FID.isInvalid())
5065 return false;
5066
5067 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5068 ModuleFile &M = *PPInfo.first;
5069 unsigned LocalIndex = PPInfo.second;
5070 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5071
5072 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5073 if (Loc.isInvalid())
5074 return false;
5075
5076 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5077 return true;
5078 else
5079 return false;
5080}
5081
5082namespace {
5083 /// \brief Visitor used to search for information about a header file.
5084 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 const FileEntry *FE;
5086
David Blaikie05785d12013-02-20 22:23:23 +00005087 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005088
5089 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005090 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5091 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005092
5093 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005094 HeaderFileInfoLookupTable *Table
5095 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5096 if (!Table)
5097 return false;
5098
5099 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005100 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005101 if (Pos == Table->end())
5102 return false;
5103
Richard Smithbdf2d932015-07-30 03:37:16 +00005104 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 return true;
5106 }
5107
David Blaikie05785d12013-02-20 22:23:23 +00005108 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005110}
Guy Benyei11169dd2012-12-18 14:30:41 +00005111
5112HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005113 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005114 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005115 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005117
5118 return HeaderFileInfo();
5119}
5120
5121void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5122 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005123 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5125 ModuleFile &F = *(*I);
5126 unsigned Idx = 0;
5127 DiagStates.clear();
5128 assert(!Diag.DiagStates.empty());
5129 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5130 while (Idx < F.PragmaDiagMappings.size()) {
5131 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5132 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5133 if (DiagStateID != 0) {
5134 Diag.DiagStatePoints.push_back(
5135 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5136 FullSourceLoc(Loc, SourceMgr)));
5137 continue;
5138 }
5139
5140 assert(DiagStateID == 0);
5141 // A new DiagState was created here.
5142 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5143 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5144 DiagStates.push_back(NewState);
5145 Diag.DiagStatePoints.push_back(
5146 DiagnosticsEngine::DiagStatePoint(NewState,
5147 FullSourceLoc(Loc, SourceMgr)));
5148 while (1) {
5149 assert(Idx < F.PragmaDiagMappings.size() &&
5150 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5151 if (Idx >= F.PragmaDiagMappings.size()) {
5152 break; // Something is messed up but at least avoid infinite loop in
5153 // release build.
5154 }
5155 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5156 if (DiagID == (unsigned)-1) {
5157 break; // no more diag/map pairs for this location.
5158 }
Alp Tokerc726c362014-06-10 09:31:37 +00005159 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5160 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5161 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 }
5163 }
5164 }
5165}
5166
5167/// \brief Get the correct cursor and offset for loading a type.
5168ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5169 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5170 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5171 ModuleFile *M = I->second;
5172 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5173}
5174
5175/// \brief Read and return the type with the given index..
5176///
5177/// The index is the type ID, shifted and minus the number of predefs. This
5178/// routine actually reads the record corresponding to the type at the given
5179/// location. It is a helper routine for GetType, which deals with reading type
5180/// IDs.
5181QualType ASTReader::readTypeRecord(unsigned Index) {
5182 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005183 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005184
5185 // Keep track of where we are in the stream, then jump back there
5186 // after reading this type.
5187 SavedStreamPosition SavedPosition(DeclsCursor);
5188
5189 ReadingKindTracker ReadingKind(Read_Type, *this);
5190
5191 // Note that we are loading a type record.
5192 Deserializing AType(this);
5193
5194 unsigned Idx = 0;
5195 DeclsCursor.JumpToBit(Loc.Offset);
5196 RecordData Record;
5197 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005198 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005199 case TYPE_EXT_QUAL: {
5200 if (Record.size() != 2) {
5201 Error("Incorrect encoding of extended qualifier type");
5202 return QualType();
5203 }
5204 QualType Base = readType(*Loc.F, Record, Idx);
5205 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5206 return Context.getQualifiedType(Base, Quals);
5207 }
5208
5209 case TYPE_COMPLEX: {
5210 if (Record.size() != 1) {
5211 Error("Incorrect encoding of complex type");
5212 return QualType();
5213 }
5214 QualType ElemType = readType(*Loc.F, Record, Idx);
5215 return Context.getComplexType(ElemType);
5216 }
5217
5218 case TYPE_POINTER: {
5219 if (Record.size() != 1) {
5220 Error("Incorrect encoding of pointer type");
5221 return QualType();
5222 }
5223 QualType PointeeType = readType(*Loc.F, Record, Idx);
5224 return Context.getPointerType(PointeeType);
5225 }
5226
Reid Kleckner8a365022013-06-24 17:51:48 +00005227 case TYPE_DECAYED: {
5228 if (Record.size() != 1) {
5229 Error("Incorrect encoding of decayed type");
5230 return QualType();
5231 }
5232 QualType OriginalType = readType(*Loc.F, Record, Idx);
5233 QualType DT = Context.getAdjustedParameterType(OriginalType);
5234 if (!isa<DecayedType>(DT))
5235 Error("Decayed type does not decay");
5236 return DT;
5237 }
5238
Reid Kleckner0503a872013-12-05 01:23:43 +00005239 case TYPE_ADJUSTED: {
5240 if (Record.size() != 2) {
5241 Error("Incorrect encoding of adjusted type");
5242 return QualType();
5243 }
5244 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5245 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5246 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5247 }
5248
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 case TYPE_BLOCK_POINTER: {
5250 if (Record.size() != 1) {
5251 Error("Incorrect encoding of block pointer type");
5252 return QualType();
5253 }
5254 QualType PointeeType = readType(*Loc.F, Record, Idx);
5255 return Context.getBlockPointerType(PointeeType);
5256 }
5257
5258 case TYPE_LVALUE_REFERENCE: {
5259 if (Record.size() != 2) {
5260 Error("Incorrect encoding of lvalue reference type");
5261 return QualType();
5262 }
5263 QualType PointeeType = readType(*Loc.F, Record, Idx);
5264 return Context.getLValueReferenceType(PointeeType, Record[1]);
5265 }
5266
5267 case TYPE_RVALUE_REFERENCE: {
5268 if (Record.size() != 1) {
5269 Error("Incorrect encoding of rvalue reference type");
5270 return QualType();
5271 }
5272 QualType PointeeType = readType(*Loc.F, Record, Idx);
5273 return Context.getRValueReferenceType(PointeeType);
5274 }
5275
5276 case TYPE_MEMBER_POINTER: {
5277 if (Record.size() != 2) {
5278 Error("Incorrect encoding of member pointer type");
5279 return QualType();
5280 }
5281 QualType PointeeType = readType(*Loc.F, Record, Idx);
5282 QualType ClassType = readType(*Loc.F, Record, Idx);
5283 if (PointeeType.isNull() || ClassType.isNull())
5284 return QualType();
5285
5286 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5287 }
5288
5289 case TYPE_CONSTANT_ARRAY: {
5290 QualType ElementType = readType(*Loc.F, Record, Idx);
5291 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5292 unsigned IndexTypeQuals = Record[2];
5293 unsigned Idx = 3;
5294 llvm::APInt Size = ReadAPInt(Record, Idx);
5295 return Context.getConstantArrayType(ElementType, Size,
5296 ASM, IndexTypeQuals);
5297 }
5298
5299 case TYPE_INCOMPLETE_ARRAY: {
5300 QualType ElementType = readType(*Loc.F, Record, Idx);
5301 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5302 unsigned IndexTypeQuals = Record[2];
5303 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5304 }
5305
5306 case TYPE_VARIABLE_ARRAY: {
5307 QualType ElementType = readType(*Loc.F, Record, Idx);
5308 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5309 unsigned IndexTypeQuals = Record[2];
5310 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5311 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5312 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5313 ASM, IndexTypeQuals,
5314 SourceRange(LBLoc, RBLoc));
5315 }
5316
5317 case TYPE_VECTOR: {
5318 if (Record.size() != 3) {
5319 Error("incorrect encoding of vector type in AST file");
5320 return QualType();
5321 }
5322
5323 QualType ElementType = readType(*Loc.F, Record, Idx);
5324 unsigned NumElements = Record[1];
5325 unsigned VecKind = Record[2];
5326 return Context.getVectorType(ElementType, NumElements,
5327 (VectorType::VectorKind)VecKind);
5328 }
5329
5330 case TYPE_EXT_VECTOR: {
5331 if (Record.size() != 3) {
5332 Error("incorrect encoding of extended vector type in AST file");
5333 return QualType();
5334 }
5335
5336 QualType ElementType = readType(*Loc.F, Record, Idx);
5337 unsigned NumElements = Record[1];
5338 return Context.getExtVectorType(ElementType, NumElements);
5339 }
5340
5341 case TYPE_FUNCTION_NO_PROTO: {
5342 if (Record.size() != 6) {
5343 Error("incorrect encoding of no-proto function type");
5344 return QualType();
5345 }
5346 QualType ResultType = readType(*Loc.F, Record, Idx);
5347 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5348 (CallingConv)Record[4], Record[5]);
5349 return Context.getFunctionNoProtoType(ResultType, Info);
5350 }
5351
5352 case TYPE_FUNCTION_PROTO: {
5353 QualType ResultType = readType(*Loc.F, Record, Idx);
5354
5355 FunctionProtoType::ExtProtoInfo EPI;
5356 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5357 /*hasregparm*/ Record[2],
5358 /*regparm*/ Record[3],
5359 static_cast<CallingConv>(Record[4]),
5360 /*produces*/ Record[5]);
5361
5362 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005363
5364 EPI.Variadic = Record[Idx++];
5365 EPI.HasTrailingReturn = Record[Idx++];
5366 EPI.TypeQuals = Record[Idx++];
5367 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005368 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005369 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005370
5371 unsigned NumParams = Record[Idx++];
5372 SmallVector<QualType, 16> ParamTypes;
5373 for (unsigned I = 0; I != NumParams; ++I)
5374 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5375
Jordan Rose5c382722013-03-08 21:51:21 +00005376 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005377 }
5378
5379 case TYPE_UNRESOLVED_USING: {
5380 unsigned Idx = 0;
5381 return Context.getTypeDeclType(
5382 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5383 }
5384
5385 case TYPE_TYPEDEF: {
5386 if (Record.size() != 2) {
5387 Error("incorrect encoding of typedef type");
5388 return QualType();
5389 }
5390 unsigned Idx = 0;
5391 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5392 QualType Canonical = readType(*Loc.F, Record, Idx);
5393 if (!Canonical.isNull())
5394 Canonical = Context.getCanonicalType(Canonical);
5395 return Context.getTypedefType(Decl, Canonical);
5396 }
5397
5398 case TYPE_TYPEOF_EXPR:
5399 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5400
5401 case TYPE_TYPEOF: {
5402 if (Record.size() != 1) {
5403 Error("incorrect encoding of typeof(type) in AST file");
5404 return QualType();
5405 }
5406 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5407 return Context.getTypeOfType(UnderlyingType);
5408 }
5409
5410 case TYPE_DECLTYPE: {
5411 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5412 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5413 }
5414
5415 case TYPE_UNARY_TRANSFORM: {
5416 QualType BaseType = readType(*Loc.F, Record, Idx);
5417 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5418 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5419 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5420 }
5421
Richard Smith74aeef52013-04-26 16:15:35 +00005422 case TYPE_AUTO: {
5423 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005424 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005425 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005426 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005427 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005428
5429 case TYPE_RECORD: {
5430 if (Record.size() != 2) {
5431 Error("incorrect encoding of record type");
5432 return QualType();
5433 }
5434 unsigned Idx = 0;
5435 bool IsDependent = Record[Idx++];
5436 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5437 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5438 QualType T = Context.getRecordType(RD);
5439 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5440 return T;
5441 }
5442
5443 case TYPE_ENUM: {
5444 if (Record.size() != 2) {
5445 Error("incorrect encoding of enum type");
5446 return QualType();
5447 }
5448 unsigned Idx = 0;
5449 bool IsDependent = Record[Idx++];
5450 QualType T
5451 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5452 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5453 return T;
5454 }
5455
5456 case TYPE_ATTRIBUTED: {
5457 if (Record.size() != 3) {
5458 Error("incorrect encoding of attributed type");
5459 return QualType();
5460 }
5461 QualType modifiedType = readType(*Loc.F, Record, Idx);
5462 QualType equivalentType = readType(*Loc.F, Record, Idx);
5463 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5464 return Context.getAttributedType(kind, modifiedType, equivalentType);
5465 }
5466
5467 case TYPE_PAREN: {
5468 if (Record.size() != 1) {
5469 Error("incorrect encoding of paren type");
5470 return QualType();
5471 }
5472 QualType InnerType = readType(*Loc.F, Record, Idx);
5473 return Context.getParenType(InnerType);
5474 }
5475
5476 case TYPE_PACK_EXPANSION: {
5477 if (Record.size() != 2) {
5478 Error("incorrect encoding of pack expansion type");
5479 return QualType();
5480 }
5481 QualType Pattern = readType(*Loc.F, Record, Idx);
5482 if (Pattern.isNull())
5483 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005484 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005485 if (Record[1])
5486 NumExpansions = Record[1] - 1;
5487 return Context.getPackExpansionType(Pattern, NumExpansions);
5488 }
5489
5490 case TYPE_ELABORATED: {
5491 unsigned Idx = 0;
5492 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5493 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5494 QualType NamedType = readType(*Loc.F, Record, Idx);
5495 return Context.getElaboratedType(Keyword, NNS, NamedType);
5496 }
5497
5498 case TYPE_OBJC_INTERFACE: {
5499 unsigned Idx = 0;
5500 ObjCInterfaceDecl *ItfD
5501 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5502 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5503 }
5504
5505 case TYPE_OBJC_OBJECT: {
5506 unsigned Idx = 0;
5507 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005508 unsigned NumTypeArgs = Record[Idx++];
5509 SmallVector<QualType, 4> TypeArgs;
5510 for (unsigned I = 0; I != NumTypeArgs; ++I)
5511 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005512 unsigned NumProtos = Record[Idx++];
5513 SmallVector<ObjCProtocolDecl*, 4> Protos;
5514 for (unsigned I = 0; I != NumProtos; ++I)
5515 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005516 bool IsKindOf = Record[Idx++];
5517 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005518 }
5519
5520 case TYPE_OBJC_OBJECT_POINTER: {
5521 unsigned Idx = 0;
5522 QualType Pointee = readType(*Loc.F, Record, Idx);
5523 return Context.getObjCObjectPointerType(Pointee);
5524 }
5525
5526 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5527 unsigned Idx = 0;
5528 QualType Parm = readType(*Loc.F, Record, Idx);
5529 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005530 return Context.getSubstTemplateTypeParmType(
5531 cast<TemplateTypeParmType>(Parm),
5532 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005533 }
5534
5535 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5536 unsigned Idx = 0;
5537 QualType Parm = readType(*Loc.F, Record, Idx);
5538 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5539 return Context.getSubstTemplateTypeParmPackType(
5540 cast<TemplateTypeParmType>(Parm),
5541 ArgPack);
5542 }
5543
5544 case TYPE_INJECTED_CLASS_NAME: {
5545 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5546 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5547 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5548 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005549 const Type *T = nullptr;
5550 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5551 if (const Type *Existing = DI->getTypeForDecl()) {
5552 T = Existing;
5553 break;
5554 }
5555 }
5556 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005557 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005558 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5559 DI->setTypeForDecl(T);
5560 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005561 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005562 }
5563
5564 case TYPE_TEMPLATE_TYPE_PARM: {
5565 unsigned Idx = 0;
5566 unsigned Depth = Record[Idx++];
5567 unsigned Index = Record[Idx++];
5568 bool Pack = Record[Idx++];
5569 TemplateTypeParmDecl *D
5570 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5571 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5572 }
5573
5574 case TYPE_DEPENDENT_NAME: {
5575 unsigned Idx = 0;
5576 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5577 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005578 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005579 QualType Canon = readType(*Loc.F, Record, Idx);
5580 if (!Canon.isNull())
5581 Canon = Context.getCanonicalType(Canon);
5582 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5583 }
5584
5585 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5586 unsigned Idx = 0;
5587 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5588 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005589 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005590 unsigned NumArgs = Record[Idx++];
5591 SmallVector<TemplateArgument, 8> Args;
5592 Args.reserve(NumArgs);
5593 while (NumArgs--)
5594 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5595 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5596 Args.size(), Args.data());
5597 }
5598
5599 case TYPE_DEPENDENT_SIZED_ARRAY: {
5600 unsigned Idx = 0;
5601
5602 // ArrayType
5603 QualType ElementType = readType(*Loc.F, Record, Idx);
5604 ArrayType::ArraySizeModifier ASM
5605 = (ArrayType::ArraySizeModifier)Record[Idx++];
5606 unsigned IndexTypeQuals = Record[Idx++];
5607
5608 // DependentSizedArrayType
5609 Expr *NumElts = ReadExpr(*Loc.F);
5610 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5611
5612 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5613 IndexTypeQuals, Brackets);
5614 }
5615
5616 case TYPE_TEMPLATE_SPECIALIZATION: {
5617 unsigned Idx = 0;
5618 bool IsDependent = Record[Idx++];
5619 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5620 SmallVector<TemplateArgument, 8> Args;
5621 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5622 QualType Underlying = readType(*Loc.F, Record, Idx);
5623 QualType T;
5624 if (Underlying.isNull())
5625 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5626 Args.size());
5627 else
5628 T = Context.getTemplateSpecializationType(Name, Args.data(),
5629 Args.size(), Underlying);
5630 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5631 return T;
5632 }
5633
5634 case TYPE_ATOMIC: {
5635 if (Record.size() != 1) {
5636 Error("Incorrect encoding of atomic type");
5637 return QualType();
5638 }
5639 QualType ValueType = readType(*Loc.F, Record, Idx);
5640 return Context.getAtomicType(ValueType);
5641 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00005642
5643 case TYPE_PIPE: {
5644 if (Record.size() != 1) {
5645 Error("Incorrect encoding of pipe type");
5646 return QualType();
5647 }
5648
5649 // Reading the pipe element type.
5650 QualType ElementType = readType(*Loc.F, Record, Idx);
5651 return Context.getPipeType(ElementType);
5652 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005653 }
5654 llvm_unreachable("Invalid TypeCode!");
5655}
5656
Richard Smith564417a2014-03-20 21:47:22 +00005657void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5658 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005659 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005660 const RecordData &Record, unsigned &Idx) {
5661 ExceptionSpecificationType EST =
5662 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005663 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005664 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005665 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005666 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005667 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005668 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005669 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005670 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005671 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5672 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005673 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005674 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005675 }
5676}
5677
Guy Benyei11169dd2012-12-18 14:30:41 +00005678class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5679 ASTReader &Reader;
5680 ModuleFile &F;
5681 const ASTReader::RecordData &Record;
5682 unsigned &Idx;
5683
5684 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5685 unsigned &I) {
5686 return Reader.ReadSourceLocation(F, R, I);
5687 }
5688
5689 template<typename T>
5690 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5691 return Reader.ReadDeclAs<T>(F, Record, Idx);
5692 }
5693
5694public:
5695 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5696 const ASTReader::RecordData &Record, unsigned &Idx)
5697 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5698 { }
5699
5700 // We want compile-time assurance that we've enumerated all of
5701 // these, so unfortunately we have to declare them first, then
5702 // define them out-of-line.
5703#define ABSTRACT_TYPELOC(CLASS, PARENT)
5704#define TYPELOC(CLASS, PARENT) \
5705 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5706#include "clang/AST/TypeLocNodes.def"
5707
5708 void VisitFunctionTypeLoc(FunctionTypeLoc);
5709 void VisitArrayTypeLoc(ArrayTypeLoc);
5710};
5711
5712void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5713 // nothing to do
5714}
5715void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5716 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5717 if (TL.needsExtraLocalData()) {
5718 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5719 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5720 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5721 TL.setModeAttr(Record[Idx++]);
5722 }
5723}
5724void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5725 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5726}
5727void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5728 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5729}
Reid Kleckner8a365022013-06-24 17:51:48 +00005730void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5731 // nothing to do
5732}
Reid Kleckner0503a872013-12-05 01:23:43 +00005733void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5734 // nothing to do
5735}
Guy Benyei11169dd2012-12-18 14:30:41 +00005736void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5737 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5738}
5739void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5740 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5741}
5742void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5743 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5744}
5745void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5746 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5747 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5748}
5749void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5750 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5751 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5752 if (Record[Idx++])
5753 TL.setSizeExpr(Reader.ReadExpr(F));
5754 else
Craig Toppera13603a2014-05-22 05:54:18 +00005755 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005756}
5757void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5758 VisitArrayTypeLoc(TL);
5759}
5760void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5761 VisitArrayTypeLoc(TL);
5762}
5763void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5764 VisitArrayTypeLoc(TL);
5765}
5766void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5767 DependentSizedArrayTypeLoc TL) {
5768 VisitArrayTypeLoc(TL);
5769}
5770void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5771 DependentSizedExtVectorTypeLoc TL) {
5772 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5773}
5774void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5775 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5776}
5777void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5778 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5779}
5780void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5781 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5782 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5783 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5784 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005785 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5786 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005787 }
5788}
5789void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5790 VisitFunctionTypeLoc(TL);
5791}
5792void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5793 VisitFunctionTypeLoc(TL);
5794}
5795void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5796 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5797}
5798void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5799 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5800}
5801void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5802 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5803 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5804 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5805}
5806void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5807 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5808 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5809 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5810 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5811}
5812void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5813 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5814}
5815void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5816 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5817 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5818 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5819 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5820}
5821void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5822 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5823}
5824void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5825 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5826}
5827void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5828 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5829}
5830void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5831 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5832 if (TL.hasAttrOperand()) {
5833 SourceRange range;
5834 range.setBegin(ReadSourceLocation(Record, Idx));
5835 range.setEnd(ReadSourceLocation(Record, Idx));
5836 TL.setAttrOperandParensRange(range);
5837 }
5838 if (TL.hasAttrExprOperand()) {
5839 if (Record[Idx++])
5840 TL.setAttrExprOperand(Reader.ReadExpr(F));
5841 else
Craig Toppera13603a2014-05-22 05:54:18 +00005842 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005843 } else if (TL.hasAttrEnumOperand())
5844 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5845}
5846void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5847 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5848}
5849void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5850 SubstTemplateTypeParmTypeLoc TL) {
5851 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5852}
5853void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5854 SubstTemplateTypeParmPackTypeLoc TL) {
5855 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5856}
5857void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5858 TemplateSpecializationTypeLoc TL) {
5859 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5860 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5861 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5862 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5863 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5864 TL.setArgLocInfo(i,
5865 Reader.GetTemplateArgumentLocInfo(F,
5866 TL.getTypePtr()->getArg(i).getKind(),
5867 Record, Idx));
5868}
5869void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5870 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5871 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5872}
5873void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5874 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5875 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5876}
5877void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5878 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5879}
5880void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5881 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5882 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5883 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5884}
5885void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5886 DependentTemplateSpecializationTypeLoc TL) {
5887 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5888 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5889 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5890 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5891 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5892 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5893 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5894 TL.setArgLocInfo(I,
5895 Reader.GetTemplateArgumentLocInfo(F,
5896 TL.getTypePtr()->getArg(I).getKind(),
5897 Record, Idx));
5898}
5899void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5900 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5901}
5902void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5903 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5904}
5905void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5906 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005907 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5908 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5909 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5910 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5911 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5912 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005913 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5914 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5915}
5916void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5917 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5918}
5919void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5920 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5921 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5922 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5923}
Xiuli Pan9c14e282016-01-09 12:53:17 +00005924void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
5925 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5926}
Guy Benyei11169dd2012-12-18 14:30:41 +00005927
5928TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5929 const RecordData &Record,
5930 unsigned &Idx) {
5931 QualType InfoTy = readType(F, Record, Idx);
5932 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005933 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005934
5935 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5936 TypeLocReader TLR(*this, F, Record, Idx);
5937 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5938 TLR.Visit(TL);
5939 return TInfo;
5940}
5941
5942QualType ASTReader::GetType(TypeID ID) {
5943 unsigned FastQuals = ID & Qualifiers::FastMask;
5944 unsigned Index = ID >> Qualifiers::FastWidth;
5945
5946 if (Index < NUM_PREDEF_TYPE_IDS) {
5947 QualType T;
5948 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00005949 case PREDEF_TYPE_NULL_ID:
5950 return QualType();
5951 case PREDEF_TYPE_VOID_ID:
5952 T = Context.VoidTy;
5953 break;
5954 case PREDEF_TYPE_BOOL_ID:
5955 T = Context.BoolTy;
5956 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005957
5958 case PREDEF_TYPE_CHAR_U_ID:
5959 case PREDEF_TYPE_CHAR_S_ID:
5960 // FIXME: Check that the signedness of CharTy is correct!
5961 T = Context.CharTy;
5962 break;
5963
Alexey Baderbdf7c842015-09-15 12:18:29 +00005964 case PREDEF_TYPE_UCHAR_ID:
5965 T = Context.UnsignedCharTy;
5966 break;
5967 case PREDEF_TYPE_USHORT_ID:
5968 T = Context.UnsignedShortTy;
5969 break;
5970 case PREDEF_TYPE_UINT_ID:
5971 T = Context.UnsignedIntTy;
5972 break;
5973 case PREDEF_TYPE_ULONG_ID:
5974 T = Context.UnsignedLongTy;
5975 break;
5976 case PREDEF_TYPE_ULONGLONG_ID:
5977 T = Context.UnsignedLongLongTy;
5978 break;
5979 case PREDEF_TYPE_UINT128_ID:
5980 T = Context.UnsignedInt128Ty;
5981 break;
5982 case PREDEF_TYPE_SCHAR_ID:
5983 T = Context.SignedCharTy;
5984 break;
5985 case PREDEF_TYPE_WCHAR_ID:
5986 T = Context.WCharTy;
5987 break;
5988 case PREDEF_TYPE_SHORT_ID:
5989 T = Context.ShortTy;
5990 break;
5991 case PREDEF_TYPE_INT_ID:
5992 T = Context.IntTy;
5993 break;
5994 case PREDEF_TYPE_LONG_ID:
5995 T = Context.LongTy;
5996 break;
5997 case PREDEF_TYPE_LONGLONG_ID:
5998 T = Context.LongLongTy;
5999 break;
6000 case PREDEF_TYPE_INT128_ID:
6001 T = Context.Int128Ty;
6002 break;
6003 case PREDEF_TYPE_HALF_ID:
6004 T = Context.HalfTy;
6005 break;
6006 case PREDEF_TYPE_FLOAT_ID:
6007 T = Context.FloatTy;
6008 break;
6009 case PREDEF_TYPE_DOUBLE_ID:
6010 T = Context.DoubleTy;
6011 break;
6012 case PREDEF_TYPE_LONGDOUBLE_ID:
6013 T = Context.LongDoubleTy;
6014 break;
6015 case PREDEF_TYPE_OVERLOAD_ID:
6016 T = Context.OverloadTy;
6017 break;
6018 case PREDEF_TYPE_BOUND_MEMBER:
6019 T = Context.BoundMemberTy;
6020 break;
6021 case PREDEF_TYPE_PSEUDO_OBJECT:
6022 T = Context.PseudoObjectTy;
6023 break;
6024 case PREDEF_TYPE_DEPENDENT_ID:
6025 T = Context.DependentTy;
6026 break;
6027 case PREDEF_TYPE_UNKNOWN_ANY:
6028 T = Context.UnknownAnyTy;
6029 break;
6030 case PREDEF_TYPE_NULLPTR_ID:
6031 T = Context.NullPtrTy;
6032 break;
6033 case PREDEF_TYPE_CHAR16_ID:
6034 T = Context.Char16Ty;
6035 break;
6036 case PREDEF_TYPE_CHAR32_ID:
6037 T = Context.Char32Ty;
6038 break;
6039 case PREDEF_TYPE_OBJC_ID:
6040 T = Context.ObjCBuiltinIdTy;
6041 break;
6042 case PREDEF_TYPE_OBJC_CLASS:
6043 T = Context.ObjCBuiltinClassTy;
6044 break;
6045 case PREDEF_TYPE_OBJC_SEL:
6046 T = Context.ObjCBuiltinSelTy;
6047 break;
6048 case PREDEF_TYPE_IMAGE1D_ID:
6049 T = Context.OCLImage1dTy;
6050 break;
6051 case PREDEF_TYPE_IMAGE1D_ARR_ID:
6052 T = Context.OCLImage1dArrayTy;
6053 break;
6054 case PREDEF_TYPE_IMAGE1D_BUFF_ID:
6055 T = Context.OCLImage1dBufferTy;
6056 break;
6057 case PREDEF_TYPE_IMAGE2D_ID:
6058 T = Context.OCLImage2dTy;
6059 break;
6060 case PREDEF_TYPE_IMAGE2D_ARR_ID:
6061 T = Context.OCLImage2dArrayTy;
6062 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006063 case PREDEF_TYPE_IMAGE2D_DEP_ID:
6064 T = Context.OCLImage2dDepthTy;
6065 break;
6066 case PREDEF_TYPE_IMAGE2D_ARR_DEP_ID:
6067 T = Context.OCLImage2dArrayDepthTy;
6068 break;
6069 case PREDEF_TYPE_IMAGE2D_MSAA_ID:
6070 T = Context.OCLImage2dMSAATy;
6071 break;
6072 case PREDEF_TYPE_IMAGE2D_ARR_MSAA_ID:
6073 T = Context.OCLImage2dArrayMSAATy;
6074 break;
6075 case PREDEF_TYPE_IMAGE2D_MSAA_DEP_ID:
6076 T = Context.OCLImage2dMSAADepthTy;
6077 break;
6078 case PREDEF_TYPE_IMAGE2D_ARR_MSAA_DEPTH_ID:
6079 T = Context.OCLImage2dArrayMSAADepthTy;
6080 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006081 case PREDEF_TYPE_IMAGE3D_ID:
6082 T = Context.OCLImage3dTy;
6083 break;
6084 case PREDEF_TYPE_SAMPLER_ID:
6085 T = Context.OCLSamplerTy;
6086 break;
6087 case PREDEF_TYPE_EVENT_ID:
6088 T = Context.OCLEventTy;
6089 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006090 case PREDEF_TYPE_CLK_EVENT_ID:
6091 T = Context.OCLClkEventTy;
6092 break;
6093 case PREDEF_TYPE_QUEUE_ID:
6094 T = Context.OCLQueueTy;
6095 break;
6096 case PREDEF_TYPE_NDRANGE_ID:
6097 T = Context.OCLNDRangeTy;
6098 break;
6099 case PREDEF_TYPE_RESERVE_ID_ID:
6100 T = Context.OCLReserveIDTy;
6101 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006102 case PREDEF_TYPE_AUTO_DEDUCT:
6103 T = Context.getAutoDeductType();
6104 break;
6105
6106 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6107 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006108 break;
6109
6110 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6111 T = Context.ARCUnbridgedCastTy;
6112 break;
6113
Guy Benyei11169dd2012-12-18 14:30:41 +00006114 case PREDEF_TYPE_BUILTIN_FN:
6115 T = Context.BuiltinFnTy;
6116 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006117
6118 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6119 T = Context.OMPArraySectionTy;
6120 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006121 }
6122
6123 assert(!T.isNull() && "Unknown predefined type");
6124 return T.withFastQualifiers(FastQuals);
6125 }
6126
6127 Index -= NUM_PREDEF_TYPE_IDS;
6128 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6129 if (TypesLoaded[Index].isNull()) {
6130 TypesLoaded[Index] = readTypeRecord(Index);
6131 if (TypesLoaded[Index].isNull())
6132 return QualType();
6133
6134 TypesLoaded[Index]->setFromAST();
6135 if (DeserializationListener)
6136 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6137 TypesLoaded[Index]);
6138 }
6139
6140 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6141}
6142
6143QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6144 return GetType(getGlobalTypeID(F, LocalID));
6145}
6146
6147serialization::TypeID
6148ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6149 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6150 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6151
6152 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6153 return LocalID;
6154
6155 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6156 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6157 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6158
6159 unsigned GlobalIndex = LocalIndex + I->second;
6160 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6161}
6162
6163TemplateArgumentLocInfo
6164ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6165 TemplateArgument::ArgKind Kind,
6166 const RecordData &Record,
6167 unsigned &Index) {
6168 switch (Kind) {
6169 case TemplateArgument::Expression:
6170 return ReadExpr(F);
6171 case TemplateArgument::Type:
6172 return GetTypeSourceInfo(F, Record, Index);
6173 case TemplateArgument::Template: {
6174 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6175 Index);
6176 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6177 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6178 SourceLocation());
6179 }
6180 case TemplateArgument::TemplateExpansion: {
6181 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6182 Index);
6183 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6184 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6185 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6186 EllipsisLoc);
6187 }
6188 case TemplateArgument::Null:
6189 case TemplateArgument::Integral:
6190 case TemplateArgument::Declaration:
6191 case TemplateArgument::NullPtr:
6192 case TemplateArgument::Pack:
6193 // FIXME: Is this right?
6194 return TemplateArgumentLocInfo();
6195 }
6196 llvm_unreachable("unexpected template argument loc");
6197}
6198
6199TemplateArgumentLoc
6200ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6201 const RecordData &Record, unsigned &Index) {
6202 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6203
6204 if (Arg.getKind() == TemplateArgument::Expression) {
6205 if (Record[Index++]) // bool InfoHasSameExpr.
6206 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6207 }
6208 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6209 Record, Index));
6210}
6211
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006212const ASTTemplateArgumentListInfo*
6213ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6214 const RecordData &Record,
6215 unsigned &Index) {
6216 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6217 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6218 unsigned NumArgsAsWritten = Record[Index++];
6219 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6220 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6221 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6222 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6223}
6224
Guy Benyei11169dd2012-12-18 14:30:41 +00006225Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6226 return GetDecl(ID);
6227}
6228
Richard Smith50895422015-01-31 03:04:55 +00006229template<typename TemplateSpecializationDecl>
6230static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6231 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6232 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6233}
6234
Richard Smith053f6c62014-05-16 23:01:30 +00006235void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006236 if (NumCurrentElementsDeserializing) {
6237 // We arrange to not care about the complete redeclaration chain while we're
6238 // deserializing. Just remember that the AST has marked this one as complete
6239 // but that it's not actually complete yet, so we know we still need to
6240 // complete it later.
6241 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6242 return;
6243 }
6244
Richard Smith053f6c62014-05-16 23:01:30 +00006245 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6246
Richard Smith053f6c62014-05-16 23:01:30 +00006247 // If this is a named declaration, complete it by looking it up
6248 // within its context.
6249 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006250 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006251 // all mergeable entities within it.
6252 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6253 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6254 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006255 if (!getContext().getLangOpts().CPlusPlus &&
6256 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006257 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006258 // the identifier instead. (For C++ modules, we don't store decls
6259 // in the serialized identifier table, so we do the lookup in the TU.)
6260 auto *II = Name.getAsIdentifierInfo();
6261 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006262 if (II->isOutOfDate())
6263 updateOutOfDateIdentifier(*II);
6264 } else
6265 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006266 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006267 // Find all declarations of this kind from the relevant context.
6268 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6269 auto *DC = cast<DeclContext>(DCDecl);
6270 SmallVector<Decl*, 8> Decls;
6271 FindExternalLexicalDecls(
6272 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6273 }
Richard Smith053f6c62014-05-16 23:01:30 +00006274 }
6275 }
Richard Smith50895422015-01-31 03:04:55 +00006276
6277 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6278 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6279 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6280 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6281 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6282 if (auto *Template = FD->getPrimaryTemplate())
6283 Template->LoadLazySpecializations();
6284 }
Richard Smith053f6c62014-05-16 23:01:30 +00006285}
6286
Richard Smithc2bb8182015-03-24 06:36:48 +00006287uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
6288 const RecordData &Record,
6289 unsigned &Idx) {
6290 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
6291 Error("malformed AST file: missing C++ ctor initializers");
6292 return 0;
6293 }
6294
6295 unsigned LocalID = Record[Idx++];
6296 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6297}
6298
6299CXXCtorInitializer **
6300ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6301 RecordLocation Loc = getLocalBitOffset(Offset);
6302 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6303 SavedStreamPosition SavedPosition(Cursor);
6304 Cursor.JumpToBit(Loc.Offset);
6305 ReadingKindTracker ReadingKind(Read_Decl, *this);
6306
6307 RecordData Record;
6308 unsigned Code = Cursor.ReadCode();
6309 unsigned RecCode = Cursor.readRecord(Code, Record);
6310 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6311 Error("malformed AST file: missing C++ ctor initializers");
6312 return nullptr;
6313 }
6314
6315 unsigned Idx = 0;
6316 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6317}
6318
Richard Smithcd45dbc2014-04-19 03:48:30 +00006319uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6320 const RecordData &Record,
6321 unsigned &Idx) {
6322 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6323 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006324 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006325 }
6326
Guy Benyei11169dd2012-12-18 14:30:41 +00006327 unsigned LocalID = Record[Idx++];
6328 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6329}
6330
6331CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6332 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006333 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006334 SavedStreamPosition SavedPosition(Cursor);
6335 Cursor.JumpToBit(Loc.Offset);
6336 ReadingKindTracker ReadingKind(Read_Decl, *this);
6337 RecordData Record;
6338 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006339 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006340 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006341 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006342 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006343 }
6344
6345 unsigned Idx = 0;
6346 unsigned NumBases = Record[Idx++];
6347 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6348 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6349 for (unsigned I = 0; I != NumBases; ++I)
6350 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6351 return Bases;
6352}
6353
6354serialization::DeclID
6355ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6356 if (LocalID < NUM_PREDEF_DECL_IDS)
6357 return LocalID;
6358
6359 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6360 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6361 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6362
6363 return LocalID + I->second;
6364}
6365
6366bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6367 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006368 // Predefined decls aren't from any module.
6369 if (ID < NUM_PREDEF_DECL_IDS)
6370 return false;
6371
Richard Smithbcda1a92015-07-12 23:51:20 +00006372 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6373 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006374}
6375
Douglas Gregor9f782892013-01-21 15:25:38 +00006376ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006377 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006378 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006379 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6380 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6381 return I->second;
6382}
6383
6384SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6385 if (ID < NUM_PREDEF_DECL_IDS)
6386 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006387
Guy Benyei11169dd2012-12-18 14:30:41 +00006388 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6389
6390 if (Index > DeclsLoaded.size()) {
6391 Error("declaration ID out-of-range for AST file");
6392 return SourceLocation();
6393 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006394
Guy Benyei11169dd2012-12-18 14:30:41 +00006395 if (Decl *D = DeclsLoaded[Index])
6396 return D->getLocation();
6397
6398 unsigned RawLocation = 0;
6399 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6400 return ReadSourceLocation(*Rec.F, RawLocation);
6401}
6402
Richard Smithfe620d22015-03-05 23:24:12 +00006403static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6404 switch (ID) {
6405 case PREDEF_DECL_NULL_ID:
6406 return nullptr;
6407
6408 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6409 return Context.getTranslationUnitDecl();
6410
6411 case PREDEF_DECL_OBJC_ID_ID:
6412 return Context.getObjCIdDecl();
6413
6414 case PREDEF_DECL_OBJC_SEL_ID:
6415 return Context.getObjCSelDecl();
6416
6417 case PREDEF_DECL_OBJC_CLASS_ID:
6418 return Context.getObjCClassDecl();
6419
6420 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6421 return Context.getObjCProtocolDecl();
6422
6423 case PREDEF_DECL_INT_128_ID:
6424 return Context.getInt128Decl();
6425
6426 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6427 return Context.getUInt128Decl();
6428
6429 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6430 return Context.getObjCInstanceTypeDecl();
6431
6432 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6433 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006434
Richard Smith9b88a4c2015-07-27 05:40:23 +00006435 case PREDEF_DECL_VA_LIST_TAG:
6436 return Context.getVaListTagDecl();
6437
Charles Davisc7d5c942015-09-17 20:55:33 +00006438 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6439 return Context.getBuiltinMSVaListDecl();
6440
Richard Smithf19e1272015-03-07 00:04:49 +00006441 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6442 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006443
6444 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6445 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00006446
6447 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6448 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00006449
6450 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6451 return Context.getCFConstantStringTagDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006452 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006453 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006454}
6455
Richard Smithcd45dbc2014-04-19 03:48:30 +00006456Decl *ASTReader::GetExistingDecl(DeclID ID) {
6457 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006458 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6459 if (D) {
6460 // Track that we have merged the declaration with ID \p ID into the
6461 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006462 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006463 if (Merged.empty())
6464 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006465 }
Richard Smithfe620d22015-03-05 23:24:12 +00006466 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006467 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006468
Guy Benyei11169dd2012-12-18 14:30:41 +00006469 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6470
6471 if (Index >= DeclsLoaded.size()) {
6472 assert(0 && "declaration ID out-of-range for AST file");
6473 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006474 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006475 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006476
6477 return DeclsLoaded[Index];
6478}
6479
6480Decl *ASTReader::GetDecl(DeclID ID) {
6481 if (ID < NUM_PREDEF_DECL_IDS)
6482 return GetExistingDecl(ID);
6483
6484 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6485
6486 if (Index >= DeclsLoaded.size()) {
6487 assert(0 && "declaration ID out-of-range for AST file");
6488 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006489 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006490 }
6491
Guy Benyei11169dd2012-12-18 14:30:41 +00006492 if (!DeclsLoaded[Index]) {
6493 ReadDeclRecord(ID);
6494 if (DeserializationListener)
6495 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6496 }
6497
6498 return DeclsLoaded[Index];
6499}
6500
6501DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6502 DeclID GlobalID) {
6503 if (GlobalID < NUM_PREDEF_DECL_IDS)
6504 return GlobalID;
6505
6506 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6507 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6508 ModuleFile *Owner = I->second;
6509
6510 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6511 = M.GlobalToLocalDeclIDs.find(Owner);
6512 if (Pos == M.GlobalToLocalDeclIDs.end())
6513 return 0;
6514
6515 return GlobalID - Owner->BaseDeclID + Pos->second;
6516}
6517
6518serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6519 const RecordData &Record,
6520 unsigned &Idx) {
6521 if (Idx >= Record.size()) {
6522 Error("Corrupted AST file");
6523 return 0;
6524 }
6525
6526 return getGlobalDeclID(F, Record[Idx++]);
6527}
6528
6529/// \brief Resolve the offset of a statement into a statement.
6530///
6531/// This operation will read a new statement from the external
6532/// source each time it is called, and is meant to be used via a
6533/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6534Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6535 // Switch case IDs are per Decl.
6536 ClearSwitchCaseIDs();
6537
6538 // Offset here is a global offset across the entire chain.
6539 RecordLocation Loc = getLocalBitOffset(Offset);
6540 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6541 return ReadStmtFromStream(*Loc.F);
6542}
6543
Richard Smith3cb15722015-08-05 22:41:45 +00006544void ASTReader::FindExternalLexicalDecls(
6545 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6546 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006547 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6548
Richard Smith9ccdd932015-08-06 22:14:12 +00006549 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006550 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6551 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6552 auto K = (Decl::Kind)+LexicalDecls[I];
6553 if (!IsKindWeWant(K))
6554 continue;
6555
6556 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6557
6558 // Don't add predefined declarations to the lexical context more
6559 // than once.
6560 if (ID < NUM_PREDEF_DECL_IDS) {
6561 if (PredefsVisited[ID])
6562 continue;
6563
6564 PredefsVisited[ID] = true;
6565 }
6566
6567 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006568 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006569 if (!DC->isDeclInLexicalTraversal(D))
6570 Decls.push_back(D);
6571 }
6572 }
6573 };
6574
6575 if (isa<TranslationUnitDecl>(DC)) {
6576 for (auto Lexical : TULexicalDecls)
6577 Visit(Lexical.first, Lexical.second);
6578 } else {
6579 auto I = LexicalDecls.find(DC);
6580 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006581 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006582 }
6583
Guy Benyei11169dd2012-12-18 14:30:41 +00006584 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006585}
6586
6587namespace {
6588
6589class DeclIDComp {
6590 ASTReader &Reader;
6591 ModuleFile &Mod;
6592
6593public:
6594 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6595
6596 bool operator()(LocalDeclID L, LocalDeclID R) const {
6597 SourceLocation LHS = getLocation(L);
6598 SourceLocation RHS = getLocation(R);
6599 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6600 }
6601
6602 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6603 SourceLocation RHS = getLocation(R);
6604 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6605 }
6606
6607 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6608 SourceLocation LHS = getLocation(L);
6609 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6610 }
6611
6612 SourceLocation getLocation(LocalDeclID ID) const {
6613 return Reader.getSourceManager().getFileLoc(
6614 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6615 }
6616};
6617
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006618}
Guy Benyei11169dd2012-12-18 14:30:41 +00006619
6620void ASTReader::FindFileRegionDecls(FileID File,
6621 unsigned Offset, unsigned Length,
6622 SmallVectorImpl<Decl *> &Decls) {
6623 SourceManager &SM = getSourceManager();
6624
6625 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6626 if (I == FileDeclIDs.end())
6627 return;
6628
6629 FileDeclsInfo &DInfo = I->second;
6630 if (DInfo.Decls.empty())
6631 return;
6632
6633 SourceLocation
6634 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6635 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6636
6637 DeclIDComp DIDComp(*this, *DInfo.Mod);
6638 ArrayRef<serialization::LocalDeclID>::iterator
6639 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6640 BeginLoc, DIDComp);
6641 if (BeginIt != DInfo.Decls.begin())
6642 --BeginIt;
6643
6644 // If we are pointing at a top-level decl inside an objc container, we need
6645 // to backtrack until we find it otherwise we will fail to report that the
6646 // region overlaps with an objc container.
6647 while (BeginIt != DInfo.Decls.begin() &&
6648 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6649 ->isTopLevelDeclInObjCContainer())
6650 --BeginIt;
6651
6652 ArrayRef<serialization::LocalDeclID>::iterator
6653 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6654 EndLoc, DIDComp);
6655 if (EndIt != DInfo.Decls.end())
6656 ++EndIt;
6657
6658 for (ArrayRef<serialization::LocalDeclID>::iterator
6659 DIt = BeginIt; DIt != EndIt; ++DIt)
6660 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6661}
6662
Richard Smith9ce12e32013-02-07 03:30:24 +00006663bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006664ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6665 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006666 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006667 "DeclContext has no visible decls in storage");
6668 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006669 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006670
Richard Smithd88a7f12015-09-01 20:35:42 +00006671 auto It = Lookups.find(DC);
6672 if (It == Lookups.end())
6673 return false;
6674
Richard Smith8c913ec2014-08-14 02:21:01 +00006675 Deserializing LookupResults(this);
6676
Richard Smithd88a7f12015-09-01 20:35:42 +00006677 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006678 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006679 for (DeclID ID : It->second.Table.find(Name)) {
6680 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6681 if (ND->getDeclName() == Name)
6682 Decls.push_back(ND);
6683 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006684
Guy Benyei11169dd2012-12-18 14:30:41 +00006685 ++NumVisibleDeclContextsRead;
6686 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006687 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006688}
6689
Guy Benyei11169dd2012-12-18 14:30:41 +00006690void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6691 if (!DC->hasExternalVisibleStorage())
6692 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006693
6694 auto It = Lookups.find(DC);
6695 assert(It != Lookups.end() &&
6696 "have external visible storage but no lookup tables");
6697
Craig Topper79be4cd2013-07-05 04:33:53 +00006698 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006699
Richard Smithd88a7f12015-09-01 20:35:42 +00006700 for (DeclID ID : It->second.Table.findAll()) {
6701 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6702 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006703 }
6704
Guy Benyei11169dd2012-12-18 14:30:41 +00006705 ++NumVisibleDeclContextsRead;
6706
Craig Topper79be4cd2013-07-05 04:33:53 +00006707 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006708 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6709 }
6710 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6711}
6712
Richard Smithd88a7f12015-09-01 20:35:42 +00006713const serialization::reader::DeclContextLookupTable *
6714ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6715 auto I = Lookups.find(Primary);
6716 return I == Lookups.end() ? nullptr : &I->second;
6717}
6718
Guy Benyei11169dd2012-12-18 14:30:41 +00006719/// \brief Under non-PCH compilation the consumer receives the objc methods
6720/// before receiving the implementation, and codegen depends on this.
6721/// We simulate this by deserializing and passing to consumer the methods of the
6722/// implementation before passing the deserialized implementation decl.
6723static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6724 ASTConsumer *Consumer) {
6725 assert(ImplD && Consumer);
6726
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006727 for (auto *I : ImplD->methods())
6728 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006729
6730 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6731}
6732
6733void ASTReader::PassInterestingDeclsToConsumer() {
6734 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006735
6736 if (PassingDeclsToConsumer)
6737 return;
6738
6739 // Guard variable to avoid recursively redoing the process of passing
6740 // decls to consumer.
6741 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6742 true);
6743
Richard Smith9e2341d2015-03-23 03:25:59 +00006744 // Ensure that we've loaded all potentially-interesting declarations
6745 // that need to be eagerly loaded.
6746 for (auto ID : EagerlyDeserializedDecls)
6747 GetDecl(ID);
6748 EagerlyDeserializedDecls.clear();
6749
Guy Benyei11169dd2012-12-18 14:30:41 +00006750 while (!InterestingDecls.empty()) {
6751 Decl *D = InterestingDecls.front();
6752 InterestingDecls.pop_front();
6753
6754 PassInterestingDeclToConsumer(D);
6755 }
6756}
6757
6758void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6759 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6760 PassObjCImplDeclToConsumer(ImplD, Consumer);
6761 else
6762 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6763}
6764
6765void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6766 this->Consumer = Consumer;
6767
Richard Smith9e2341d2015-03-23 03:25:59 +00006768 if (Consumer)
6769 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006770
6771 if (DeserializationListener)
6772 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006773}
6774
6775void ASTReader::PrintStats() {
6776 std::fprintf(stderr, "*** AST File Statistics:\n");
6777
6778 unsigned NumTypesLoaded
6779 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6780 QualType());
6781 unsigned NumDeclsLoaded
6782 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006783 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006784 unsigned NumIdentifiersLoaded
6785 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6786 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006787 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006788 unsigned NumMacrosLoaded
6789 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6790 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006791 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006792 unsigned NumSelectorsLoaded
6793 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6794 SelectorsLoaded.end(),
6795 Selector());
6796
6797 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6798 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6799 NumSLocEntriesRead, TotalNumSLocEntries,
6800 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6801 if (!TypesLoaded.empty())
6802 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6803 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6804 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6805 if (!DeclsLoaded.empty())
6806 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6807 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6808 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6809 if (!IdentifiersLoaded.empty())
6810 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6811 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6812 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6813 if (!MacrosLoaded.empty())
6814 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6815 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6816 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6817 if (!SelectorsLoaded.empty())
6818 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6819 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6820 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6821 if (TotalNumStatements)
6822 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6823 NumStatementsRead, TotalNumStatements,
6824 ((float)NumStatementsRead/TotalNumStatements * 100));
6825 if (TotalNumMacros)
6826 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6827 NumMacrosRead, TotalNumMacros,
6828 ((float)NumMacrosRead/TotalNumMacros * 100));
6829 if (TotalLexicalDeclContexts)
6830 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6831 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6832 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6833 * 100));
6834 if (TotalVisibleDeclContexts)
6835 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6836 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6837 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6838 * 100));
6839 if (TotalNumMethodPoolEntries) {
6840 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6841 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6842 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6843 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006844 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006845 if (NumMethodPoolLookups) {
6846 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6847 NumMethodPoolHits, NumMethodPoolLookups,
6848 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6849 }
6850 if (NumMethodPoolTableLookups) {
6851 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6852 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6853 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6854 * 100.0));
6855 }
6856
Douglas Gregor00a50f72013-01-25 00:38:33 +00006857 if (NumIdentifierLookupHits) {
6858 std::fprintf(stderr,
6859 " %u / %u identifier table lookups succeeded (%f%%)\n",
6860 NumIdentifierLookupHits, NumIdentifierLookups,
6861 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6862 }
6863
Douglas Gregore060e572013-01-25 01:03:03 +00006864 if (GlobalIndex) {
6865 std::fprintf(stderr, "\n");
6866 GlobalIndex->printStats();
6867 }
6868
Guy Benyei11169dd2012-12-18 14:30:41 +00006869 std::fprintf(stderr, "\n");
6870 dump();
6871 std::fprintf(stderr, "\n");
6872}
6873
6874template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6875static void
6876dumpModuleIDMap(StringRef Name,
6877 const ContinuousRangeMap<Key, ModuleFile *,
6878 InitialCapacity> &Map) {
6879 if (Map.begin() == Map.end())
6880 return;
6881
6882 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6883 llvm::errs() << Name << ":\n";
6884 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6885 I != IEnd; ++I) {
6886 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6887 << "\n";
6888 }
6889}
6890
Yaron Kerencdae9412016-01-29 19:38:18 +00006891LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00006892 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6893 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6894 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6895 dumpModuleIDMap("Global type map", GlobalTypeMap);
6896 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6897 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6898 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6899 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6900 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6901 dumpModuleIDMap("Global preprocessed entity map",
6902 GlobalPreprocessedEntityMap);
6903
6904 llvm::errs() << "\n*** PCH/Modules Loaded:";
6905 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6906 MEnd = ModuleMgr.end();
6907 M != MEnd; ++M)
6908 (*M)->dump();
6909}
6910
6911/// Return the amount of memory used by memory buffers, breaking down
6912/// by heap-backed versus mmap'ed memory.
6913void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6914 for (ModuleConstIterator I = ModuleMgr.begin(),
6915 E = ModuleMgr.end(); I != E; ++I) {
6916 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6917 size_t bytes = buf->getBufferSize();
6918 switch (buf->getBufferKind()) {
6919 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6920 sizes.malloc_bytes += bytes;
6921 break;
6922 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6923 sizes.mmap_bytes += bytes;
6924 break;
6925 }
6926 }
6927 }
6928}
6929
6930void ASTReader::InitializeSema(Sema &S) {
6931 SemaObj = &S;
6932 S.addExternalSource(this);
6933
6934 // Makes sure any declarations that were deserialized "too early"
6935 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006936 for (uint64_t ID : PreloadedDeclIDs) {
6937 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6938 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006939 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006940 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006941
Richard Smith3d8e97e2013-10-18 06:54:39 +00006942 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006943 if (!FPPragmaOptions.empty()) {
6944 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6945 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6946 }
6947
Richard Smith3d8e97e2013-10-18 06:54:39 +00006948 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006949 if (!OpenCLExtensions.empty()) {
6950 unsigned I = 0;
6951#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6952#include "clang/Basic/OpenCLExtensions.def"
6953
6954 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6955 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006956
6957 UpdateSema();
6958}
6959
6960void ASTReader::UpdateSema() {
6961 assert(SemaObj && "no Sema to update");
6962
6963 // Load the offsets of the declarations that Sema references.
6964 // They will be lazily deserialized when needed.
6965 if (!SemaDeclRefs.empty()) {
6966 assert(SemaDeclRefs.size() % 2 == 0);
6967 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6968 if (!SemaObj->StdNamespace)
6969 SemaObj->StdNamespace = SemaDeclRefs[I];
6970 if (!SemaObj->StdBadAlloc)
6971 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6972 }
6973 SemaDeclRefs.clear();
6974 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006975
6976 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6977 // encountered the pragma in the source.
6978 if(OptimizeOffPragmaLocation.isValid())
6979 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006980}
6981
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006982IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006983 // Note that we are loading an identifier.
6984 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006985
Douglas Gregor7211ac12013-01-25 23:32:03 +00006986 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006987 NumIdentifierLookups,
6988 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006989
6990 // We don't need to do identifier table lookups in C++ modules (we preload
6991 // all interesting declarations, and don't need to use the scope for name
6992 // lookups). Perform the lookup in PCH files, though, since we don't build
6993 // a complete initial identifier table if we're carrying on from a PCH.
6994 if (Context.getLangOpts().CPlusPlus) {
6995 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006996 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006997 break;
6998 } else {
6999 // If there is a global index, look there first to determine which modules
7000 // provably do not have any results for this identifier.
7001 GlobalModuleIndex::HitSet Hits;
7002 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7003 if (!loadGlobalIndex()) {
7004 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7005 HitsPtr = &Hits;
7006 }
7007 }
7008
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007009 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007010 }
7011
Guy Benyei11169dd2012-12-18 14:30:41 +00007012 IdentifierInfo *II = Visitor.getIdentifierInfo();
7013 markIdentifierUpToDate(II);
7014 return II;
7015}
7016
7017namespace clang {
7018 /// \brief An identifier-lookup iterator that enumerates all of the
7019 /// identifiers stored within a set of AST files.
7020 class ASTIdentifierIterator : public IdentifierIterator {
7021 /// \brief The AST reader whose identifiers are being enumerated.
7022 const ASTReader &Reader;
7023
7024 /// \brief The current index into the chain of AST files stored in
7025 /// the AST reader.
7026 unsigned Index;
7027
7028 /// \brief The current position within the identifier lookup table
7029 /// of the current AST file.
7030 ASTIdentifierLookupTable::key_iterator Current;
7031
7032 /// \brief The end position within the identifier lookup table of
7033 /// the current AST file.
7034 ASTIdentifierLookupTable::key_iterator End;
7035
7036 public:
7037 explicit ASTIdentifierIterator(const ASTReader &Reader);
7038
Craig Topper3e89dfe2014-03-13 02:13:41 +00007039 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007040 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007041}
Guy Benyei11169dd2012-12-18 14:30:41 +00007042
7043ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7044 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7045 ASTIdentifierLookupTable *IdTable
7046 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7047 Current = IdTable->key_begin();
7048 End = IdTable->key_end();
7049}
7050
7051StringRef ASTIdentifierIterator::Next() {
7052 while (Current == End) {
7053 // If we have exhausted all of our AST files, we're done.
7054 if (Index == 0)
7055 return StringRef();
7056
7057 --Index;
7058 ASTIdentifierLookupTable *IdTable
7059 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7060 IdentifierLookupTable;
7061 Current = IdTable->key_begin();
7062 End = IdTable->key_end();
7063 }
7064
7065 // We have any identifiers remaining in the current AST file; return
7066 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007067 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007068 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007069 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007070}
7071
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007072IdentifierIterator *ASTReader::getIdentifiers() {
7073 if (!loadGlobalIndex())
7074 return GlobalIndex->createIdentifierIterator();
7075
Guy Benyei11169dd2012-12-18 14:30:41 +00007076 return new ASTIdentifierIterator(*this);
7077}
7078
7079namespace clang { namespace serialization {
7080 class ReadMethodPoolVisitor {
7081 ASTReader &Reader;
7082 Selector Sel;
7083 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007084 unsigned InstanceBits;
7085 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007086 bool InstanceHasMoreThanOneDecl;
7087 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007088 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7089 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007090
7091 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007092 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007093 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007094 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007095 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7096 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007097
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007098 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007099 if (!M.SelectorLookupTable)
7100 return false;
7101
7102 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007103 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007104 return true;
7105
Richard Smithbdf2d932015-07-30 03:37:16 +00007106 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007107 ASTSelectorLookupTable *PoolTable
7108 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007109 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007110 if (Pos == PoolTable->end())
7111 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007112
Richard Smithbdf2d932015-07-30 03:37:16 +00007113 ++Reader.NumMethodPoolTableHits;
7114 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007115 // FIXME: Not quite happy with the statistics here. We probably should
7116 // disable this tracking when called via LoadSelector.
7117 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007118 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007119 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007120 if (Reader.DeserializationListener)
7121 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007122
Richard Smithbdf2d932015-07-30 03:37:16 +00007123 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7124 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7125 InstanceBits = Data.InstanceBits;
7126 FactoryBits = Data.FactoryBits;
7127 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7128 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007129 return true;
7130 }
7131
7132 /// \brief Retrieve the instance methods found by this visitor.
7133 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7134 return InstanceMethods;
7135 }
7136
7137 /// \brief Retrieve the instance methods found by this visitor.
7138 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7139 return FactoryMethods;
7140 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007141
7142 unsigned getInstanceBits() const { return InstanceBits; }
7143 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007144 bool instanceHasMoreThanOneDecl() const {
7145 return InstanceHasMoreThanOneDecl;
7146 }
7147 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007148 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007149} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00007150
7151/// \brief Add the given set of methods to the method list.
7152static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7153 ObjCMethodList &List) {
7154 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7155 S.addMethodToGlobalList(&List, Methods[I]);
7156 }
7157}
7158
7159void ASTReader::ReadMethodPool(Selector Sel) {
7160 // Get the selector generation and update it to the current generation.
7161 unsigned &Generation = SelectorGeneration[Sel];
7162 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007163 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007164
7165 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007166 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007167 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007168 ModuleMgr.visit(Visitor);
7169
Guy Benyei11169dd2012-12-18 14:30:41 +00007170 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007171 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007172 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007173
7174 ++NumMethodPoolHits;
7175
Guy Benyei11169dd2012-12-18 14:30:41 +00007176 if (!getSema())
7177 return;
7178
7179 Sema &S = *getSema();
7180 Sema::GlobalMethodPool::iterator Pos
7181 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007182
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007183 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007184 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007185 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007186 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007187
7188 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7189 // when building a module we keep every method individually and may need to
7190 // update hasMoreThanOneDecl as we add the methods.
7191 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7192 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007193}
7194
7195void ASTReader::ReadKnownNamespaces(
7196 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7197 Namespaces.clear();
7198
7199 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7200 if (NamespaceDecl *Namespace
7201 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7202 Namespaces.push_back(Namespace);
7203 }
7204}
7205
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007206void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007207 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007208 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7209 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007210 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007211 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007212 Undefined.insert(std::make_pair(D, Loc));
7213 }
7214}
Nick Lewycky8334af82013-01-26 00:35:08 +00007215
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007216void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7217 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7218 Exprs) {
7219 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7220 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7221 uint64_t Count = DelayedDeleteExprs[Idx++];
7222 for (uint64_t C = 0; C < Count; ++C) {
7223 SourceLocation DeleteLoc =
7224 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7225 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7226 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7227 }
7228 }
7229}
7230
Guy Benyei11169dd2012-12-18 14:30:41 +00007231void ASTReader::ReadTentativeDefinitions(
7232 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7233 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7234 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7235 if (Var)
7236 TentativeDefs.push_back(Var);
7237 }
7238 TentativeDefinitions.clear();
7239}
7240
7241void ASTReader::ReadUnusedFileScopedDecls(
7242 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7243 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7244 DeclaratorDecl *D
7245 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7246 if (D)
7247 Decls.push_back(D);
7248 }
7249 UnusedFileScopedDecls.clear();
7250}
7251
7252void ASTReader::ReadDelegatingConstructors(
7253 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7254 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7255 CXXConstructorDecl *D
7256 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7257 if (D)
7258 Decls.push_back(D);
7259 }
7260 DelegatingCtorDecls.clear();
7261}
7262
7263void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7264 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7265 TypedefNameDecl *D
7266 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7267 if (D)
7268 Decls.push_back(D);
7269 }
7270 ExtVectorDecls.clear();
7271}
7272
Nico Weber72889432014-09-06 01:25:55 +00007273void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7274 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7275 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7276 ++I) {
7277 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7278 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7279 if (D)
7280 Decls.insert(D);
7281 }
7282 UnusedLocalTypedefNameCandidates.clear();
7283}
7284
Guy Benyei11169dd2012-12-18 14:30:41 +00007285void ASTReader::ReadReferencedSelectors(
7286 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7287 if (ReferencedSelectorsData.empty())
7288 return;
7289
7290 // If there are @selector references added them to its pool. This is for
7291 // implementation of -Wselector.
7292 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7293 unsigned I = 0;
7294 while (I < DataSize) {
7295 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7296 SourceLocation SelLoc
7297 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7298 Sels.push_back(std::make_pair(Sel, SelLoc));
7299 }
7300 ReferencedSelectorsData.clear();
7301}
7302
7303void ASTReader::ReadWeakUndeclaredIdentifiers(
7304 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7305 if (WeakUndeclaredIdentifiers.empty())
7306 return;
7307
7308 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7309 IdentifierInfo *WeakId
7310 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7311 IdentifierInfo *AliasId
7312 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7313 SourceLocation Loc
7314 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7315 bool Used = WeakUndeclaredIdentifiers[I++];
7316 WeakInfo WI(AliasId, Loc);
7317 WI.setUsed(Used);
7318 WeakIDs.push_back(std::make_pair(WeakId, WI));
7319 }
7320 WeakUndeclaredIdentifiers.clear();
7321}
7322
7323void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7324 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7325 ExternalVTableUse VT;
7326 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7327 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7328 VT.DefinitionRequired = VTableUses[Idx++];
7329 VTables.push_back(VT);
7330 }
7331
7332 VTableUses.clear();
7333}
7334
7335void ASTReader::ReadPendingInstantiations(
7336 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7337 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7338 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7339 SourceLocation Loc
7340 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7341
7342 Pending.push_back(std::make_pair(D, Loc));
7343 }
7344 PendingInstantiations.clear();
7345}
7346
Richard Smithe40f2ba2013-08-07 21:41:30 +00007347void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007348 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007349 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7350 /* In loop */) {
7351 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7352
7353 LateParsedTemplate *LT = new LateParsedTemplate;
7354 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7355
7356 ModuleFile *F = getOwningModuleFile(LT->D);
7357 assert(F && "No module");
7358
7359 unsigned TokN = LateParsedTemplates[Idx++];
7360 LT->Toks.reserve(TokN);
7361 for (unsigned T = 0; T < TokN; ++T)
7362 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7363
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007364 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007365 }
7366
7367 LateParsedTemplates.clear();
7368}
7369
Guy Benyei11169dd2012-12-18 14:30:41 +00007370void ASTReader::LoadSelector(Selector Sel) {
7371 // It would be complicated to avoid reading the methods anyway. So don't.
7372 ReadMethodPool(Sel);
7373}
7374
7375void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7376 assert(ID && "Non-zero identifier ID required");
7377 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7378 IdentifiersLoaded[ID - 1] = II;
7379 if (DeserializationListener)
7380 DeserializationListener->IdentifierRead(ID, II);
7381}
7382
7383/// \brief Set the globally-visible declarations associated with the given
7384/// identifier.
7385///
7386/// If the AST reader is currently in a state where the given declaration IDs
7387/// cannot safely be resolved, they are queued until it is safe to resolve
7388/// them.
7389///
7390/// \param II an IdentifierInfo that refers to one or more globally-visible
7391/// declarations.
7392///
7393/// \param DeclIDs the set of declaration IDs with the name @p II that are
7394/// visible at global scope.
7395///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007396/// \param Decls if non-null, this vector will be populated with the set of
7397/// deserialized declarations. These declarations will not be pushed into
7398/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007399void
7400ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7401 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007402 SmallVectorImpl<Decl *> *Decls) {
7403 if (NumCurrentElementsDeserializing && !Decls) {
7404 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007405 return;
7406 }
7407
7408 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007409 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007410 // Queue this declaration so that it will be added to the
7411 // translation unit scope and identifier's declaration chain
7412 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007413 PreloadedDeclIDs.push_back(DeclIDs[I]);
7414 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007415 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007416
7417 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7418
7419 // If we're simply supposed to record the declarations, do so now.
7420 if (Decls) {
7421 Decls->push_back(D);
7422 continue;
7423 }
7424
7425 // Introduce this declaration into the translation-unit scope
7426 // and add it to the declaration chain for this identifier, so
7427 // that (unqualified) name lookup will find it.
7428 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007429 }
7430}
7431
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007432IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007433 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007434 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007435
7436 if (IdentifiersLoaded.empty()) {
7437 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007438 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007439 }
7440
7441 ID -= 1;
7442 if (!IdentifiersLoaded[ID]) {
7443 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7444 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7445 ModuleFile *M = I->second;
7446 unsigned Index = ID - M->BaseIdentifierID;
7447 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7448
7449 // All of the strings in the AST file are preceded by a 16-bit length.
7450 // Extract that 16-bit length to avoid having to execute strlen().
7451 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7452 // unsigned integers. This is important to avoid integer overflow when
7453 // we cast them to 'unsigned'.
7454 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7455 unsigned StrLen = (((unsigned) StrLenPtr[0])
7456 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00007457 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7458 IdentifiersLoaded[ID] = &II;
7459 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007460 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00007461 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007462 }
7463
7464 return IdentifiersLoaded[ID];
7465}
7466
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007467IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7468 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007469}
7470
7471IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7472 if (LocalID < NUM_PREDEF_IDENT_IDS)
7473 return LocalID;
7474
7475 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7476 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7477 assert(I != M.IdentifierRemap.end()
7478 && "Invalid index into identifier index remap");
7479
7480 return LocalID + I->second;
7481}
7482
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007483MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007484 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007485 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007486
7487 if (MacrosLoaded.empty()) {
7488 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007489 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007490 }
7491
7492 ID -= NUM_PREDEF_MACRO_IDS;
7493 if (!MacrosLoaded[ID]) {
7494 GlobalMacroMapType::iterator I
7495 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7496 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7497 ModuleFile *M = I->second;
7498 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007499 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7500
7501 if (DeserializationListener)
7502 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7503 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007504 }
7505
7506 return MacrosLoaded[ID];
7507}
7508
7509MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7510 if (LocalID < NUM_PREDEF_MACRO_IDS)
7511 return LocalID;
7512
7513 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7514 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7515 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7516
7517 return LocalID + I->second;
7518}
7519
7520serialization::SubmoduleID
7521ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7522 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7523 return LocalID;
7524
7525 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7526 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7527 assert(I != M.SubmoduleRemap.end()
7528 && "Invalid index into submodule index remap");
7529
7530 return LocalID + I->second;
7531}
7532
7533Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7534 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7535 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007536 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007537 }
7538
7539 if (GlobalID > SubmodulesLoaded.size()) {
7540 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007541 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007542 }
7543
7544 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7545}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007546
7547Module *ASTReader::getModule(unsigned ID) {
7548 return getSubmodule(ID);
7549}
7550
Richard Smithd88a7f12015-09-01 20:35:42 +00007551ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7552 if (ID & 1) {
7553 // It's a module, look it up by submodule ID.
7554 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7555 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7556 } else {
7557 // It's a prefix (preamble, PCH, ...). Look it up by index.
7558 unsigned IndexFromEnd = ID >> 1;
7559 assert(IndexFromEnd && "got reference to unknown module file");
7560 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7561 }
7562}
7563
7564unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7565 if (!F)
7566 return 1;
7567
7568 // For a file representing a module, use the submodule ID of the top-level
7569 // module as the file ID. For any other kind of file, the number of such
7570 // files loaded beforehand will be the same on reload.
7571 // FIXME: Is this true even if we have an explicit module file and a PCH?
7572 if (F->isModule())
7573 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7574
7575 auto PCHModules = getModuleManager().pch_modules();
7576 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7577 assert(I != PCHModules.end() && "emitting reference to unknown file");
7578 return (I - PCHModules.end()) << 1;
7579}
7580
Adrian Prantl15bcf702015-06-30 17:39:43 +00007581llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7582ASTReader::getSourceDescriptor(unsigned ID) {
7583 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007584 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007585
7586 // If there is only a single PCH, return it instead.
7587 // Chained PCH are not suported.
7588 if (ModuleMgr.size() == 1) {
7589 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00007590 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
7591 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir,
7592 MF.FileName, MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007593 }
7594 return None;
7595}
7596
Guy Benyei11169dd2012-12-18 14:30:41 +00007597Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7598 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7599}
7600
7601Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7602 if (ID == 0)
7603 return Selector();
7604
7605 if (ID > SelectorsLoaded.size()) {
7606 Error("selector ID out of range in AST file");
7607 return Selector();
7608 }
7609
Craig Toppera13603a2014-05-22 05:54:18 +00007610 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007611 // Load this selector from the selector table.
7612 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7613 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7614 ModuleFile &M = *I->second;
7615 ASTSelectorLookupTrait Trait(*this, M);
7616 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7617 SelectorsLoaded[ID - 1] =
7618 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7619 if (DeserializationListener)
7620 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7621 }
7622
7623 return SelectorsLoaded[ID - 1];
7624}
7625
7626Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7627 return DecodeSelector(ID);
7628}
7629
7630uint32_t ASTReader::GetNumExternalSelectors() {
7631 // ID 0 (the null selector) is considered an external selector.
7632 return getTotalNumSelectors() + 1;
7633}
7634
7635serialization::SelectorID
7636ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7637 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7638 return LocalID;
7639
7640 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7641 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7642 assert(I != M.SelectorRemap.end()
7643 && "Invalid index into selector index remap");
7644
7645 return LocalID + I->second;
7646}
7647
7648DeclarationName
7649ASTReader::ReadDeclarationName(ModuleFile &F,
7650 const RecordData &Record, unsigned &Idx) {
7651 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7652 switch (Kind) {
7653 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007654 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007655
7656 case DeclarationName::ObjCZeroArgSelector:
7657 case DeclarationName::ObjCOneArgSelector:
7658 case DeclarationName::ObjCMultiArgSelector:
7659 return DeclarationName(ReadSelector(F, Record, Idx));
7660
7661 case DeclarationName::CXXConstructorName:
7662 return Context.DeclarationNames.getCXXConstructorName(
7663 Context.getCanonicalType(readType(F, Record, Idx)));
7664
7665 case DeclarationName::CXXDestructorName:
7666 return Context.DeclarationNames.getCXXDestructorName(
7667 Context.getCanonicalType(readType(F, Record, Idx)));
7668
7669 case DeclarationName::CXXConversionFunctionName:
7670 return Context.DeclarationNames.getCXXConversionFunctionName(
7671 Context.getCanonicalType(readType(F, Record, Idx)));
7672
7673 case DeclarationName::CXXOperatorName:
7674 return Context.DeclarationNames.getCXXOperatorName(
7675 (OverloadedOperatorKind)Record[Idx++]);
7676
7677 case DeclarationName::CXXLiteralOperatorName:
7678 return Context.DeclarationNames.getCXXLiteralOperatorName(
7679 GetIdentifierInfo(F, Record, Idx));
7680
7681 case DeclarationName::CXXUsingDirective:
7682 return DeclarationName::getUsingDirectiveName();
7683 }
7684
7685 llvm_unreachable("Invalid NameKind!");
7686}
7687
7688void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7689 DeclarationNameLoc &DNLoc,
7690 DeclarationName Name,
7691 const RecordData &Record, unsigned &Idx) {
7692 switch (Name.getNameKind()) {
7693 case DeclarationName::CXXConstructorName:
7694 case DeclarationName::CXXDestructorName:
7695 case DeclarationName::CXXConversionFunctionName:
7696 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7697 break;
7698
7699 case DeclarationName::CXXOperatorName:
7700 DNLoc.CXXOperatorName.BeginOpNameLoc
7701 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7702 DNLoc.CXXOperatorName.EndOpNameLoc
7703 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7704 break;
7705
7706 case DeclarationName::CXXLiteralOperatorName:
7707 DNLoc.CXXLiteralOperatorName.OpNameLoc
7708 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7709 break;
7710
7711 case DeclarationName::Identifier:
7712 case DeclarationName::ObjCZeroArgSelector:
7713 case DeclarationName::ObjCOneArgSelector:
7714 case DeclarationName::ObjCMultiArgSelector:
7715 case DeclarationName::CXXUsingDirective:
7716 break;
7717 }
7718}
7719
7720void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7721 DeclarationNameInfo &NameInfo,
7722 const RecordData &Record, unsigned &Idx) {
7723 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7724 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7725 DeclarationNameLoc DNLoc;
7726 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7727 NameInfo.setInfo(DNLoc);
7728}
7729
7730void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7731 const RecordData &Record, unsigned &Idx) {
7732 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7733 unsigned NumTPLists = Record[Idx++];
7734 Info.NumTemplParamLists = NumTPLists;
7735 if (NumTPLists) {
7736 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7737 for (unsigned i=0; i != NumTPLists; ++i)
7738 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7739 }
7740}
7741
7742TemplateName
7743ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7744 unsigned &Idx) {
7745 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7746 switch (Kind) {
7747 case TemplateName::Template:
7748 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7749
7750 case TemplateName::OverloadedTemplate: {
7751 unsigned size = Record[Idx++];
7752 UnresolvedSet<8> Decls;
7753 while (size--)
7754 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7755
7756 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7757 }
7758
7759 case TemplateName::QualifiedTemplate: {
7760 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7761 bool hasTemplKeyword = Record[Idx++];
7762 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7763 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7764 }
7765
7766 case TemplateName::DependentTemplate: {
7767 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7768 if (Record[Idx++]) // isIdentifier
7769 return Context.getDependentTemplateName(NNS,
7770 GetIdentifierInfo(F, Record,
7771 Idx));
7772 return Context.getDependentTemplateName(NNS,
7773 (OverloadedOperatorKind)Record[Idx++]);
7774 }
7775
7776 case TemplateName::SubstTemplateTemplateParm: {
7777 TemplateTemplateParmDecl *param
7778 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7779 if (!param) return TemplateName();
7780 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7781 return Context.getSubstTemplateTemplateParm(param, replacement);
7782 }
7783
7784 case TemplateName::SubstTemplateTemplateParmPack: {
7785 TemplateTemplateParmDecl *Param
7786 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7787 if (!Param)
7788 return TemplateName();
7789
7790 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7791 if (ArgPack.getKind() != TemplateArgument::Pack)
7792 return TemplateName();
7793
7794 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7795 }
7796 }
7797
7798 llvm_unreachable("Unhandled template name kind!");
7799}
7800
Richard Smith2bb3c342015-08-09 01:05:31 +00007801TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7802 const RecordData &Record,
7803 unsigned &Idx,
7804 bool Canonicalize) {
7805 if (Canonicalize) {
7806 // The caller wants a canonical template argument. Sometimes the AST only
7807 // wants template arguments in canonical form (particularly as the template
7808 // argument lists of template specializations) so ensure we preserve that
7809 // canonical form across serialization.
7810 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7811 return Context.getCanonicalTemplateArgument(Arg);
7812 }
7813
Guy Benyei11169dd2012-12-18 14:30:41 +00007814 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7815 switch (Kind) {
7816 case TemplateArgument::Null:
7817 return TemplateArgument();
7818 case TemplateArgument::Type:
7819 return TemplateArgument(readType(F, Record, Idx));
7820 case TemplateArgument::Declaration: {
7821 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007822 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007823 }
7824 case TemplateArgument::NullPtr:
7825 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7826 case TemplateArgument::Integral: {
7827 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7828 QualType T = readType(F, Record, Idx);
7829 return TemplateArgument(Context, Value, T);
7830 }
7831 case TemplateArgument::Template:
7832 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7833 case TemplateArgument::TemplateExpansion: {
7834 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007835 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007836 if (unsigned NumExpansions = Record[Idx++])
7837 NumTemplateExpansions = NumExpansions - 1;
7838 return TemplateArgument(Name, NumTemplateExpansions);
7839 }
7840 case TemplateArgument::Expression:
7841 return TemplateArgument(ReadExpr(F));
7842 case TemplateArgument::Pack: {
7843 unsigned NumArgs = Record[Idx++];
7844 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7845 for (unsigned I = 0; I != NumArgs; ++I)
7846 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007847 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007848 }
7849 }
7850
7851 llvm_unreachable("Unhandled template argument kind!");
7852}
7853
7854TemplateParameterList *
7855ASTReader::ReadTemplateParameterList(ModuleFile &F,
7856 const RecordData &Record, unsigned &Idx) {
7857 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7858 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7859 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7860
7861 unsigned NumParams = Record[Idx++];
7862 SmallVector<NamedDecl *, 16> Params;
7863 Params.reserve(NumParams);
7864 while (NumParams--)
7865 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7866
7867 TemplateParameterList* TemplateParams =
7868 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
David Majnemer902f8c62015-12-27 07:16:27 +00007869 Params, RAngleLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00007870 return TemplateParams;
7871}
7872
7873void
7874ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007875ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007876 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007877 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007878 unsigned NumTemplateArgs = Record[Idx++];
7879 TemplArgs.reserve(NumTemplateArgs);
7880 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007881 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007882}
7883
7884/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007885void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007886 const RecordData &Record, unsigned &Idx) {
7887 unsigned NumDecls = Record[Idx++];
7888 Set.reserve(Context, NumDecls);
7889 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007890 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007891 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007892 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007893 }
7894}
7895
7896CXXBaseSpecifier
7897ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7898 const RecordData &Record, unsigned &Idx) {
7899 bool isVirtual = static_cast<bool>(Record[Idx++]);
7900 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7901 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7902 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7903 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7904 SourceRange Range = ReadSourceRange(F, Record, Idx);
7905 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7906 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7907 EllipsisLoc);
7908 Result.setInheritConstructors(inheritConstructors);
7909 return Result;
7910}
7911
Richard Smithc2bb8182015-03-24 06:36:48 +00007912CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007913ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7914 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007915 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007916 assert(NumInitializers && "wrote ctor initializers but have no inits");
7917 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7918 for (unsigned i = 0; i != NumInitializers; ++i) {
7919 TypeSourceInfo *TInfo = nullptr;
7920 bool IsBaseVirtual = false;
7921 FieldDecl *Member = nullptr;
7922 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007923
Richard Smithc2bb8182015-03-24 06:36:48 +00007924 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7925 switch (Type) {
7926 case CTOR_INITIALIZER_BASE:
7927 TInfo = GetTypeSourceInfo(F, Record, Idx);
7928 IsBaseVirtual = Record[Idx++];
7929 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007930
Richard Smithc2bb8182015-03-24 06:36:48 +00007931 case CTOR_INITIALIZER_DELEGATING:
7932 TInfo = GetTypeSourceInfo(F, Record, Idx);
7933 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007934
Richard Smithc2bb8182015-03-24 06:36:48 +00007935 case CTOR_INITIALIZER_MEMBER:
7936 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7937 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007938
Richard Smithc2bb8182015-03-24 06:36:48 +00007939 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7940 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7941 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007942 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007943
7944 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7945 Expr *Init = ReadExpr(F);
7946 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7947 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7948 bool IsWritten = Record[Idx++];
7949 unsigned SourceOrderOrNumArrayIndices;
7950 SmallVector<VarDecl *, 8> Indices;
7951 if (IsWritten) {
7952 SourceOrderOrNumArrayIndices = Record[Idx++];
7953 } else {
7954 SourceOrderOrNumArrayIndices = Record[Idx++];
7955 Indices.reserve(SourceOrderOrNumArrayIndices);
7956 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7957 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7958 }
7959
7960 CXXCtorInitializer *BOMInit;
7961 if (Type == CTOR_INITIALIZER_BASE) {
7962 BOMInit = new (Context)
7963 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7964 RParenLoc, MemberOrEllipsisLoc);
7965 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7966 BOMInit = new (Context)
7967 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7968 } else if (IsWritten) {
7969 if (Member)
7970 BOMInit = new (Context) CXXCtorInitializer(
7971 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7972 else
7973 BOMInit = new (Context)
7974 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7975 LParenLoc, Init, RParenLoc);
7976 } else {
7977 if (IndirectMember) {
7978 assert(Indices.empty() && "Indirect field improperly initialized");
7979 BOMInit = new (Context)
7980 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7981 LParenLoc, Init, RParenLoc);
7982 } else {
7983 BOMInit = CXXCtorInitializer::Create(
7984 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7985 Indices.data(), Indices.size());
7986 }
7987 }
7988
7989 if (IsWritten)
7990 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7991 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007992 }
7993
Richard Smithc2bb8182015-03-24 06:36:48 +00007994 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007995}
7996
7997NestedNameSpecifier *
7998ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7999 const RecordData &Record, unsigned &Idx) {
8000 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008001 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008002 for (unsigned I = 0; I != N; ++I) {
8003 NestedNameSpecifier::SpecifierKind Kind
8004 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8005 switch (Kind) {
8006 case NestedNameSpecifier::Identifier: {
8007 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8008 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8009 break;
8010 }
8011
8012 case NestedNameSpecifier::Namespace: {
8013 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8014 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8015 break;
8016 }
8017
8018 case NestedNameSpecifier::NamespaceAlias: {
8019 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8020 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8021 break;
8022 }
8023
8024 case NestedNameSpecifier::TypeSpec:
8025 case NestedNameSpecifier::TypeSpecWithTemplate: {
8026 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8027 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008028 return nullptr;
8029
Guy Benyei11169dd2012-12-18 14:30:41 +00008030 bool Template = Record[Idx++];
8031 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8032 break;
8033 }
8034
8035 case NestedNameSpecifier::Global: {
8036 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8037 // No associated value, and there can't be a prefix.
8038 break;
8039 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008040
8041 case NestedNameSpecifier::Super: {
8042 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8043 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8044 break;
8045 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008046 }
8047 Prev = NNS;
8048 }
8049 return NNS;
8050}
8051
8052NestedNameSpecifierLoc
8053ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8054 unsigned &Idx) {
8055 unsigned N = Record[Idx++];
8056 NestedNameSpecifierLocBuilder Builder;
8057 for (unsigned I = 0; I != N; ++I) {
8058 NestedNameSpecifier::SpecifierKind Kind
8059 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8060 switch (Kind) {
8061 case NestedNameSpecifier::Identifier: {
8062 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8063 SourceRange Range = ReadSourceRange(F, Record, Idx);
8064 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8065 break;
8066 }
8067
8068 case NestedNameSpecifier::Namespace: {
8069 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8070 SourceRange Range = ReadSourceRange(F, Record, Idx);
8071 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8072 break;
8073 }
8074
8075 case NestedNameSpecifier::NamespaceAlias: {
8076 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8077 SourceRange Range = ReadSourceRange(F, Record, Idx);
8078 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8079 break;
8080 }
8081
8082 case NestedNameSpecifier::TypeSpec:
8083 case NestedNameSpecifier::TypeSpecWithTemplate: {
8084 bool Template = Record[Idx++];
8085 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8086 if (!T)
8087 return NestedNameSpecifierLoc();
8088 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8089
8090 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8091 Builder.Extend(Context,
8092 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8093 T->getTypeLoc(), ColonColonLoc);
8094 break;
8095 }
8096
8097 case NestedNameSpecifier::Global: {
8098 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8099 Builder.MakeGlobal(Context, ColonColonLoc);
8100 break;
8101 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008102
8103 case NestedNameSpecifier::Super: {
8104 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8105 SourceRange Range = ReadSourceRange(F, Record, Idx);
8106 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8107 break;
8108 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008109 }
8110 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008111
Guy Benyei11169dd2012-12-18 14:30:41 +00008112 return Builder.getWithLocInContext(Context);
8113}
8114
8115SourceRange
8116ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8117 unsigned &Idx) {
8118 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8119 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8120 return SourceRange(beg, end);
8121}
8122
8123/// \brief Read an integral value
8124llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8125 unsigned BitWidth = Record[Idx++];
8126 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8127 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8128 Idx += NumWords;
8129 return Result;
8130}
8131
8132/// \brief Read a signed integral value
8133llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8134 bool isUnsigned = Record[Idx++];
8135 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8136}
8137
8138/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008139llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8140 const llvm::fltSemantics &Sem,
8141 unsigned &Idx) {
8142 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008143}
8144
8145// \brief Read a string
8146std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8147 unsigned Len = Record[Idx++];
8148 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8149 Idx += Len;
8150 return Result;
8151}
8152
Richard Smith7ed1bc92014-12-05 22:42:13 +00008153std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8154 unsigned &Idx) {
8155 std::string Filename = ReadString(Record, Idx);
8156 ResolveImportedPath(F, Filename);
8157 return Filename;
8158}
8159
Guy Benyei11169dd2012-12-18 14:30:41 +00008160VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8161 unsigned &Idx) {
8162 unsigned Major = Record[Idx++];
8163 unsigned Minor = Record[Idx++];
8164 unsigned Subminor = Record[Idx++];
8165 if (Minor == 0)
8166 return VersionTuple(Major);
8167 if (Subminor == 0)
8168 return VersionTuple(Major, Minor - 1);
8169 return VersionTuple(Major, Minor - 1, Subminor - 1);
8170}
8171
8172CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8173 const RecordData &Record,
8174 unsigned &Idx) {
8175 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8176 return CXXTemporary::Create(Context, Decl);
8177}
8178
8179DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008180 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008181}
8182
8183DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8184 return Diags.Report(Loc, DiagID);
8185}
8186
8187/// \brief Retrieve the identifier table associated with the
8188/// preprocessor.
8189IdentifierTable &ASTReader::getIdentifierTable() {
8190 return PP.getIdentifierTable();
8191}
8192
8193/// \brief Record that the given ID maps to the given switch-case
8194/// statement.
8195void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008196 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008197 "Already have a SwitchCase with this ID");
8198 (*CurrSwitchCaseStmts)[ID] = SC;
8199}
8200
8201/// \brief Retrieve the switch-case statement with the given ID.
8202SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008203 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008204 return (*CurrSwitchCaseStmts)[ID];
8205}
8206
8207void ASTReader::ClearSwitchCaseIDs() {
8208 CurrSwitchCaseStmts->clear();
8209}
8210
8211void ASTReader::ReadComments() {
8212 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008213 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008214 serialization::ModuleFile *> >::iterator
8215 I = CommentsCursors.begin(),
8216 E = CommentsCursors.end();
8217 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008218 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008219 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008220 serialization::ModuleFile &F = *I->second;
8221 SavedStreamPosition SavedPosition(Cursor);
8222
8223 RecordData Record;
8224 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008225 llvm::BitstreamEntry Entry =
8226 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008227
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008228 switch (Entry.Kind) {
8229 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8230 case llvm::BitstreamEntry::Error:
8231 Error("malformed block record in AST file");
8232 return;
8233 case llvm::BitstreamEntry::EndBlock:
8234 goto NextCursor;
8235 case llvm::BitstreamEntry::Record:
8236 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008237 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008238 }
8239
8240 // Read a record.
8241 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008242 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008243 case COMMENTS_RAW_COMMENT: {
8244 unsigned Idx = 0;
8245 SourceRange SR = ReadSourceRange(F, Record, Idx);
8246 RawComment::CommentKind Kind =
8247 (RawComment::CommentKind) Record[Idx++];
8248 bool IsTrailingComment = Record[Idx++];
8249 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008250 Comments.push_back(new (Context) RawComment(
8251 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8252 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008253 break;
8254 }
8255 }
8256 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008257 NextCursor:
8258 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008259 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008260}
8261
Richard Smithcd45dbc2014-04-19 03:48:30 +00008262std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8263 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008264 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008265 return M->getFullModuleName();
8266
8267 // Otherwise, use the name of the top-level module the decl is within.
8268 if (ModuleFile *M = getOwningModuleFile(D))
8269 return M->ModuleName;
8270
8271 // Not from a module.
8272 return "";
8273}
8274
Guy Benyei11169dd2012-12-18 14:30:41 +00008275void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008276 while (!PendingIdentifierInfos.empty() ||
8277 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008278 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008279 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008280 // If any identifiers with corresponding top-level declarations have
8281 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008282 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8283 TopLevelDeclsMap;
8284 TopLevelDeclsMap TopLevelDecls;
8285
Guy Benyei11169dd2012-12-18 14:30:41 +00008286 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008287 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008288 SmallVector<uint32_t, 4> DeclIDs =
8289 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008290 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008291
8292 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008293 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008294
Richard Smith851072e2014-05-19 20:59:20 +00008295 // For each decl chain that we wanted to complete while deserializing, mark
8296 // it as "still needs to be completed".
8297 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8298 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8299 }
8300 PendingIncompleteDeclChains.clear();
8301
Guy Benyei11169dd2012-12-18 14:30:41 +00008302 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008303 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008304 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008305 PendingDeclChains.clear();
8306
Douglas Gregor6168bd22013-02-18 15:53:43 +00008307 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008308 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8309 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008310 IdentifierInfo *II = TLD->first;
8311 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008312 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008313 }
8314 }
8315
Guy Benyei11169dd2012-12-18 14:30:41 +00008316 // Load any pending macro definitions.
8317 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008318 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8319 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8320 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8321 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008322 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008323 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008324 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008325 if (Info.M->Kind != MK_ImplicitModule &&
8326 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008327 resolvePendingMacro(II, Info);
8328 }
8329 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008330 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008331 ++IDIdx) {
8332 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008333 if (Info.M->Kind == MK_ImplicitModule ||
8334 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008335 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008336 }
8337 }
8338 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008339
8340 // Wire up the DeclContexts for Decls that we delayed setting until
8341 // recursive loading is completed.
8342 while (!PendingDeclContextInfos.empty()) {
8343 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8344 PendingDeclContextInfos.pop_front();
8345 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8346 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8347 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8348 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008349
Richard Smithd1c46742014-04-30 02:24:17 +00008350 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008351 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008352 auto Update = PendingUpdateRecords.pop_back_val();
8353 ReadingKindTracker ReadingKind(Read_Decl, *this);
8354 loadDeclUpdateRecords(Update.first, Update.second);
8355 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008356 }
Richard Smith8a639892015-01-24 01:07:20 +00008357
8358 // At this point, all update records for loaded decls are in place, so any
8359 // fake class definitions should have become real.
8360 assert(PendingFakeDefinitionData.empty() &&
8361 "faked up a class definition but never saw the real one");
8362
Guy Benyei11169dd2012-12-18 14:30:41 +00008363 // If we deserialized any C++ or Objective-C class definitions, any
8364 // Objective-C protocol definitions, or any redeclarable templates, make sure
8365 // that all redeclarations point to the definitions. Note that this can only
8366 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008367 for (Decl *D : PendingDefinitions) {
8368 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008369 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008370 // Make sure that the TagType points at the definition.
8371 const_cast<TagType*>(TagT)->decl = TD;
8372 }
Richard Smith8ce51082015-03-11 01:44:51 +00008373
Craig Topperc6914d02014-08-25 04:15:02 +00008374 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008375 for (auto *R = getMostRecentExistingDecl(RD); R;
8376 R = R->getPreviousDecl()) {
8377 assert((R == D) ==
8378 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008379 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008380 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008381 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008382 }
8383
8384 continue;
8385 }
Richard Smith8ce51082015-03-11 01:44:51 +00008386
Craig Topperc6914d02014-08-25 04:15:02 +00008387 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008388 // Make sure that the ObjCInterfaceType points at the definition.
8389 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8390 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008391
8392 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8393 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8394
Guy Benyei11169dd2012-12-18 14:30:41 +00008395 continue;
8396 }
Richard Smith8ce51082015-03-11 01:44:51 +00008397
Craig Topperc6914d02014-08-25 04:15:02 +00008398 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008399 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8400 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8401
Guy Benyei11169dd2012-12-18 14:30:41 +00008402 continue;
8403 }
Richard Smith8ce51082015-03-11 01:44:51 +00008404
Craig Topperc6914d02014-08-25 04:15:02 +00008405 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008406 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8407 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008408 }
8409 PendingDefinitions.clear();
8410
8411 // Load the bodies of any functions or methods we've encountered. We do
8412 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008413 // have been fully wired up (hasBody relies on this).
8414 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008415 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8416 PBEnd = PendingBodies.end();
8417 PB != PBEnd; ++PB) {
8418 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8419 // FIXME: Check for =delete/=default?
8420 // FIXME: Complain about ODR violations here?
8421 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8422 FD->setLazyBody(PB->second);
8423 continue;
8424 }
8425
8426 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8427 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8428 MD->setLazyBody(PB->second);
8429 }
8430 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008431
8432 // Do some cleanup.
8433 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8434 getContext().deduplicateMergedDefinitonsFor(ND);
8435 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008436}
8437
8438void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008439 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8440 return;
8441
Richard Smitha0ce9c42014-07-29 23:23:27 +00008442 // Trigger the import of the full definition of each class that had any
8443 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008444 // These updates may in turn find and diagnose some ODR failures, so take
8445 // ownership of the set first.
8446 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8447 PendingOdrMergeFailures.clear();
8448 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008449 Merge.first->buildLookup();
8450 Merge.first->decls_begin();
8451 Merge.first->bases_begin();
8452 Merge.first->vbases_begin();
8453 for (auto *RD : Merge.second) {
8454 RD->decls_begin();
8455 RD->bases_begin();
8456 RD->vbases_begin();
8457 }
8458 }
8459
8460 // For each declaration from a merged context, check that the canonical
8461 // definition of that context also contains a declaration of the same
8462 // entity.
8463 //
8464 // Caution: this loop does things that might invalidate iterators into
8465 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8466 while (!PendingOdrMergeChecks.empty()) {
8467 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8468
8469 // FIXME: Skip over implicit declarations for now. This matters for things
8470 // like implicitly-declared special member functions. This isn't entirely
8471 // correct; we can end up with multiple unmerged declarations of the same
8472 // implicit entity.
8473 if (D->isImplicit())
8474 continue;
8475
8476 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008477
8478 bool Found = false;
8479 const Decl *DCanon = D->getCanonicalDecl();
8480
Richard Smith01bdb7a2014-08-28 05:44:07 +00008481 for (auto RI : D->redecls()) {
8482 if (RI->getLexicalDeclContext() == CanonDef) {
8483 Found = true;
8484 break;
8485 }
8486 }
8487 if (Found)
8488 continue;
8489
Richard Smith0f4e2c42015-08-06 04:23:48 +00008490 // Quick check failed, time to do the slow thing. Note, we can't just
8491 // look up the name of D in CanonDef here, because the member that is
8492 // in CanonDef might not be found by name lookup (it might have been
8493 // replaced by a more recent declaration in the lookup table), and we
8494 // can't necessarily find it in the redeclaration chain because it might
8495 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008496 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008497 for (auto *CanonMember : CanonDef->decls()) {
8498 if (CanonMember->getCanonicalDecl() == DCanon) {
8499 // This can happen if the declaration is merely mergeable and not
8500 // actually redeclarable (we looked for redeclarations earlier).
8501 //
8502 // FIXME: We should be able to detect this more efficiently, without
8503 // pulling in all of the members of CanonDef.
8504 Found = true;
8505 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008506 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008507 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8508 if (ND->getDeclName() == D->getDeclName())
8509 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008510 }
8511
8512 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008513 // The AST doesn't like TagDecls becoming invalid after they've been
8514 // completed. We only really need to mark FieldDecls as invalid here.
8515 if (!isa<TagDecl>(D))
8516 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008517
8518 // Ensure we don't accidentally recursively enter deserialization while
8519 // we're producing our diagnostic.
8520 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008521
8522 std::string CanonDefModule =
8523 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8524 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8525 << D << getOwningModuleNameForDiagnostic(D)
8526 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8527
8528 if (Candidates.empty())
8529 Diag(cast<Decl>(CanonDef)->getLocation(),
8530 diag::note_module_odr_violation_no_possible_decls) << D;
8531 else {
8532 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8533 Diag(Candidates[I]->getLocation(),
8534 diag::note_module_odr_violation_possible_decl)
8535 << Candidates[I];
8536 }
8537
8538 DiagnosedOdrMergeFailures.insert(CanonDef);
8539 }
8540 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008541
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008542 if (OdrMergeFailures.empty())
8543 return;
8544
8545 // Ensure we don't accidentally recursively enter deserialization while
8546 // we're producing our diagnostics.
8547 Deserializing RecursionGuard(this);
8548
Richard Smithcd45dbc2014-04-19 03:48:30 +00008549 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008550 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008551 // If we've already pointed out a specific problem with this class, don't
8552 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008553 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008554 continue;
8555
8556 bool Diagnosed = false;
8557 for (auto *RD : Merge.second) {
8558 // Multiple different declarations got merged together; tell the user
8559 // where they came from.
8560 if (Merge.first != RD) {
8561 // FIXME: Walk the definition, figure out what's different,
8562 // and diagnose that.
8563 if (!Diagnosed) {
8564 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8565 Diag(Merge.first->getLocation(),
8566 diag::err_module_odr_violation_different_definitions)
8567 << Merge.first << Module.empty() << Module;
8568 Diagnosed = true;
8569 }
8570
8571 Diag(RD->getLocation(),
8572 diag::note_module_odr_violation_different_definitions)
8573 << getOwningModuleNameForDiagnostic(RD);
8574 }
8575 }
8576
8577 if (!Diagnosed) {
8578 // All definitions are updates to the same declaration. This happens if a
8579 // module instantiates the declaration of a class template specialization
8580 // and two or more other modules instantiate its definition.
8581 //
8582 // FIXME: Indicate which modules had instantiations of this definition.
8583 // FIXME: How can this even happen?
8584 Diag(Merge.first->getLocation(),
8585 diag::err_module_odr_violation_different_instantiations)
8586 << Merge.first;
8587 }
8588 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008589}
8590
Richard Smithce18a182015-07-14 00:26:00 +00008591void ASTReader::StartedDeserializing() {
8592 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8593 ReadTimer->startTimer();
8594}
8595
Guy Benyei11169dd2012-12-18 14:30:41 +00008596void ASTReader::FinishedDeserializing() {
8597 assert(NumCurrentElementsDeserializing &&
8598 "FinishedDeserializing not paired with StartedDeserializing");
8599 if (NumCurrentElementsDeserializing == 1) {
8600 // We decrease NumCurrentElementsDeserializing only after pending actions
8601 // are finished, to avoid recursively re-calling finishPendingActions().
8602 finishPendingActions();
8603 }
8604 --NumCurrentElementsDeserializing;
8605
Richard Smitha0ce9c42014-07-29 23:23:27 +00008606 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008607 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008608 while (!PendingExceptionSpecUpdates.empty()) {
8609 auto Updates = std::move(PendingExceptionSpecUpdates);
8610 PendingExceptionSpecUpdates.clear();
8611 for (auto Update : Updates) {
8612 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008613 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00008614 if (auto *Listener = Context.getASTMutationListener())
8615 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00008616 for (auto *Redecl : Update.second->redecls())
8617 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008618 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008619 }
8620
Richard Smithce18a182015-07-14 00:26:00 +00008621 if (ReadTimer)
8622 ReadTimer->stopTimer();
8623
Richard Smith0f4e2c42015-08-06 04:23:48 +00008624 diagnoseOdrViolations();
8625
Richard Smith04d05b52014-03-23 00:27:18 +00008626 // We are not in recursive loading, so it's safe to pass the "interesting"
8627 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008628 if (Consumer)
8629 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008630 }
8631}
8632
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008633void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008634 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8635 // Remove any fake results before adding any real ones.
8636 auto It = PendingFakeLookupResults.find(II);
8637 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008638 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008639 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008640 // FIXME: this works around module+PCH performance issue.
8641 // Rather than erase the result from the map, which is O(n), just clear
8642 // the vector of NamedDecls.
8643 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008644 }
8645 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008646
8647 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8648 SemaObj->TUScope->AddDecl(D);
8649 } else if (SemaObj->TUScope) {
8650 // Adding the decl to IdResolver may have failed because it was already in
8651 // (even though it was not added in scope). If it is already in, make sure
8652 // it gets in the scope as well.
8653 if (std::find(SemaObj->IdResolver.begin(Name),
8654 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8655 SemaObj->TUScope->AddDecl(D);
8656 }
8657}
8658
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008659ASTReader::ASTReader(
8660 Preprocessor &PP, ASTContext &Context,
8661 const PCHContainerReader &PCHContainerRdr,
8662 ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
8663 StringRef isysroot, bool DisableValidation,
8664 bool AllowASTWithCompilerErrors,
8665 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8666 bool UseGlobalIndex,
8667 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008668 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008669 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008670 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008671 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008672 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008673 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008674 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008675 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8676 AllowConfigurationMismatch(AllowConfigurationMismatch),
8677 ValidateSystemInputs(ValidateSystemInputs),
8678 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008679 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8680 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8681 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8682 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008683 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8684 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8685 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8686 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8687 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8688 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008689 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008690 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008691
8692 for (const auto &Ext : Extensions) {
8693 auto BlockName = Ext->getExtensionMetadata().BlockName;
8694 auto Known = ModuleFileExtensions.find(BlockName);
8695 if (Known != ModuleFileExtensions.end()) {
8696 Diags.Report(diag::warn_duplicate_module_file_extension)
8697 << BlockName;
8698 continue;
8699 }
8700
8701 ModuleFileExtensions.insert({BlockName, Ext});
8702 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008703}
8704
8705ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008706 if (OwnsDeserializationListener)
8707 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008708}