blob: c09e97c1584bfcb61c524996f776033285c36278 [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
Guy Benyei11169dd2012-12-18 14:30:41 +0000771IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
772 const unsigned char* d,
773 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000774 using namespace llvm::support;
775 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000776 bool IsInteresting = RawID & 0x01;
777
778 // Wipe out the "is interesting" bit.
779 RawID = RawID >> 1;
780
Richard Smith76c2f2c2015-07-17 20:09:43 +0000781 // Build the IdentifierInfo and link the identifier ID with it.
782 IdentifierInfo *II = KnownII;
783 if (!II) {
784 II = &Reader.getIdentifierTable().getOwn(k);
785 KnownII = II;
786 }
787 if (!II->isFromAST()) {
788 II->setIsFromAST();
Ben Langmuirb9ad4e62015-10-28 22:25:37 +0000789 bool IsModule = Reader.PP.getCurrentModule() != nullptr;
790 if (isInterestingIdentifier(Reader, *II, IsModule))
Richard Smith76c2f2c2015-07-17 20:09:43 +0000791 II->setChangedSinceDeserialization();
792 }
793 Reader.markIdentifierUpToDate(II);
794
Guy Benyei11169dd2012-12-18 14:30:41 +0000795 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
796 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000797 // For uninteresting identifiers, there's nothing else to do. Just notify
798 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000799 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000800 return II;
801 }
802
Justin Bogner57ba0b22014-03-28 22:03:24 +0000803 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
804 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000805 bool CPlusPlusOperatorKeyword = readBit(Bits);
806 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000807 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000808 bool Poisoned = readBit(Bits);
809 bool ExtensionToken = readBit(Bits);
810 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000811
812 assert(Bits == 0 && "Extra bits in the identifier?");
813 DataLen -= 8;
814
Guy Benyei11169dd2012-12-18 14:30:41 +0000815 // Set or check the various bits in the IdentifierInfo structure.
816 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000817 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000818 II->revertTokenIDToIdentifier();
819 if (!F.isModule())
820 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
821 else if (HasRevertedBuiltin && II->getBuiltinID()) {
822 II->revertBuiltin();
823 assert((II->hasRevertedBuiltin() ||
824 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
825 "Incorrect ObjC keyword or builtin ID");
826 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000827 assert(II->isExtensionToken() == ExtensionToken &&
828 "Incorrect extension token flag");
829 (void)ExtensionToken;
830 if (Poisoned)
831 II->setIsPoisoned(true);
832 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
833 "Incorrect C++ operator keyword flag");
834 (void)CPlusPlusOperatorKeyword;
835
836 // If this identifier is a macro, deserialize the macro
837 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000838 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000839 uint32_t MacroDirectivesOffset =
840 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000841 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000842
Richard Smithd7329392015-04-21 21:46:32 +0000843 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000844 }
845
846 Reader.SetIdentifierInfo(ID, II);
847
848 // Read all of the declarations visible at global scope with this
849 // name.
850 if (DataLen > 0) {
851 SmallVector<uint32_t, 4> DeclIDs;
852 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000853 DeclIDs.push_back(Reader.getGlobalDeclID(
854 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000855 Reader.SetGloballyVisibleDecls(II, DeclIDs);
856 }
857
858 return II;
859}
860
Richard Smitha06c7e62015-08-26 23:55:49 +0000861DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
862 : Kind(Name.getNameKind()) {
863 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000864 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000865 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000866 break;
867 case DeclarationName::ObjCZeroArgSelector:
868 case DeclarationName::ObjCOneArgSelector:
869 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000870 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000871 break;
872 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000873 Data = Name.getCXXOverloadedOperator();
874 break;
875 case DeclarationName::CXXLiteralOperatorName:
876 Data = (uint64_t)Name.getCXXLiteralIdentifier();
877 break;
878 case DeclarationName::CXXConstructorName:
879 case DeclarationName::CXXDestructorName:
880 case DeclarationName::CXXConversionFunctionName:
881 case DeclarationName::CXXUsingDirective:
882 Data = 0;
883 break;
884 }
885}
886
887unsigned DeclarationNameKey::getHash() const {
888 llvm::FoldingSetNodeID ID;
889 ID.AddInteger(Kind);
890
891 switch (Kind) {
892 case DeclarationName::Identifier:
893 case DeclarationName::CXXLiteralOperatorName:
894 ID.AddString(((IdentifierInfo*)Data)->getName());
895 break;
896 case DeclarationName::ObjCZeroArgSelector:
897 case DeclarationName::ObjCOneArgSelector:
898 case DeclarationName::ObjCMultiArgSelector:
899 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
900 break;
901 case DeclarationName::CXXOperatorName:
902 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000903 break;
904 case DeclarationName::CXXConstructorName:
905 case DeclarationName::CXXDestructorName:
906 case DeclarationName::CXXConversionFunctionName:
907 case DeclarationName::CXXUsingDirective:
908 break;
909 }
910
911 return ID.ComputeHash();
912}
913
Richard Smithd88a7f12015-09-01 20:35:42 +0000914ModuleFile *
915ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
916 using namespace llvm::support;
917 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
918 return Reader.getLocalModuleFile(F, ModuleFileID);
919}
920
Guy Benyei11169dd2012-12-18 14:30:41 +0000921std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000922ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000923 using namespace llvm::support;
924 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
925 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000926 return std::make_pair(KeyLen, DataLen);
927}
928
Richard Smitha06c7e62015-08-26 23:55:49 +0000929ASTDeclContextNameLookupTrait::internal_key_type
930ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000931 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000932
Richard Smitha06c7e62015-08-26 23:55:49 +0000933 auto Kind = (DeclarationName::NameKind)*d++;
934 uint64_t Data;
935 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000936 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000937 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000938 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000939 break;
940 case DeclarationName::ObjCZeroArgSelector:
941 case DeclarationName::ObjCOneArgSelector:
942 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000943 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000944 (uint64_t)Reader.getLocalSelector(
945 F, endian::readNext<uint32_t, little, unaligned>(
946 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000947 break;
948 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000949 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +0000950 break;
951 case DeclarationName::CXXLiteralOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000952 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000953 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000954 break;
955 case DeclarationName::CXXConstructorName:
956 case DeclarationName::CXXDestructorName:
957 case DeclarationName::CXXConversionFunctionName:
958 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +0000959 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000960 break;
961 }
962
Richard Smitha06c7e62015-08-26 23:55:49 +0000963 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000964}
965
Richard Smithd88a7f12015-09-01 20:35:42 +0000966void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
967 const unsigned char *d,
968 unsigned DataLen,
969 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000970 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +0000971 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
972 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
973 Val.insert(Reader.getGlobalDeclID(F, LocalID));
974 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000975}
976
Richard Smith0f4e2c42015-08-06 04:23:48 +0000977bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
978 BitstreamCursor &Cursor,
979 uint64_t Offset,
980 DeclContext *DC) {
981 assert(Offset != 0);
982
Guy Benyei11169dd2012-12-18 14:30:41 +0000983 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +0000984 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000985
Richard Smith0f4e2c42015-08-06 04:23:48 +0000986 RecordData Record;
987 StringRef Blob;
988 unsigned Code = Cursor.ReadCode();
989 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
990 if (RecCode != DECL_CONTEXT_LEXICAL) {
991 Error("Expected lexical block");
992 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000993 }
994
Richard Smith82f8fcd2015-08-06 22:07:25 +0000995 assert(!isa<TranslationUnitDecl>(DC) &&
996 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +0000997 // If we are handling a C++ class template instantiation, we can see multiple
998 // lexical updates for the same record. It's important that we select only one
999 // of them, so that field numbering works properly. Just pick the first one we
1000 // see.
1001 auto &Lex = LexicalDecls[DC];
1002 if (!Lex.first) {
1003 Lex = std::make_pair(
1004 &M, llvm::makeArrayRef(
1005 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1006 Blob.data()),
1007 Blob.size() / 4));
1008 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001009 DC->setHasExternalLexicalStorage(true);
1010 return false;
1011}
Guy Benyei11169dd2012-12-18 14:30:41 +00001012
Richard Smith0f4e2c42015-08-06 04:23:48 +00001013bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1014 BitstreamCursor &Cursor,
1015 uint64_t Offset,
1016 DeclID ID) {
1017 assert(Offset != 0);
1018
1019 SavedStreamPosition SavedPosition(Cursor);
1020 Cursor.JumpToBit(Offset);
1021
1022 RecordData Record;
1023 StringRef Blob;
1024 unsigned Code = Cursor.ReadCode();
1025 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1026 if (RecCode != DECL_CONTEXT_VISIBLE) {
1027 Error("Expected visible lookup table block");
1028 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001029 }
1030
Richard Smith0f4e2c42015-08-06 04:23:48 +00001031 // We can't safely determine the primary context yet, so delay attaching the
1032 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001033 auto *Data = (const unsigned char*)Blob.data();
1034 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001035 return false;
1036}
1037
1038void ASTReader::Error(StringRef Msg) {
1039 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001040 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1041 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001042 Diag(diag::note_module_cache_path)
1043 << PP.getHeaderSearchInfo().getModuleCachePath();
1044 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001045}
1046
1047void ASTReader::Error(unsigned DiagID,
1048 StringRef Arg1, StringRef Arg2) {
1049 if (Diags.isDiagnosticInFlight())
1050 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1051 else
1052 Diag(DiagID) << Arg1 << Arg2;
1053}
1054
1055//===----------------------------------------------------------------------===//
1056// Source Manager Deserialization
1057//===----------------------------------------------------------------------===//
1058
1059/// \brief Read the line table in the source manager block.
1060/// \returns true if there was an error.
1061bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001062 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001063 unsigned Idx = 0;
1064 LineTableInfo &LineTable = SourceMgr.getLineTable();
1065
1066 // Parse the file names
1067 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001068 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001069 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001070 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001071 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1072 }
Richard Smith63078492015-09-01 07:41:55 +00001073 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001074
1075 // Parse the line entries
1076 std::vector<LineEntry> Entries;
1077 while (Idx < Record.size()) {
1078 int FID = Record[Idx++];
1079 assert(FID >= 0 && "Serialized line entries for non-local file.");
1080 // Remap FileID from 1-based old view.
1081 FID += F.SLocEntryBaseID - 1;
1082
1083 // Extract the line entries
1084 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001085 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001086 Entries.clear();
1087 Entries.reserve(NumEntries);
1088 for (unsigned I = 0; I != NumEntries; ++I) {
1089 unsigned FileOffset = Record[Idx++];
1090 unsigned LineNo = Record[Idx++];
1091 int FilenameID = FileIDs[Record[Idx++]];
1092 SrcMgr::CharacteristicKind FileKind
1093 = (SrcMgr::CharacteristicKind)Record[Idx++];
1094 unsigned IncludeOffset = Record[Idx++];
1095 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1096 FileKind, IncludeOffset));
1097 }
1098 LineTable.AddEntry(FileID::get(FID), Entries);
1099 }
1100
1101 return false;
1102}
1103
1104/// \brief Read a source manager block
1105bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1106 using namespace SrcMgr;
1107
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001108 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001109
1110 // Set the source-location entry cursor to the current position in
1111 // the stream. This cursor will be used to read the contents of the
1112 // source manager block initially, and then lazily read
1113 // source-location entries as needed.
1114 SLocEntryCursor = F.Stream;
1115
1116 // The stream itself is going to skip over the source manager block.
1117 if (F.Stream.SkipBlock()) {
1118 Error("malformed block record in AST file");
1119 return true;
1120 }
1121
1122 // Enter the source manager block.
1123 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1124 Error("malformed source manager block record in AST file");
1125 return true;
1126 }
1127
1128 RecordData Record;
1129 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001130 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1131
1132 switch (E.Kind) {
1133 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1134 case llvm::BitstreamEntry::Error:
1135 Error("malformed block record in AST file");
1136 return true;
1137 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001138 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001139 case llvm::BitstreamEntry::Record:
1140 // The interesting case.
1141 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001142 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001143
Guy Benyei11169dd2012-12-18 14:30:41 +00001144 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001145 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001146 StringRef Blob;
1147 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001148 default: // Default behavior: ignore.
1149 break;
1150
1151 case SM_SLOC_FILE_ENTRY:
1152 case SM_SLOC_BUFFER_ENTRY:
1153 case SM_SLOC_EXPANSION_ENTRY:
1154 // Once we hit one of the source location entries, we're done.
1155 return false;
1156 }
1157 }
1158}
1159
1160/// \brief If a header file is not found at the path that we expect it to be
1161/// and the PCH file was moved from its original location, try to resolve the
1162/// file by assuming that header+PCH were moved together and the header is in
1163/// the same place relative to the PCH.
1164static std::string
1165resolveFileRelativeToOriginalDir(const std::string &Filename,
1166 const std::string &OriginalDir,
1167 const std::string &CurrDir) {
1168 assert(OriginalDir != CurrDir &&
1169 "No point trying to resolve the file if the PCH dir didn't change");
1170 using namespace llvm::sys;
1171 SmallString<128> filePath(Filename);
1172 fs::make_absolute(filePath);
1173 assert(path::is_absolute(OriginalDir));
1174 SmallString<128> currPCHPath(CurrDir);
1175
1176 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1177 fileDirE = path::end(path::parent_path(filePath));
1178 path::const_iterator origDirI = path::begin(OriginalDir),
1179 origDirE = path::end(OriginalDir);
1180 // Skip the common path components from filePath and OriginalDir.
1181 while (fileDirI != fileDirE && origDirI != origDirE &&
1182 *fileDirI == *origDirI) {
1183 ++fileDirI;
1184 ++origDirI;
1185 }
1186 for (; origDirI != origDirE; ++origDirI)
1187 path::append(currPCHPath, "..");
1188 path::append(currPCHPath, fileDirI, fileDirE);
1189 path::append(currPCHPath, path::filename(Filename));
1190 return currPCHPath.str();
1191}
1192
1193bool ASTReader::ReadSLocEntry(int ID) {
1194 if (ID == 0)
1195 return false;
1196
1197 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1198 Error("source location entry ID out-of-range for AST file");
1199 return true;
1200 }
1201
1202 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1203 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001204 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001205 unsigned BaseOffset = F->SLocEntryBaseOffset;
1206
1207 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001208 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1209 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001210 Error("incorrectly-formatted source location entry in AST file");
1211 return true;
1212 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001213
Guy Benyei11169dd2012-12-18 14:30:41 +00001214 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001215 StringRef Blob;
1216 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001217 default:
1218 Error("incorrectly-formatted source location entry in AST file");
1219 return true;
1220
1221 case SM_SLOC_FILE_ENTRY: {
1222 // We will detect whether a file changed and return 'Failure' for it, but
1223 // we will also try to fail gracefully by setting up the SLocEntry.
1224 unsigned InputID = Record[4];
1225 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001226 const FileEntry *File = IF.getFile();
1227 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001228
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001229 // Note that we only check if a File was returned. If it was out-of-date
1230 // we have complained but we will continue creating a FileID to recover
1231 // gracefully.
1232 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001233 return true;
1234
1235 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1236 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1237 // This is the module's main file.
1238 IncludeLoc = getImportLocation(F);
1239 }
1240 SrcMgr::CharacteristicKind
1241 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1242 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1243 ID, BaseOffset + Record[0]);
1244 SrcMgr::FileInfo &FileInfo =
1245 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1246 FileInfo.NumCreatedFIDs = Record[5];
1247 if (Record[3])
1248 FileInfo.setHasLineDirectives();
1249
1250 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1251 unsigned NumFileDecls = Record[7];
1252 if (NumFileDecls) {
1253 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1254 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1255 NumFileDecls));
1256 }
1257
1258 const SrcMgr::ContentCache *ContentCache
1259 = SourceMgr.getOrCreateContentCache(File,
1260 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1261 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1262 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1263 unsigned Code = SLocEntryCursor.ReadCode();
1264 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001265 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001266
1267 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1268 Error("AST record has invalid code");
1269 return true;
1270 }
1271
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001272 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001273 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001274 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001275 }
1276
1277 break;
1278 }
1279
1280 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001281 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001282 unsigned Offset = Record[0];
1283 SrcMgr::CharacteristicKind
1284 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1285 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001286 if (IncludeLoc.isInvalid() &&
1287 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001288 IncludeLoc = getImportLocation(F);
1289 }
1290 unsigned Code = SLocEntryCursor.ReadCode();
1291 Record.clear();
1292 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001293 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001294
1295 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1296 Error("AST record has invalid code");
1297 return true;
1298 }
1299
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001300 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1301 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001302 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001303 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001304 break;
1305 }
1306
1307 case SM_SLOC_EXPANSION_ENTRY: {
1308 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1309 SourceMgr.createExpansionLoc(SpellingLoc,
1310 ReadSourceLocation(*F, Record[2]),
1311 ReadSourceLocation(*F, Record[3]),
1312 Record[4],
1313 ID,
1314 BaseOffset + Record[0]);
1315 break;
1316 }
1317 }
1318
1319 return false;
1320}
1321
1322std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1323 if (ID == 0)
1324 return std::make_pair(SourceLocation(), "");
1325
1326 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1327 Error("source location entry ID out-of-range for AST file");
1328 return std::make_pair(SourceLocation(), "");
1329 }
1330
1331 // Find which module file this entry lands in.
1332 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001333 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001334 return std::make_pair(SourceLocation(), "");
1335
1336 // FIXME: Can we map this down to a particular submodule? That would be
1337 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001338 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001339}
1340
1341/// \brief Find the location where the module F is imported.
1342SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1343 if (F->ImportLoc.isValid())
1344 return F->ImportLoc;
1345
1346 // Otherwise we have a PCH. It's considered to be "imported" at the first
1347 // location of its includer.
1348 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001349 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001350 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001351 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001352 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001353 return F->ImportedBy[0]->FirstLoc;
1354}
1355
1356/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1357/// specified cursor. Read the abbreviations that are at the top of the block
1358/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001359bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001360 if (Cursor.EnterSubBlock(BlockID))
1361 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001362
1363 while (true) {
1364 uint64_t Offset = Cursor.GetCurrentBitNo();
1365 unsigned Code = Cursor.ReadCode();
1366
1367 // We expect all abbrevs to be at the start of the block.
1368 if (Code != llvm::bitc::DEFINE_ABBREV) {
1369 Cursor.JumpToBit(Offset);
1370 return false;
1371 }
1372 Cursor.ReadAbbrevRecord();
1373 }
1374}
1375
Richard Smithe40f2ba2013-08-07 21:41:30 +00001376Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001377 unsigned &Idx) {
1378 Token Tok;
1379 Tok.startToken();
1380 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1381 Tok.setLength(Record[Idx++]);
1382 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1383 Tok.setIdentifierInfo(II);
1384 Tok.setKind((tok::TokenKind)Record[Idx++]);
1385 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1386 return Tok;
1387}
1388
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001389MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001390 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001391
1392 // Keep track of where we are in the stream, then jump back there
1393 // after reading this macro.
1394 SavedStreamPosition SavedPosition(Stream);
1395
1396 Stream.JumpToBit(Offset);
1397 RecordData Record;
1398 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001399 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001400
Guy Benyei11169dd2012-12-18 14:30:41 +00001401 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001402 // Advance to the next record, but if we get to the end of the block, don't
1403 // pop it (removing all the abbreviations from the cursor) since we want to
1404 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001405 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001406 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1407
1408 switch (Entry.Kind) {
1409 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1410 case llvm::BitstreamEntry::Error:
1411 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001412 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001413 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001414 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001415 case llvm::BitstreamEntry::Record:
1416 // The interesting case.
1417 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001418 }
1419
1420 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001421 Record.clear();
1422 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001423 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001424 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001425 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001426 case PP_MACRO_DIRECTIVE_HISTORY:
1427 return Macro;
1428
Guy Benyei11169dd2012-12-18 14:30:41 +00001429 case PP_MACRO_OBJECT_LIKE:
1430 case PP_MACRO_FUNCTION_LIKE: {
1431 // If we already have a macro, that means that we've hit the end
1432 // of the definition of the macro we were looking for. We're
1433 // done.
1434 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001435 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001436
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001437 unsigned NextIndex = 1; // Skip identifier ID.
1438 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001439 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001440 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001441 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001442 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001443 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001444
Guy Benyei11169dd2012-12-18 14:30:41 +00001445 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1446 // Decode function-like macro info.
1447 bool isC99VarArgs = Record[NextIndex++];
1448 bool isGNUVarArgs = Record[NextIndex++];
1449 bool hasCommaPasting = Record[NextIndex++];
1450 MacroArgs.clear();
1451 unsigned NumArgs = Record[NextIndex++];
1452 for (unsigned i = 0; i != NumArgs; ++i)
1453 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1454
1455 // Install function-like macro info.
1456 MI->setIsFunctionLike();
1457 if (isC99VarArgs) MI->setIsC99Varargs();
1458 if (isGNUVarArgs) MI->setIsGNUVarargs();
1459 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001460 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001461 }
1462
Guy Benyei11169dd2012-12-18 14:30:41 +00001463 // Remember that we saw this macro last so that we add the tokens that
1464 // form its body to it.
1465 Macro = MI;
1466
1467 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1468 Record[NextIndex]) {
1469 // We have a macro definition. Register the association
1470 PreprocessedEntityID
1471 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1472 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001473 PreprocessingRecord::PPEntityID PPID =
1474 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1475 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1476 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001477 if (PPDef)
1478 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001479 }
1480
1481 ++NumMacrosRead;
1482 break;
1483 }
1484
1485 case PP_TOKEN: {
1486 // If we see a TOKEN before a PP_MACRO_*, then the file is
1487 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001488 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001489
John McCallf413f5e2013-05-03 00:10:13 +00001490 unsigned Idx = 0;
1491 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001492 Macro->AddTokenToBody(Tok);
1493 break;
1494 }
1495 }
1496 }
1497}
1498
1499PreprocessedEntityID
1500ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1501 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1502 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1503 assert(I != M.PreprocessedEntityRemap.end()
1504 && "Invalid index into preprocessed entity index remap");
1505
1506 return LocalID + I->second;
1507}
1508
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001509unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1510 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001511}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001512
Guy Benyei11169dd2012-12-18 14:30:41 +00001513HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001514HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001515 internal_key_type ikey = {FE->getSize(),
1516 M.HasTimestamps ? FE->getModificationTime() : 0,
1517 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001518 return ikey;
1519}
Guy Benyei11169dd2012-12-18 14:30:41 +00001520
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001521bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001522 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001523 return false;
1524
Richard Smith7ed1bc92014-12-05 22:42:13 +00001525 if (llvm::sys::path::is_absolute(a.Filename) &&
1526 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001527 return true;
1528
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001530 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001531 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1532 if (!Key.Imported)
1533 return FileMgr.getFile(Key.Filename);
1534
1535 std::string Resolved = Key.Filename;
1536 Reader.ResolveImportedPath(M, Resolved);
1537 return FileMgr.getFile(Resolved);
1538 };
1539
1540 const FileEntry *FEA = GetFile(a);
1541 const FileEntry *FEB = GetFile(b);
1542 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001543}
1544
1545std::pair<unsigned, unsigned>
1546HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001547 using namespace llvm::support;
1548 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001549 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001550 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001551}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001552
1553HeaderFileInfoTrait::internal_key_type
1554HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001555 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001556 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001557 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1558 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001559 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001560 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001561 return ikey;
1562}
1563
Guy Benyei11169dd2012-12-18 14:30:41 +00001564HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001565HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001566 unsigned DataLen) {
1567 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001568 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001569 HeaderFileInfo HFI;
1570 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001571 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1572 HFI.isImport |= (Flags >> 4) & 0x01;
1573 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1574 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001575 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001576 // FIXME: Find a better way to handle this. Maybe just store a
1577 // "has been included" flag?
1578 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1579 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001580 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1581 M, endian::readNext<uint32_t, little, unaligned>(d));
1582 if (unsigned FrameworkOffset =
1583 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001584 // The framework offset is 1 greater than the actual offset,
1585 // since 0 is used as an indicator for "no framework name".
1586 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1587 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1588 }
Richard Smith386bb072015-08-18 23:42:23 +00001589
1590 assert((End - d) % 4 == 0 &&
1591 "Wrong data length in HeaderFileInfo deserialization");
1592 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001593 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001594 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1595 LocalSMID >>= 2;
1596
1597 // This header is part of a module. Associate it with the module to enable
1598 // implicit module import.
1599 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1600 Module *Mod = Reader.getSubmodule(GlobalSMID);
1601 FileManager &FileMgr = Reader.getFileManager();
1602 ModuleMap &ModMap =
1603 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1604
1605 std::string Filename = key.Filename;
1606 if (key.Imported)
1607 Reader.ResolveImportedPath(M, Filename);
1608 // FIXME: This is not always the right filename-as-written, but we're not
1609 // going to use this information to rebuild the module, so it doesn't make
1610 // a lot of difference.
1611 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001612 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1613 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001614 }
1615
Guy Benyei11169dd2012-12-18 14:30:41 +00001616 // This HeaderFileInfo was externally loaded.
1617 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001618 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001619 return HFI;
1620}
1621
Richard Smithd7329392015-04-21 21:46:32 +00001622void ASTReader::addPendingMacro(IdentifierInfo *II,
1623 ModuleFile *M,
1624 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001625 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1626 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001627}
1628
1629void ASTReader::ReadDefinedMacros() {
1630 // Note that we are loading defined macros.
1631 Deserializing Macros(this);
1632
Pete Cooper57d3f142015-07-30 17:22:52 +00001633 for (auto &I : llvm::reverse(ModuleMgr)) {
1634 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001635
1636 // If there was no preprocessor block, skip this file.
1637 if (!MacroCursor.getBitStreamReader())
1638 continue;
1639
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001640 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001641 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001642
1643 RecordData Record;
1644 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001645 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1646
1647 switch (E.Kind) {
1648 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1649 case llvm::BitstreamEntry::Error:
1650 Error("malformed block record in AST file");
1651 return;
1652 case llvm::BitstreamEntry::EndBlock:
1653 goto NextCursor;
1654
1655 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001656 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001657 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001658 default: // Default behavior: ignore.
1659 break;
1660
1661 case PP_MACRO_OBJECT_LIKE:
1662 case PP_MACRO_FUNCTION_LIKE:
Pete Cooper57d3f142015-07-30 17:22:52 +00001663 getLocalIdentifier(*I, Record[0]);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001664 break;
1665
1666 case PP_TOKEN:
1667 // Ignore tokens.
1668 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001669 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001670 break;
1671 }
1672 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001673 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001674 }
1675}
1676
1677namespace {
1678 /// \brief Visitor class used to look up identifirs in an AST file.
1679 class IdentifierLookupVisitor {
1680 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001681 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001682 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001683 unsigned &NumIdentifierLookups;
1684 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001685 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001686
Guy Benyei11169dd2012-12-18 14:30:41 +00001687 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001688 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1689 unsigned &NumIdentifierLookups,
1690 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001691 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1692 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001693 NumIdentifierLookups(NumIdentifierLookups),
1694 NumIdentifierLookupHits(NumIdentifierLookupHits),
1695 Found()
1696 {
1697 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001698
1699 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001700 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001701 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001702 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001703
Guy Benyei11169dd2012-12-18 14:30:41 +00001704 ASTIdentifierLookupTable *IdTable
1705 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1706 if (!IdTable)
1707 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001708
1709 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001710 Found);
1711 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001712 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001713 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001714 if (Pos == IdTable->end())
1715 return false;
1716
1717 // Dereferencing the iterator has the effect of building the
1718 // IdentifierInfo node and populating it with the various
1719 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001720 ++NumIdentifierLookupHits;
1721 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001722 return true;
1723 }
1724
1725 // \brief Retrieve the identifier info found within the module
1726 // files.
1727 IdentifierInfo *getIdentifierInfo() const { return Found; }
1728 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001729}
Guy Benyei11169dd2012-12-18 14:30:41 +00001730
1731void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1732 // Note that we are loading an identifier.
1733 Deserializing AnIdentifier(this);
1734
1735 unsigned PriorGeneration = 0;
1736 if (getContext().getLangOpts().Modules)
1737 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001738
1739 // If there is a global index, look there first to determine which modules
1740 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001741 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001742 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001743 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001744 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1745 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001746 }
1747 }
1748
Douglas Gregor7211ac12013-01-25 23:32:03 +00001749 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001750 NumIdentifierLookups,
1751 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001752 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001753 markIdentifierUpToDate(&II);
1754}
1755
1756void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1757 if (!II)
1758 return;
1759
1760 II->setOutOfDate(false);
1761
1762 // Update the generation for this identifier.
1763 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001764 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001765}
1766
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001767void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1768 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001769 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001770
1771 BitstreamCursor &Cursor = M.MacroCursor;
1772 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001773 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001774
Richard Smith713369b2015-04-23 20:40:50 +00001775 struct ModuleMacroRecord {
1776 SubmoduleID SubModID;
1777 MacroInfo *MI;
1778 SmallVector<SubmoduleID, 8> Overrides;
1779 };
1780 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001781
Richard Smithd7329392015-04-21 21:46:32 +00001782 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1783 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1784 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001785 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001786 while (true) {
1787 llvm::BitstreamEntry Entry =
1788 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1789 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1790 Error("malformed block record in AST file");
1791 return;
1792 }
1793
1794 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001795 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001796 case PP_MACRO_DIRECTIVE_HISTORY:
1797 break;
1798
1799 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001800 ModuleMacros.push_back(ModuleMacroRecord());
1801 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001802 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1803 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001804 for (int I = 2, N = Record.size(); I != N; ++I)
1805 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001806 continue;
1807 }
1808
1809 default:
1810 Error("malformed block record in AST file");
1811 return;
1812 }
1813
1814 // We found the macro directive history; that's the last record
1815 // for this macro.
1816 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001817 }
1818
Richard Smithd7329392015-04-21 21:46:32 +00001819 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001820 {
1821 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001822 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001823 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001824 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001825 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001826 Module *Mod = getSubmodule(ModID);
1827 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001828 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001829 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001830 }
1831
1832 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001833 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001834 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001835 }
1836 }
1837
1838 // Don't read the directive history for a module; we don't have anywhere
1839 // to put it.
1840 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1841 return;
1842
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001843 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001844 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001845 unsigned Idx = 0, N = Record.size();
1846 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001847 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001848 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001849 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1850 switch (K) {
1851 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001852 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001853 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001854 break;
1855 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001856 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001857 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001858 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001859 }
1860 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001861 bool isPublic = Record[Idx++];
1862 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1863 break;
1864 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001865
1866 if (!Latest)
1867 Latest = MD;
1868 if (Earliest)
1869 Earliest->setPrevious(MD);
1870 Earliest = MD;
1871 }
1872
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001873 if (Latest)
1874 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001875}
1876
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001877ASTReader::InputFileInfo
1878ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001879 // Go find this input file.
1880 BitstreamCursor &Cursor = F.InputFilesCursor;
1881 SavedStreamPosition SavedPosition(Cursor);
1882 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1883
1884 unsigned Code = Cursor.ReadCode();
1885 RecordData Record;
1886 StringRef Blob;
1887
1888 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1889 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1890 "invalid record type for input file");
1891 (void)Result;
1892
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001893 std::string Filename;
1894 off_t StoredSize;
1895 time_t StoredTime;
1896 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001897
Ben Langmuir198c1682014-03-07 07:27:49 +00001898 assert(Record[0] == ID && "Bogus stored ID or offset");
1899 StoredSize = static_cast<off_t>(Record[1]);
1900 StoredTime = static_cast<time_t>(Record[2]);
1901 Overridden = static_cast<bool>(Record[3]);
1902 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001903 ResolveImportedPath(F, Filename);
1904
Hans Wennborg73945142014-03-14 17:45:06 +00001905 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1906 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;
1930 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001931
Ben Langmuir198c1682014-03-07 07:27:49 +00001932 const FileEntry *File
1933 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1934 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1935
1936 // If we didn't find the file, resolve it relative to the
1937 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001938 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001939 F.OriginalDir != CurrentDir) {
1940 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1941 F.OriginalDir,
1942 CurrentDir);
1943 if (!Resolved.empty())
1944 File = FileMgr.getFile(Resolved);
1945 }
1946
1947 // For an overridden file, create a virtual file with the stored
1948 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001949 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001950 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1951 }
1952
Craig Toppera13603a2014-05-22 05:54:18 +00001953 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001954 if (Complain) {
1955 std::string ErrorStr = "could not find file '";
1956 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00001957 ErrorStr += "' referenced by AST file '";
1958 ErrorStr += F.FileName;
1959 ErrorStr += "'";
Ben Langmuir198c1682014-03-07 07:27:49 +00001960 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001961 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001962 // Record that we didn't find the file.
1963 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1964 return InputFile();
1965 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001966
Ben Langmuir198c1682014-03-07 07:27:49 +00001967 // Check if there was a request to override the contents of the file
1968 // that was part of the precompiled header. Overridding such a file
1969 // can lead to problems when lexing using the source locations from the
1970 // PCH.
1971 SourceManager &SM = getSourceManager();
1972 if (!Overridden && SM.isFileOverridden(File)) {
1973 if (Complain)
1974 Error(diag::err_fe_pch_file_overridden, Filename);
1975 // After emitting the diagnostic, recover by disabling the override so
1976 // that the original file will be used.
1977 SM.disableFileContentsOverride(File);
1978 // The FileEntry is a virtual file entry with the size of the contents
1979 // that would override the original contents. Set it to the original's
1980 // size/time.
1981 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1982 StoredSize, StoredTime);
1983 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001984
Ben Langmuir198c1682014-03-07 07:27:49 +00001985 bool IsOutOfDate = false;
1986
1987 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001988 if (!Overridden && //
1989 (StoredSize != File->getSize() ||
1990#if defined(LLVM_ON_WIN32)
1991 false
1992#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001993 // In our regression testing, the Windows file system seems to
1994 // have inconsistent modification times that sometimes
1995 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001996 //
Richard Smithe75ee0f2015-08-17 07:13:32 +00001997 // FIXME: This probably also breaks HeaderFileInfo lookups on Windows.
1998 (StoredTime && StoredTime != File->getModificationTime() &&
1999 !DisableValidation)
Guy Benyei11169dd2012-12-18 14:30:41 +00002000#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002001 )) {
2002 if (Complain) {
2003 // Build a list of the PCH imports that got us here (in reverse).
2004 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2005 while (ImportStack.back()->ImportedBy.size() > 0)
2006 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002007
Ben Langmuir198c1682014-03-07 07:27:49 +00002008 // The top-level PCH is stale.
2009 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2010 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002011
Ben Langmuir198c1682014-03-07 07:27:49 +00002012 // Print the import stack.
2013 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2014 Diag(diag::note_pch_required_by)
2015 << Filename << ImportStack[0]->FileName;
2016 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002017 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002018 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002019 }
2020
Ben Langmuir198c1682014-03-07 07:27:49 +00002021 if (!Diags.isDiagnosticInFlight())
2022 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002023 }
2024
Ben Langmuir198c1682014-03-07 07:27:49 +00002025 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002026 }
2027
Ben Langmuir198c1682014-03-07 07:27:49 +00002028 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2029
2030 // Note that we've loaded this input file.
2031 F.InputFilesLoaded[ID-1] = IF;
2032 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002033}
2034
Richard Smith7ed1bc92014-12-05 22:42:13 +00002035/// \brief If we are loading a relocatable PCH or module file, and the filename
2036/// is not an absolute path, add the system or module root to the beginning of
2037/// the file name.
2038void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2039 // Resolve relative to the base directory, if we have one.
2040 if (!M.BaseDirectory.empty())
2041 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002042}
2043
Richard Smith7ed1bc92014-12-05 22:42:13 +00002044void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002045 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2046 return;
2047
Richard Smith7ed1bc92014-12-05 22:42:13 +00002048 SmallString<128> Buffer;
2049 llvm::sys::path::append(Buffer, Prefix, Filename);
2050 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002051}
2052
Richard Smith0f99d6a2015-08-09 08:48:41 +00002053static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2054 switch (ARR) {
2055 case ASTReader::Failure: return true;
2056 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2057 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2058 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2059 case ASTReader::ConfigurationMismatch:
2060 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2061 case ASTReader::HadErrors: return true;
2062 case ASTReader::Success: return false;
2063 }
2064
2065 llvm_unreachable("unknown ASTReadResult");
2066}
2067
Richard Smith0516b182015-09-08 19:40:14 +00002068ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2069 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2070 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2071 std::string &SuggestedPredefines) {
2072 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2073 return Failure;
2074
2075 // Read all of the records in the options block.
2076 RecordData Record;
2077 ASTReadResult Result = Success;
2078 while (1) {
2079 llvm::BitstreamEntry Entry = Stream.advance();
2080
2081 switch (Entry.Kind) {
2082 case llvm::BitstreamEntry::Error:
2083 case llvm::BitstreamEntry::SubBlock:
2084 return Failure;
2085
2086 case llvm::BitstreamEntry::EndBlock:
2087 return Result;
2088
2089 case llvm::BitstreamEntry::Record:
2090 // The interesting case.
2091 break;
2092 }
2093
2094 // Read and process a record.
2095 Record.clear();
2096 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2097 case LANGUAGE_OPTIONS: {
2098 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2099 if (ParseLanguageOptions(Record, Complain, Listener,
2100 AllowCompatibleConfigurationMismatch))
2101 Result = ConfigurationMismatch;
2102 break;
2103 }
2104
2105 case TARGET_OPTIONS: {
2106 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2107 if (ParseTargetOptions(Record, Complain, Listener,
2108 AllowCompatibleConfigurationMismatch))
2109 Result = ConfigurationMismatch;
2110 break;
2111 }
2112
2113 case DIAGNOSTIC_OPTIONS: {
2114 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2115 if (!AllowCompatibleConfigurationMismatch &&
2116 ParseDiagnosticOptions(Record, Complain, Listener))
2117 return OutOfDate;
2118 break;
2119 }
2120
2121 case FILE_SYSTEM_OPTIONS: {
2122 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2123 if (!AllowCompatibleConfigurationMismatch &&
2124 ParseFileSystemOptions(Record, Complain, Listener))
2125 Result = ConfigurationMismatch;
2126 break;
2127 }
2128
2129 case HEADER_SEARCH_OPTIONS: {
2130 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2131 if (!AllowCompatibleConfigurationMismatch &&
2132 ParseHeaderSearchOptions(Record, Complain, Listener))
2133 Result = ConfigurationMismatch;
2134 break;
2135 }
2136
2137 case PREPROCESSOR_OPTIONS:
2138 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2139 if (!AllowCompatibleConfigurationMismatch &&
2140 ParsePreprocessorOptions(Record, Complain, Listener,
2141 SuggestedPredefines))
2142 Result = ConfigurationMismatch;
2143 break;
2144 }
2145 }
2146}
2147
Guy Benyei11169dd2012-12-18 14:30:41 +00002148ASTReader::ASTReadResult
2149ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002150 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002151 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002152 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002153 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002154
2155 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2156 Error("malformed block record in AST file");
2157 return Failure;
2158 }
2159
2160 // Read all of the records and blocks in the control block.
2161 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002162 unsigned NumInputs = 0;
2163 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002164 while (1) {
2165 llvm::BitstreamEntry Entry = Stream.advance();
2166
2167 switch (Entry.Kind) {
2168 case llvm::BitstreamEntry::Error:
2169 Error("malformed block record in AST file");
2170 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002171 case llvm::BitstreamEntry::EndBlock: {
2172 // Validate input files.
2173 const HeaderSearchOptions &HSOpts =
2174 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002175
Richard Smitha1825302014-10-23 22:18:29 +00002176 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002177 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2178 // loaded module files, ignore missing inputs.
2179 if (!DisableValidation && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002180 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002181
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002182 // If we are reading a module, we will create a verification timestamp,
2183 // so we verify all input files. Otherwise, verify only user input
2184 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002185
2186 unsigned N = NumUserInputs;
2187 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002188 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002189 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002190 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002191 N = NumInputs;
2192
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002193 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002194 InputFile IF = getInputFile(F, I+1, Complain);
2195 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002196 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002197 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002198 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002199
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002200 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002201 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002202
Ben Langmuircb69b572014-03-07 06:40:32 +00002203 if (Listener && Listener->needsInputFileVisitation()) {
2204 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2205 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002206 for (unsigned I = 0; I < N; ++I) {
2207 bool IsSystem = I >= NumUserInputs;
2208 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002209 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2210 F.Kind == MK_ExplicitModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002211 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002212 }
2213
Guy Benyei11169dd2012-12-18 14:30:41 +00002214 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002215 }
2216
Chris Lattnere7b154b2013-01-19 21:39:22 +00002217 case llvm::BitstreamEntry::SubBlock:
2218 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002219 case INPUT_FILES_BLOCK_ID:
2220 F.InputFilesCursor = Stream;
2221 if (Stream.SkipBlock() || // Skip with the main cursor
2222 // Read the abbreviations
2223 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2224 Error("malformed block record in AST file");
2225 return Failure;
2226 }
2227 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002228
2229 case OPTIONS_BLOCK_ID:
2230 // If we're reading the first module for this group, check its options
2231 // are compatible with ours. For modules it imports, no further checking
2232 // is required, because we checked them when we built it.
2233 if (Listener && !ImportedBy) {
2234 // Should we allow the configuration of the module file to differ from
2235 // the configuration of the current translation unit in a compatible
2236 // way?
2237 //
2238 // FIXME: Allow this for files explicitly specified with -include-pch.
2239 bool AllowCompatibleConfigurationMismatch =
2240 F.Kind == MK_ExplicitModule;
2241
2242 auto Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2243 AllowCompatibleConfigurationMismatch,
2244 *Listener, SuggestedPredefines);
2245 if (Result == Failure) {
2246 Error("malformed block record in AST file");
2247 return Result;
2248 }
2249
2250 if (!DisableValidation && Result != Success &&
2251 (Result != ConfigurationMismatch || !AllowConfigurationMismatch))
2252 return Result;
2253 } else if (Stream.SkipBlock()) {
2254 Error("malformed block record in AST file");
2255 return Failure;
2256 }
2257 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002258
Guy Benyei11169dd2012-12-18 14:30:41 +00002259 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002260 if (Stream.SkipBlock()) {
2261 Error("malformed block record in AST file");
2262 return Failure;
2263 }
2264 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002265 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002266
2267 case llvm::BitstreamEntry::Record:
2268 // The interesting case.
2269 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002270 }
2271
2272 // Read and process a record.
2273 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002274 StringRef Blob;
2275 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002276 case METADATA: {
2277 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2278 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002279 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2280 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002281 return VersionMismatch;
2282 }
2283
Richard Smithe75ee0f2015-08-17 07:13:32 +00002284 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002285 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2286 Diag(diag::err_pch_with_compiler_errors);
2287 return HadErrors;
2288 }
2289
2290 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002291 // Relative paths in a relocatable PCH are relative to our sysroot.
2292 if (F.RelocatablePCH)
2293 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002294
Richard Smithe75ee0f2015-08-17 07:13:32 +00002295 F.HasTimestamps = Record[5];
2296
Guy Benyei11169dd2012-12-18 14:30:41 +00002297 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002298 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002299 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2300 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002301 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002302 return VersionMismatch;
2303 }
2304 break;
2305 }
2306
Ben Langmuir487ea142014-10-23 18:05:36 +00002307 case SIGNATURE:
2308 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2309 F.Signature = Record[0];
2310 break;
2311
Guy Benyei11169dd2012-12-18 14:30:41 +00002312 case IMPORTS: {
2313 // Load each of the imported PCH files.
2314 unsigned Idx = 0, N = Record.size();
2315 while (Idx < N) {
2316 // Read information about the AST file.
2317 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2318 // The import location will be the local one for now; we will adjust
2319 // all import locations of module imports after the global source
2320 // location info are setup.
2321 SourceLocation ImportLoc =
2322 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002323 off_t StoredSize = (off_t)Record[Idx++];
2324 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002325 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002326 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002327
Richard Smith0f99d6a2015-08-09 08:48:41 +00002328 // If our client can't cope with us being out of date, we can't cope with
2329 // our dependency being missing.
2330 unsigned Capabilities = ClientLoadCapabilities;
2331 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2332 Capabilities &= ~ARR_Missing;
2333
Guy Benyei11169dd2012-12-18 14:30:41 +00002334 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002335 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2336 Loaded, StoredSize, StoredModTime,
2337 StoredSignature, Capabilities);
2338
2339 // If we diagnosed a problem, produce a backtrace.
2340 if (isDiagnosedResult(Result, Capabilities))
2341 Diag(diag::note_module_file_imported_by)
2342 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2343
2344 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002345 case Failure: return Failure;
2346 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002347 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002348 case OutOfDate: return OutOfDate;
2349 case VersionMismatch: return VersionMismatch;
2350 case ConfigurationMismatch: return ConfigurationMismatch;
2351 case HadErrors: return HadErrors;
2352 case Success: break;
2353 }
2354 }
2355 break;
2356 }
2357
Guy Benyei11169dd2012-12-18 14:30:41 +00002358 case ORIGINAL_FILE:
2359 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002360 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002361 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002362 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002363 break;
2364
2365 case ORIGINAL_FILE_ID:
2366 F.OriginalSourceFileID = FileID::get(Record[0]);
2367 break;
2368
2369 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002370 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 break;
2372
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002373 case MODULE_NAME:
2374 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002375 if (Listener)
2376 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002377 break;
2378
Richard Smith223d3f22014-12-06 03:21:08 +00002379 case MODULE_DIRECTORY: {
2380 assert(!F.ModuleName.empty() &&
2381 "MODULE_DIRECTORY found before MODULE_NAME");
2382 // If we've already loaded a module map file covering this module, we may
2383 // have a better path for it (relative to the current build).
2384 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2385 if (M && M->Directory) {
2386 // If we're implicitly loading a module, the base directory can't
2387 // change between the build and use.
2388 if (F.Kind != MK_ExplicitModule) {
2389 const DirectoryEntry *BuildDir =
2390 PP.getFileManager().getDirectory(Blob);
2391 if (!BuildDir || BuildDir != M->Directory) {
2392 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2393 Diag(diag::err_imported_module_relocated)
2394 << F.ModuleName << Blob << M->Directory->getName();
2395 return OutOfDate;
2396 }
2397 }
2398 F.BaseDirectory = M->Directory->getName();
2399 } else {
2400 F.BaseDirectory = Blob;
2401 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002402 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002403 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002404
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002405 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002406 if (ASTReadResult Result =
2407 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2408 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002409 break;
2410
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002411 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002412 NumInputs = Record[0];
2413 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002414 F.InputFileOffsets =
2415 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002416 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002417 break;
2418 }
2419 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002420}
2421
Ben Langmuir2c9af442014-04-10 17:57:43 +00002422ASTReader::ASTReadResult
2423ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002424 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002425
2426 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2427 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002428 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 }
2430
2431 // Read all of the records and blocks for the AST file.
2432 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002433 while (1) {
2434 llvm::BitstreamEntry Entry = Stream.advance();
2435
2436 switch (Entry.Kind) {
2437 case llvm::BitstreamEntry::Error:
2438 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002439 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002440 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002441 // Outside of C++, we do not store a lookup map for the translation unit.
2442 // Instead, mark it as needing a lookup map to be built if this module
2443 // contains any declarations lexically within it (which it always does!).
2444 // This usually has no cost, since we very rarely need the lookup map for
2445 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002446 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002447 if (DC->hasExternalLexicalStorage() &&
2448 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002449 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002450
Ben Langmuir2c9af442014-04-10 17:57:43 +00002451 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002452 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002453 case llvm::BitstreamEntry::SubBlock:
2454 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 case DECLTYPES_BLOCK_ID:
2456 // We lazily load the decls block, but we want to set up the
2457 // DeclsCursor cursor to point into it. Clone our current bitcode
2458 // cursor to it, enter the block and read the abbrevs in that block.
2459 // With the main cursor, we just skip over it.
2460 F.DeclsCursor = Stream;
2461 if (Stream.SkipBlock() || // Skip with the main cursor.
2462 // Read the abbrevs.
2463 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2464 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002465 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 }
2467 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002468
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 case PREPROCESSOR_BLOCK_ID:
2470 F.MacroCursor = Stream;
2471 if (!PP.getExternalSource())
2472 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002473
Guy Benyei11169dd2012-12-18 14:30:41 +00002474 if (Stream.SkipBlock() ||
2475 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_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 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2480 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002481
Guy Benyei11169dd2012-12-18 14:30:41 +00002482 case PREPROCESSOR_DETAIL_BLOCK_ID:
2483 F.PreprocessorDetailCursor = Stream;
2484 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002485 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002487 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002488 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002489 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002491 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2492
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 if (!PP.getPreprocessingRecord())
2494 PP.createPreprocessingRecord();
2495 if (!PP.getPreprocessingRecord()->getExternalSource())
2496 PP.getPreprocessingRecord()->SetExternalSource(*this);
2497 break;
2498
2499 case SOURCE_MANAGER_BLOCK_ID:
2500 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002501 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002503
Guy Benyei11169dd2012-12-18 14:30:41 +00002504 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002505 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2506 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002507 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002508
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002510 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002511 if (Stream.SkipBlock() ||
2512 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2513 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002514 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002515 }
2516 CommentsCursors.push_back(std::make_pair(C, &F));
2517 break;
2518 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002519
Guy Benyei11169dd2012-12-18 14:30:41 +00002520 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002521 if (Stream.SkipBlock()) {
2522 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002523 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002524 }
2525 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 }
2527 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002528
2529 case llvm::BitstreamEntry::Record:
2530 // The interesting case.
2531 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 }
2533
2534 // Read and process a record.
2535 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002536 StringRef Blob;
2537 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 default: // Default behavior: ignore.
2539 break;
2540
2541 case TYPE_OFFSET: {
2542 if (F.LocalNumTypes != 0) {
2543 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002544 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002545 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002546 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 F.LocalNumTypes = Record[0];
2548 unsigned LocalBaseTypeIndex = Record[1];
2549 F.BaseTypeIndex = getTotalNumTypes();
2550
2551 if (F.LocalNumTypes > 0) {
2552 // Introduce the global -> local mapping for types within this module.
2553 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2554
2555 // Introduce the local -> global mapping for types within this module.
2556 F.TypeRemap.insertOrReplace(
2557 std::make_pair(LocalBaseTypeIndex,
2558 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002559
2560 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 }
2562 break;
2563 }
2564
2565 case DECL_OFFSET: {
2566 if (F.LocalNumDecls != 0) {
2567 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002568 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002569 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002570 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 F.LocalNumDecls = Record[0];
2572 unsigned LocalBaseDeclID = Record[1];
2573 F.BaseDeclID = getTotalNumDecls();
2574
2575 if (F.LocalNumDecls > 0) {
2576 // Introduce the global -> local mapping for declarations within this
2577 // module.
2578 GlobalDeclMap.insert(
2579 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2580
2581 // Introduce the local -> global mapping for declarations within this
2582 // module.
2583 F.DeclRemap.insertOrReplace(
2584 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2585
2586 // Introduce the global -> local mapping for declarations within this
2587 // module.
2588 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002589
Ben Langmuir52ca6782014-10-20 16:27:32 +00002590 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2591 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002592 break;
2593 }
2594
2595 case TU_UPDATE_LEXICAL: {
2596 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002597 LexicalContents Contents(
2598 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2599 Blob.data()),
2600 static_cast<unsigned int>(Blob.size() / 4));
2601 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 TU->setHasExternalLexicalStorage(true);
2603 break;
2604 }
2605
2606 case UPDATE_VISIBLE: {
2607 unsigned Idx = 0;
2608 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002609 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002610 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002611 // If we've already loaded the decl, perform the updates when we finish
2612 // loading this block.
2613 if (Decl *D = GetExistingDecl(ID))
2614 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002615 break;
2616 }
2617
2618 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002619 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002621 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2622 (const unsigned char *)F.IdentifierTableData + Record[0],
2623 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2624 (const unsigned char *)F.IdentifierTableData,
2625 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002626
2627 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2628 }
2629 break;
2630
2631 case IDENTIFIER_OFFSET: {
2632 if (F.LocalNumIdentifiers != 0) {
2633 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002634 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002636 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 F.LocalNumIdentifiers = Record[0];
2638 unsigned LocalBaseIdentifierID = Record[1];
2639 F.BaseIdentifierID = getTotalNumIdentifiers();
2640
2641 if (F.LocalNumIdentifiers > 0) {
2642 // Introduce the global -> local mapping for identifiers within this
2643 // module.
2644 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2645 &F));
2646
2647 // Introduce the local -> global mapping for identifiers within this
2648 // module.
2649 F.IdentifierRemap.insertOrReplace(
2650 std::make_pair(LocalBaseIdentifierID,
2651 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002652
Ben Langmuir52ca6782014-10-20 16:27:32 +00002653 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2654 + F.LocalNumIdentifiers);
2655 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 break;
2657 }
2658
Richard Smith33e0f7e2015-07-22 02:08:40 +00002659 case INTERESTING_IDENTIFIERS:
2660 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2661 break;
2662
Ben Langmuir332aafe2014-01-31 01:06:56 +00002663 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002664 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2665 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002666 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002667 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002668 break;
2669
2670 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002671 if (SpecialTypes.empty()) {
2672 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2673 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2674 break;
2675 }
2676
2677 if (SpecialTypes.size() != Record.size()) {
2678 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002679 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002680 }
2681
2682 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2683 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2684 if (!SpecialTypes[I])
2685 SpecialTypes[I] = ID;
2686 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2687 // merge step?
2688 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 break;
2690
2691 case STATISTICS:
2692 TotalNumStatements += Record[0];
2693 TotalNumMacros += Record[1];
2694 TotalLexicalDeclContexts += Record[2];
2695 TotalVisibleDeclContexts += Record[3];
2696 break;
2697
2698 case UNUSED_FILESCOPED_DECLS:
2699 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2700 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2701 break;
2702
2703 case DELEGATING_CTORS:
2704 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2705 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2706 break;
2707
2708 case WEAK_UNDECLARED_IDENTIFIERS:
2709 if (Record.size() % 4 != 0) {
2710 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002711 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 }
2713
2714 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2715 // files. This isn't the way to do it :)
2716 WeakUndeclaredIdentifiers.clear();
2717
2718 // Translate the weak, undeclared identifiers into global IDs.
2719 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2720 WeakUndeclaredIdentifiers.push_back(
2721 getGlobalIdentifierID(F, Record[I++]));
2722 WeakUndeclaredIdentifiers.push_back(
2723 getGlobalIdentifierID(F, Record[I++]));
2724 WeakUndeclaredIdentifiers.push_back(
2725 ReadSourceLocation(F, Record, I).getRawEncoding());
2726 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2727 }
2728 break;
2729
Guy Benyei11169dd2012-12-18 14:30:41 +00002730 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002731 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 F.LocalNumSelectors = Record[0];
2733 unsigned LocalBaseSelectorID = Record[1];
2734 F.BaseSelectorID = getTotalNumSelectors();
2735
2736 if (F.LocalNumSelectors > 0) {
2737 // Introduce the global -> local mapping for selectors within this
2738 // module.
2739 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2740
2741 // Introduce the local -> global mapping for selectors within this
2742 // module.
2743 F.SelectorRemap.insertOrReplace(
2744 std::make_pair(LocalBaseSelectorID,
2745 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002746
2747 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 }
2749 break;
2750 }
2751
2752 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002753 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002754 if (Record[0])
2755 F.SelectorLookupTable
2756 = ASTSelectorLookupTable::Create(
2757 F.SelectorLookupTableData + Record[0],
2758 F.SelectorLookupTableData,
2759 ASTSelectorLookupTrait(*this, F));
2760 TotalNumMethodPoolEntries += Record[1];
2761 break;
2762
2763 case REFERENCED_SELECTOR_POOL:
2764 if (!Record.empty()) {
2765 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2766 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2767 Record[Idx++]));
2768 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2769 getRawEncoding());
2770 }
2771 }
2772 break;
2773
2774 case PP_COUNTER_VALUE:
2775 if (!Record.empty() && Listener)
2776 Listener->ReadCounter(F, Record[0]);
2777 break;
2778
2779 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002780 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002781 F.NumFileSortedDecls = Record[0];
2782 break;
2783
2784 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002785 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002786 F.LocalNumSLocEntries = Record[0];
2787 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002788 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002789 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002790 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002791 if (!F.SLocEntryBaseID) {
2792 Error("ran out of source locations");
2793 break;
2794 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002795 // Make our entry in the range map. BaseID is negative and growing, so
2796 // we invert it. Because we invert it, though, we need the other end of
2797 // the range.
2798 unsigned RangeStart =
2799 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2800 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2801 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2802
2803 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2804 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2805 GlobalSLocOffsetMap.insert(
2806 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2807 - SLocSpaceSize,&F));
2808
2809 // Initialize the remapping table.
2810 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002811 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002812 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002813 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002814 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2815
2816 TotalNumSLocEntries += F.LocalNumSLocEntries;
2817 break;
2818 }
2819
2820 case MODULE_OFFSET_MAP: {
2821 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002822 const unsigned char *Data = (const unsigned char*)Blob.data();
2823 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002824
2825 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2826 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2827 F.SLocRemap.insert(std::make_pair(0U, 0));
2828 F.SLocRemap.insert(std::make_pair(2U, 1));
2829 }
2830
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002832 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2833 RemapBuilder;
2834 RemapBuilder SLocRemap(F.SLocRemap);
2835 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2836 RemapBuilder MacroRemap(F.MacroRemap);
2837 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2838 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2839 RemapBuilder SelectorRemap(F.SelectorRemap);
2840 RemapBuilder DeclRemap(F.DeclRemap);
2841 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002842
Richard Smithd8879c82015-08-24 21:59:32 +00002843 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002844 using namespace llvm::support;
2845 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002846 StringRef Name = StringRef((const char*)Data, Len);
2847 Data += Len;
2848 ModuleFile *OM = ModuleMgr.lookup(Name);
2849 if (!OM) {
2850 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002851 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002852 }
2853
Justin Bogner57ba0b22014-03-28 22:03:24 +00002854 uint32_t SLocOffset =
2855 endian::readNext<uint32_t, little, unaligned>(Data);
2856 uint32_t IdentifierIDOffset =
2857 endian::readNext<uint32_t, little, unaligned>(Data);
2858 uint32_t MacroIDOffset =
2859 endian::readNext<uint32_t, little, unaligned>(Data);
2860 uint32_t PreprocessedEntityIDOffset =
2861 endian::readNext<uint32_t, little, unaligned>(Data);
2862 uint32_t SubmoduleIDOffset =
2863 endian::readNext<uint32_t, little, unaligned>(Data);
2864 uint32_t SelectorIDOffset =
2865 endian::readNext<uint32_t, little, unaligned>(Data);
2866 uint32_t DeclIDOffset =
2867 endian::readNext<uint32_t, little, unaligned>(Data);
2868 uint32_t TypeIndexOffset =
2869 endian::readNext<uint32_t, little, unaligned>(Data);
2870
Ben Langmuir785180e2014-10-20 16:27:30 +00002871 uint32_t None = std::numeric_limits<uint32_t>::max();
2872
2873 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2874 RemapBuilder &Remap) {
2875 if (Offset != None)
2876 Remap.insert(std::make_pair(Offset,
2877 static_cast<int>(BaseOffset - Offset)));
2878 };
2879 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2880 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2881 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2882 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2883 PreprocessedEntityRemap);
2884 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2885 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2886 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2887 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002888
2889 // Global -> local mappings.
2890 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2891 }
2892 break;
2893 }
2894
2895 case SOURCE_MANAGER_LINE_TABLE:
2896 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002897 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002898 break;
2899
2900 case SOURCE_LOCATION_PRELOADS: {
2901 // Need to transform from the local view (1-based IDs) to the global view,
2902 // which is based off F.SLocEntryBaseID.
2903 if (!F.PreloadSLocEntries.empty()) {
2904 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002905 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002906 }
2907
2908 F.PreloadSLocEntries.swap(Record);
2909 break;
2910 }
2911
2912 case EXT_VECTOR_DECLS:
2913 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2914 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2915 break;
2916
2917 case VTABLE_USES:
2918 if (Record.size() % 3 != 0) {
2919 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002920 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002921 }
2922
2923 // Later tables overwrite earlier ones.
2924 // FIXME: Modules will have some trouble with this. This is clearly not
2925 // the right way to do this.
2926 VTableUses.clear();
2927
2928 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2929 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2930 VTableUses.push_back(
2931 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2932 VTableUses.push_back(Record[Idx++]);
2933 }
2934 break;
2935
Guy Benyei11169dd2012-12-18 14:30:41 +00002936 case PENDING_IMPLICIT_INSTANTIATIONS:
2937 if (PendingInstantiations.size() % 2 != 0) {
2938 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002939 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002940 }
2941
2942 if (Record.size() % 2 != 0) {
2943 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002944 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002945 }
2946
2947 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2948 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2949 PendingInstantiations.push_back(
2950 ReadSourceLocation(F, Record, I).getRawEncoding());
2951 }
2952 break;
2953
2954 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002955 if (Record.size() != 2) {
2956 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002957 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002958 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002959 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2960 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2961 break;
2962
2963 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002964 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2965 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2966 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002967
2968 unsigned LocalBasePreprocessedEntityID = Record[0];
2969
2970 unsigned StartingID;
2971 if (!PP.getPreprocessingRecord())
2972 PP.createPreprocessingRecord();
2973 if (!PP.getPreprocessingRecord()->getExternalSource())
2974 PP.getPreprocessingRecord()->SetExternalSource(*this);
2975 StartingID
2976 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002977 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002978 F.BasePreprocessedEntityID = StartingID;
2979
2980 if (F.NumPreprocessedEntities > 0) {
2981 // Introduce the global -> local mapping for preprocessed entities in
2982 // this module.
2983 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2984
2985 // Introduce the local -> global mapping for preprocessed entities in
2986 // this module.
2987 F.PreprocessedEntityRemap.insertOrReplace(
2988 std::make_pair(LocalBasePreprocessedEntityID,
2989 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2990 }
2991
2992 break;
2993 }
2994
2995 case DECL_UPDATE_OFFSETS: {
2996 if (Record.size() % 2 != 0) {
2997 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002998 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002999 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003000 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3001 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3002 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3003
3004 // If we've already loaded the decl, perform the updates when we finish
3005 // loading this block.
3006 if (Decl *D = GetExistingDecl(ID))
3007 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3008 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003009 break;
3010 }
3011
3012 case DECL_REPLACEMENTS: {
3013 if (Record.size() % 3 != 0) {
3014 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003015 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003016 }
3017 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3018 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3019 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3020 break;
3021 }
3022
3023 case OBJC_CATEGORIES_MAP: {
3024 if (F.LocalNumObjCCategoriesInMap != 0) {
3025 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003026 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 }
3028
3029 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003030 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003031 break;
3032 }
3033
3034 case OBJC_CATEGORIES:
3035 F.ObjCCategories.swap(Record);
3036 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003037
Guy Benyei11169dd2012-12-18 14:30:41 +00003038 case CXX_BASE_SPECIFIER_OFFSETS: {
3039 if (F.LocalNumCXXBaseSpecifiers != 0) {
3040 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003041 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003042 }
Richard Smithc2bb8182015-03-24 06:36:48 +00003043
Guy Benyei11169dd2012-12-18 14:30:41 +00003044 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003045 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00003046 break;
3047 }
3048
3049 case CXX_CTOR_INITIALIZERS_OFFSETS: {
3050 if (F.LocalNumCXXCtorInitializers != 0) {
3051 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
3052 return Failure;
3053 }
3054
3055 F.LocalNumCXXCtorInitializers = Record[0];
3056 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003057 break;
3058 }
3059
3060 case DIAG_PRAGMA_MAPPINGS:
3061 if (F.PragmaDiagMappings.empty())
3062 F.PragmaDiagMappings.swap(Record);
3063 else
3064 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3065 Record.begin(), Record.end());
3066 break;
3067
3068 case CUDA_SPECIAL_DECL_REFS:
3069 // Later tables overwrite earlier ones.
3070 // FIXME: Modules will have trouble with this.
3071 CUDASpecialDeclRefs.clear();
3072 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3073 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3074 break;
3075
3076 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003077 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003078 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003079 if (Record[0]) {
3080 F.HeaderFileInfoTable
3081 = HeaderFileInfoLookupTable::Create(
3082 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3083 (const unsigned char *)F.HeaderFileInfoTableData,
3084 HeaderFileInfoTrait(*this, F,
3085 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003086 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003087
3088 PP.getHeaderSearchInfo().SetExternalSource(this);
3089 if (!PP.getHeaderSearchInfo().getExternalLookup())
3090 PP.getHeaderSearchInfo().SetExternalLookup(this);
3091 }
3092 break;
3093 }
3094
3095 case FP_PRAGMA_OPTIONS:
3096 // Later tables overwrite earlier ones.
3097 FPPragmaOptions.swap(Record);
3098 break;
3099
3100 case OPENCL_EXTENSIONS:
3101 // Later tables overwrite earlier ones.
3102 OpenCLExtensions.swap(Record);
3103 break;
3104
3105 case TENTATIVE_DEFINITIONS:
3106 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3107 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3108 break;
3109
3110 case KNOWN_NAMESPACES:
3111 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3112 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3113 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003114
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003115 case UNDEFINED_BUT_USED:
3116 if (UndefinedButUsed.size() % 2 != 0) {
3117 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003118 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003119 }
3120
3121 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003122 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003123 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003124 }
3125 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003126 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3127 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003128 ReadSourceLocation(F, Record, I).getRawEncoding());
3129 }
3130 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003131 case DELETE_EXPRS_TO_ANALYZE:
3132 for (unsigned I = 0, N = Record.size(); I != N;) {
3133 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3134 const uint64_t Count = Record[I++];
3135 DelayedDeleteExprs.push_back(Count);
3136 for (uint64_t C = 0; C < Count; ++C) {
3137 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3138 bool IsArrayForm = Record[I++] == 1;
3139 DelayedDeleteExprs.push_back(IsArrayForm);
3140 }
3141 }
3142 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003143
Guy Benyei11169dd2012-12-18 14:30:41 +00003144 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003145 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 // If we aren't loading a module (which has its own exports), make
3147 // all of the imported modules visible.
3148 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003149 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3150 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3151 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3152 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003153 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003154 }
3155 }
3156 break;
3157 }
3158
Guy Benyei11169dd2012-12-18 14:30:41 +00003159 case MACRO_OFFSET: {
3160 if (F.LocalNumMacros != 0) {
3161 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003162 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003163 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003164 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003165 F.LocalNumMacros = Record[0];
3166 unsigned LocalBaseMacroID = Record[1];
3167 F.BaseMacroID = getTotalNumMacros();
3168
3169 if (F.LocalNumMacros > 0) {
3170 // Introduce the global -> local mapping for macros within this module.
3171 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3172
3173 // Introduce the local -> global mapping for macros within this module.
3174 F.MacroRemap.insertOrReplace(
3175 std::make_pair(LocalBaseMacroID,
3176 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003177
3178 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003179 }
3180 break;
3181 }
3182
Richard Smithe40f2ba2013-08-07 21:41:30 +00003183 case LATE_PARSED_TEMPLATE: {
3184 LateParsedTemplates.append(Record.begin(), Record.end());
3185 break;
3186 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003187
3188 case OPTIMIZE_PRAGMA_OPTIONS:
3189 if (Record.size() != 1) {
3190 Error("invalid pragma optimize record");
3191 return Failure;
3192 }
3193 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3194 break;
Nico Weber72889432014-09-06 01:25:55 +00003195
3196 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3197 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3198 UnusedLocalTypedefNameCandidates.push_back(
3199 getGlobalDeclID(F, Record[I]));
3200 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003201 }
3202 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003203}
3204
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003205ASTReader::ASTReadResult
3206ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3207 const ModuleFile *ImportedBy,
3208 unsigned ClientLoadCapabilities) {
3209 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003210 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003211
Richard Smithe842a472014-10-22 02:05:46 +00003212 if (F.Kind == MK_ExplicitModule) {
3213 // For an explicitly-loaded module, we don't care whether the original
3214 // module map file exists or matches.
3215 return Success;
3216 }
3217
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003218 // Try to resolve ModuleName in the current header search context and
3219 // verify that it is found in the same module map file as we saved. If the
3220 // top-level AST file is a main file, skip this check because there is no
3221 // usable header search context.
3222 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003223 "MODULE_NAME should come before MODULE_MAP_FILE");
3224 if (F.Kind == MK_ImplicitModule &&
3225 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3226 // An implicitly-loaded module file should have its module listed in some
3227 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003228 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003229 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3230 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3231 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003232 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003233 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3234 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3235 // This module was defined by an imported (explicit) module.
3236 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3237 << ASTFE->getName();
3238 else
3239 // This module was built with a different module map.
3240 Diag(diag::err_imported_module_not_found)
3241 << F.ModuleName << F.FileName << ImportedBy->FileName
3242 << F.ModuleMapPath;
3243 }
3244 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003245 }
3246
Richard Smithe842a472014-10-22 02:05:46 +00003247 assert(M->Name == F.ModuleName && "found module with different name");
3248
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003249 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003250 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003251 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3252 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003253 assert(ImportedBy && "top-level import should be verified");
3254 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3255 Diag(diag::err_imported_module_modmap_changed)
3256 << F.ModuleName << ImportedBy->FileName
3257 << ModMap->getName() << F.ModuleMapPath;
3258 return OutOfDate;
3259 }
3260
3261 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3262 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3263 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003264 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003265 const FileEntry *F =
3266 FileMgr.getFile(Filename, false, false);
3267 if (F == nullptr) {
3268 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3269 Error("could not find file '" + Filename +"' referenced by AST file");
3270 return OutOfDate;
3271 }
3272 AdditionalStoredMaps.insert(F);
3273 }
3274
3275 // Check any additional module map files (e.g. module.private.modulemap)
3276 // that are not in the pcm.
3277 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3278 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3279 // Remove files that match
3280 // Note: SmallPtrSet::erase is really remove
3281 if (!AdditionalStoredMaps.erase(ModMap)) {
3282 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3283 Diag(diag::err_module_different_modmap)
3284 << F.ModuleName << /*new*/0 << ModMap->getName();
3285 return OutOfDate;
3286 }
3287 }
3288 }
3289
3290 // Check any additional module map files that are in the pcm, but not
3291 // found in header search. Cases that match are already removed.
3292 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3293 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3294 Diag(diag::err_module_different_modmap)
3295 << F.ModuleName << /*not new*/1 << ModMap->getName();
3296 return OutOfDate;
3297 }
3298 }
3299
3300 if (Listener)
3301 Listener->ReadModuleMapFile(F.ModuleMapPath);
3302 return Success;
3303}
3304
3305
Douglas Gregorc1489562013-02-12 23:36:21 +00003306/// \brief Move the given method to the back of the global list of methods.
3307static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3308 // Find the entry for this selector in the method pool.
3309 Sema::GlobalMethodPool::iterator Known
3310 = S.MethodPool.find(Method->getSelector());
3311 if (Known == S.MethodPool.end())
3312 return;
3313
3314 // Retrieve the appropriate method list.
3315 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3316 : Known->second.second;
3317 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003318 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003319 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003320 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003321 Found = true;
3322 } else {
3323 // Keep searching.
3324 continue;
3325 }
3326 }
3327
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003328 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003329 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003330 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003331 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003332 }
3333}
3334
Richard Smithde711422015-04-23 21:20:19 +00003335void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003336 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003337 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003338 bool wasHidden = D->Hidden;
3339 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003340
Richard Smith49f906a2014-03-01 00:08:04 +00003341 if (wasHidden && SemaObj) {
3342 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3343 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003344 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003345 }
3346 }
3347}
3348
Richard Smith49f906a2014-03-01 00:08:04 +00003349void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003350 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003351 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003352 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003353 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003354 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003355 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003356 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003357
3358 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003359 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003360 // there is nothing more to do.
3361 continue;
3362 }
Richard Smith49f906a2014-03-01 00:08:04 +00003363
Guy Benyei11169dd2012-12-18 14:30:41 +00003364 if (!Mod->isAvailable()) {
3365 // Modules that aren't available cannot be made visible.
3366 continue;
3367 }
3368
3369 // Update the module's name visibility.
3370 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003371
Guy Benyei11169dd2012-12-18 14:30:41 +00003372 // If we've already deserialized any names from this module,
3373 // mark them as visible.
3374 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3375 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003376 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003377 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003378 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003379 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3380 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003381 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003382
Guy Benyei11169dd2012-12-18 14:30:41 +00003383 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003384 SmallVector<Module *, 16> Exports;
3385 Mod->getExportedModules(Exports);
3386 for (SmallVectorImpl<Module *>::iterator
3387 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3388 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003389 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003390 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003391 }
3392 }
3393}
3394
Douglas Gregore060e572013-01-25 01:03:03 +00003395bool ASTReader::loadGlobalIndex() {
3396 if (GlobalIndex)
3397 return false;
3398
3399 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3400 !Context.getLangOpts().Modules)
3401 return true;
3402
3403 // Try to load the global index.
3404 TriedLoadingGlobalIndex = true;
3405 StringRef ModuleCachePath
3406 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3407 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003408 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003409 if (!Result.first)
3410 return true;
3411
3412 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003413 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003414 return false;
3415}
3416
3417bool ASTReader::isGlobalIndexUnavailable() const {
3418 return Context.getLangOpts().Modules && UseGlobalIndex &&
3419 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3420}
3421
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003422static void updateModuleTimestamp(ModuleFile &MF) {
3423 // Overwrite the timestamp file contents so that file's mtime changes.
3424 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003425 std::error_code EC;
3426 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3427 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003428 return;
3429 OS << "Timestamp file\n";
3430}
3431
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003432/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3433/// cursor into the start of the given block ID, returning false on success and
3434/// true on failure.
3435static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3436 while (1) {
3437 llvm::BitstreamEntry Entry = Cursor.advance();
3438 switch (Entry.Kind) {
3439 case llvm::BitstreamEntry::Error:
3440 case llvm::BitstreamEntry::EndBlock:
3441 return true;
3442
3443 case llvm::BitstreamEntry::Record:
3444 // Ignore top-level records.
3445 Cursor.skipRecord(Entry.ID);
3446 break;
3447
3448 case llvm::BitstreamEntry::SubBlock:
3449 if (Entry.ID == BlockID) {
3450 if (Cursor.EnterSubBlock(BlockID))
3451 return true;
3452 // Found it!
3453 return false;
3454 }
3455
3456 if (Cursor.SkipBlock())
3457 return true;
3458 }
3459 }
3460}
3461
Guy Benyei11169dd2012-12-18 14:30:41 +00003462ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3463 ModuleKind Type,
3464 SourceLocation ImportLoc,
3465 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003466 llvm::SaveAndRestore<SourceLocation>
3467 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3468
Richard Smithd1c46742014-04-30 02:24:17 +00003469 // Defer any pending actions until we get to the end of reading the AST file.
3470 Deserializing AnASTFile(this);
3471
Guy Benyei11169dd2012-12-18 14:30:41 +00003472 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003473 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003474
3475 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003476 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003477 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003478 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003479 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003480 ClientLoadCapabilities)) {
3481 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003482 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003483 case OutOfDate:
3484 case VersionMismatch:
3485 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003486 case HadErrors: {
3487 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3488 for (const ImportedModule &IM : Loaded)
3489 LoadedSet.insert(IM.Mod);
3490
Douglas Gregor7029ce12013-03-19 00:28:20 +00003491 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003492 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003493 Context.getLangOpts().Modules
3494 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003495 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003496
3497 // If we find that any modules are unusable, the global index is going
3498 // to be out-of-date. Just remove it.
3499 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003500 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003501 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003502 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003503 case Success:
3504 break;
3505 }
3506
3507 // Here comes stuff that we only do once the entire chain is loaded.
3508
3509 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003510 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3511 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003512 M != MEnd; ++M) {
3513 ModuleFile &F = *M->Mod;
3514
3515 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003516 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3517 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003518
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003519 // Read the extension blocks.
3520 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3521 if (ASTReadResult Result = ReadExtensionBlock(F))
3522 return Result;
3523 }
3524
Guy Benyei11169dd2012-12-18 14:30:41 +00003525 // Once read, set the ModuleFile bit base offset and update the size in
3526 // bits of all files we've seen.
3527 F.GlobalBitOffset = TotalModulesSizeInBits;
3528 TotalModulesSizeInBits += F.SizeInBits;
3529 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3530
3531 // Preload SLocEntries.
3532 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3533 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3534 // Load it through the SourceManager and don't call ReadSLocEntry()
3535 // directly because the entry may have already been loaded in which case
3536 // calling ReadSLocEntry() directly would trigger an assertion in
3537 // SourceManager.
3538 SourceMgr.getLoadedSLocEntryByID(Index);
3539 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003540
3541 // Preload all the pending interesting identifiers by marking them out of
3542 // date.
3543 for (auto Offset : F.PreloadIdentifierOffsets) {
3544 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3545 F.IdentifierTableData + Offset);
3546
3547 ASTIdentifierLookupTrait Trait(*this, F);
3548 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3549 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003550 auto &II = PP.getIdentifierTable().getOwn(Key);
3551 II.setOutOfDate(true);
3552
3553 // Mark this identifier as being from an AST file so that we can track
3554 // whether we need to serialize it.
3555 if (!II.isFromAST()) {
3556 II.setIsFromAST();
Ben Langmuirb9ad4e62015-10-28 22:25:37 +00003557 bool IsModule = PP.getCurrentModule() != nullptr;
3558 if (isInterestingIdentifier(*this, II, IsModule))
Richard Smith79bf9202015-08-24 03:33:22 +00003559 II.setChangedSinceDeserialization();
3560 }
3561
3562 // Associate the ID with the identifier so that the writer can reuse it.
3563 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3564 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003565 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003566 }
3567
Douglas Gregor603cd862013-03-22 18:50:14 +00003568 // Setup the import locations and notify the module manager that we've
3569 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003570 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3571 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003572 M != MEnd; ++M) {
3573 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003574
3575 ModuleMgr.moduleFileAccepted(&F);
3576
3577 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003578 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003579 if (!M->ImportedBy)
3580 F.ImportLoc = M->ImportLoc;
3581 else
3582 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3583 M->ImportLoc.getRawEncoding());
3584 }
3585
Richard Smith33e0f7e2015-07-22 02:08:40 +00003586 if (!Context.getLangOpts().CPlusPlus ||
3587 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3588 // Mark all of the identifiers in the identifier table as being out of date,
3589 // so that various accessors know to check the loaded modules when the
3590 // identifier is used.
3591 //
3592 // For C++ modules, we don't need information on many identifiers (just
3593 // those that provide macros or are poisoned), so we mark all of
3594 // the interesting ones via PreloadIdentifierOffsets.
3595 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3596 IdEnd = PP.getIdentifierTable().end();
3597 Id != IdEnd; ++Id)
3598 Id->second->setOutOfDate(true);
3599 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003600
3601 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003602 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3603 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003604 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3605 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003606
3607 switch (Unresolved.Kind) {
3608 case UnresolvedModuleRef::Conflict:
3609 if (ResolvedMod) {
3610 Module::Conflict Conflict;
3611 Conflict.Other = ResolvedMod;
3612 Conflict.Message = Unresolved.String.str();
3613 Unresolved.Mod->Conflicts.push_back(Conflict);
3614 }
3615 continue;
3616
3617 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003618 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003619 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003620 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003621
Douglas Gregorfb912652013-03-20 21:10:35 +00003622 case UnresolvedModuleRef::Export:
3623 if (ResolvedMod || Unresolved.IsWildcard)
3624 Unresolved.Mod->Exports.push_back(
3625 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3626 continue;
3627 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003628 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003629 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003630
3631 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3632 // Might be unnecessary as use declarations are only used to build the
3633 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003634
3635 InitializeContext();
3636
Richard Smith3d8e97e2013-10-18 06:54:39 +00003637 if (SemaObj)
3638 UpdateSema();
3639
Guy Benyei11169dd2012-12-18 14:30:41 +00003640 if (DeserializationListener)
3641 DeserializationListener->ReaderInitialized(this);
3642
3643 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003644 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003645 PrimaryModule.OriginalSourceFileID
3646 = FileID::get(PrimaryModule.SLocEntryBaseID
3647 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3648
3649 // If this AST file is a precompiled preamble, then set the
3650 // preamble file ID of the source manager to the file source file
3651 // from which the preamble was built.
3652 if (Type == MK_Preamble) {
3653 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3654 } else if (Type == MK_MainFile) {
3655 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3656 }
3657 }
3658
3659 // For any Objective-C class definitions we have already loaded, make sure
3660 // that we load any additional categories.
3661 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3662 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3663 ObjCClassesLoaded[I],
3664 PreviousGeneration);
3665 }
Douglas Gregore060e572013-01-25 01:03:03 +00003666
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003667 if (PP.getHeaderSearchInfo()
3668 .getHeaderSearchOpts()
3669 .ModulesValidateOncePerBuildSession) {
3670 // Now we are certain that the module and all modules it depends on are
3671 // up to date. Create or update timestamp files for modules that are
3672 // located in the module cache (not for PCH files that could be anywhere
3673 // in the filesystem).
3674 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3675 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003676 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003677 updateModuleTimestamp(*M.Mod);
3678 }
3679 }
3680 }
3681
Guy Benyei11169dd2012-12-18 14:30:41 +00003682 return Success;
3683}
3684
Ben Langmuir487ea142014-10-23 18:05:36 +00003685static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3686
Ben Langmuir70a1b812015-03-24 04:43:52 +00003687/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3688static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3689 return Stream.Read(8) == 'C' &&
3690 Stream.Read(8) == 'P' &&
3691 Stream.Read(8) == 'C' &&
3692 Stream.Read(8) == 'H';
3693}
3694
Richard Smith0f99d6a2015-08-09 08:48:41 +00003695static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3696 switch (Kind) {
3697 case MK_PCH:
3698 return 0; // PCH
3699 case MK_ImplicitModule:
3700 case MK_ExplicitModule:
3701 return 1; // module
3702 case MK_MainFile:
3703 case MK_Preamble:
3704 return 2; // main source file
3705 }
3706 llvm_unreachable("unknown module kind");
3707}
3708
Guy Benyei11169dd2012-12-18 14:30:41 +00003709ASTReader::ASTReadResult
3710ASTReader::ReadASTCore(StringRef FileName,
3711 ModuleKind Type,
3712 SourceLocation ImportLoc,
3713 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003714 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003715 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003716 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003717 unsigned ClientLoadCapabilities) {
3718 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003719 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003720 ModuleManager::AddModuleResult AddResult
3721 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003722 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003723 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003724 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003725
Douglas Gregor7029ce12013-03-19 00:28:20 +00003726 switch (AddResult) {
3727 case ModuleManager::AlreadyLoaded:
3728 return Success;
3729
3730 case ModuleManager::NewlyLoaded:
3731 // Load module file below.
3732 break;
3733
3734 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003735 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003736 // it.
3737 if (ClientLoadCapabilities & ARR_Missing)
3738 return Missing;
3739
3740 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003741 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3742 << FileName << ErrorStr.empty()
3743 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003744 return Failure;
3745
3746 case ModuleManager::OutOfDate:
3747 // We couldn't load the module file because it is out-of-date. If the
3748 // client can handle out-of-date, return it.
3749 if (ClientLoadCapabilities & ARR_OutOfDate)
3750 return OutOfDate;
3751
3752 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003753 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3754 << FileName << ErrorStr.empty()
3755 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003756 return Failure;
3757 }
3758
Douglas Gregor7029ce12013-03-19 00:28:20 +00003759 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003760
3761 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3762 // module?
3763 if (FileName != "-") {
3764 CurrentDir = llvm::sys::path::parent_path(FileName);
3765 if (CurrentDir.empty()) CurrentDir = ".";
3766 }
3767
3768 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003769 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003770 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003771 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003772 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3773
Guy Benyei11169dd2012-12-18 14:30:41 +00003774 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003775 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003776 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3777 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003778 return Failure;
3779 }
3780
3781 // This is used for compatibility with older PCH formats.
3782 bool HaveReadControlBlock = false;
Chris Lattnerefa77172013-01-20 00:00:22 +00003783 while (1) {
3784 llvm::BitstreamEntry Entry = Stream.advance();
3785
3786 switch (Entry.Kind) {
3787 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003788 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003789 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003790 Error("invalid record at top-level of AST file");
3791 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003792
3793 case llvm::BitstreamEntry::SubBlock:
3794 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003795 }
3796
Chris Lattnerefa77172013-01-20 00:00:22 +00003797 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003798 case CONTROL_BLOCK_ID:
3799 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003800 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003801 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003802 // Check that we didn't try to load a non-module AST file as a module.
3803 //
3804 // FIXME: Should we also perform the converse check? Loading a module as
3805 // a PCH file sort of works, but it's a bit wonky.
3806 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule) &&
3807 F.ModuleName.empty()) {
3808 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3809 if (Result != OutOfDate ||
3810 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3811 Diag(diag::err_module_file_not_module) << FileName;
3812 return Result;
3813 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003814 break;
3815
3816 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003817 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003818 case OutOfDate: return OutOfDate;
3819 case VersionMismatch: return VersionMismatch;
3820 case ConfigurationMismatch: return ConfigurationMismatch;
3821 case HadErrors: return HadErrors;
3822 }
3823 break;
Richard Smithf8c32552015-09-02 17:45:54 +00003824
Guy Benyei11169dd2012-12-18 14:30:41 +00003825 case AST_BLOCK_ID:
3826 if (!HaveReadControlBlock) {
3827 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003828 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003829 return VersionMismatch;
3830 }
3831
3832 // Record that we've loaded this module.
3833 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3834 return Success;
3835
3836 default:
3837 if (Stream.SkipBlock()) {
3838 Error("malformed block record in AST file");
3839 return Failure;
3840 }
3841 break;
3842 }
3843 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003844
3845 return Success;
3846}
3847
3848/// Parse a record and blob containing module file extension metadata.
3849static bool parseModuleFileExtensionMetadata(
3850 const SmallVectorImpl<uint64_t> &Record,
3851 StringRef Blob,
3852 ModuleFileExtensionMetadata &Metadata) {
3853 if (Record.size() < 4) return true;
3854
3855 Metadata.MajorVersion = Record[0];
3856 Metadata.MinorVersion = Record[1];
3857
3858 unsigned BlockNameLen = Record[2];
3859 unsigned UserInfoLen = Record[3];
3860
3861 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
3862
3863 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
3864 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
3865 Blob.data() + BlockNameLen + UserInfoLen);
3866 return false;
3867}
3868
3869ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
3870 BitstreamCursor &Stream = F.Stream;
3871
3872 RecordData Record;
3873 while (true) {
3874 llvm::BitstreamEntry Entry = Stream.advance();
3875 switch (Entry.Kind) {
3876 case llvm::BitstreamEntry::SubBlock:
3877 if (Stream.SkipBlock())
3878 return Failure;
3879
3880 continue;
3881
3882 case llvm::BitstreamEntry::EndBlock:
3883 return Success;
3884
3885 case llvm::BitstreamEntry::Error:
3886 return HadErrors;
3887
3888 case llvm::BitstreamEntry::Record:
3889 break;
3890 }
3891
3892 Record.clear();
3893 StringRef Blob;
3894 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
3895 switch (RecCode) {
3896 case EXTENSION_METADATA: {
3897 ModuleFileExtensionMetadata Metadata;
3898 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
3899 return Failure;
3900
3901 // Find a module file extension with this block name.
3902 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
3903 if (Known == ModuleFileExtensions.end()) break;
3904
3905 // Form a reader.
3906 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
3907 F, Stream)) {
3908 F.ExtensionReaders.push_back(std::move(Reader));
3909 }
3910
3911 break;
3912 }
3913 }
3914 }
3915
3916 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00003917}
3918
Richard Smitha7e2cc62015-05-01 01:53:09 +00003919void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003920 // If there's a listener, notify them that we "read" the translation unit.
3921 if (DeserializationListener)
3922 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3923 Context.getTranslationUnitDecl());
3924
Guy Benyei11169dd2012-12-18 14:30:41 +00003925 // FIXME: Find a better way to deal with collisions between these
3926 // built-in types. Right now, we just ignore the problem.
3927
3928 // Load the special types.
3929 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3930 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3931 if (!Context.CFConstantStringTypeDecl)
3932 Context.setCFConstantStringType(GetType(String));
3933 }
3934
3935 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3936 QualType FileType = GetType(File);
3937 if (FileType.isNull()) {
3938 Error("FILE type is NULL");
3939 return;
3940 }
3941
3942 if (!Context.FILEDecl) {
3943 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3944 Context.setFILEDecl(Typedef->getDecl());
3945 else {
3946 const TagType *Tag = FileType->getAs<TagType>();
3947 if (!Tag) {
3948 Error("Invalid FILE type in AST file");
3949 return;
3950 }
3951 Context.setFILEDecl(Tag->getDecl());
3952 }
3953 }
3954 }
3955
3956 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3957 QualType Jmp_bufType = GetType(Jmp_buf);
3958 if (Jmp_bufType.isNull()) {
3959 Error("jmp_buf type is NULL");
3960 return;
3961 }
3962
3963 if (!Context.jmp_bufDecl) {
3964 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3965 Context.setjmp_bufDecl(Typedef->getDecl());
3966 else {
3967 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3968 if (!Tag) {
3969 Error("Invalid jmp_buf type in AST file");
3970 return;
3971 }
3972 Context.setjmp_bufDecl(Tag->getDecl());
3973 }
3974 }
3975 }
3976
3977 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3978 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3979 if (Sigjmp_bufType.isNull()) {
3980 Error("sigjmp_buf type is NULL");
3981 return;
3982 }
3983
3984 if (!Context.sigjmp_bufDecl) {
3985 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3986 Context.setsigjmp_bufDecl(Typedef->getDecl());
3987 else {
3988 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3989 assert(Tag && "Invalid sigjmp_buf type in AST file");
3990 Context.setsigjmp_bufDecl(Tag->getDecl());
3991 }
3992 }
3993 }
3994
3995 if (unsigned ObjCIdRedef
3996 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3997 if (Context.ObjCIdRedefinitionType.isNull())
3998 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3999 }
4000
4001 if (unsigned ObjCClassRedef
4002 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4003 if (Context.ObjCClassRedefinitionType.isNull())
4004 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4005 }
4006
4007 if (unsigned ObjCSelRedef
4008 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4009 if (Context.ObjCSelRedefinitionType.isNull())
4010 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4011 }
4012
4013 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4014 QualType Ucontext_tType = GetType(Ucontext_t);
4015 if (Ucontext_tType.isNull()) {
4016 Error("ucontext_t type is NULL");
4017 return;
4018 }
4019
4020 if (!Context.ucontext_tDecl) {
4021 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4022 Context.setucontext_tDecl(Typedef->getDecl());
4023 else {
4024 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4025 assert(Tag && "Invalid ucontext_t type in AST file");
4026 Context.setucontext_tDecl(Tag->getDecl());
4027 }
4028 }
4029 }
4030 }
4031
4032 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4033
4034 // If there were any CUDA special declarations, deserialize them.
4035 if (!CUDASpecialDeclRefs.empty()) {
4036 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4037 Context.setcudaConfigureCallDecl(
4038 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4039 }
Richard Smith56be7542014-03-21 00:33:59 +00004040
Guy Benyei11169dd2012-12-18 14:30:41 +00004041 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004042 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004043 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004044 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004045 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004046 /*ImportLoc=*/Import.ImportLoc);
4047 PP.makeModuleVisible(Imported, Import.ImportLoc);
4048 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004049 }
4050 ImportedModules.clear();
4051}
4052
4053void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004054 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004055}
4056
Ben Langmuir70a1b812015-03-24 04:43:52 +00004057/// \brief Reads and return the signature record from \p StreamFile's control
4058/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00004059static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4060 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004061 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004062 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004063
4064 // Scan for the CONTROL_BLOCK_ID block.
4065 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4066 return 0;
4067
4068 // Scan for SIGNATURE inside the control block.
4069 ASTReader::RecordData Record;
4070 while (1) {
4071 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4072 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4073 Entry.Kind != llvm::BitstreamEntry::Record)
4074 return 0;
4075
4076 Record.clear();
4077 StringRef Blob;
4078 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4079 return Record[0];
4080 }
4081}
4082
Guy Benyei11169dd2012-12-18 14:30:41 +00004083/// \brief Retrieve the name of the original source file name
4084/// directly from the AST file, without actually loading the AST
4085/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004086std::string ASTReader::getOriginalSourceFile(
4087 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004088 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004089 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004090 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004091 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004092 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4093 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004094 return std::string();
4095 }
4096
4097 // Initialize the stream
4098 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004099 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004100 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004101
4102 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004103 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004104 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4105 return std::string();
4106 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004107
Chris Lattnere7b154b2013-01-19 21:39:22 +00004108 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004109 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004110 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4111 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004112 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004113
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004114 // Scan for ORIGINAL_FILE inside the control block.
4115 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004116 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004117 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004118 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4119 return std::string();
4120
4121 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4122 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4123 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004124 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004125
Guy Benyei11169dd2012-12-18 14:30:41 +00004126 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004127 StringRef Blob;
4128 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4129 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004130 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004131}
4132
4133namespace {
4134 class SimplePCHValidator : public ASTReaderListener {
4135 const LangOptions &ExistingLangOpts;
4136 const TargetOptions &ExistingTargetOpts;
4137 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004138 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004139 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004140
Guy Benyei11169dd2012-12-18 14:30:41 +00004141 public:
4142 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4143 const TargetOptions &ExistingTargetOpts,
4144 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004145 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004146 FileManager &FileMgr)
4147 : ExistingLangOpts(ExistingLangOpts),
4148 ExistingTargetOpts(ExistingTargetOpts),
4149 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004150 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004151 FileMgr(FileMgr)
4152 {
4153 }
4154
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004155 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4156 bool AllowCompatibleDifferences) override {
4157 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4158 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004159 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004160 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4161 bool AllowCompatibleDifferences) override {
4162 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4163 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004164 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004165 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4166 StringRef SpecificModuleCachePath,
4167 bool Complain) override {
4168 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4169 ExistingModuleCachePath,
4170 nullptr, ExistingLangOpts);
4171 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004172 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4173 bool Complain,
4174 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004175 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004176 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004177 }
4178 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004179}
Guy Benyei11169dd2012-12-18 14:30:41 +00004180
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004181bool ASTReader::readASTFileControlBlock(
4182 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004183 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004184 bool FindModuleFileExtensions,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004185 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004186 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004187 // FIXME: This allows use of the VFS; we do not allow use of the
4188 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004189 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004190 if (!Buffer) {
4191 return true;
4192 }
4193
4194 // Initialize the stream
4195 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004196 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004197 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004198
4199 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004200 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004201 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004202
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004203 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004204 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004205 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004206
4207 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004208 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004209 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004210 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004211
Guy Benyei11169dd2012-12-18 14:30:41 +00004212 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004213 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004214 bool DoneWithControlBlock = false;
4215 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004216 llvm::BitstreamEntry Entry = Stream.advance();
4217
4218 switch (Entry.Kind) {
4219 case llvm::BitstreamEntry::SubBlock: {
4220 switch (Entry.ID) {
4221 case OPTIONS_BLOCK_ID: {
4222 std::string IgnoredSuggestedPredefines;
4223 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4224 /*AllowCompatibleConfigurationMismatch*/ false,
4225 Listener, IgnoredSuggestedPredefines) != Success)
4226 return true;
4227 break;
4228 }
4229
4230 case INPUT_FILES_BLOCK_ID:
4231 InputFilesCursor = Stream;
4232 if (Stream.SkipBlock() ||
4233 (NeedsInputFiles &&
4234 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4235 return true;
4236 break;
4237
4238 default:
4239 if (Stream.SkipBlock())
4240 return true;
4241 break;
4242 }
4243
4244 continue;
4245 }
4246
4247 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004248 DoneWithControlBlock = true;
4249 break;
Richard Smith0516b182015-09-08 19:40:14 +00004250
4251 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004252 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004253
4254 case llvm::BitstreamEntry::Record:
4255 break;
4256 }
4257
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004258 if (DoneWithControlBlock) break;
4259
Guy Benyei11169dd2012-12-18 14:30:41 +00004260 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004261 StringRef Blob;
4262 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004263 switch ((ControlRecordTypes)RecCode) {
4264 case METADATA: {
4265 if (Record[0] != VERSION_MAJOR)
4266 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004267
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004268 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004269 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004270
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004271 break;
4272 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004273 case MODULE_NAME:
4274 Listener.ReadModuleName(Blob);
4275 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004276 case MODULE_DIRECTORY:
4277 ModuleDir = Blob;
4278 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004279 case MODULE_MAP_FILE: {
4280 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004281 auto Path = ReadString(Record, Idx);
4282 ResolveImportedPath(Path, ModuleDir);
4283 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004284 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004285 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004286 case INPUT_FILE_OFFSETS: {
4287 if (!NeedsInputFiles)
4288 break;
4289
4290 unsigned NumInputFiles = Record[0];
4291 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004292 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004293 for (unsigned I = 0; I != NumInputFiles; ++I) {
4294 // Go find this input file.
4295 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004296
4297 if (isSystemFile && !NeedsSystemInputFiles)
4298 break; // the rest are system input files
4299
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004300 BitstreamCursor &Cursor = InputFilesCursor;
4301 SavedStreamPosition SavedPosition(Cursor);
4302 Cursor.JumpToBit(InputFileOffs[I]);
4303
4304 unsigned Code = Cursor.ReadCode();
4305 RecordData Record;
4306 StringRef Blob;
4307 bool shouldContinue = false;
4308 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4309 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004310 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004311 std::string Filename = Blob;
4312 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004313 shouldContinue = Listener.visitInputFile(
4314 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004315 break;
4316 }
4317 if (!shouldContinue)
4318 break;
4319 }
4320 break;
4321 }
4322
Richard Smithd4b230b2014-10-27 23:01:16 +00004323 case IMPORTS: {
4324 if (!NeedsImports)
4325 break;
4326
4327 unsigned Idx = 0, N = Record.size();
4328 while (Idx < N) {
4329 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004330 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004331 std::string Filename = ReadString(Record, Idx);
4332 ResolveImportedPath(Filename, ModuleDir);
4333 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004334 }
4335 break;
4336 }
4337
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004338 default:
4339 // No other validation to perform.
4340 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004341 }
4342 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004343
4344 // Look for module file extension blocks, if requested.
4345 if (FindModuleFileExtensions) {
4346 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4347 bool DoneWithExtensionBlock = false;
4348 while (!DoneWithExtensionBlock) {
4349 llvm::BitstreamEntry Entry = Stream.advance();
4350
4351 switch (Entry.Kind) {
4352 case llvm::BitstreamEntry::SubBlock:
4353 if (Stream.SkipBlock())
4354 return true;
4355
4356 continue;
4357
4358 case llvm::BitstreamEntry::EndBlock:
4359 DoneWithExtensionBlock = true;
4360 continue;
4361
4362 case llvm::BitstreamEntry::Error:
4363 return true;
4364
4365 case llvm::BitstreamEntry::Record:
4366 break;
4367 }
4368
4369 Record.clear();
4370 StringRef Blob;
4371 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4372 switch (RecCode) {
4373 case EXTENSION_METADATA: {
4374 ModuleFileExtensionMetadata Metadata;
4375 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4376 return true;
4377
4378 Listener.readModuleFileExtension(Metadata);
4379 break;
4380 }
4381 }
4382 }
4383 }
4384 }
4385
4386 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004387}
4388
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004389bool ASTReader::isAcceptableASTFile(
4390 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004391 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004392 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4393 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004394 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4395 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004396 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004397 /*FindModuleFileExtensions=*/false,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004398 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004399}
4400
Ben Langmuir2c9af442014-04-10 17:57:43 +00004401ASTReader::ASTReadResult
4402ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004403 // Enter the submodule block.
4404 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4405 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004406 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004407 }
4408
4409 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4410 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004411 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004412 RecordData Record;
4413 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004414 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4415
4416 switch (Entry.Kind) {
4417 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4418 case llvm::BitstreamEntry::Error:
4419 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004420 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004421 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004422 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004423 case llvm::BitstreamEntry::Record:
4424 // The interesting case.
4425 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004426 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004427
Guy Benyei11169dd2012-12-18 14:30:41 +00004428 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004429 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004430 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004431 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4432
4433 if ((Kind == SUBMODULE_METADATA) != First) {
4434 Error("submodule metadata record should be at beginning of block");
4435 return Failure;
4436 }
4437 First = false;
4438
4439 // Submodule information is only valid if we have a current module.
4440 // FIXME: Should we error on these cases?
4441 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4442 Kind != SUBMODULE_DEFINITION)
4443 continue;
4444
4445 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004446 default: // Default behavior: ignore.
4447 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004448
Richard Smith03478d92014-10-23 22:12:14 +00004449 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004450 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004452 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 }
Richard Smith03478d92014-10-23 22:12:14 +00004454
Chris Lattner0e6c9402013-01-20 02:38:54 +00004455 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004456 unsigned Idx = 0;
4457 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4458 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4459 bool IsFramework = Record[Idx++];
4460 bool IsExplicit = Record[Idx++];
4461 bool IsSystem = Record[Idx++];
4462 bool IsExternC = Record[Idx++];
4463 bool InferSubmodules = Record[Idx++];
4464 bool InferExplicitSubmodules = Record[Idx++];
4465 bool InferExportWildcard = Record[Idx++];
4466 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004467
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004468 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004469 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004470 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004471
Guy Benyei11169dd2012-12-18 14:30:41 +00004472 // Retrieve this (sub)module from the module map, creating it if
4473 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004474 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004475 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004476
4477 // FIXME: set the definition loc for CurrentModule, or call
4478 // ModMap.setInferredModuleAllowedBy()
4479
Guy Benyei11169dd2012-12-18 14:30:41 +00004480 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4481 if (GlobalIndex >= SubmodulesLoaded.size() ||
4482 SubmodulesLoaded[GlobalIndex]) {
4483 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004484 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004485 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004486
Douglas Gregor7029ce12013-03-19 00:28:20 +00004487 if (!ParentModule) {
4488 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4489 if (CurFile != F.File) {
4490 if (!Diags.isDiagnosticInFlight()) {
4491 Diag(diag::err_module_file_conflict)
4492 << CurrentModule->getTopLevelModuleName()
4493 << CurFile->getName()
4494 << F.File->getName();
4495 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004496 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004497 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004498 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004499
4500 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004501 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004502
Adrian Prantl15bcf702015-06-30 17:39:43 +00004503 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004504 CurrentModule->IsFromModuleFile = true;
4505 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004506 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004507 CurrentModule->InferSubmodules = InferSubmodules;
4508 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4509 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004510 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004511 if (DeserializationListener)
4512 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4513
4514 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004515
Douglas Gregorfb912652013-03-20 21:10:35 +00004516 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004517 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004518 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004519 CurrentModule->UnresolvedConflicts.clear();
4520 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 break;
4522 }
4523
4524 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004525 std::string Filename = Blob;
4526 ResolveImportedPath(F, Filename);
4527 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004529 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4530 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004531 // This can be a spurious difference caused by changing the VFS to
4532 // point to a different copy of the file, and it is too late to
4533 // to rebuild safely.
4534 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4535 // after input file validation only real problems would remain and we
4536 // could just error. For now, assume it's okay.
4537 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004538 }
4539 }
4540 break;
4541 }
4542
Richard Smith202210b2014-10-24 20:23:01 +00004543 case SUBMODULE_HEADER:
4544 case SUBMODULE_EXCLUDED_HEADER:
4545 case SUBMODULE_PRIVATE_HEADER:
4546 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004547 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4548 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004549 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004550
Richard Smith202210b2014-10-24 20:23:01 +00004551 case SUBMODULE_TEXTUAL_HEADER:
4552 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4553 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4554 // them here.
4555 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004556
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004558 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004559 break;
4560 }
4561
4562 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004563 std::string Dirname = Blob;
4564 ResolveImportedPath(F, Dirname);
4565 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004567 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4568 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004569 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4570 Error("mismatched umbrella directories in submodule");
4571 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004572 }
4573 }
4574 break;
4575 }
4576
4577 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004578 F.BaseSubmoduleID = getTotalNumSubmodules();
4579 F.LocalNumSubmodules = Record[0];
4580 unsigned LocalBaseSubmoduleID = Record[1];
4581 if (F.LocalNumSubmodules > 0) {
4582 // Introduce the global -> local mapping for submodules within this
4583 // module.
4584 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4585
4586 // Introduce the local -> global mapping for submodules within this
4587 // module.
4588 F.SubmoduleRemap.insertOrReplace(
4589 std::make_pair(LocalBaseSubmoduleID,
4590 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004591
Ben Langmuir52ca6782014-10-20 16:27:32 +00004592 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4593 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004594 break;
4595 }
4596
4597 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004598 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004599 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004600 Unresolved.File = &F;
4601 Unresolved.Mod = CurrentModule;
4602 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004603 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004604 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004605 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 }
4607 break;
4608 }
4609
4610 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004611 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004612 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 Unresolved.File = &F;
4614 Unresolved.Mod = CurrentModule;
4615 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004616 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004618 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 }
4620
4621 // Once we've loaded the set of exports, there's no reason to keep
4622 // the parsed, unresolved exports around.
4623 CurrentModule->UnresolvedExports.clear();
4624 break;
4625 }
4626 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004627 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004628 Context.getTargetInfo());
4629 break;
4630 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004631
4632 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004633 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004634 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004635 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004636
4637 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004638 CurrentModule->ConfigMacros.push_back(Blob.str());
4639 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004640
4641 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004642 UnresolvedModuleRef Unresolved;
4643 Unresolved.File = &F;
4644 Unresolved.Mod = CurrentModule;
4645 Unresolved.ID = Record[0];
4646 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4647 Unresolved.IsWildcard = false;
4648 Unresolved.String = Blob;
4649 UnresolvedModuleRefs.push_back(Unresolved);
4650 break;
4651 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 }
4653 }
4654}
4655
4656/// \brief Parse the record that corresponds to a LangOptions data
4657/// structure.
4658///
4659/// This routine parses the language options from the AST file and then gives
4660/// them to the AST listener if one is set.
4661///
4662/// \returns true if the listener deems the file unacceptable, false otherwise.
4663bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4664 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004665 ASTReaderListener &Listener,
4666 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 LangOptions LangOpts;
4668 unsigned Idx = 0;
4669#define LANGOPT(Name, Bits, Default, Description) \
4670 LangOpts.Name = Record[Idx++];
4671#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4672 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4673#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004674#define SANITIZER(NAME, ID) \
4675 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004676#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004677
Ben Langmuircd98cb72015-06-23 18:20:18 +00004678 for (unsigned N = Record[Idx++]; N; --N)
4679 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4680
Guy Benyei11169dd2012-12-18 14:30:41 +00004681 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4682 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4683 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004684
Ben Langmuird4a667a2015-06-23 18:20:23 +00004685 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004686
4687 // Comment options.
4688 for (unsigned N = Record[Idx++]; N; --N) {
4689 LangOpts.CommentOpts.BlockCommandNames.push_back(
4690 ReadString(Record, Idx));
4691 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004692 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004693
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004694 return Listener.ReadLanguageOptions(LangOpts, Complain,
4695 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004696}
4697
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004698bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4699 ASTReaderListener &Listener,
4700 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004701 unsigned Idx = 0;
4702 TargetOptions TargetOpts;
4703 TargetOpts.Triple = ReadString(Record, Idx);
4704 TargetOpts.CPU = ReadString(Record, Idx);
4705 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004706 for (unsigned N = Record[Idx++]; N; --N) {
4707 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4708 }
4709 for (unsigned N = Record[Idx++]; N; --N) {
4710 TargetOpts.Features.push_back(ReadString(Record, Idx));
4711 }
4712
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004713 return Listener.ReadTargetOptions(TargetOpts, Complain,
4714 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004715}
4716
4717bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4718 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004719 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004720 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004721#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004722#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004723 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004724#include "clang/Basic/DiagnosticOptions.def"
4725
Richard Smith3be1cb22014-08-07 00:24:21 +00004726 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004727 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004728 for (unsigned N = Record[Idx++]; N; --N)
4729 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004730
4731 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4732}
4733
4734bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4735 ASTReaderListener &Listener) {
4736 FileSystemOptions FSOpts;
4737 unsigned Idx = 0;
4738 FSOpts.WorkingDir = ReadString(Record, Idx);
4739 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4740}
4741
4742bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4743 bool Complain,
4744 ASTReaderListener &Listener) {
4745 HeaderSearchOptions HSOpts;
4746 unsigned Idx = 0;
4747 HSOpts.Sysroot = ReadString(Record, Idx);
4748
4749 // Include entries.
4750 for (unsigned N = Record[Idx++]; N; --N) {
4751 std::string Path = ReadString(Record, Idx);
4752 frontend::IncludeDirGroup Group
4753 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004754 bool IsFramework = Record[Idx++];
4755 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004756 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4757 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004758 }
4759
4760 // System header prefixes.
4761 for (unsigned N = Record[Idx++]; N; --N) {
4762 std::string Prefix = ReadString(Record, Idx);
4763 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004764 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004765 }
4766
4767 HSOpts.ResourceDir = ReadString(Record, Idx);
4768 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004769 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004770 HSOpts.DisableModuleHash = Record[Idx++];
4771 HSOpts.UseBuiltinIncludes = Record[Idx++];
4772 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4773 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4774 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004775 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004776
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004777 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4778 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004779}
4780
4781bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4782 bool Complain,
4783 ASTReaderListener &Listener,
4784 std::string &SuggestedPredefines) {
4785 PreprocessorOptions PPOpts;
4786 unsigned Idx = 0;
4787
4788 // Macro definitions/undefs
4789 for (unsigned N = Record[Idx++]; N; --N) {
4790 std::string Macro = ReadString(Record, Idx);
4791 bool IsUndef = Record[Idx++];
4792 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4793 }
4794
4795 // Includes
4796 for (unsigned N = Record[Idx++]; N; --N) {
4797 PPOpts.Includes.push_back(ReadString(Record, Idx));
4798 }
4799
4800 // Macro Includes
4801 for (unsigned N = Record[Idx++]; N; --N) {
4802 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4803 }
4804
4805 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004806 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004807 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4808 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4809 PPOpts.ObjCXXARCStandardLibrary =
4810 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4811 SuggestedPredefines.clear();
4812 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4813 SuggestedPredefines);
4814}
4815
4816std::pair<ModuleFile *, unsigned>
4817ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4818 GlobalPreprocessedEntityMapType::iterator
4819 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4820 assert(I != GlobalPreprocessedEntityMap.end() &&
4821 "Corrupted global preprocessed entity map");
4822 ModuleFile *M = I->second;
4823 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4824 return std::make_pair(M, LocalIndex);
4825}
4826
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004827llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004828ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4829 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4830 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4831 Mod.NumPreprocessedEntities);
4832
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004833 return llvm::make_range(PreprocessingRecord::iterator(),
4834 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004835}
4836
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004837llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004838ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004839 return llvm::make_range(
4840 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4841 ModuleDeclIterator(this, &Mod,
4842 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004843}
4844
4845PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4846 PreprocessedEntityID PPID = Index+1;
4847 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4848 ModuleFile &M = *PPInfo.first;
4849 unsigned LocalIndex = PPInfo.second;
4850 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4851
Guy Benyei11169dd2012-12-18 14:30:41 +00004852 if (!PP.getPreprocessingRecord()) {
4853 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004854 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004855 }
4856
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004857 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4858 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4859
4860 llvm::BitstreamEntry Entry =
4861 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4862 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004863 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004864
Guy Benyei11169dd2012-12-18 14:30:41 +00004865 // Read the record.
4866 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4867 ReadSourceLocation(M, PPOffs.End));
4868 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004869 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004870 RecordData Record;
4871 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004872 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4873 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004874 switch (RecType) {
4875 case PPD_MACRO_EXPANSION: {
4876 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004877 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004878 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004879 if (isBuiltin)
4880 Name = getLocalIdentifier(M, Record[1]);
4881 else {
Richard Smith66a81862015-05-04 02:25:31 +00004882 PreprocessedEntityID GlobalID =
4883 getGlobalPreprocessedEntityID(M, Record[1]);
4884 Def = cast<MacroDefinitionRecord>(
4885 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004886 }
4887
4888 MacroExpansion *ME;
4889 if (isBuiltin)
4890 ME = new (PPRec) MacroExpansion(Name, Range);
4891 else
4892 ME = new (PPRec) MacroExpansion(Def, Range);
4893
4894 return ME;
4895 }
4896
4897 case PPD_MACRO_DEFINITION: {
4898 // Decode the identifier info and then check again; if the macro is
4899 // still defined and associated with the identifier,
4900 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004901 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004902
4903 if (DeserializationListener)
4904 DeserializationListener->MacroDefinitionRead(PPID, MD);
4905
4906 return MD;
4907 }
4908
4909 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004910 const char *FullFileNameStart = Blob.data() + Record[0];
4911 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004912 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004913 if (!FullFileName.empty())
4914 File = PP.getFileManager().getFile(FullFileName);
4915
4916 // FIXME: Stable encoding
4917 InclusionDirective::InclusionKind Kind
4918 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4919 InclusionDirective *ID
4920 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004921 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004922 Record[1], Record[3],
4923 File,
4924 Range);
4925 return ID;
4926 }
4927 }
4928
4929 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4930}
4931
4932/// \brief \arg SLocMapI points at a chunk of a module that contains no
4933/// preprocessed entities or the entities it contains are not the ones we are
4934/// looking for. Find the next module that contains entities and return the ID
4935/// of the first entry.
4936PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4937 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4938 ++SLocMapI;
4939 for (GlobalSLocOffsetMapType::const_iterator
4940 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4941 ModuleFile &M = *SLocMapI->second;
4942 if (M.NumPreprocessedEntities)
4943 return M.BasePreprocessedEntityID;
4944 }
4945
4946 return getTotalNumPreprocessedEntities();
4947}
4948
4949namespace {
4950
4951template <unsigned PPEntityOffset::*PPLoc>
4952struct PPEntityComp {
4953 const ASTReader &Reader;
4954 ModuleFile &M;
4955
4956 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4957
4958 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4959 SourceLocation LHS = getLoc(L);
4960 SourceLocation RHS = getLoc(R);
4961 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4962 }
4963
4964 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4965 SourceLocation LHS = getLoc(L);
4966 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4967 }
4968
4969 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4970 SourceLocation RHS = getLoc(R);
4971 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4972 }
4973
4974 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4975 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4976 }
4977};
4978
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004979}
Guy Benyei11169dd2012-12-18 14:30:41 +00004980
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004981PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4982 bool EndsAfter) const {
4983 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004984 return getTotalNumPreprocessedEntities();
4985
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004986 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4987 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004988 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4989 "Corrupted global sloc offset map");
4990
4991 if (SLocMapI->second->NumPreprocessedEntities == 0)
4992 return findNextPreprocessedEntity(SLocMapI);
4993
4994 ModuleFile &M = *SLocMapI->second;
4995 typedef const PPEntityOffset *pp_iterator;
4996 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4997 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4998
4999 size_t Count = M.NumPreprocessedEntities;
5000 size_t Half;
5001 pp_iterator First = pp_begin;
5002 pp_iterator PPI;
5003
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005004 if (EndsAfter) {
5005 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5006 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
5007 } else {
5008 // Do a binary search manually instead of using std::lower_bound because
5009 // The end locations of entities may be unordered (when a macro expansion
5010 // is inside another macro argument), but for this case it is not important
5011 // whether we get the first macro expansion or its containing macro.
5012 while (Count > 0) {
5013 Half = Count / 2;
5014 PPI = First;
5015 std::advance(PPI, Half);
5016 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
5017 Loc)) {
5018 First = PPI;
5019 ++First;
5020 Count = Count - Half - 1;
5021 } else
5022 Count = Half;
5023 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005024 }
5025
5026 if (PPI == pp_end)
5027 return findNextPreprocessedEntity(SLocMapI);
5028
5029 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5030}
5031
Guy Benyei11169dd2012-12-18 14:30:41 +00005032/// \brief Returns a pair of [Begin, End) indices of preallocated
5033/// preprocessed entities that \arg Range encompasses.
5034std::pair<unsigned, unsigned>
5035 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5036 if (Range.isInvalid())
5037 return std::make_pair(0,0);
5038 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5039
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005040 PreprocessedEntityID BeginID =
5041 findPreprocessedEntity(Range.getBegin(), false);
5042 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 return std::make_pair(BeginID, EndID);
5044}
5045
5046/// \brief Optionally returns true or false if the preallocated preprocessed
5047/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005048Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 FileID FID) {
5050 if (FID.isInvalid())
5051 return false;
5052
5053 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5054 ModuleFile &M = *PPInfo.first;
5055 unsigned LocalIndex = PPInfo.second;
5056 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5057
5058 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5059 if (Loc.isInvalid())
5060 return false;
5061
5062 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5063 return true;
5064 else
5065 return false;
5066}
5067
5068namespace {
5069 /// \brief Visitor used to search for information about a header file.
5070 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 const FileEntry *FE;
5072
David Blaikie05785d12013-02-20 22:23:23 +00005073 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005074
5075 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005076 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5077 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005078
5079 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005080 HeaderFileInfoLookupTable *Table
5081 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5082 if (!Table)
5083 return false;
5084
5085 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005086 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005087 if (Pos == Table->end())
5088 return false;
5089
Richard Smithbdf2d932015-07-30 03:37:16 +00005090 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005091 return true;
5092 }
5093
David Blaikie05785d12013-02-20 22:23:23 +00005094 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005095 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005096}
Guy Benyei11169dd2012-12-18 14:30:41 +00005097
5098HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005099 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005100 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005101 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005103
5104 return HeaderFileInfo();
5105}
5106
5107void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5108 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005109 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005110 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5111 ModuleFile &F = *(*I);
5112 unsigned Idx = 0;
5113 DiagStates.clear();
5114 assert(!Diag.DiagStates.empty());
5115 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5116 while (Idx < F.PragmaDiagMappings.size()) {
5117 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5118 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5119 if (DiagStateID != 0) {
5120 Diag.DiagStatePoints.push_back(
5121 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5122 FullSourceLoc(Loc, SourceMgr)));
5123 continue;
5124 }
5125
5126 assert(DiagStateID == 0);
5127 // A new DiagState was created here.
5128 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5129 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5130 DiagStates.push_back(NewState);
5131 Diag.DiagStatePoints.push_back(
5132 DiagnosticsEngine::DiagStatePoint(NewState,
5133 FullSourceLoc(Loc, SourceMgr)));
5134 while (1) {
5135 assert(Idx < F.PragmaDiagMappings.size() &&
5136 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5137 if (Idx >= F.PragmaDiagMappings.size()) {
5138 break; // Something is messed up but at least avoid infinite loop in
5139 // release build.
5140 }
5141 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5142 if (DiagID == (unsigned)-1) {
5143 break; // no more diag/map pairs for this location.
5144 }
Alp Tokerc726c362014-06-10 09:31:37 +00005145 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5146 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5147 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 }
5149 }
5150 }
5151}
5152
5153/// \brief Get the correct cursor and offset for loading a type.
5154ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5155 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5156 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5157 ModuleFile *M = I->second;
5158 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5159}
5160
5161/// \brief Read and return the type with the given index..
5162///
5163/// The index is the type ID, shifted and minus the number of predefs. This
5164/// routine actually reads the record corresponding to the type at the given
5165/// location. It is a helper routine for GetType, which deals with reading type
5166/// IDs.
5167QualType ASTReader::readTypeRecord(unsigned Index) {
5168 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005169 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005170
5171 // Keep track of where we are in the stream, then jump back there
5172 // after reading this type.
5173 SavedStreamPosition SavedPosition(DeclsCursor);
5174
5175 ReadingKindTracker ReadingKind(Read_Type, *this);
5176
5177 // Note that we are loading a type record.
5178 Deserializing AType(this);
5179
5180 unsigned Idx = 0;
5181 DeclsCursor.JumpToBit(Loc.Offset);
5182 RecordData Record;
5183 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005184 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005185 case TYPE_EXT_QUAL: {
5186 if (Record.size() != 2) {
5187 Error("Incorrect encoding of extended qualifier type");
5188 return QualType();
5189 }
5190 QualType Base = readType(*Loc.F, Record, Idx);
5191 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5192 return Context.getQualifiedType(Base, Quals);
5193 }
5194
5195 case TYPE_COMPLEX: {
5196 if (Record.size() != 1) {
5197 Error("Incorrect encoding of complex type");
5198 return QualType();
5199 }
5200 QualType ElemType = readType(*Loc.F, Record, Idx);
5201 return Context.getComplexType(ElemType);
5202 }
5203
5204 case TYPE_POINTER: {
5205 if (Record.size() != 1) {
5206 Error("Incorrect encoding of pointer type");
5207 return QualType();
5208 }
5209 QualType PointeeType = readType(*Loc.F, Record, Idx);
5210 return Context.getPointerType(PointeeType);
5211 }
5212
Reid Kleckner8a365022013-06-24 17:51:48 +00005213 case TYPE_DECAYED: {
5214 if (Record.size() != 1) {
5215 Error("Incorrect encoding of decayed type");
5216 return QualType();
5217 }
5218 QualType OriginalType = readType(*Loc.F, Record, Idx);
5219 QualType DT = Context.getAdjustedParameterType(OriginalType);
5220 if (!isa<DecayedType>(DT))
5221 Error("Decayed type does not decay");
5222 return DT;
5223 }
5224
Reid Kleckner0503a872013-12-05 01:23:43 +00005225 case TYPE_ADJUSTED: {
5226 if (Record.size() != 2) {
5227 Error("Incorrect encoding of adjusted type");
5228 return QualType();
5229 }
5230 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5231 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5232 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5233 }
5234
Guy Benyei11169dd2012-12-18 14:30:41 +00005235 case TYPE_BLOCK_POINTER: {
5236 if (Record.size() != 1) {
5237 Error("Incorrect encoding of block pointer type");
5238 return QualType();
5239 }
5240 QualType PointeeType = readType(*Loc.F, Record, Idx);
5241 return Context.getBlockPointerType(PointeeType);
5242 }
5243
5244 case TYPE_LVALUE_REFERENCE: {
5245 if (Record.size() != 2) {
5246 Error("Incorrect encoding of lvalue reference type");
5247 return QualType();
5248 }
5249 QualType PointeeType = readType(*Loc.F, Record, Idx);
5250 return Context.getLValueReferenceType(PointeeType, Record[1]);
5251 }
5252
5253 case TYPE_RVALUE_REFERENCE: {
5254 if (Record.size() != 1) {
5255 Error("Incorrect encoding of rvalue reference type");
5256 return QualType();
5257 }
5258 QualType PointeeType = readType(*Loc.F, Record, Idx);
5259 return Context.getRValueReferenceType(PointeeType);
5260 }
5261
5262 case TYPE_MEMBER_POINTER: {
5263 if (Record.size() != 2) {
5264 Error("Incorrect encoding of member pointer type");
5265 return QualType();
5266 }
5267 QualType PointeeType = readType(*Loc.F, Record, Idx);
5268 QualType ClassType = readType(*Loc.F, Record, Idx);
5269 if (PointeeType.isNull() || ClassType.isNull())
5270 return QualType();
5271
5272 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5273 }
5274
5275 case TYPE_CONSTANT_ARRAY: {
5276 QualType ElementType = readType(*Loc.F, Record, Idx);
5277 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5278 unsigned IndexTypeQuals = Record[2];
5279 unsigned Idx = 3;
5280 llvm::APInt Size = ReadAPInt(Record, Idx);
5281 return Context.getConstantArrayType(ElementType, Size,
5282 ASM, IndexTypeQuals);
5283 }
5284
5285 case TYPE_INCOMPLETE_ARRAY: {
5286 QualType ElementType = readType(*Loc.F, Record, Idx);
5287 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5288 unsigned IndexTypeQuals = Record[2];
5289 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5290 }
5291
5292 case TYPE_VARIABLE_ARRAY: {
5293 QualType ElementType = readType(*Loc.F, Record, Idx);
5294 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5295 unsigned IndexTypeQuals = Record[2];
5296 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5297 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5298 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5299 ASM, IndexTypeQuals,
5300 SourceRange(LBLoc, RBLoc));
5301 }
5302
5303 case TYPE_VECTOR: {
5304 if (Record.size() != 3) {
5305 Error("incorrect encoding of vector type in AST file");
5306 return QualType();
5307 }
5308
5309 QualType ElementType = readType(*Loc.F, Record, Idx);
5310 unsigned NumElements = Record[1];
5311 unsigned VecKind = Record[2];
5312 return Context.getVectorType(ElementType, NumElements,
5313 (VectorType::VectorKind)VecKind);
5314 }
5315
5316 case TYPE_EXT_VECTOR: {
5317 if (Record.size() != 3) {
5318 Error("incorrect encoding of extended vector type in AST file");
5319 return QualType();
5320 }
5321
5322 QualType ElementType = readType(*Loc.F, Record, Idx);
5323 unsigned NumElements = Record[1];
5324 return Context.getExtVectorType(ElementType, NumElements);
5325 }
5326
5327 case TYPE_FUNCTION_NO_PROTO: {
5328 if (Record.size() != 6) {
5329 Error("incorrect encoding of no-proto function type");
5330 return QualType();
5331 }
5332 QualType ResultType = readType(*Loc.F, Record, Idx);
5333 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5334 (CallingConv)Record[4], Record[5]);
5335 return Context.getFunctionNoProtoType(ResultType, Info);
5336 }
5337
5338 case TYPE_FUNCTION_PROTO: {
5339 QualType ResultType = readType(*Loc.F, Record, Idx);
5340
5341 FunctionProtoType::ExtProtoInfo EPI;
5342 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5343 /*hasregparm*/ Record[2],
5344 /*regparm*/ Record[3],
5345 static_cast<CallingConv>(Record[4]),
5346 /*produces*/ Record[5]);
5347
5348 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005349
5350 EPI.Variadic = Record[Idx++];
5351 EPI.HasTrailingReturn = Record[Idx++];
5352 EPI.TypeQuals = Record[Idx++];
5353 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005354 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005355 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005356
5357 unsigned NumParams = Record[Idx++];
5358 SmallVector<QualType, 16> ParamTypes;
5359 for (unsigned I = 0; I != NumParams; ++I)
5360 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5361
Jordan Rose5c382722013-03-08 21:51:21 +00005362 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005363 }
5364
5365 case TYPE_UNRESOLVED_USING: {
5366 unsigned Idx = 0;
5367 return Context.getTypeDeclType(
5368 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5369 }
5370
5371 case TYPE_TYPEDEF: {
5372 if (Record.size() != 2) {
5373 Error("incorrect encoding of typedef type");
5374 return QualType();
5375 }
5376 unsigned Idx = 0;
5377 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5378 QualType Canonical = readType(*Loc.F, Record, Idx);
5379 if (!Canonical.isNull())
5380 Canonical = Context.getCanonicalType(Canonical);
5381 return Context.getTypedefType(Decl, Canonical);
5382 }
5383
5384 case TYPE_TYPEOF_EXPR:
5385 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5386
5387 case TYPE_TYPEOF: {
5388 if (Record.size() != 1) {
5389 Error("incorrect encoding of typeof(type) in AST file");
5390 return QualType();
5391 }
5392 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5393 return Context.getTypeOfType(UnderlyingType);
5394 }
5395
5396 case TYPE_DECLTYPE: {
5397 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5398 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5399 }
5400
5401 case TYPE_UNARY_TRANSFORM: {
5402 QualType BaseType = readType(*Loc.F, Record, Idx);
5403 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5404 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5405 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5406 }
5407
Richard Smith74aeef52013-04-26 16:15:35 +00005408 case TYPE_AUTO: {
5409 QualType Deduced = readType(*Loc.F, Record, Idx);
5410 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005411 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005412 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005413 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005414
5415 case TYPE_RECORD: {
5416 if (Record.size() != 2) {
5417 Error("incorrect encoding of record type");
5418 return QualType();
5419 }
5420 unsigned Idx = 0;
5421 bool IsDependent = Record[Idx++];
5422 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5423 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5424 QualType T = Context.getRecordType(RD);
5425 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5426 return T;
5427 }
5428
5429 case TYPE_ENUM: {
5430 if (Record.size() != 2) {
5431 Error("incorrect encoding of enum type");
5432 return QualType();
5433 }
5434 unsigned Idx = 0;
5435 bool IsDependent = Record[Idx++];
5436 QualType T
5437 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5438 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5439 return T;
5440 }
5441
5442 case TYPE_ATTRIBUTED: {
5443 if (Record.size() != 3) {
5444 Error("incorrect encoding of attributed type");
5445 return QualType();
5446 }
5447 QualType modifiedType = readType(*Loc.F, Record, Idx);
5448 QualType equivalentType = readType(*Loc.F, Record, Idx);
5449 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5450 return Context.getAttributedType(kind, modifiedType, equivalentType);
5451 }
5452
5453 case TYPE_PAREN: {
5454 if (Record.size() != 1) {
5455 Error("incorrect encoding of paren type");
5456 return QualType();
5457 }
5458 QualType InnerType = readType(*Loc.F, Record, Idx);
5459 return Context.getParenType(InnerType);
5460 }
5461
5462 case TYPE_PACK_EXPANSION: {
5463 if (Record.size() != 2) {
5464 Error("incorrect encoding of pack expansion type");
5465 return QualType();
5466 }
5467 QualType Pattern = readType(*Loc.F, Record, Idx);
5468 if (Pattern.isNull())
5469 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005470 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005471 if (Record[1])
5472 NumExpansions = Record[1] - 1;
5473 return Context.getPackExpansionType(Pattern, NumExpansions);
5474 }
5475
5476 case TYPE_ELABORATED: {
5477 unsigned Idx = 0;
5478 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5479 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5480 QualType NamedType = readType(*Loc.F, Record, Idx);
5481 return Context.getElaboratedType(Keyword, NNS, NamedType);
5482 }
5483
5484 case TYPE_OBJC_INTERFACE: {
5485 unsigned Idx = 0;
5486 ObjCInterfaceDecl *ItfD
5487 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5488 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5489 }
5490
5491 case TYPE_OBJC_OBJECT: {
5492 unsigned Idx = 0;
5493 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005494 unsigned NumTypeArgs = Record[Idx++];
5495 SmallVector<QualType, 4> TypeArgs;
5496 for (unsigned I = 0; I != NumTypeArgs; ++I)
5497 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005498 unsigned NumProtos = Record[Idx++];
5499 SmallVector<ObjCProtocolDecl*, 4> Protos;
5500 for (unsigned I = 0; I != NumProtos; ++I)
5501 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005502 bool IsKindOf = Record[Idx++];
5503 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005504 }
5505
5506 case TYPE_OBJC_OBJECT_POINTER: {
5507 unsigned Idx = 0;
5508 QualType Pointee = readType(*Loc.F, Record, Idx);
5509 return Context.getObjCObjectPointerType(Pointee);
5510 }
5511
5512 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5513 unsigned Idx = 0;
5514 QualType Parm = readType(*Loc.F, Record, Idx);
5515 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005516 return Context.getSubstTemplateTypeParmType(
5517 cast<TemplateTypeParmType>(Parm),
5518 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005519 }
5520
5521 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5522 unsigned Idx = 0;
5523 QualType Parm = readType(*Loc.F, Record, Idx);
5524 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5525 return Context.getSubstTemplateTypeParmPackType(
5526 cast<TemplateTypeParmType>(Parm),
5527 ArgPack);
5528 }
5529
5530 case TYPE_INJECTED_CLASS_NAME: {
5531 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5532 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5533 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5534 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005535 const Type *T = nullptr;
5536 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5537 if (const Type *Existing = DI->getTypeForDecl()) {
5538 T = Existing;
5539 break;
5540 }
5541 }
5542 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005543 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005544 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5545 DI->setTypeForDecl(T);
5546 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005547 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005548 }
5549
5550 case TYPE_TEMPLATE_TYPE_PARM: {
5551 unsigned Idx = 0;
5552 unsigned Depth = Record[Idx++];
5553 unsigned Index = Record[Idx++];
5554 bool Pack = Record[Idx++];
5555 TemplateTypeParmDecl *D
5556 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5557 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5558 }
5559
5560 case TYPE_DEPENDENT_NAME: {
5561 unsigned Idx = 0;
5562 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5563 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005564 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005565 QualType Canon = readType(*Loc.F, Record, Idx);
5566 if (!Canon.isNull())
5567 Canon = Context.getCanonicalType(Canon);
5568 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5569 }
5570
5571 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5572 unsigned Idx = 0;
5573 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5574 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005575 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005576 unsigned NumArgs = Record[Idx++];
5577 SmallVector<TemplateArgument, 8> Args;
5578 Args.reserve(NumArgs);
5579 while (NumArgs--)
5580 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5581 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5582 Args.size(), Args.data());
5583 }
5584
5585 case TYPE_DEPENDENT_SIZED_ARRAY: {
5586 unsigned Idx = 0;
5587
5588 // ArrayType
5589 QualType ElementType = readType(*Loc.F, Record, Idx);
5590 ArrayType::ArraySizeModifier ASM
5591 = (ArrayType::ArraySizeModifier)Record[Idx++];
5592 unsigned IndexTypeQuals = Record[Idx++];
5593
5594 // DependentSizedArrayType
5595 Expr *NumElts = ReadExpr(*Loc.F);
5596 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5597
5598 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5599 IndexTypeQuals, Brackets);
5600 }
5601
5602 case TYPE_TEMPLATE_SPECIALIZATION: {
5603 unsigned Idx = 0;
5604 bool IsDependent = Record[Idx++];
5605 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5606 SmallVector<TemplateArgument, 8> Args;
5607 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5608 QualType Underlying = readType(*Loc.F, Record, Idx);
5609 QualType T;
5610 if (Underlying.isNull())
5611 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5612 Args.size());
5613 else
5614 T = Context.getTemplateSpecializationType(Name, Args.data(),
5615 Args.size(), Underlying);
5616 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5617 return T;
5618 }
5619
5620 case TYPE_ATOMIC: {
5621 if (Record.size() != 1) {
5622 Error("Incorrect encoding of atomic type");
5623 return QualType();
5624 }
5625 QualType ValueType = readType(*Loc.F, Record, Idx);
5626 return Context.getAtomicType(ValueType);
5627 }
5628 }
5629 llvm_unreachable("Invalid TypeCode!");
5630}
5631
Richard Smith564417a2014-03-20 21:47:22 +00005632void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5633 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005634 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005635 const RecordData &Record, unsigned &Idx) {
5636 ExceptionSpecificationType EST =
5637 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005638 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005639 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005640 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005641 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005642 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005643 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005644 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005645 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005646 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5647 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005648 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005649 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005650 }
5651}
5652
Guy Benyei11169dd2012-12-18 14:30:41 +00005653class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5654 ASTReader &Reader;
5655 ModuleFile &F;
5656 const ASTReader::RecordData &Record;
5657 unsigned &Idx;
5658
5659 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5660 unsigned &I) {
5661 return Reader.ReadSourceLocation(F, R, I);
5662 }
5663
5664 template<typename T>
5665 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5666 return Reader.ReadDeclAs<T>(F, Record, Idx);
5667 }
5668
5669public:
5670 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5671 const ASTReader::RecordData &Record, unsigned &Idx)
5672 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5673 { }
5674
5675 // We want compile-time assurance that we've enumerated all of
5676 // these, so unfortunately we have to declare them first, then
5677 // define them out-of-line.
5678#define ABSTRACT_TYPELOC(CLASS, PARENT)
5679#define TYPELOC(CLASS, PARENT) \
5680 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5681#include "clang/AST/TypeLocNodes.def"
5682
5683 void VisitFunctionTypeLoc(FunctionTypeLoc);
5684 void VisitArrayTypeLoc(ArrayTypeLoc);
5685};
5686
5687void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5688 // nothing to do
5689}
5690void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5691 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5692 if (TL.needsExtraLocalData()) {
5693 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5694 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5695 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5696 TL.setModeAttr(Record[Idx++]);
5697 }
5698}
5699void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5700 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5701}
5702void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5703 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5704}
Reid Kleckner8a365022013-06-24 17:51:48 +00005705void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5706 // nothing to do
5707}
Reid Kleckner0503a872013-12-05 01:23:43 +00005708void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5709 // nothing to do
5710}
Guy Benyei11169dd2012-12-18 14:30:41 +00005711void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5712 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5713}
5714void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5715 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5716}
5717void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5718 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5719}
5720void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5721 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5722 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5723}
5724void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5725 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5726 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5727 if (Record[Idx++])
5728 TL.setSizeExpr(Reader.ReadExpr(F));
5729 else
Craig Toppera13603a2014-05-22 05:54:18 +00005730 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005731}
5732void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5733 VisitArrayTypeLoc(TL);
5734}
5735void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5736 VisitArrayTypeLoc(TL);
5737}
5738void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5739 VisitArrayTypeLoc(TL);
5740}
5741void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5742 DependentSizedArrayTypeLoc TL) {
5743 VisitArrayTypeLoc(TL);
5744}
5745void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5746 DependentSizedExtVectorTypeLoc TL) {
5747 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5748}
5749void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5750 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5751}
5752void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5753 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5754}
5755void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5756 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5757 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5758 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5759 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005760 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5761 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005762 }
5763}
5764void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5765 VisitFunctionTypeLoc(TL);
5766}
5767void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5768 VisitFunctionTypeLoc(TL);
5769}
5770void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5771 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5772}
5773void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5774 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5775}
5776void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5777 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5778 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5779 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5780}
5781void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5782 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5783 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5784 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5785 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5786}
5787void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5788 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5789}
5790void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5791 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5792 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5793 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5794 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5795}
5796void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5797 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5798}
5799void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5800 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5801}
5802void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5803 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5804}
5805void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5806 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5807 if (TL.hasAttrOperand()) {
5808 SourceRange range;
5809 range.setBegin(ReadSourceLocation(Record, Idx));
5810 range.setEnd(ReadSourceLocation(Record, Idx));
5811 TL.setAttrOperandParensRange(range);
5812 }
5813 if (TL.hasAttrExprOperand()) {
5814 if (Record[Idx++])
5815 TL.setAttrExprOperand(Reader.ReadExpr(F));
5816 else
Craig Toppera13603a2014-05-22 05:54:18 +00005817 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005818 } else if (TL.hasAttrEnumOperand())
5819 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5820}
5821void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5822 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5823}
5824void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5825 SubstTemplateTypeParmTypeLoc TL) {
5826 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5827}
5828void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5829 SubstTemplateTypeParmPackTypeLoc TL) {
5830 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5831}
5832void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5833 TemplateSpecializationTypeLoc TL) {
5834 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5835 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5836 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5837 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5838 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5839 TL.setArgLocInfo(i,
5840 Reader.GetTemplateArgumentLocInfo(F,
5841 TL.getTypePtr()->getArg(i).getKind(),
5842 Record, Idx));
5843}
5844void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5845 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5846 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5847}
5848void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5849 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5850 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5851}
5852void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5853 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5854}
5855void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5856 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5857 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5858 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5859}
5860void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5861 DependentTemplateSpecializationTypeLoc TL) {
5862 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5863 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5864 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5865 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5866 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5867 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5868 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5869 TL.setArgLocInfo(I,
5870 Reader.GetTemplateArgumentLocInfo(F,
5871 TL.getTypePtr()->getArg(I).getKind(),
5872 Record, Idx));
5873}
5874void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5875 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5876}
5877void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5878 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5879}
5880void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5881 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005882 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5883 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5884 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5885 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5886 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5887 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005888 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5889 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5890}
5891void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5892 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5893}
5894void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5895 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5896 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5897 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5898}
5899
5900TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5901 const RecordData &Record,
5902 unsigned &Idx) {
5903 QualType InfoTy = readType(F, Record, Idx);
5904 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005905 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005906
5907 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5908 TypeLocReader TLR(*this, F, Record, Idx);
5909 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5910 TLR.Visit(TL);
5911 return TInfo;
5912}
5913
5914QualType ASTReader::GetType(TypeID ID) {
5915 unsigned FastQuals = ID & Qualifiers::FastMask;
5916 unsigned Index = ID >> Qualifiers::FastWidth;
5917
5918 if (Index < NUM_PREDEF_TYPE_IDS) {
5919 QualType T;
5920 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00005921 case PREDEF_TYPE_NULL_ID:
5922 return QualType();
5923 case PREDEF_TYPE_VOID_ID:
5924 T = Context.VoidTy;
5925 break;
5926 case PREDEF_TYPE_BOOL_ID:
5927 T = Context.BoolTy;
5928 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005929
5930 case PREDEF_TYPE_CHAR_U_ID:
5931 case PREDEF_TYPE_CHAR_S_ID:
5932 // FIXME: Check that the signedness of CharTy is correct!
5933 T = Context.CharTy;
5934 break;
5935
Alexey Baderbdf7c842015-09-15 12:18:29 +00005936 case PREDEF_TYPE_UCHAR_ID:
5937 T = Context.UnsignedCharTy;
5938 break;
5939 case PREDEF_TYPE_USHORT_ID:
5940 T = Context.UnsignedShortTy;
5941 break;
5942 case PREDEF_TYPE_UINT_ID:
5943 T = Context.UnsignedIntTy;
5944 break;
5945 case PREDEF_TYPE_ULONG_ID:
5946 T = Context.UnsignedLongTy;
5947 break;
5948 case PREDEF_TYPE_ULONGLONG_ID:
5949 T = Context.UnsignedLongLongTy;
5950 break;
5951 case PREDEF_TYPE_UINT128_ID:
5952 T = Context.UnsignedInt128Ty;
5953 break;
5954 case PREDEF_TYPE_SCHAR_ID:
5955 T = Context.SignedCharTy;
5956 break;
5957 case PREDEF_TYPE_WCHAR_ID:
5958 T = Context.WCharTy;
5959 break;
5960 case PREDEF_TYPE_SHORT_ID:
5961 T = Context.ShortTy;
5962 break;
5963 case PREDEF_TYPE_INT_ID:
5964 T = Context.IntTy;
5965 break;
5966 case PREDEF_TYPE_LONG_ID:
5967 T = Context.LongTy;
5968 break;
5969 case PREDEF_TYPE_LONGLONG_ID:
5970 T = Context.LongLongTy;
5971 break;
5972 case PREDEF_TYPE_INT128_ID:
5973 T = Context.Int128Ty;
5974 break;
5975 case PREDEF_TYPE_HALF_ID:
5976 T = Context.HalfTy;
5977 break;
5978 case PREDEF_TYPE_FLOAT_ID:
5979 T = Context.FloatTy;
5980 break;
5981 case PREDEF_TYPE_DOUBLE_ID:
5982 T = Context.DoubleTy;
5983 break;
5984 case PREDEF_TYPE_LONGDOUBLE_ID:
5985 T = Context.LongDoubleTy;
5986 break;
5987 case PREDEF_TYPE_OVERLOAD_ID:
5988 T = Context.OverloadTy;
5989 break;
5990 case PREDEF_TYPE_BOUND_MEMBER:
5991 T = Context.BoundMemberTy;
5992 break;
5993 case PREDEF_TYPE_PSEUDO_OBJECT:
5994 T = Context.PseudoObjectTy;
5995 break;
5996 case PREDEF_TYPE_DEPENDENT_ID:
5997 T = Context.DependentTy;
5998 break;
5999 case PREDEF_TYPE_UNKNOWN_ANY:
6000 T = Context.UnknownAnyTy;
6001 break;
6002 case PREDEF_TYPE_NULLPTR_ID:
6003 T = Context.NullPtrTy;
6004 break;
6005 case PREDEF_TYPE_CHAR16_ID:
6006 T = Context.Char16Ty;
6007 break;
6008 case PREDEF_TYPE_CHAR32_ID:
6009 T = Context.Char32Ty;
6010 break;
6011 case PREDEF_TYPE_OBJC_ID:
6012 T = Context.ObjCBuiltinIdTy;
6013 break;
6014 case PREDEF_TYPE_OBJC_CLASS:
6015 T = Context.ObjCBuiltinClassTy;
6016 break;
6017 case PREDEF_TYPE_OBJC_SEL:
6018 T = Context.ObjCBuiltinSelTy;
6019 break;
6020 case PREDEF_TYPE_IMAGE1D_ID:
6021 T = Context.OCLImage1dTy;
6022 break;
6023 case PREDEF_TYPE_IMAGE1D_ARR_ID:
6024 T = Context.OCLImage1dArrayTy;
6025 break;
6026 case PREDEF_TYPE_IMAGE1D_BUFF_ID:
6027 T = Context.OCLImage1dBufferTy;
6028 break;
6029 case PREDEF_TYPE_IMAGE2D_ID:
6030 T = Context.OCLImage2dTy;
6031 break;
6032 case PREDEF_TYPE_IMAGE2D_ARR_ID:
6033 T = Context.OCLImage2dArrayTy;
6034 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006035 case PREDEF_TYPE_IMAGE2D_DEP_ID:
6036 T = Context.OCLImage2dDepthTy;
6037 break;
6038 case PREDEF_TYPE_IMAGE2D_ARR_DEP_ID:
6039 T = Context.OCLImage2dArrayDepthTy;
6040 break;
6041 case PREDEF_TYPE_IMAGE2D_MSAA_ID:
6042 T = Context.OCLImage2dMSAATy;
6043 break;
6044 case PREDEF_TYPE_IMAGE2D_ARR_MSAA_ID:
6045 T = Context.OCLImage2dArrayMSAATy;
6046 break;
6047 case PREDEF_TYPE_IMAGE2D_MSAA_DEP_ID:
6048 T = Context.OCLImage2dMSAADepthTy;
6049 break;
6050 case PREDEF_TYPE_IMAGE2D_ARR_MSAA_DEPTH_ID:
6051 T = Context.OCLImage2dArrayMSAADepthTy;
6052 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006053 case PREDEF_TYPE_IMAGE3D_ID:
6054 T = Context.OCLImage3dTy;
6055 break;
6056 case PREDEF_TYPE_SAMPLER_ID:
6057 T = Context.OCLSamplerTy;
6058 break;
6059 case PREDEF_TYPE_EVENT_ID:
6060 T = Context.OCLEventTy;
6061 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006062 case PREDEF_TYPE_CLK_EVENT_ID:
6063 T = Context.OCLClkEventTy;
6064 break;
6065 case PREDEF_TYPE_QUEUE_ID:
6066 T = Context.OCLQueueTy;
6067 break;
6068 case PREDEF_TYPE_NDRANGE_ID:
6069 T = Context.OCLNDRangeTy;
6070 break;
6071 case PREDEF_TYPE_RESERVE_ID_ID:
6072 T = Context.OCLReserveIDTy;
6073 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006074 case PREDEF_TYPE_AUTO_DEDUCT:
6075 T = Context.getAutoDeductType();
6076 break;
6077
6078 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6079 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006080 break;
6081
6082 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6083 T = Context.ARCUnbridgedCastTy;
6084 break;
6085
Guy Benyei11169dd2012-12-18 14:30:41 +00006086 case PREDEF_TYPE_BUILTIN_FN:
6087 T = Context.BuiltinFnTy;
6088 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006089
6090 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6091 T = Context.OMPArraySectionTy;
6092 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006093 }
6094
6095 assert(!T.isNull() && "Unknown predefined type");
6096 return T.withFastQualifiers(FastQuals);
6097 }
6098
6099 Index -= NUM_PREDEF_TYPE_IDS;
6100 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6101 if (TypesLoaded[Index].isNull()) {
6102 TypesLoaded[Index] = readTypeRecord(Index);
6103 if (TypesLoaded[Index].isNull())
6104 return QualType();
6105
6106 TypesLoaded[Index]->setFromAST();
6107 if (DeserializationListener)
6108 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6109 TypesLoaded[Index]);
6110 }
6111
6112 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6113}
6114
6115QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6116 return GetType(getGlobalTypeID(F, LocalID));
6117}
6118
6119serialization::TypeID
6120ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6121 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6122 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6123
6124 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6125 return LocalID;
6126
6127 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6128 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6129 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6130
6131 unsigned GlobalIndex = LocalIndex + I->second;
6132 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6133}
6134
6135TemplateArgumentLocInfo
6136ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6137 TemplateArgument::ArgKind Kind,
6138 const RecordData &Record,
6139 unsigned &Index) {
6140 switch (Kind) {
6141 case TemplateArgument::Expression:
6142 return ReadExpr(F);
6143 case TemplateArgument::Type:
6144 return GetTypeSourceInfo(F, Record, Index);
6145 case TemplateArgument::Template: {
6146 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6147 Index);
6148 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6149 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6150 SourceLocation());
6151 }
6152 case TemplateArgument::TemplateExpansion: {
6153 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6154 Index);
6155 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6156 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6157 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6158 EllipsisLoc);
6159 }
6160 case TemplateArgument::Null:
6161 case TemplateArgument::Integral:
6162 case TemplateArgument::Declaration:
6163 case TemplateArgument::NullPtr:
6164 case TemplateArgument::Pack:
6165 // FIXME: Is this right?
6166 return TemplateArgumentLocInfo();
6167 }
6168 llvm_unreachable("unexpected template argument loc");
6169}
6170
6171TemplateArgumentLoc
6172ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6173 const RecordData &Record, unsigned &Index) {
6174 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6175
6176 if (Arg.getKind() == TemplateArgument::Expression) {
6177 if (Record[Index++]) // bool InfoHasSameExpr.
6178 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6179 }
6180 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6181 Record, Index));
6182}
6183
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006184const ASTTemplateArgumentListInfo*
6185ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6186 const RecordData &Record,
6187 unsigned &Index) {
6188 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6189 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6190 unsigned NumArgsAsWritten = Record[Index++];
6191 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6192 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6193 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6194 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6195}
6196
Guy Benyei11169dd2012-12-18 14:30:41 +00006197Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6198 return GetDecl(ID);
6199}
6200
Richard Smith50895422015-01-31 03:04:55 +00006201template<typename TemplateSpecializationDecl>
6202static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6203 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6204 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6205}
6206
Richard Smith053f6c62014-05-16 23:01:30 +00006207void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006208 if (NumCurrentElementsDeserializing) {
6209 // We arrange to not care about the complete redeclaration chain while we're
6210 // deserializing. Just remember that the AST has marked this one as complete
6211 // but that it's not actually complete yet, so we know we still need to
6212 // complete it later.
6213 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6214 return;
6215 }
6216
Richard Smith053f6c62014-05-16 23:01:30 +00006217 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6218
Richard Smith053f6c62014-05-16 23:01:30 +00006219 // If this is a named declaration, complete it by looking it up
6220 // within its context.
6221 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006222 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006223 // all mergeable entities within it.
6224 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6225 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6226 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006227 if (!getContext().getLangOpts().CPlusPlus &&
6228 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006229 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006230 // the identifier instead. (For C++ modules, we don't store decls
6231 // in the serialized identifier table, so we do the lookup in the TU.)
6232 auto *II = Name.getAsIdentifierInfo();
6233 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006234 if (II->isOutOfDate())
6235 updateOutOfDateIdentifier(*II);
6236 } else
6237 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006238 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006239 // Find all declarations of this kind from the relevant context.
6240 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6241 auto *DC = cast<DeclContext>(DCDecl);
6242 SmallVector<Decl*, 8> Decls;
6243 FindExternalLexicalDecls(
6244 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6245 }
Richard Smith053f6c62014-05-16 23:01:30 +00006246 }
6247 }
Richard Smith50895422015-01-31 03:04:55 +00006248
6249 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6250 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6251 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6252 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6253 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6254 if (auto *Template = FD->getPrimaryTemplate())
6255 Template->LoadLazySpecializations();
6256 }
Richard Smith053f6c62014-05-16 23:01:30 +00006257}
6258
Richard Smithc2bb8182015-03-24 06:36:48 +00006259uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
6260 const RecordData &Record,
6261 unsigned &Idx) {
6262 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
6263 Error("malformed AST file: missing C++ ctor initializers");
6264 return 0;
6265 }
6266
6267 unsigned LocalID = Record[Idx++];
6268 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6269}
6270
6271CXXCtorInitializer **
6272ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6273 RecordLocation Loc = getLocalBitOffset(Offset);
6274 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6275 SavedStreamPosition SavedPosition(Cursor);
6276 Cursor.JumpToBit(Loc.Offset);
6277 ReadingKindTracker ReadingKind(Read_Decl, *this);
6278
6279 RecordData Record;
6280 unsigned Code = Cursor.ReadCode();
6281 unsigned RecCode = Cursor.readRecord(Code, Record);
6282 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6283 Error("malformed AST file: missing C++ ctor initializers");
6284 return nullptr;
6285 }
6286
6287 unsigned Idx = 0;
6288 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6289}
6290
Richard Smithcd45dbc2014-04-19 03:48:30 +00006291uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6292 const RecordData &Record,
6293 unsigned &Idx) {
6294 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6295 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006296 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006297 }
6298
Guy Benyei11169dd2012-12-18 14:30:41 +00006299 unsigned LocalID = Record[Idx++];
6300 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6301}
6302
6303CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6304 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006305 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006306 SavedStreamPosition SavedPosition(Cursor);
6307 Cursor.JumpToBit(Loc.Offset);
6308 ReadingKindTracker ReadingKind(Read_Decl, *this);
6309 RecordData Record;
6310 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006311 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006312 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006313 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006314 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006315 }
6316
6317 unsigned Idx = 0;
6318 unsigned NumBases = Record[Idx++];
6319 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6320 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6321 for (unsigned I = 0; I != NumBases; ++I)
6322 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6323 return Bases;
6324}
6325
6326serialization::DeclID
6327ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6328 if (LocalID < NUM_PREDEF_DECL_IDS)
6329 return LocalID;
6330
6331 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6332 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6333 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6334
6335 return LocalID + I->second;
6336}
6337
6338bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6339 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006340 // Predefined decls aren't from any module.
6341 if (ID < NUM_PREDEF_DECL_IDS)
6342 return false;
6343
Richard Smithbcda1a92015-07-12 23:51:20 +00006344 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6345 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006346}
6347
Douglas Gregor9f782892013-01-21 15:25:38 +00006348ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006349 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006350 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006351 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6352 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6353 return I->second;
6354}
6355
6356SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6357 if (ID < NUM_PREDEF_DECL_IDS)
6358 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006359
Guy Benyei11169dd2012-12-18 14:30:41 +00006360 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6361
6362 if (Index > DeclsLoaded.size()) {
6363 Error("declaration ID out-of-range for AST file");
6364 return SourceLocation();
6365 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006366
Guy Benyei11169dd2012-12-18 14:30:41 +00006367 if (Decl *D = DeclsLoaded[Index])
6368 return D->getLocation();
6369
6370 unsigned RawLocation = 0;
6371 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6372 return ReadSourceLocation(*Rec.F, RawLocation);
6373}
6374
Richard Smithfe620d22015-03-05 23:24:12 +00006375static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6376 switch (ID) {
6377 case PREDEF_DECL_NULL_ID:
6378 return nullptr;
6379
6380 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6381 return Context.getTranslationUnitDecl();
6382
6383 case PREDEF_DECL_OBJC_ID_ID:
6384 return Context.getObjCIdDecl();
6385
6386 case PREDEF_DECL_OBJC_SEL_ID:
6387 return Context.getObjCSelDecl();
6388
6389 case PREDEF_DECL_OBJC_CLASS_ID:
6390 return Context.getObjCClassDecl();
6391
6392 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6393 return Context.getObjCProtocolDecl();
6394
6395 case PREDEF_DECL_INT_128_ID:
6396 return Context.getInt128Decl();
6397
6398 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6399 return Context.getUInt128Decl();
6400
6401 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6402 return Context.getObjCInstanceTypeDecl();
6403
6404 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6405 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006406
Richard Smith9b88a4c2015-07-27 05:40:23 +00006407 case PREDEF_DECL_VA_LIST_TAG:
6408 return Context.getVaListTagDecl();
6409
Charles Davisc7d5c942015-09-17 20:55:33 +00006410 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6411 return Context.getBuiltinMSVaListDecl();
6412
Richard Smithf19e1272015-03-07 00:04:49 +00006413 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6414 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006415 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006416 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006417}
6418
Richard Smithcd45dbc2014-04-19 03:48:30 +00006419Decl *ASTReader::GetExistingDecl(DeclID ID) {
6420 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006421 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6422 if (D) {
6423 // Track that we have merged the declaration with ID \p ID into the
6424 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006425 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006426 if (Merged.empty())
6427 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006428 }
Richard Smithfe620d22015-03-05 23:24:12 +00006429 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006430 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006431
Guy Benyei11169dd2012-12-18 14:30:41 +00006432 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6433
6434 if (Index >= DeclsLoaded.size()) {
6435 assert(0 && "declaration ID out-of-range for AST file");
6436 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006437 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006438 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006439
6440 return DeclsLoaded[Index];
6441}
6442
6443Decl *ASTReader::GetDecl(DeclID ID) {
6444 if (ID < NUM_PREDEF_DECL_IDS)
6445 return GetExistingDecl(ID);
6446
6447 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6448
6449 if (Index >= DeclsLoaded.size()) {
6450 assert(0 && "declaration ID out-of-range for AST file");
6451 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006452 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006453 }
6454
Guy Benyei11169dd2012-12-18 14:30:41 +00006455 if (!DeclsLoaded[Index]) {
6456 ReadDeclRecord(ID);
6457 if (DeserializationListener)
6458 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6459 }
6460
6461 return DeclsLoaded[Index];
6462}
6463
6464DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6465 DeclID GlobalID) {
6466 if (GlobalID < NUM_PREDEF_DECL_IDS)
6467 return GlobalID;
6468
6469 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6470 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6471 ModuleFile *Owner = I->second;
6472
6473 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6474 = M.GlobalToLocalDeclIDs.find(Owner);
6475 if (Pos == M.GlobalToLocalDeclIDs.end())
6476 return 0;
6477
6478 return GlobalID - Owner->BaseDeclID + Pos->second;
6479}
6480
6481serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6482 const RecordData &Record,
6483 unsigned &Idx) {
6484 if (Idx >= Record.size()) {
6485 Error("Corrupted AST file");
6486 return 0;
6487 }
6488
6489 return getGlobalDeclID(F, Record[Idx++]);
6490}
6491
6492/// \brief Resolve the offset of a statement into a statement.
6493///
6494/// This operation will read a new statement from the external
6495/// source each time it is called, and is meant to be used via a
6496/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6497Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6498 // Switch case IDs are per Decl.
6499 ClearSwitchCaseIDs();
6500
6501 // Offset here is a global offset across the entire chain.
6502 RecordLocation Loc = getLocalBitOffset(Offset);
6503 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6504 return ReadStmtFromStream(*Loc.F);
6505}
6506
Richard Smith3cb15722015-08-05 22:41:45 +00006507void ASTReader::FindExternalLexicalDecls(
6508 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6509 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006510 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6511
Richard Smith9ccdd932015-08-06 22:14:12 +00006512 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006513 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6514 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6515 auto K = (Decl::Kind)+LexicalDecls[I];
6516 if (!IsKindWeWant(K))
6517 continue;
6518
6519 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6520
6521 // Don't add predefined declarations to the lexical context more
6522 // than once.
6523 if (ID < NUM_PREDEF_DECL_IDS) {
6524 if (PredefsVisited[ID])
6525 continue;
6526
6527 PredefsVisited[ID] = true;
6528 }
6529
6530 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006531 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006532 if (!DC->isDeclInLexicalTraversal(D))
6533 Decls.push_back(D);
6534 }
6535 }
6536 };
6537
6538 if (isa<TranslationUnitDecl>(DC)) {
6539 for (auto Lexical : TULexicalDecls)
6540 Visit(Lexical.first, Lexical.second);
6541 } else {
6542 auto I = LexicalDecls.find(DC);
6543 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006544 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006545 }
6546
Guy Benyei11169dd2012-12-18 14:30:41 +00006547 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006548}
6549
6550namespace {
6551
6552class DeclIDComp {
6553 ASTReader &Reader;
6554 ModuleFile &Mod;
6555
6556public:
6557 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6558
6559 bool operator()(LocalDeclID L, LocalDeclID R) const {
6560 SourceLocation LHS = getLocation(L);
6561 SourceLocation RHS = getLocation(R);
6562 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6563 }
6564
6565 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6566 SourceLocation RHS = getLocation(R);
6567 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6568 }
6569
6570 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6571 SourceLocation LHS = getLocation(L);
6572 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6573 }
6574
6575 SourceLocation getLocation(LocalDeclID ID) const {
6576 return Reader.getSourceManager().getFileLoc(
6577 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6578 }
6579};
6580
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006581}
Guy Benyei11169dd2012-12-18 14:30:41 +00006582
6583void ASTReader::FindFileRegionDecls(FileID File,
6584 unsigned Offset, unsigned Length,
6585 SmallVectorImpl<Decl *> &Decls) {
6586 SourceManager &SM = getSourceManager();
6587
6588 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6589 if (I == FileDeclIDs.end())
6590 return;
6591
6592 FileDeclsInfo &DInfo = I->second;
6593 if (DInfo.Decls.empty())
6594 return;
6595
6596 SourceLocation
6597 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6598 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6599
6600 DeclIDComp DIDComp(*this, *DInfo.Mod);
6601 ArrayRef<serialization::LocalDeclID>::iterator
6602 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6603 BeginLoc, DIDComp);
6604 if (BeginIt != DInfo.Decls.begin())
6605 --BeginIt;
6606
6607 // If we are pointing at a top-level decl inside an objc container, we need
6608 // to backtrack until we find it otherwise we will fail to report that the
6609 // region overlaps with an objc container.
6610 while (BeginIt != DInfo.Decls.begin() &&
6611 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6612 ->isTopLevelDeclInObjCContainer())
6613 --BeginIt;
6614
6615 ArrayRef<serialization::LocalDeclID>::iterator
6616 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6617 EndLoc, DIDComp);
6618 if (EndIt != DInfo.Decls.end())
6619 ++EndIt;
6620
6621 for (ArrayRef<serialization::LocalDeclID>::iterator
6622 DIt = BeginIt; DIt != EndIt; ++DIt)
6623 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6624}
6625
Richard Smith9ce12e32013-02-07 03:30:24 +00006626bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006627ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6628 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006629 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006630 "DeclContext has no visible decls in storage");
6631 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006632 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006633
Richard Smithd88a7f12015-09-01 20:35:42 +00006634 auto It = Lookups.find(DC);
6635 if (It == Lookups.end())
6636 return false;
6637
Richard Smith8c913ec2014-08-14 02:21:01 +00006638 Deserializing LookupResults(this);
6639
Richard Smithd88a7f12015-09-01 20:35:42 +00006640 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006641 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006642 for (DeclID ID : It->second.Table.find(Name)) {
6643 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6644 if (ND->getDeclName() == Name)
6645 Decls.push_back(ND);
6646 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006647
Guy Benyei11169dd2012-12-18 14:30:41 +00006648 ++NumVisibleDeclContextsRead;
6649 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006650 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006651}
6652
Guy Benyei11169dd2012-12-18 14:30:41 +00006653void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6654 if (!DC->hasExternalVisibleStorage())
6655 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006656
6657 auto It = Lookups.find(DC);
6658 assert(It != Lookups.end() &&
6659 "have external visible storage but no lookup tables");
6660
Craig Topper79be4cd2013-07-05 04:33:53 +00006661 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006662
Richard Smithd88a7f12015-09-01 20:35:42 +00006663 for (DeclID ID : It->second.Table.findAll()) {
6664 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6665 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006666 }
6667
Guy Benyei11169dd2012-12-18 14:30:41 +00006668 ++NumVisibleDeclContextsRead;
6669
Craig Topper79be4cd2013-07-05 04:33:53 +00006670 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006671 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6672 }
6673 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6674}
6675
Richard Smithd88a7f12015-09-01 20:35:42 +00006676const serialization::reader::DeclContextLookupTable *
6677ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6678 auto I = Lookups.find(Primary);
6679 return I == Lookups.end() ? nullptr : &I->second;
6680}
6681
Guy Benyei11169dd2012-12-18 14:30:41 +00006682/// \brief Under non-PCH compilation the consumer receives the objc methods
6683/// before receiving the implementation, and codegen depends on this.
6684/// We simulate this by deserializing and passing to consumer the methods of the
6685/// implementation before passing the deserialized implementation decl.
6686static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6687 ASTConsumer *Consumer) {
6688 assert(ImplD && Consumer);
6689
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006690 for (auto *I : ImplD->methods())
6691 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006692
6693 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6694}
6695
6696void ASTReader::PassInterestingDeclsToConsumer() {
6697 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006698
6699 if (PassingDeclsToConsumer)
6700 return;
6701
6702 // Guard variable to avoid recursively redoing the process of passing
6703 // decls to consumer.
6704 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6705 true);
6706
Richard Smith9e2341d2015-03-23 03:25:59 +00006707 // Ensure that we've loaded all potentially-interesting declarations
6708 // that need to be eagerly loaded.
6709 for (auto ID : EagerlyDeserializedDecls)
6710 GetDecl(ID);
6711 EagerlyDeserializedDecls.clear();
6712
Guy Benyei11169dd2012-12-18 14:30:41 +00006713 while (!InterestingDecls.empty()) {
6714 Decl *D = InterestingDecls.front();
6715 InterestingDecls.pop_front();
6716
6717 PassInterestingDeclToConsumer(D);
6718 }
6719}
6720
6721void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6722 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6723 PassObjCImplDeclToConsumer(ImplD, Consumer);
6724 else
6725 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6726}
6727
6728void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6729 this->Consumer = Consumer;
6730
Richard Smith9e2341d2015-03-23 03:25:59 +00006731 if (Consumer)
6732 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006733
6734 if (DeserializationListener)
6735 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006736}
6737
6738void ASTReader::PrintStats() {
6739 std::fprintf(stderr, "*** AST File Statistics:\n");
6740
6741 unsigned NumTypesLoaded
6742 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6743 QualType());
6744 unsigned NumDeclsLoaded
6745 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006746 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006747 unsigned NumIdentifiersLoaded
6748 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6749 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006750 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006751 unsigned NumMacrosLoaded
6752 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6753 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006754 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006755 unsigned NumSelectorsLoaded
6756 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6757 SelectorsLoaded.end(),
6758 Selector());
6759
6760 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6761 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6762 NumSLocEntriesRead, TotalNumSLocEntries,
6763 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6764 if (!TypesLoaded.empty())
6765 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6766 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6767 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6768 if (!DeclsLoaded.empty())
6769 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6770 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6771 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6772 if (!IdentifiersLoaded.empty())
6773 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6774 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6775 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6776 if (!MacrosLoaded.empty())
6777 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6778 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6779 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6780 if (!SelectorsLoaded.empty())
6781 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6782 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6783 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6784 if (TotalNumStatements)
6785 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6786 NumStatementsRead, TotalNumStatements,
6787 ((float)NumStatementsRead/TotalNumStatements * 100));
6788 if (TotalNumMacros)
6789 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6790 NumMacrosRead, TotalNumMacros,
6791 ((float)NumMacrosRead/TotalNumMacros * 100));
6792 if (TotalLexicalDeclContexts)
6793 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6794 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6795 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6796 * 100));
6797 if (TotalVisibleDeclContexts)
6798 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6799 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6800 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6801 * 100));
6802 if (TotalNumMethodPoolEntries) {
6803 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6804 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6805 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6806 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006807 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006808 if (NumMethodPoolLookups) {
6809 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6810 NumMethodPoolHits, NumMethodPoolLookups,
6811 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6812 }
6813 if (NumMethodPoolTableLookups) {
6814 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6815 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6816 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6817 * 100.0));
6818 }
6819
Douglas Gregor00a50f72013-01-25 00:38:33 +00006820 if (NumIdentifierLookupHits) {
6821 std::fprintf(stderr,
6822 " %u / %u identifier table lookups succeeded (%f%%)\n",
6823 NumIdentifierLookupHits, NumIdentifierLookups,
6824 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6825 }
6826
Douglas Gregore060e572013-01-25 01:03:03 +00006827 if (GlobalIndex) {
6828 std::fprintf(stderr, "\n");
6829 GlobalIndex->printStats();
6830 }
6831
Guy Benyei11169dd2012-12-18 14:30:41 +00006832 std::fprintf(stderr, "\n");
6833 dump();
6834 std::fprintf(stderr, "\n");
6835}
6836
6837template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6838static void
6839dumpModuleIDMap(StringRef Name,
6840 const ContinuousRangeMap<Key, ModuleFile *,
6841 InitialCapacity> &Map) {
6842 if (Map.begin() == Map.end())
6843 return;
6844
6845 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6846 llvm::errs() << Name << ":\n";
6847 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6848 I != IEnd; ++I) {
6849 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6850 << "\n";
6851 }
6852}
6853
6854void ASTReader::dump() {
6855 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6856 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6857 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6858 dumpModuleIDMap("Global type map", GlobalTypeMap);
6859 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6860 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6861 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6862 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6863 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6864 dumpModuleIDMap("Global preprocessed entity map",
6865 GlobalPreprocessedEntityMap);
6866
6867 llvm::errs() << "\n*** PCH/Modules Loaded:";
6868 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6869 MEnd = ModuleMgr.end();
6870 M != MEnd; ++M)
6871 (*M)->dump();
6872}
6873
6874/// Return the amount of memory used by memory buffers, breaking down
6875/// by heap-backed versus mmap'ed memory.
6876void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6877 for (ModuleConstIterator I = ModuleMgr.begin(),
6878 E = ModuleMgr.end(); I != E; ++I) {
6879 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6880 size_t bytes = buf->getBufferSize();
6881 switch (buf->getBufferKind()) {
6882 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6883 sizes.malloc_bytes += bytes;
6884 break;
6885 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6886 sizes.mmap_bytes += bytes;
6887 break;
6888 }
6889 }
6890 }
6891}
6892
6893void ASTReader::InitializeSema(Sema &S) {
6894 SemaObj = &S;
6895 S.addExternalSource(this);
6896
6897 // Makes sure any declarations that were deserialized "too early"
6898 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006899 for (uint64_t ID : PreloadedDeclIDs) {
6900 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6901 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006902 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006903 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006904
Richard Smith3d8e97e2013-10-18 06:54:39 +00006905 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006906 if (!FPPragmaOptions.empty()) {
6907 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6908 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6909 }
6910
Richard Smith3d8e97e2013-10-18 06:54:39 +00006911 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006912 if (!OpenCLExtensions.empty()) {
6913 unsigned I = 0;
6914#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6915#include "clang/Basic/OpenCLExtensions.def"
6916
6917 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6918 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006919
6920 UpdateSema();
6921}
6922
6923void ASTReader::UpdateSema() {
6924 assert(SemaObj && "no Sema to update");
6925
6926 // Load the offsets of the declarations that Sema references.
6927 // They will be lazily deserialized when needed.
6928 if (!SemaDeclRefs.empty()) {
6929 assert(SemaDeclRefs.size() % 2 == 0);
6930 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6931 if (!SemaObj->StdNamespace)
6932 SemaObj->StdNamespace = SemaDeclRefs[I];
6933 if (!SemaObj->StdBadAlloc)
6934 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6935 }
6936 SemaDeclRefs.clear();
6937 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006938
6939 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6940 // encountered the pragma in the source.
6941 if(OptimizeOffPragmaLocation.isValid())
6942 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006943}
6944
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006945IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006946 // Note that we are loading an identifier.
6947 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006948
Douglas Gregor7211ac12013-01-25 23:32:03 +00006949 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006950 NumIdentifierLookups,
6951 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006952
6953 // We don't need to do identifier table lookups in C++ modules (we preload
6954 // all interesting declarations, and don't need to use the scope for name
6955 // lookups). Perform the lookup in PCH files, though, since we don't build
6956 // a complete initial identifier table if we're carrying on from a PCH.
6957 if (Context.getLangOpts().CPlusPlus) {
6958 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006959 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006960 break;
6961 } else {
6962 // If there is a global index, look there first to determine which modules
6963 // provably do not have any results for this identifier.
6964 GlobalModuleIndex::HitSet Hits;
6965 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6966 if (!loadGlobalIndex()) {
6967 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6968 HitsPtr = &Hits;
6969 }
6970 }
6971
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006972 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006973 }
6974
Guy Benyei11169dd2012-12-18 14:30:41 +00006975 IdentifierInfo *II = Visitor.getIdentifierInfo();
6976 markIdentifierUpToDate(II);
6977 return II;
6978}
6979
6980namespace clang {
6981 /// \brief An identifier-lookup iterator that enumerates all of the
6982 /// identifiers stored within a set of AST files.
6983 class ASTIdentifierIterator : public IdentifierIterator {
6984 /// \brief The AST reader whose identifiers are being enumerated.
6985 const ASTReader &Reader;
6986
6987 /// \brief The current index into the chain of AST files stored in
6988 /// the AST reader.
6989 unsigned Index;
6990
6991 /// \brief The current position within the identifier lookup table
6992 /// of the current AST file.
6993 ASTIdentifierLookupTable::key_iterator Current;
6994
6995 /// \brief The end position within the identifier lookup table of
6996 /// the current AST file.
6997 ASTIdentifierLookupTable::key_iterator End;
6998
6999 public:
7000 explicit ASTIdentifierIterator(const ASTReader &Reader);
7001
Craig Topper3e89dfe2014-03-13 02:13:41 +00007002 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007003 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007004}
Guy Benyei11169dd2012-12-18 14:30:41 +00007005
7006ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7007 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7008 ASTIdentifierLookupTable *IdTable
7009 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7010 Current = IdTable->key_begin();
7011 End = IdTable->key_end();
7012}
7013
7014StringRef ASTIdentifierIterator::Next() {
7015 while (Current == End) {
7016 // If we have exhausted all of our AST files, we're done.
7017 if (Index == 0)
7018 return StringRef();
7019
7020 --Index;
7021 ASTIdentifierLookupTable *IdTable
7022 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7023 IdentifierLookupTable;
7024 Current = IdTable->key_begin();
7025 End = IdTable->key_end();
7026 }
7027
7028 // We have any identifiers remaining in the current AST file; return
7029 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007030 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007031 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007032 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007033}
7034
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007035IdentifierIterator *ASTReader::getIdentifiers() {
7036 if (!loadGlobalIndex())
7037 return GlobalIndex->createIdentifierIterator();
7038
Guy Benyei11169dd2012-12-18 14:30:41 +00007039 return new ASTIdentifierIterator(*this);
7040}
7041
7042namespace clang { namespace serialization {
7043 class ReadMethodPoolVisitor {
7044 ASTReader &Reader;
7045 Selector Sel;
7046 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007047 unsigned InstanceBits;
7048 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007049 bool InstanceHasMoreThanOneDecl;
7050 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007051 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7052 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007053
7054 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007055 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007056 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007057 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007058 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7059 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007060
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007061 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007062 if (!M.SelectorLookupTable)
7063 return false;
7064
7065 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007066 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007067 return true;
7068
Richard Smithbdf2d932015-07-30 03:37:16 +00007069 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007070 ASTSelectorLookupTable *PoolTable
7071 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007072 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007073 if (Pos == PoolTable->end())
7074 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007075
Richard Smithbdf2d932015-07-30 03:37:16 +00007076 ++Reader.NumMethodPoolTableHits;
7077 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007078 // FIXME: Not quite happy with the statistics here. We probably should
7079 // disable this tracking when called via LoadSelector.
7080 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007081 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007082 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007083 if (Reader.DeserializationListener)
7084 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007085
Richard Smithbdf2d932015-07-30 03:37:16 +00007086 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7087 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7088 InstanceBits = Data.InstanceBits;
7089 FactoryBits = Data.FactoryBits;
7090 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7091 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007092 return true;
7093 }
7094
7095 /// \brief Retrieve the instance methods found by this visitor.
7096 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7097 return InstanceMethods;
7098 }
7099
7100 /// \brief Retrieve the instance methods found by this visitor.
7101 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7102 return FactoryMethods;
7103 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007104
7105 unsigned getInstanceBits() const { return InstanceBits; }
7106 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007107 bool instanceHasMoreThanOneDecl() const {
7108 return InstanceHasMoreThanOneDecl;
7109 }
7110 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007111 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007112} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00007113
7114/// \brief Add the given set of methods to the method list.
7115static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7116 ObjCMethodList &List) {
7117 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7118 S.addMethodToGlobalList(&List, Methods[I]);
7119 }
7120}
7121
7122void ASTReader::ReadMethodPool(Selector Sel) {
7123 // Get the selector generation and update it to the current generation.
7124 unsigned &Generation = SelectorGeneration[Sel];
7125 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007126 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007127
7128 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007129 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007130 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007131 ModuleMgr.visit(Visitor);
7132
Guy Benyei11169dd2012-12-18 14:30:41 +00007133 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007134 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007135 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007136
7137 ++NumMethodPoolHits;
7138
Guy Benyei11169dd2012-12-18 14:30:41 +00007139 if (!getSema())
7140 return;
7141
7142 Sema &S = *getSema();
7143 Sema::GlobalMethodPool::iterator Pos
7144 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007145
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007146 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007147 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007148 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007149 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007150
7151 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7152 // when building a module we keep every method individually and may need to
7153 // update hasMoreThanOneDecl as we add the methods.
7154 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7155 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007156}
7157
7158void ASTReader::ReadKnownNamespaces(
7159 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7160 Namespaces.clear();
7161
7162 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7163 if (NamespaceDecl *Namespace
7164 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7165 Namespaces.push_back(Namespace);
7166 }
7167}
7168
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007169void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007170 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007171 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7172 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007173 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007174 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007175 Undefined.insert(std::make_pair(D, Loc));
7176 }
7177}
Nick Lewycky8334af82013-01-26 00:35:08 +00007178
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007179void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7180 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7181 Exprs) {
7182 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7183 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7184 uint64_t Count = DelayedDeleteExprs[Idx++];
7185 for (uint64_t C = 0; C < Count; ++C) {
7186 SourceLocation DeleteLoc =
7187 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7188 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7189 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7190 }
7191 }
7192}
7193
Guy Benyei11169dd2012-12-18 14:30:41 +00007194void ASTReader::ReadTentativeDefinitions(
7195 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7196 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7197 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7198 if (Var)
7199 TentativeDefs.push_back(Var);
7200 }
7201 TentativeDefinitions.clear();
7202}
7203
7204void ASTReader::ReadUnusedFileScopedDecls(
7205 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7206 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7207 DeclaratorDecl *D
7208 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7209 if (D)
7210 Decls.push_back(D);
7211 }
7212 UnusedFileScopedDecls.clear();
7213}
7214
7215void ASTReader::ReadDelegatingConstructors(
7216 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7217 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7218 CXXConstructorDecl *D
7219 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7220 if (D)
7221 Decls.push_back(D);
7222 }
7223 DelegatingCtorDecls.clear();
7224}
7225
7226void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7227 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7228 TypedefNameDecl *D
7229 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7230 if (D)
7231 Decls.push_back(D);
7232 }
7233 ExtVectorDecls.clear();
7234}
7235
Nico Weber72889432014-09-06 01:25:55 +00007236void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7237 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7238 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7239 ++I) {
7240 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7241 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7242 if (D)
7243 Decls.insert(D);
7244 }
7245 UnusedLocalTypedefNameCandidates.clear();
7246}
7247
Guy Benyei11169dd2012-12-18 14:30:41 +00007248void ASTReader::ReadReferencedSelectors(
7249 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7250 if (ReferencedSelectorsData.empty())
7251 return;
7252
7253 // If there are @selector references added them to its pool. This is for
7254 // implementation of -Wselector.
7255 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7256 unsigned I = 0;
7257 while (I < DataSize) {
7258 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7259 SourceLocation SelLoc
7260 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7261 Sels.push_back(std::make_pair(Sel, SelLoc));
7262 }
7263 ReferencedSelectorsData.clear();
7264}
7265
7266void ASTReader::ReadWeakUndeclaredIdentifiers(
7267 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7268 if (WeakUndeclaredIdentifiers.empty())
7269 return;
7270
7271 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7272 IdentifierInfo *WeakId
7273 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7274 IdentifierInfo *AliasId
7275 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7276 SourceLocation Loc
7277 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7278 bool Used = WeakUndeclaredIdentifiers[I++];
7279 WeakInfo WI(AliasId, Loc);
7280 WI.setUsed(Used);
7281 WeakIDs.push_back(std::make_pair(WeakId, WI));
7282 }
7283 WeakUndeclaredIdentifiers.clear();
7284}
7285
7286void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7287 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7288 ExternalVTableUse VT;
7289 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7290 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7291 VT.DefinitionRequired = VTableUses[Idx++];
7292 VTables.push_back(VT);
7293 }
7294
7295 VTableUses.clear();
7296}
7297
7298void ASTReader::ReadPendingInstantiations(
7299 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7300 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7301 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7302 SourceLocation Loc
7303 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7304
7305 Pending.push_back(std::make_pair(D, Loc));
7306 }
7307 PendingInstantiations.clear();
7308}
7309
Richard Smithe40f2ba2013-08-07 21:41:30 +00007310void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007311 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007312 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7313 /* In loop */) {
7314 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7315
7316 LateParsedTemplate *LT = new LateParsedTemplate;
7317 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7318
7319 ModuleFile *F = getOwningModuleFile(LT->D);
7320 assert(F && "No module");
7321
7322 unsigned TokN = LateParsedTemplates[Idx++];
7323 LT->Toks.reserve(TokN);
7324 for (unsigned T = 0; T < TokN; ++T)
7325 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7326
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007327 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007328 }
7329
7330 LateParsedTemplates.clear();
7331}
7332
Guy Benyei11169dd2012-12-18 14:30:41 +00007333void ASTReader::LoadSelector(Selector Sel) {
7334 // It would be complicated to avoid reading the methods anyway. So don't.
7335 ReadMethodPool(Sel);
7336}
7337
7338void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7339 assert(ID && "Non-zero identifier ID required");
7340 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7341 IdentifiersLoaded[ID - 1] = II;
7342 if (DeserializationListener)
7343 DeserializationListener->IdentifierRead(ID, II);
7344}
7345
7346/// \brief Set the globally-visible declarations associated with the given
7347/// identifier.
7348///
7349/// If the AST reader is currently in a state where the given declaration IDs
7350/// cannot safely be resolved, they are queued until it is safe to resolve
7351/// them.
7352///
7353/// \param II an IdentifierInfo that refers to one or more globally-visible
7354/// declarations.
7355///
7356/// \param DeclIDs the set of declaration IDs with the name @p II that are
7357/// visible at global scope.
7358///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007359/// \param Decls if non-null, this vector will be populated with the set of
7360/// deserialized declarations. These declarations will not be pushed into
7361/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007362void
7363ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7364 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007365 SmallVectorImpl<Decl *> *Decls) {
7366 if (NumCurrentElementsDeserializing && !Decls) {
7367 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007368 return;
7369 }
7370
7371 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007372 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007373 // Queue this declaration so that it will be added to the
7374 // translation unit scope and identifier's declaration chain
7375 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007376 PreloadedDeclIDs.push_back(DeclIDs[I]);
7377 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007378 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007379
7380 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7381
7382 // If we're simply supposed to record the declarations, do so now.
7383 if (Decls) {
7384 Decls->push_back(D);
7385 continue;
7386 }
7387
7388 // Introduce this declaration into the translation-unit scope
7389 // and add it to the declaration chain for this identifier, so
7390 // that (unqualified) name lookup will find it.
7391 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007392 }
7393}
7394
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007395IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007396 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007397 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007398
7399 if (IdentifiersLoaded.empty()) {
7400 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007401 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007402 }
7403
7404 ID -= 1;
7405 if (!IdentifiersLoaded[ID]) {
7406 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7407 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7408 ModuleFile *M = I->second;
7409 unsigned Index = ID - M->BaseIdentifierID;
7410 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7411
7412 // All of the strings in the AST file are preceded by a 16-bit length.
7413 // Extract that 16-bit length to avoid having to execute strlen().
7414 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7415 // unsigned integers. This is important to avoid integer overflow when
7416 // we cast them to 'unsigned'.
7417 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7418 unsigned StrLen = (((unsigned) StrLenPtr[0])
7419 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007420 IdentifiersLoaded[ID]
7421 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007422 if (DeserializationListener)
7423 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7424 }
7425
7426 return IdentifiersLoaded[ID];
7427}
7428
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007429IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7430 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007431}
7432
7433IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7434 if (LocalID < NUM_PREDEF_IDENT_IDS)
7435 return LocalID;
7436
7437 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7438 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7439 assert(I != M.IdentifierRemap.end()
7440 && "Invalid index into identifier index remap");
7441
7442 return LocalID + I->second;
7443}
7444
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007445MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007446 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007447 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007448
7449 if (MacrosLoaded.empty()) {
7450 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007451 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007452 }
7453
7454 ID -= NUM_PREDEF_MACRO_IDS;
7455 if (!MacrosLoaded[ID]) {
7456 GlobalMacroMapType::iterator I
7457 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7458 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7459 ModuleFile *M = I->second;
7460 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007461 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7462
7463 if (DeserializationListener)
7464 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7465 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007466 }
7467
7468 return MacrosLoaded[ID];
7469}
7470
7471MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7472 if (LocalID < NUM_PREDEF_MACRO_IDS)
7473 return LocalID;
7474
7475 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7476 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7477 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7478
7479 return LocalID + I->second;
7480}
7481
7482serialization::SubmoduleID
7483ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7484 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7485 return LocalID;
7486
7487 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7488 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7489 assert(I != M.SubmoduleRemap.end()
7490 && "Invalid index into submodule index remap");
7491
7492 return LocalID + I->second;
7493}
7494
7495Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7496 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7497 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007498 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007499 }
7500
7501 if (GlobalID > SubmodulesLoaded.size()) {
7502 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007503 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007504 }
7505
7506 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7507}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007508
7509Module *ASTReader::getModule(unsigned ID) {
7510 return getSubmodule(ID);
7511}
7512
Richard Smithd88a7f12015-09-01 20:35:42 +00007513ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7514 if (ID & 1) {
7515 // It's a module, look it up by submodule ID.
7516 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7517 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7518 } else {
7519 // It's a prefix (preamble, PCH, ...). Look it up by index.
7520 unsigned IndexFromEnd = ID >> 1;
7521 assert(IndexFromEnd && "got reference to unknown module file");
7522 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7523 }
7524}
7525
7526unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7527 if (!F)
7528 return 1;
7529
7530 // For a file representing a module, use the submodule ID of the top-level
7531 // module as the file ID. For any other kind of file, the number of such
7532 // files loaded beforehand will be the same on reload.
7533 // FIXME: Is this true even if we have an explicit module file and a PCH?
7534 if (F->isModule())
7535 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7536
7537 auto PCHModules = getModuleManager().pch_modules();
7538 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7539 assert(I != PCHModules.end() && "emitting reference to unknown file");
7540 return (I - PCHModules.end()) << 1;
7541}
7542
Adrian Prantl15bcf702015-06-30 17:39:43 +00007543llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7544ASTReader::getSourceDescriptor(unsigned ID) {
7545 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007546 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007547
7548 // If there is only a single PCH, return it instead.
7549 // Chained PCH are not suported.
7550 if (ModuleMgr.size() == 1) {
7551 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantlc6458d62015-09-19 00:10:32 +00007552 return ASTReader::ASTSourceDescriptor(
7553 MF.OriginalSourceFileName, MF.OriginalDir, MF.FileName, MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007554 }
7555 return None;
7556}
7557
Guy Benyei11169dd2012-12-18 14:30:41 +00007558Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7559 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7560}
7561
7562Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7563 if (ID == 0)
7564 return Selector();
7565
7566 if (ID > SelectorsLoaded.size()) {
7567 Error("selector ID out of range in AST file");
7568 return Selector();
7569 }
7570
Craig Toppera13603a2014-05-22 05:54:18 +00007571 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007572 // Load this selector from the selector table.
7573 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7574 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7575 ModuleFile &M = *I->second;
7576 ASTSelectorLookupTrait Trait(*this, M);
7577 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7578 SelectorsLoaded[ID - 1] =
7579 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7580 if (DeserializationListener)
7581 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7582 }
7583
7584 return SelectorsLoaded[ID - 1];
7585}
7586
7587Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7588 return DecodeSelector(ID);
7589}
7590
7591uint32_t ASTReader::GetNumExternalSelectors() {
7592 // ID 0 (the null selector) is considered an external selector.
7593 return getTotalNumSelectors() + 1;
7594}
7595
7596serialization::SelectorID
7597ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7598 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7599 return LocalID;
7600
7601 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7602 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7603 assert(I != M.SelectorRemap.end()
7604 && "Invalid index into selector index remap");
7605
7606 return LocalID + I->second;
7607}
7608
7609DeclarationName
7610ASTReader::ReadDeclarationName(ModuleFile &F,
7611 const RecordData &Record, unsigned &Idx) {
7612 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7613 switch (Kind) {
7614 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007615 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007616
7617 case DeclarationName::ObjCZeroArgSelector:
7618 case DeclarationName::ObjCOneArgSelector:
7619 case DeclarationName::ObjCMultiArgSelector:
7620 return DeclarationName(ReadSelector(F, Record, Idx));
7621
7622 case DeclarationName::CXXConstructorName:
7623 return Context.DeclarationNames.getCXXConstructorName(
7624 Context.getCanonicalType(readType(F, Record, Idx)));
7625
7626 case DeclarationName::CXXDestructorName:
7627 return Context.DeclarationNames.getCXXDestructorName(
7628 Context.getCanonicalType(readType(F, Record, Idx)));
7629
7630 case DeclarationName::CXXConversionFunctionName:
7631 return Context.DeclarationNames.getCXXConversionFunctionName(
7632 Context.getCanonicalType(readType(F, Record, Idx)));
7633
7634 case DeclarationName::CXXOperatorName:
7635 return Context.DeclarationNames.getCXXOperatorName(
7636 (OverloadedOperatorKind)Record[Idx++]);
7637
7638 case DeclarationName::CXXLiteralOperatorName:
7639 return Context.DeclarationNames.getCXXLiteralOperatorName(
7640 GetIdentifierInfo(F, Record, Idx));
7641
7642 case DeclarationName::CXXUsingDirective:
7643 return DeclarationName::getUsingDirectiveName();
7644 }
7645
7646 llvm_unreachable("Invalid NameKind!");
7647}
7648
7649void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7650 DeclarationNameLoc &DNLoc,
7651 DeclarationName Name,
7652 const RecordData &Record, unsigned &Idx) {
7653 switch (Name.getNameKind()) {
7654 case DeclarationName::CXXConstructorName:
7655 case DeclarationName::CXXDestructorName:
7656 case DeclarationName::CXXConversionFunctionName:
7657 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7658 break;
7659
7660 case DeclarationName::CXXOperatorName:
7661 DNLoc.CXXOperatorName.BeginOpNameLoc
7662 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7663 DNLoc.CXXOperatorName.EndOpNameLoc
7664 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7665 break;
7666
7667 case DeclarationName::CXXLiteralOperatorName:
7668 DNLoc.CXXLiteralOperatorName.OpNameLoc
7669 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7670 break;
7671
7672 case DeclarationName::Identifier:
7673 case DeclarationName::ObjCZeroArgSelector:
7674 case DeclarationName::ObjCOneArgSelector:
7675 case DeclarationName::ObjCMultiArgSelector:
7676 case DeclarationName::CXXUsingDirective:
7677 break;
7678 }
7679}
7680
7681void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7682 DeclarationNameInfo &NameInfo,
7683 const RecordData &Record, unsigned &Idx) {
7684 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7685 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7686 DeclarationNameLoc DNLoc;
7687 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7688 NameInfo.setInfo(DNLoc);
7689}
7690
7691void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7692 const RecordData &Record, unsigned &Idx) {
7693 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7694 unsigned NumTPLists = Record[Idx++];
7695 Info.NumTemplParamLists = NumTPLists;
7696 if (NumTPLists) {
7697 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7698 for (unsigned i=0; i != NumTPLists; ++i)
7699 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7700 }
7701}
7702
7703TemplateName
7704ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7705 unsigned &Idx) {
7706 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7707 switch (Kind) {
7708 case TemplateName::Template:
7709 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7710
7711 case TemplateName::OverloadedTemplate: {
7712 unsigned size = Record[Idx++];
7713 UnresolvedSet<8> Decls;
7714 while (size--)
7715 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7716
7717 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7718 }
7719
7720 case TemplateName::QualifiedTemplate: {
7721 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7722 bool hasTemplKeyword = Record[Idx++];
7723 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7724 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7725 }
7726
7727 case TemplateName::DependentTemplate: {
7728 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7729 if (Record[Idx++]) // isIdentifier
7730 return Context.getDependentTemplateName(NNS,
7731 GetIdentifierInfo(F, Record,
7732 Idx));
7733 return Context.getDependentTemplateName(NNS,
7734 (OverloadedOperatorKind)Record[Idx++]);
7735 }
7736
7737 case TemplateName::SubstTemplateTemplateParm: {
7738 TemplateTemplateParmDecl *param
7739 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7740 if (!param) return TemplateName();
7741 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7742 return Context.getSubstTemplateTemplateParm(param, replacement);
7743 }
7744
7745 case TemplateName::SubstTemplateTemplateParmPack: {
7746 TemplateTemplateParmDecl *Param
7747 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7748 if (!Param)
7749 return TemplateName();
7750
7751 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7752 if (ArgPack.getKind() != TemplateArgument::Pack)
7753 return TemplateName();
7754
7755 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7756 }
7757 }
7758
7759 llvm_unreachable("Unhandled template name kind!");
7760}
7761
Richard Smith2bb3c342015-08-09 01:05:31 +00007762TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7763 const RecordData &Record,
7764 unsigned &Idx,
7765 bool Canonicalize) {
7766 if (Canonicalize) {
7767 // The caller wants a canonical template argument. Sometimes the AST only
7768 // wants template arguments in canonical form (particularly as the template
7769 // argument lists of template specializations) so ensure we preserve that
7770 // canonical form across serialization.
7771 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7772 return Context.getCanonicalTemplateArgument(Arg);
7773 }
7774
Guy Benyei11169dd2012-12-18 14:30:41 +00007775 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7776 switch (Kind) {
7777 case TemplateArgument::Null:
7778 return TemplateArgument();
7779 case TemplateArgument::Type:
7780 return TemplateArgument(readType(F, Record, Idx));
7781 case TemplateArgument::Declaration: {
7782 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007783 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007784 }
7785 case TemplateArgument::NullPtr:
7786 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7787 case TemplateArgument::Integral: {
7788 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7789 QualType T = readType(F, Record, Idx);
7790 return TemplateArgument(Context, Value, T);
7791 }
7792 case TemplateArgument::Template:
7793 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7794 case TemplateArgument::TemplateExpansion: {
7795 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007796 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007797 if (unsigned NumExpansions = Record[Idx++])
7798 NumTemplateExpansions = NumExpansions - 1;
7799 return TemplateArgument(Name, NumTemplateExpansions);
7800 }
7801 case TemplateArgument::Expression:
7802 return TemplateArgument(ReadExpr(F));
7803 case TemplateArgument::Pack: {
7804 unsigned NumArgs = Record[Idx++];
7805 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7806 for (unsigned I = 0; I != NumArgs; ++I)
7807 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007808 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007809 }
7810 }
7811
7812 llvm_unreachable("Unhandled template argument kind!");
7813}
7814
7815TemplateParameterList *
7816ASTReader::ReadTemplateParameterList(ModuleFile &F,
7817 const RecordData &Record, unsigned &Idx) {
7818 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7819 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7820 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7821
7822 unsigned NumParams = Record[Idx++];
7823 SmallVector<NamedDecl *, 16> Params;
7824 Params.reserve(NumParams);
7825 while (NumParams--)
7826 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7827
7828 TemplateParameterList* TemplateParams =
7829 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7830 Params.data(), Params.size(), RAngleLoc);
7831 return TemplateParams;
7832}
7833
7834void
7835ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007836ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007837 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007838 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007839 unsigned NumTemplateArgs = Record[Idx++];
7840 TemplArgs.reserve(NumTemplateArgs);
7841 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007842 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007843}
7844
7845/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007846void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007847 const RecordData &Record, unsigned &Idx) {
7848 unsigned NumDecls = Record[Idx++];
7849 Set.reserve(Context, NumDecls);
7850 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007851 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007852 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007853 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007854 }
7855}
7856
7857CXXBaseSpecifier
7858ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7859 const RecordData &Record, unsigned &Idx) {
7860 bool isVirtual = static_cast<bool>(Record[Idx++]);
7861 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7862 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7863 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7864 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7865 SourceRange Range = ReadSourceRange(F, Record, Idx);
7866 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7867 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7868 EllipsisLoc);
7869 Result.setInheritConstructors(inheritConstructors);
7870 return Result;
7871}
7872
Richard Smithc2bb8182015-03-24 06:36:48 +00007873CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007874ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7875 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007876 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007877 assert(NumInitializers && "wrote ctor initializers but have no inits");
7878 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7879 for (unsigned i = 0; i != NumInitializers; ++i) {
7880 TypeSourceInfo *TInfo = nullptr;
7881 bool IsBaseVirtual = false;
7882 FieldDecl *Member = nullptr;
7883 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007884
Richard Smithc2bb8182015-03-24 06:36:48 +00007885 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7886 switch (Type) {
7887 case CTOR_INITIALIZER_BASE:
7888 TInfo = GetTypeSourceInfo(F, Record, Idx);
7889 IsBaseVirtual = Record[Idx++];
7890 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007891
Richard Smithc2bb8182015-03-24 06:36:48 +00007892 case CTOR_INITIALIZER_DELEGATING:
7893 TInfo = GetTypeSourceInfo(F, Record, Idx);
7894 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007895
Richard Smithc2bb8182015-03-24 06:36:48 +00007896 case CTOR_INITIALIZER_MEMBER:
7897 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7898 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007899
Richard Smithc2bb8182015-03-24 06:36:48 +00007900 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7901 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7902 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007903 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007904
7905 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7906 Expr *Init = ReadExpr(F);
7907 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7908 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7909 bool IsWritten = Record[Idx++];
7910 unsigned SourceOrderOrNumArrayIndices;
7911 SmallVector<VarDecl *, 8> Indices;
7912 if (IsWritten) {
7913 SourceOrderOrNumArrayIndices = Record[Idx++];
7914 } else {
7915 SourceOrderOrNumArrayIndices = Record[Idx++];
7916 Indices.reserve(SourceOrderOrNumArrayIndices);
7917 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7918 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7919 }
7920
7921 CXXCtorInitializer *BOMInit;
7922 if (Type == CTOR_INITIALIZER_BASE) {
7923 BOMInit = new (Context)
7924 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7925 RParenLoc, MemberOrEllipsisLoc);
7926 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7927 BOMInit = new (Context)
7928 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7929 } else if (IsWritten) {
7930 if (Member)
7931 BOMInit = new (Context) CXXCtorInitializer(
7932 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7933 else
7934 BOMInit = new (Context)
7935 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7936 LParenLoc, Init, RParenLoc);
7937 } else {
7938 if (IndirectMember) {
7939 assert(Indices.empty() && "Indirect field improperly initialized");
7940 BOMInit = new (Context)
7941 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7942 LParenLoc, Init, RParenLoc);
7943 } else {
7944 BOMInit = CXXCtorInitializer::Create(
7945 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7946 Indices.data(), Indices.size());
7947 }
7948 }
7949
7950 if (IsWritten)
7951 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7952 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007953 }
7954
Richard Smithc2bb8182015-03-24 06:36:48 +00007955 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007956}
7957
7958NestedNameSpecifier *
7959ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7960 const RecordData &Record, unsigned &Idx) {
7961 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007962 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007963 for (unsigned I = 0; I != N; ++I) {
7964 NestedNameSpecifier::SpecifierKind Kind
7965 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7966 switch (Kind) {
7967 case NestedNameSpecifier::Identifier: {
7968 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7969 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7970 break;
7971 }
7972
7973 case NestedNameSpecifier::Namespace: {
7974 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7975 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7976 break;
7977 }
7978
7979 case NestedNameSpecifier::NamespaceAlias: {
7980 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7981 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7982 break;
7983 }
7984
7985 case NestedNameSpecifier::TypeSpec:
7986 case NestedNameSpecifier::TypeSpecWithTemplate: {
7987 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7988 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007989 return nullptr;
7990
Guy Benyei11169dd2012-12-18 14:30:41 +00007991 bool Template = Record[Idx++];
7992 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7993 break;
7994 }
7995
7996 case NestedNameSpecifier::Global: {
7997 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7998 // No associated value, and there can't be a prefix.
7999 break;
8000 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008001
8002 case NestedNameSpecifier::Super: {
8003 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8004 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8005 break;
8006 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008007 }
8008 Prev = NNS;
8009 }
8010 return NNS;
8011}
8012
8013NestedNameSpecifierLoc
8014ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8015 unsigned &Idx) {
8016 unsigned N = Record[Idx++];
8017 NestedNameSpecifierLocBuilder Builder;
8018 for (unsigned I = 0; I != N; ++I) {
8019 NestedNameSpecifier::SpecifierKind Kind
8020 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8021 switch (Kind) {
8022 case NestedNameSpecifier::Identifier: {
8023 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8024 SourceRange Range = ReadSourceRange(F, Record, Idx);
8025 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8026 break;
8027 }
8028
8029 case NestedNameSpecifier::Namespace: {
8030 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8031 SourceRange Range = ReadSourceRange(F, Record, Idx);
8032 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8033 break;
8034 }
8035
8036 case NestedNameSpecifier::NamespaceAlias: {
8037 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8038 SourceRange Range = ReadSourceRange(F, Record, Idx);
8039 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8040 break;
8041 }
8042
8043 case NestedNameSpecifier::TypeSpec:
8044 case NestedNameSpecifier::TypeSpecWithTemplate: {
8045 bool Template = Record[Idx++];
8046 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8047 if (!T)
8048 return NestedNameSpecifierLoc();
8049 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8050
8051 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8052 Builder.Extend(Context,
8053 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8054 T->getTypeLoc(), ColonColonLoc);
8055 break;
8056 }
8057
8058 case NestedNameSpecifier::Global: {
8059 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8060 Builder.MakeGlobal(Context, ColonColonLoc);
8061 break;
8062 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008063
8064 case NestedNameSpecifier::Super: {
8065 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8066 SourceRange Range = ReadSourceRange(F, Record, Idx);
8067 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8068 break;
8069 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008070 }
8071 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008072
Guy Benyei11169dd2012-12-18 14:30:41 +00008073 return Builder.getWithLocInContext(Context);
8074}
8075
8076SourceRange
8077ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8078 unsigned &Idx) {
8079 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8080 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8081 return SourceRange(beg, end);
8082}
8083
8084/// \brief Read an integral value
8085llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8086 unsigned BitWidth = Record[Idx++];
8087 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8088 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8089 Idx += NumWords;
8090 return Result;
8091}
8092
8093/// \brief Read a signed integral value
8094llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8095 bool isUnsigned = Record[Idx++];
8096 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8097}
8098
8099/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008100llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8101 const llvm::fltSemantics &Sem,
8102 unsigned &Idx) {
8103 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008104}
8105
8106// \brief Read a string
8107std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8108 unsigned Len = Record[Idx++];
8109 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8110 Idx += Len;
8111 return Result;
8112}
8113
Richard Smith7ed1bc92014-12-05 22:42:13 +00008114std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8115 unsigned &Idx) {
8116 std::string Filename = ReadString(Record, Idx);
8117 ResolveImportedPath(F, Filename);
8118 return Filename;
8119}
8120
Guy Benyei11169dd2012-12-18 14:30:41 +00008121VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8122 unsigned &Idx) {
8123 unsigned Major = Record[Idx++];
8124 unsigned Minor = Record[Idx++];
8125 unsigned Subminor = Record[Idx++];
8126 if (Minor == 0)
8127 return VersionTuple(Major);
8128 if (Subminor == 0)
8129 return VersionTuple(Major, Minor - 1);
8130 return VersionTuple(Major, Minor - 1, Subminor - 1);
8131}
8132
8133CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8134 const RecordData &Record,
8135 unsigned &Idx) {
8136 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8137 return CXXTemporary::Create(Context, Decl);
8138}
8139
8140DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008141 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008142}
8143
8144DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8145 return Diags.Report(Loc, DiagID);
8146}
8147
8148/// \brief Retrieve the identifier table associated with the
8149/// preprocessor.
8150IdentifierTable &ASTReader::getIdentifierTable() {
8151 return PP.getIdentifierTable();
8152}
8153
8154/// \brief Record that the given ID maps to the given switch-case
8155/// statement.
8156void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008157 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008158 "Already have a SwitchCase with this ID");
8159 (*CurrSwitchCaseStmts)[ID] = SC;
8160}
8161
8162/// \brief Retrieve the switch-case statement with the given ID.
8163SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008164 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008165 return (*CurrSwitchCaseStmts)[ID];
8166}
8167
8168void ASTReader::ClearSwitchCaseIDs() {
8169 CurrSwitchCaseStmts->clear();
8170}
8171
8172void ASTReader::ReadComments() {
8173 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008174 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008175 serialization::ModuleFile *> >::iterator
8176 I = CommentsCursors.begin(),
8177 E = CommentsCursors.end();
8178 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008179 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008180 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008181 serialization::ModuleFile &F = *I->second;
8182 SavedStreamPosition SavedPosition(Cursor);
8183
8184 RecordData Record;
8185 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008186 llvm::BitstreamEntry Entry =
8187 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008188
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008189 switch (Entry.Kind) {
8190 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8191 case llvm::BitstreamEntry::Error:
8192 Error("malformed block record in AST file");
8193 return;
8194 case llvm::BitstreamEntry::EndBlock:
8195 goto NextCursor;
8196 case llvm::BitstreamEntry::Record:
8197 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008198 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008199 }
8200
8201 // Read a record.
8202 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008203 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008204 case COMMENTS_RAW_COMMENT: {
8205 unsigned Idx = 0;
8206 SourceRange SR = ReadSourceRange(F, Record, Idx);
8207 RawComment::CommentKind Kind =
8208 (RawComment::CommentKind) Record[Idx++];
8209 bool IsTrailingComment = Record[Idx++];
8210 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008211 Comments.push_back(new (Context) RawComment(
8212 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8213 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008214 break;
8215 }
8216 }
8217 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008218 NextCursor:
8219 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008220 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008221}
8222
Richard Smithcd45dbc2014-04-19 03:48:30 +00008223std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8224 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008225 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008226 return M->getFullModuleName();
8227
8228 // Otherwise, use the name of the top-level module the decl is within.
8229 if (ModuleFile *M = getOwningModuleFile(D))
8230 return M->ModuleName;
8231
8232 // Not from a module.
8233 return "";
8234}
8235
Guy Benyei11169dd2012-12-18 14:30:41 +00008236void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008237 while (!PendingIdentifierInfos.empty() ||
8238 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008239 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008240 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008241 // If any identifiers with corresponding top-level declarations have
8242 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008243 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8244 TopLevelDeclsMap;
8245 TopLevelDeclsMap TopLevelDecls;
8246
Guy Benyei11169dd2012-12-18 14:30:41 +00008247 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008248 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008249 SmallVector<uint32_t, 4> DeclIDs =
8250 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008251 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008252
8253 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008254 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008255
Richard Smith851072e2014-05-19 20:59:20 +00008256 // For each decl chain that we wanted to complete while deserializing, mark
8257 // it as "still needs to be completed".
8258 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8259 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8260 }
8261 PendingIncompleteDeclChains.clear();
8262
Guy Benyei11169dd2012-12-18 14:30:41 +00008263 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008264 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008265 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008266 PendingDeclChains.clear();
8267
Douglas Gregor6168bd22013-02-18 15:53:43 +00008268 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008269 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8270 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008271 IdentifierInfo *II = TLD->first;
8272 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008273 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008274 }
8275 }
8276
Guy Benyei11169dd2012-12-18 14:30:41 +00008277 // Load any pending macro definitions.
8278 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008279 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8280 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8281 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8282 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008283 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008284 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008285 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008286 if (Info.M->Kind != MK_ImplicitModule &&
8287 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008288 resolvePendingMacro(II, Info);
8289 }
8290 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008291 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008292 ++IDIdx) {
8293 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008294 if (Info.M->Kind == MK_ImplicitModule ||
8295 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008296 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008297 }
8298 }
8299 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008300
8301 // Wire up the DeclContexts for Decls that we delayed setting until
8302 // recursive loading is completed.
8303 while (!PendingDeclContextInfos.empty()) {
8304 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8305 PendingDeclContextInfos.pop_front();
8306 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8307 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8308 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8309 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008310
Richard Smithd1c46742014-04-30 02:24:17 +00008311 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008312 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008313 auto Update = PendingUpdateRecords.pop_back_val();
8314 ReadingKindTracker ReadingKind(Read_Decl, *this);
8315 loadDeclUpdateRecords(Update.first, Update.second);
8316 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008317 }
Richard Smith8a639892015-01-24 01:07:20 +00008318
8319 // At this point, all update records for loaded decls are in place, so any
8320 // fake class definitions should have become real.
8321 assert(PendingFakeDefinitionData.empty() &&
8322 "faked up a class definition but never saw the real one");
8323
Guy Benyei11169dd2012-12-18 14:30:41 +00008324 // If we deserialized any C++ or Objective-C class definitions, any
8325 // Objective-C protocol definitions, or any redeclarable templates, make sure
8326 // that all redeclarations point to the definitions. Note that this can only
8327 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008328 for (Decl *D : PendingDefinitions) {
8329 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008330 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008331 // Make sure that the TagType points at the definition.
8332 const_cast<TagType*>(TagT)->decl = TD;
8333 }
Richard Smith8ce51082015-03-11 01:44:51 +00008334
Craig Topperc6914d02014-08-25 04:15:02 +00008335 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008336 for (auto *R = getMostRecentExistingDecl(RD); R;
8337 R = R->getPreviousDecl()) {
8338 assert((R == D) ==
8339 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008340 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008341 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008342 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008343 }
8344
8345 continue;
8346 }
Richard Smith8ce51082015-03-11 01:44:51 +00008347
Craig Topperc6914d02014-08-25 04:15:02 +00008348 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008349 // Make sure that the ObjCInterfaceType points at the definition.
8350 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8351 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008352
8353 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8354 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8355
Guy Benyei11169dd2012-12-18 14:30:41 +00008356 continue;
8357 }
Richard Smith8ce51082015-03-11 01:44:51 +00008358
Craig Topperc6914d02014-08-25 04:15:02 +00008359 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008360 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8361 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8362
Guy Benyei11169dd2012-12-18 14:30:41 +00008363 continue;
8364 }
Richard Smith8ce51082015-03-11 01:44:51 +00008365
Craig Topperc6914d02014-08-25 04:15:02 +00008366 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008367 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8368 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008369 }
8370 PendingDefinitions.clear();
8371
8372 // Load the bodies of any functions or methods we've encountered. We do
8373 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008374 // have been fully wired up (hasBody relies on this).
8375 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008376 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8377 PBEnd = PendingBodies.end();
8378 PB != PBEnd; ++PB) {
8379 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8380 // FIXME: Check for =delete/=default?
8381 // FIXME: Complain about ODR violations here?
8382 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8383 FD->setLazyBody(PB->second);
8384 continue;
8385 }
8386
8387 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8388 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8389 MD->setLazyBody(PB->second);
8390 }
8391 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008392
8393 // Do some cleanup.
8394 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8395 getContext().deduplicateMergedDefinitonsFor(ND);
8396 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008397}
8398
8399void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008400 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8401 return;
8402
Richard Smitha0ce9c42014-07-29 23:23:27 +00008403 // Trigger the import of the full definition of each class that had any
8404 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008405 // These updates may in turn find and diagnose some ODR failures, so take
8406 // ownership of the set first.
8407 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8408 PendingOdrMergeFailures.clear();
8409 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008410 Merge.first->buildLookup();
8411 Merge.first->decls_begin();
8412 Merge.first->bases_begin();
8413 Merge.first->vbases_begin();
8414 for (auto *RD : Merge.second) {
8415 RD->decls_begin();
8416 RD->bases_begin();
8417 RD->vbases_begin();
8418 }
8419 }
8420
8421 // For each declaration from a merged context, check that the canonical
8422 // definition of that context also contains a declaration of the same
8423 // entity.
8424 //
8425 // Caution: this loop does things that might invalidate iterators into
8426 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8427 while (!PendingOdrMergeChecks.empty()) {
8428 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8429
8430 // FIXME: Skip over implicit declarations for now. This matters for things
8431 // like implicitly-declared special member functions. This isn't entirely
8432 // correct; we can end up with multiple unmerged declarations of the same
8433 // implicit entity.
8434 if (D->isImplicit())
8435 continue;
8436
8437 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008438
8439 bool Found = false;
8440 const Decl *DCanon = D->getCanonicalDecl();
8441
Richard Smith01bdb7a2014-08-28 05:44:07 +00008442 for (auto RI : D->redecls()) {
8443 if (RI->getLexicalDeclContext() == CanonDef) {
8444 Found = true;
8445 break;
8446 }
8447 }
8448 if (Found)
8449 continue;
8450
Richard Smith0f4e2c42015-08-06 04:23:48 +00008451 // Quick check failed, time to do the slow thing. Note, we can't just
8452 // look up the name of D in CanonDef here, because the member that is
8453 // in CanonDef might not be found by name lookup (it might have been
8454 // replaced by a more recent declaration in the lookup table), and we
8455 // can't necessarily find it in the redeclaration chain because it might
8456 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008457 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008458 for (auto *CanonMember : CanonDef->decls()) {
8459 if (CanonMember->getCanonicalDecl() == DCanon) {
8460 // This can happen if the declaration is merely mergeable and not
8461 // actually redeclarable (we looked for redeclarations earlier).
8462 //
8463 // FIXME: We should be able to detect this more efficiently, without
8464 // pulling in all of the members of CanonDef.
8465 Found = true;
8466 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008467 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008468 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8469 if (ND->getDeclName() == D->getDeclName())
8470 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008471 }
8472
8473 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008474 // The AST doesn't like TagDecls becoming invalid after they've been
8475 // completed. We only really need to mark FieldDecls as invalid here.
8476 if (!isa<TagDecl>(D))
8477 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008478
8479 // Ensure we don't accidentally recursively enter deserialization while
8480 // we're producing our diagnostic.
8481 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008482
8483 std::string CanonDefModule =
8484 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8485 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8486 << D << getOwningModuleNameForDiagnostic(D)
8487 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8488
8489 if (Candidates.empty())
8490 Diag(cast<Decl>(CanonDef)->getLocation(),
8491 diag::note_module_odr_violation_no_possible_decls) << D;
8492 else {
8493 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8494 Diag(Candidates[I]->getLocation(),
8495 diag::note_module_odr_violation_possible_decl)
8496 << Candidates[I];
8497 }
8498
8499 DiagnosedOdrMergeFailures.insert(CanonDef);
8500 }
8501 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008502
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008503 if (OdrMergeFailures.empty())
8504 return;
8505
8506 // Ensure we don't accidentally recursively enter deserialization while
8507 // we're producing our diagnostics.
8508 Deserializing RecursionGuard(this);
8509
Richard Smithcd45dbc2014-04-19 03:48:30 +00008510 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008511 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008512 // If we've already pointed out a specific problem with this class, don't
8513 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008514 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008515 continue;
8516
8517 bool Diagnosed = false;
8518 for (auto *RD : Merge.second) {
8519 // Multiple different declarations got merged together; tell the user
8520 // where they came from.
8521 if (Merge.first != RD) {
8522 // FIXME: Walk the definition, figure out what's different,
8523 // and diagnose that.
8524 if (!Diagnosed) {
8525 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8526 Diag(Merge.first->getLocation(),
8527 diag::err_module_odr_violation_different_definitions)
8528 << Merge.first << Module.empty() << Module;
8529 Diagnosed = true;
8530 }
8531
8532 Diag(RD->getLocation(),
8533 diag::note_module_odr_violation_different_definitions)
8534 << getOwningModuleNameForDiagnostic(RD);
8535 }
8536 }
8537
8538 if (!Diagnosed) {
8539 // All definitions are updates to the same declaration. This happens if a
8540 // module instantiates the declaration of a class template specialization
8541 // and two or more other modules instantiate its definition.
8542 //
8543 // FIXME: Indicate which modules had instantiations of this definition.
8544 // FIXME: How can this even happen?
8545 Diag(Merge.first->getLocation(),
8546 diag::err_module_odr_violation_different_instantiations)
8547 << Merge.first;
8548 }
8549 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008550}
8551
Richard Smithce18a182015-07-14 00:26:00 +00008552void ASTReader::StartedDeserializing() {
8553 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8554 ReadTimer->startTimer();
8555}
8556
Guy Benyei11169dd2012-12-18 14:30:41 +00008557void ASTReader::FinishedDeserializing() {
8558 assert(NumCurrentElementsDeserializing &&
8559 "FinishedDeserializing not paired with StartedDeserializing");
8560 if (NumCurrentElementsDeserializing == 1) {
8561 // We decrease NumCurrentElementsDeserializing only after pending actions
8562 // are finished, to avoid recursively re-calling finishPendingActions().
8563 finishPendingActions();
8564 }
8565 --NumCurrentElementsDeserializing;
8566
Richard Smitha0ce9c42014-07-29 23:23:27 +00008567 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008568 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008569 while (!PendingExceptionSpecUpdates.empty()) {
8570 auto Updates = std::move(PendingExceptionSpecUpdates);
8571 PendingExceptionSpecUpdates.clear();
8572 for (auto Update : Updates) {
8573 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008574 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00008575 if (auto *Listener = Context.getASTMutationListener())
8576 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00008577 for (auto *Redecl : Update.second->redecls())
8578 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008579 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008580 }
8581
Richard Smithce18a182015-07-14 00:26:00 +00008582 if (ReadTimer)
8583 ReadTimer->stopTimer();
8584
Richard Smith0f4e2c42015-08-06 04:23:48 +00008585 diagnoseOdrViolations();
8586
Richard Smith04d05b52014-03-23 00:27:18 +00008587 // We are not in recursive loading, so it's safe to pass the "interesting"
8588 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008589 if (Consumer)
8590 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008591 }
8592}
8593
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008594void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008595 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8596 // Remove any fake results before adding any real ones.
8597 auto It = PendingFakeLookupResults.find(II);
8598 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008599 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008600 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008601 // FIXME: this works around module+PCH performance issue.
8602 // Rather than erase the result from the map, which is O(n), just clear
8603 // the vector of NamedDecls.
8604 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008605 }
8606 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008607
8608 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8609 SemaObj->TUScope->AddDecl(D);
8610 } else if (SemaObj->TUScope) {
8611 // Adding the decl to IdResolver may have failed because it was already in
8612 // (even though it was not added in scope). If it is already in, make sure
8613 // it gets in the scope as well.
8614 if (std::find(SemaObj->IdResolver.begin(Name),
8615 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8616 SemaObj->TUScope->AddDecl(D);
8617 }
8618}
8619
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008620ASTReader::ASTReader(
8621 Preprocessor &PP, ASTContext &Context,
8622 const PCHContainerReader &PCHContainerRdr,
8623 ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
8624 StringRef isysroot, bool DisableValidation,
8625 bool AllowASTWithCompilerErrors,
8626 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8627 bool UseGlobalIndex,
8628 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008629 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008630 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008631 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008632 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008633 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008634 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008635 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008636 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8637 AllowConfigurationMismatch(AllowConfigurationMismatch),
8638 ValidateSystemInputs(ValidateSystemInputs),
8639 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008640 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8641 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8642 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8643 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008644 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8645 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8646 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8647 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8648 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8649 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008650 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008651 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008652
8653 for (const auto &Ext : Extensions) {
8654 auto BlockName = Ext->getExtensionMetadata().BlockName;
8655 auto Known = ModuleFileExtensions.find(BlockName);
8656 if (Known != ModuleFileExtensions.end()) {
8657 Diags.Report(diag::warn_duplicate_module_file_extension)
8658 << BlockName;
8659 continue;
8660 }
8661
8662 ModuleFileExtensions.insert({BlockName, Ext});
8663 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008664}
8665
8666ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008667 if (OwnsDeserializationListener)
8668 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008669}