blob: 834917de1d468b8705f8103adfb16816e9282cd6 [file] [log] [blame]
Nick Lewyckyf0f56162013-01-31 03:23:57 +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"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeLocVisitor.h"
25#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/Basic/SourceManager.h"
27#include "clang/Basic/SourceManagerInternals.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Basic/TargetOptions.h"
30#include "clang/Basic/Version.h"
31#include "clang/Basic/VersionTuple.h"
32#include "clang/Lex/HeaderSearch.h"
33#include "clang/Lex/HeaderSearchOptions.h"
34#include "clang/Lex/MacroInfo.h"
35#include "clang/Lex/PreprocessingRecord.h"
36#include "clang/Lex/Preprocessor.h"
37#include "clang/Lex/PreprocessorOptions.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/Sema.h"
40#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000041#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000042#include "clang/Serialization/ModuleManager.h"
43#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000044#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000045#include "llvm/ADT/StringExtras.h"
46#include "llvm/Bitcode/BitstreamReader.h"
47#include "llvm/Support/ErrorHandling.h"
48#include "llvm/Support/FileSystem.h"
49#include "llvm/Support/MemoryBuffer.h"
50#include "llvm/Support/Path.h"
51#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000052#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000053#include "llvm/Support/system_error.h"
54#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000055#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000056#include <iterator>
57
58using namespace clang;
59using namespace clang::serialization;
60using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000061using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000062
Ben Langmuircb69b572014-03-07 06:40:32 +000063
64//===----------------------------------------------------------------------===//
65// ChainedASTReaderListener implementation
66//===----------------------------------------------------------------------===//
67
68bool
69ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
70 return First->ReadFullVersionInformation(FullVersion) ||
71 Second->ReadFullVersionInformation(FullVersion);
72}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000073void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
74 First->ReadModuleName(ModuleName);
75 Second->ReadModuleName(ModuleName);
76}
77void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
78 First->ReadModuleMapFile(ModuleMapPath);
79 Second->ReadModuleMapFile(ModuleMapPath);
80}
Ben Langmuircb69b572014-03-07 06:40:32 +000081bool ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
82 bool Complain) {
83 return First->ReadLanguageOptions(LangOpts, Complain) ||
84 Second->ReadLanguageOptions(LangOpts, Complain);
85}
86bool
87ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
88 bool Complain) {
89 return First->ReadTargetOptions(TargetOpts, Complain) ||
90 Second->ReadTargetOptions(TargetOpts, Complain);
91}
92bool ChainedASTReaderListener::ReadDiagnosticOptions(
93 const DiagnosticOptions &DiagOpts, bool Complain) {
94 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
95 Second->ReadDiagnosticOptions(DiagOpts, Complain);
96}
97bool
98ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
99 bool Complain) {
100 return First->ReadFileSystemOptions(FSOpts, Complain) ||
101 Second->ReadFileSystemOptions(FSOpts, Complain);
102}
103
104bool ChainedASTReaderListener::ReadHeaderSearchOptions(
105 const HeaderSearchOptions &HSOpts, bool Complain) {
106 return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
107 Second->ReadHeaderSearchOptions(HSOpts, Complain);
108}
109bool ChainedASTReaderListener::ReadPreprocessorOptions(
110 const PreprocessorOptions &PPOpts, bool Complain,
111 std::string &SuggestedPredefines) {
112 return First->ReadPreprocessorOptions(PPOpts, Complain,
113 SuggestedPredefines) ||
114 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
115}
116void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
117 unsigned Value) {
118 First->ReadCounter(M, Value);
119 Second->ReadCounter(M, Value);
120}
121bool ChainedASTReaderListener::needsInputFileVisitation() {
122 return First->needsInputFileVisitation() ||
123 Second->needsInputFileVisitation();
124}
125bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
126 return First->needsSystemInputFileVisitation() ||
127 Second->needsSystemInputFileVisitation();
128}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000129void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
130 First->visitModuleFile(Filename);
131 Second->visitModuleFile(Filename);
132}
Ben Langmuircb69b572014-03-07 06:40:32 +0000133bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000134 bool isSystem,
135 bool isOverridden) {
136 return First->visitInputFile(Filename, isSystem, isOverridden) ||
137 Second->visitInputFile(Filename, isSystem, isOverridden);
Ben Langmuircb69b572014-03-07 06:40:32 +0000138}
139
Guy Benyei11169dd2012-12-18 14:30:41 +0000140//===----------------------------------------------------------------------===//
141// PCH validator implementation
142//===----------------------------------------------------------------------===//
143
144ASTReaderListener::~ASTReaderListener() {}
145
146/// \brief Compare the given set of language options against an existing set of
147/// language options.
148///
149/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
150///
151/// \returns true if the languagae options mis-match, false otherwise.
152static bool checkLanguageOptions(const LangOptions &LangOpts,
153 const LangOptions &ExistingLangOpts,
154 DiagnosticsEngine *Diags) {
155#define LANGOPT(Name, Bits, Default, Description) \
156 if (ExistingLangOpts.Name != LangOpts.Name) { \
157 if (Diags) \
158 Diags->Report(diag::err_pch_langopt_mismatch) \
159 << Description << LangOpts.Name << ExistingLangOpts.Name; \
160 return true; \
161 }
162
163#define VALUE_LANGOPT(Name, Bits, Default, Description) \
164 if (ExistingLangOpts.Name != LangOpts.Name) { \
165 if (Diags) \
166 Diags->Report(diag::err_pch_langopt_value_mismatch) \
167 << Description; \
168 return true; \
169 }
170
171#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
172 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
173 if (Diags) \
174 Diags->Report(diag::err_pch_langopt_value_mismatch) \
175 << Description; \
176 return true; \
177 }
178
179#define BENIGN_LANGOPT(Name, Bits, Default, Description)
180#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
181#include "clang/Basic/LangOptions.def"
182
183 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
184 if (Diags)
185 Diags->Report(diag::err_pch_langopt_value_mismatch)
186 << "target Objective-C runtime";
187 return true;
188 }
189
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000190 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
191 LangOpts.CommentOpts.BlockCommandNames) {
192 if (Diags)
193 Diags->Report(diag::err_pch_langopt_value_mismatch)
194 << "block command names";
195 return true;
196 }
197
Guy Benyei11169dd2012-12-18 14:30:41 +0000198 return false;
199}
200
201/// \brief Compare the given set of target options against an existing set of
202/// target options.
203///
204/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
205///
206/// \returns true if the target options mis-match, false otherwise.
207static bool checkTargetOptions(const TargetOptions &TargetOpts,
208 const TargetOptions &ExistingTargetOpts,
209 DiagnosticsEngine *Diags) {
210#define CHECK_TARGET_OPT(Field, Name) \
211 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
212 if (Diags) \
213 Diags->Report(diag::err_pch_targetopt_mismatch) \
214 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
215 return true; \
216 }
217
218 CHECK_TARGET_OPT(Triple, "target");
219 CHECK_TARGET_OPT(CPU, "target CPU");
220 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000221 CHECK_TARGET_OPT(LinkerVersion, "target linker version");
222#undef CHECK_TARGET_OPT
223
224 // Compare feature sets.
225 SmallVector<StringRef, 4> ExistingFeatures(
226 ExistingTargetOpts.FeaturesAsWritten.begin(),
227 ExistingTargetOpts.FeaturesAsWritten.end());
228 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
229 TargetOpts.FeaturesAsWritten.end());
230 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
231 std::sort(ReadFeatures.begin(), ReadFeatures.end());
232
233 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
234 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
235 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
236 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
237 ++ExistingIdx;
238 ++ReadIdx;
239 continue;
240 }
241
242 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
243 if (Diags)
244 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
245 << false << ReadFeatures[ReadIdx];
246 return true;
247 }
248
249 if (Diags)
250 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
251 << true << ExistingFeatures[ExistingIdx];
252 return true;
253 }
254
255 if (ExistingIdx < ExistingN) {
256 if (Diags)
257 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
258 << true << ExistingFeatures[ExistingIdx];
259 return true;
260 }
261
262 if (ReadIdx < ReadN) {
263 if (Diags)
264 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
265 << false << ReadFeatures[ReadIdx];
266 return true;
267 }
268
269 return false;
270}
271
272bool
273PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
274 bool Complain) {
275 const LangOptions &ExistingLangOpts = PP.getLangOpts();
276 return checkLanguageOptions(LangOpts, ExistingLangOpts,
277 Complain? &Reader.Diags : 0);
278}
279
280bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
281 bool Complain) {
282 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
283 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
284 Complain? &Reader.Diags : 0);
285}
286
287namespace {
288 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
289 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000290 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
291 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000292}
293
294/// \brief Collect the macro definitions provided by the given preprocessor
295/// options.
296static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
297 MacroDefinitionsMap &Macros,
298 SmallVectorImpl<StringRef> *MacroNames = 0){
299 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
300 StringRef Macro = PPOpts.Macros[I].first;
301 bool IsUndef = PPOpts.Macros[I].second;
302
303 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
304 StringRef MacroName = MacroPair.first;
305 StringRef MacroBody = MacroPair.second;
306
307 // For an #undef'd macro, we only care about the name.
308 if (IsUndef) {
309 if (MacroNames && !Macros.count(MacroName))
310 MacroNames->push_back(MacroName);
311
312 Macros[MacroName] = std::make_pair("", true);
313 continue;
314 }
315
316 // For a #define'd macro, figure out the actual definition.
317 if (MacroName.size() == Macro.size())
318 MacroBody = "1";
319 else {
320 // Note: GCC drops anything following an end-of-line character.
321 StringRef::size_type End = MacroBody.find_first_of("\n\r");
322 MacroBody = MacroBody.substr(0, End);
323 }
324
325 if (MacroNames && !Macros.count(MacroName))
326 MacroNames->push_back(MacroName);
327 Macros[MacroName] = std::make_pair(MacroBody, false);
328 }
329}
330
331/// \brief Check the preprocessor options deserialized from the control block
332/// against the preprocessor options in an existing preprocessor.
333///
334/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
335static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
336 const PreprocessorOptions &ExistingPPOpts,
337 DiagnosticsEngine *Diags,
338 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000339 std::string &SuggestedPredefines,
340 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000341 // Check macro definitions.
342 MacroDefinitionsMap ASTFileMacros;
343 collectMacroDefinitions(PPOpts, ASTFileMacros);
344 MacroDefinitionsMap ExistingMacros;
345 SmallVector<StringRef, 4> ExistingMacroNames;
346 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
347
348 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
349 // Dig out the macro definition in the existing preprocessor options.
350 StringRef MacroName = ExistingMacroNames[I];
351 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
352
353 // Check whether we know anything about this macro name or not.
354 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
355 = ASTFileMacros.find(MacroName);
356 if (Known == ASTFileMacros.end()) {
357 // FIXME: Check whether this identifier was referenced anywhere in the
358 // AST file. If so, we should reject the AST file. Unfortunately, this
359 // information isn't in the control block. What shall we do about it?
360
361 if (Existing.second) {
362 SuggestedPredefines += "#undef ";
363 SuggestedPredefines += MacroName.str();
364 SuggestedPredefines += '\n';
365 } else {
366 SuggestedPredefines += "#define ";
367 SuggestedPredefines += MacroName.str();
368 SuggestedPredefines += ' ';
369 SuggestedPredefines += Existing.first.str();
370 SuggestedPredefines += '\n';
371 }
372 continue;
373 }
374
375 // If the macro was defined in one but undef'd in the other, we have a
376 // conflict.
377 if (Existing.second != Known->second.second) {
378 if (Diags) {
379 Diags->Report(diag::err_pch_macro_def_undef)
380 << MacroName << Known->second.second;
381 }
382 return true;
383 }
384
385 // If the macro was #undef'd in both, or if the macro bodies are identical,
386 // it's fine.
387 if (Existing.second || Existing.first == Known->second.first)
388 continue;
389
390 // The macro bodies differ; complain.
391 if (Diags) {
392 Diags->Report(diag::err_pch_macro_def_conflict)
393 << MacroName << Known->second.first << Existing.first;
394 }
395 return true;
396 }
397
398 // Check whether we're using predefines.
399 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
400 if (Diags) {
401 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
402 }
403 return true;
404 }
405
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000406 // Detailed record is important since it is used for the module cache hash.
407 if (LangOpts.Modules &&
408 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
409 if (Diags) {
410 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
411 }
412 return true;
413 }
414
Guy Benyei11169dd2012-12-18 14:30:41 +0000415 // Compute the #include and #include_macros lines we need.
416 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
417 StringRef File = ExistingPPOpts.Includes[I];
418 if (File == ExistingPPOpts.ImplicitPCHInclude)
419 continue;
420
421 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
422 != PPOpts.Includes.end())
423 continue;
424
425 SuggestedPredefines += "#include \"";
426 SuggestedPredefines +=
427 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
428 SuggestedPredefines += "\"\n";
429 }
430
431 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
432 StringRef File = ExistingPPOpts.MacroIncludes[I];
433 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
434 File)
435 != PPOpts.MacroIncludes.end())
436 continue;
437
438 SuggestedPredefines += "#__include_macros \"";
439 SuggestedPredefines +=
440 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
441 SuggestedPredefines += "\"\n##\n";
442 }
443
444 return false;
445}
446
447bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
448 bool Complain,
449 std::string &SuggestedPredefines) {
450 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
451
452 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
453 Complain? &Reader.Diags : 0,
454 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000455 SuggestedPredefines,
456 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000457}
458
Guy Benyei11169dd2012-12-18 14:30:41 +0000459void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
460 PP.setCounterValue(Value);
461}
462
463//===----------------------------------------------------------------------===//
464// AST reader implementation
465//===----------------------------------------------------------------------===//
466
467void
468ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
469 DeserializationListener = Listener;
470}
471
472
473
474unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
475 return serialization::ComputeHash(Sel);
476}
477
478
479std::pair<unsigned, unsigned>
480ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000481 using namespace llvm::support;
482 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
483 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000484 return std::make_pair(KeyLen, DataLen);
485}
486
487ASTSelectorLookupTrait::internal_key_type
488ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000489 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000490 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000491 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
492 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
493 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000494 if (N == 0)
495 return SelTable.getNullarySelector(FirstII);
496 else if (N == 1)
497 return SelTable.getUnarySelector(FirstII);
498
499 SmallVector<IdentifierInfo *, 16> Args;
500 Args.push_back(FirstII);
501 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000502 Args.push_back(Reader.getLocalIdentifier(
503 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000504
505 return SelTable.getSelector(N, Args.data());
506}
507
508ASTSelectorLookupTrait::data_type
509ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
510 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000511 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000512
513 data_type Result;
514
Justin Bogner57ba0b22014-03-28 22:03:24 +0000515 Result.ID = Reader.getGlobalSelectorID(
516 F, endian::readNext<uint32_t, little, unaligned>(d));
517 unsigned NumInstanceMethodsAndBits =
518 endian::readNext<uint16_t, little, unaligned>(d);
519 unsigned NumFactoryMethodsAndBits =
520 endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000521 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
522 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
523 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
524 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000525
526 // Load instance methods
527 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000528 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
529 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000530 Result.Instance.push_back(Method);
531 }
532
533 // Load factory methods
534 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000535 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
536 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000537 Result.Factory.push_back(Method);
538 }
539
540 return Result;
541}
542
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000543unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
544 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000545}
546
547std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000548ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000549 using namespace llvm::support;
550 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
551 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000552 return std::make_pair(KeyLen, DataLen);
553}
554
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000555ASTIdentifierLookupTraitBase::internal_key_type
556ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000557 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000558 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000559}
560
Douglas Gregordcf25082013-02-11 18:16:18 +0000561/// \brief Whether the given identifier is "interesting".
562static bool isInterestingIdentifier(IdentifierInfo &II) {
563 return II.isPoisoned() ||
564 II.isExtensionToken() ||
565 II.getObjCOrBuiltinID() ||
566 II.hasRevertedTokenIDToIdentifier() ||
567 II.hadMacroDefinition() ||
568 II.getFETokenInfo<void>();
569}
570
Guy Benyei11169dd2012-12-18 14:30:41 +0000571IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
572 const unsigned char* d,
573 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000574 using namespace llvm::support;
575 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000576 bool IsInteresting = RawID & 0x01;
577
578 // Wipe out the "is interesting" bit.
579 RawID = RawID >> 1;
580
581 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
582 if (!IsInteresting) {
583 // For uninteresting identifiers, just build the IdentifierInfo
584 // and associate it with the persistent ID.
585 IdentifierInfo *II = KnownII;
586 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000587 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000588 KnownII = II;
589 }
590 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000591 if (!II->isFromAST()) {
592 bool WasInteresting = isInterestingIdentifier(*II);
593 II->setIsFromAST();
594 if (WasInteresting)
595 II->setChangedSinceDeserialization();
596 }
597 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000598 return II;
599 }
600
Justin Bogner57ba0b22014-03-28 22:03:24 +0000601 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
602 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000603 bool CPlusPlusOperatorKeyword = Bits & 0x01;
604 Bits >>= 1;
605 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
606 Bits >>= 1;
607 bool Poisoned = Bits & 0x01;
608 Bits >>= 1;
609 bool ExtensionToken = Bits & 0x01;
610 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000611 bool hasSubmoduleMacros = Bits & 0x01;
612 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000613 bool hadMacroDefinition = Bits & 0x01;
614 Bits >>= 1;
615
616 assert(Bits == 0 && "Extra bits in the identifier?");
617 DataLen -= 8;
618
619 // Build the IdentifierInfo itself and link the identifier ID with
620 // the new IdentifierInfo.
621 IdentifierInfo *II = KnownII;
622 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000623 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000624 KnownII = II;
625 }
626 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000627 if (!II->isFromAST()) {
628 bool WasInteresting = isInterestingIdentifier(*II);
629 II->setIsFromAST();
630 if (WasInteresting)
631 II->setChangedSinceDeserialization();
632 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000633
634 // Set or check the various bits in the IdentifierInfo structure.
635 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000636 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000637 II->RevertTokenIDToIdentifier();
638 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
639 assert(II->isExtensionToken() == ExtensionToken &&
640 "Incorrect extension token flag");
641 (void)ExtensionToken;
642 if (Poisoned)
643 II->setIsPoisoned(true);
644 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
645 "Incorrect C++ operator keyword flag");
646 (void)CPlusPlusOperatorKeyword;
647
648 // If this identifier is a macro, deserialize the macro
649 // definition.
650 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000651 uint32_t MacroDirectivesOffset =
652 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000653 DataLen -= 4;
654 SmallVector<uint32_t, 8> LocalMacroIDs;
655 if (hasSubmoduleMacros) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000656 while (uint32_t LocalMacroID =
657 endian::readNext<uint32_t, little, unaligned>(d)) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000658 DataLen -= 4;
659 LocalMacroIDs.push_back(LocalMacroID);
660 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000661 DataLen -= 4;
662 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000663
664 if (F.Kind == MK_Module) {
Richard Smith49f906a2014-03-01 00:08:04 +0000665 // Macro definitions are stored from newest to oldest, so reverse them
666 // before registering them.
667 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000668 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000669 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
670 unsigned Size = 1;
671
672 static const uint32_t HasOverridesFlag = 0x80000000U;
673 if (I + 1 != E && (I[1] & HasOverridesFlag))
674 Size += 1 + (I[1] & ~HasOverridesFlag);
675
676 MacroSizes.push_back(Size);
677 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000678 }
Richard Smith49f906a2014-03-01 00:08:04 +0000679
680 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
681 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
682 SE = MacroSizes.rend();
683 SI != SE; ++SI) {
684 I -= *SI;
685
686 uint32_t LocalMacroID = *I;
687 llvm::ArrayRef<uint32_t> Overrides;
688 if (*SI != 1)
689 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
690 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
691 }
692 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000693 } else {
694 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
695 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000696 }
697
698 Reader.SetIdentifierInfo(ID, II);
699
700 // Read all of the declarations visible at global scope with this
701 // name.
702 if (DataLen > 0) {
703 SmallVector<uint32_t, 4> DeclIDs;
704 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000705 DeclIDs.push_back(Reader.getGlobalDeclID(
706 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000707 Reader.SetGloballyVisibleDecls(II, DeclIDs);
708 }
709
710 return II;
711}
712
713unsigned
714ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
715 llvm::FoldingSetNodeID ID;
716 ID.AddInteger(Key.Kind);
717
718 switch (Key.Kind) {
719 case DeclarationName::Identifier:
720 case DeclarationName::CXXLiteralOperatorName:
721 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
722 break;
723 case DeclarationName::ObjCZeroArgSelector:
724 case DeclarationName::ObjCOneArgSelector:
725 case DeclarationName::ObjCMultiArgSelector:
726 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
727 break;
728 case DeclarationName::CXXOperatorName:
729 ID.AddInteger((OverloadedOperatorKind)Key.Data);
730 break;
731 case DeclarationName::CXXConstructorName:
732 case DeclarationName::CXXDestructorName:
733 case DeclarationName::CXXConversionFunctionName:
734 case DeclarationName::CXXUsingDirective:
735 break;
736 }
737
738 return ID.ComputeHash();
739}
740
741ASTDeclContextNameLookupTrait::internal_key_type
742ASTDeclContextNameLookupTrait::GetInternalKey(
743 const external_key_type& Name) const {
744 DeclNameKey Key;
745 Key.Kind = Name.getNameKind();
746 switch (Name.getNameKind()) {
747 case DeclarationName::Identifier:
748 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
749 break;
750 case DeclarationName::ObjCZeroArgSelector:
751 case DeclarationName::ObjCOneArgSelector:
752 case DeclarationName::ObjCMultiArgSelector:
753 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
754 break;
755 case DeclarationName::CXXOperatorName:
756 Key.Data = Name.getCXXOverloadedOperator();
757 break;
758 case DeclarationName::CXXLiteralOperatorName:
759 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
760 break;
761 case DeclarationName::CXXConstructorName:
762 case DeclarationName::CXXDestructorName:
763 case DeclarationName::CXXConversionFunctionName:
764 case DeclarationName::CXXUsingDirective:
765 Key.Data = 0;
766 break;
767 }
768
769 return Key;
770}
771
772std::pair<unsigned, unsigned>
773ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000774 using namespace llvm::support;
775 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
776 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000777 return std::make_pair(KeyLen, DataLen);
778}
779
780ASTDeclContextNameLookupTrait::internal_key_type
781ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000782 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000783
784 DeclNameKey Key;
785 Key.Kind = (DeclarationName::NameKind)*d++;
786 switch (Key.Kind) {
787 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000788 Key.Data = (uint64_t)Reader.getLocalIdentifier(
789 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000790 break;
791 case DeclarationName::ObjCZeroArgSelector:
792 case DeclarationName::ObjCOneArgSelector:
793 case DeclarationName::ObjCMultiArgSelector:
794 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000795 (uint64_t)Reader.getLocalSelector(
796 F, endian::readNext<uint32_t, little, unaligned>(
797 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000798 break;
799 case DeclarationName::CXXOperatorName:
800 Key.Data = *d++; // OverloadedOperatorKind
801 break;
802 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000803 Key.Data = (uint64_t)Reader.getLocalIdentifier(
804 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000805 break;
806 case DeclarationName::CXXConstructorName:
807 case DeclarationName::CXXDestructorName:
808 case DeclarationName::CXXConversionFunctionName:
809 case DeclarationName::CXXUsingDirective:
810 Key.Data = 0;
811 break;
812 }
813
814 return Key;
815}
816
817ASTDeclContextNameLookupTrait::data_type
818ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
819 const unsigned char* d,
820 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000821 using namespace llvm::support;
822 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000823 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
824 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000825 return std::make_pair(Start, Start + NumDecls);
826}
827
828bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000829 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000830 const std::pair<uint64_t, uint64_t> &Offsets,
831 DeclContextInfo &Info) {
832 SavedStreamPosition SavedPosition(Cursor);
833 // First the lexical decls.
834 if (Offsets.first != 0) {
835 Cursor.JumpToBit(Offsets.first);
836
837 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000838 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000839 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000840 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000841 if (RecCode != DECL_CONTEXT_LEXICAL) {
842 Error("Expected lexical block");
843 return true;
844 }
845
Chris Lattner0e6c9402013-01-20 02:38:54 +0000846 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
847 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000848 }
849
850 // Now the lookup table.
851 if (Offsets.second != 0) {
852 Cursor.JumpToBit(Offsets.second);
853
854 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000855 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000856 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000857 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000858 if (RecCode != DECL_CONTEXT_VISIBLE) {
859 Error("Expected visible lookup table block");
860 return true;
861 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000862 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
863 (const unsigned char *)Blob.data() + Record[0],
864 (const unsigned char *)Blob.data() + sizeof(uint32_t),
865 (const unsigned char *)Blob.data(),
866 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000867 }
868
869 return false;
870}
871
872void ASTReader::Error(StringRef Msg) {
873 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000874 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
875 Diag(diag::note_module_cache_path)
876 << PP.getHeaderSearchInfo().getModuleCachePath();
877 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000878}
879
880void ASTReader::Error(unsigned DiagID,
881 StringRef Arg1, StringRef Arg2) {
882 if (Diags.isDiagnosticInFlight())
883 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
884 else
885 Diag(DiagID) << Arg1 << Arg2;
886}
887
888//===----------------------------------------------------------------------===//
889// Source Manager Deserialization
890//===----------------------------------------------------------------------===//
891
892/// \brief Read the line table in the source manager block.
893/// \returns true if there was an error.
894bool ASTReader::ParseLineTable(ModuleFile &F,
895 SmallVectorImpl<uint64_t> &Record) {
896 unsigned Idx = 0;
897 LineTableInfo &LineTable = SourceMgr.getLineTable();
898
899 // Parse the file names
900 std::map<int, int> FileIDs;
901 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
902 // Extract the file name
903 unsigned FilenameLen = Record[Idx++];
904 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
905 Idx += FilenameLen;
906 MaybeAddSystemRootToFilename(F, Filename);
907 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
908 }
909
910 // Parse the line entries
911 std::vector<LineEntry> Entries;
912 while (Idx < Record.size()) {
913 int FID = Record[Idx++];
914 assert(FID >= 0 && "Serialized line entries for non-local file.");
915 // Remap FileID from 1-based old view.
916 FID += F.SLocEntryBaseID - 1;
917
918 // Extract the line entries
919 unsigned NumEntries = Record[Idx++];
920 assert(NumEntries && "Numentries is 00000");
921 Entries.clear();
922 Entries.reserve(NumEntries);
923 for (unsigned I = 0; I != NumEntries; ++I) {
924 unsigned FileOffset = Record[Idx++];
925 unsigned LineNo = Record[Idx++];
926 int FilenameID = FileIDs[Record[Idx++]];
927 SrcMgr::CharacteristicKind FileKind
928 = (SrcMgr::CharacteristicKind)Record[Idx++];
929 unsigned IncludeOffset = Record[Idx++];
930 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
931 FileKind, IncludeOffset));
932 }
933 LineTable.AddEntry(FileID::get(FID), Entries);
934 }
935
936 return false;
937}
938
939/// \brief Read a source manager block
940bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
941 using namespace SrcMgr;
942
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000943 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000944
945 // Set the source-location entry cursor to the current position in
946 // the stream. This cursor will be used to read the contents of the
947 // source manager block initially, and then lazily read
948 // source-location entries as needed.
949 SLocEntryCursor = F.Stream;
950
951 // The stream itself is going to skip over the source manager block.
952 if (F.Stream.SkipBlock()) {
953 Error("malformed block record in AST file");
954 return true;
955 }
956
957 // Enter the source manager block.
958 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
959 Error("malformed source manager block record in AST file");
960 return true;
961 }
962
963 RecordData Record;
964 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +0000965 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
966
967 switch (E.Kind) {
968 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
969 case llvm::BitstreamEntry::Error:
970 Error("malformed block record in AST file");
971 return true;
972 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +0000973 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +0000974 case llvm::BitstreamEntry::Record:
975 // The interesting case.
976 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000977 }
Chris Lattnere7b154b2013-01-19 21:39:22 +0000978
Guy Benyei11169dd2012-12-18 14:30:41 +0000979 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +0000980 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +0000981 StringRef Blob;
982 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000983 default: // Default behavior: ignore.
984 break;
985
986 case SM_SLOC_FILE_ENTRY:
987 case SM_SLOC_BUFFER_ENTRY:
988 case SM_SLOC_EXPANSION_ENTRY:
989 // Once we hit one of the source location entries, we're done.
990 return false;
991 }
992 }
993}
994
995/// \brief If a header file is not found at the path that we expect it to be
996/// and the PCH file was moved from its original location, try to resolve the
997/// file by assuming that header+PCH were moved together and the header is in
998/// the same place relative to the PCH.
999static std::string
1000resolveFileRelativeToOriginalDir(const std::string &Filename,
1001 const std::string &OriginalDir,
1002 const std::string &CurrDir) {
1003 assert(OriginalDir != CurrDir &&
1004 "No point trying to resolve the file if the PCH dir didn't change");
1005 using namespace llvm::sys;
1006 SmallString<128> filePath(Filename);
1007 fs::make_absolute(filePath);
1008 assert(path::is_absolute(OriginalDir));
1009 SmallString<128> currPCHPath(CurrDir);
1010
1011 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1012 fileDirE = path::end(path::parent_path(filePath));
1013 path::const_iterator origDirI = path::begin(OriginalDir),
1014 origDirE = path::end(OriginalDir);
1015 // Skip the common path components from filePath and OriginalDir.
1016 while (fileDirI != fileDirE && origDirI != origDirE &&
1017 *fileDirI == *origDirI) {
1018 ++fileDirI;
1019 ++origDirI;
1020 }
1021 for (; origDirI != origDirE; ++origDirI)
1022 path::append(currPCHPath, "..");
1023 path::append(currPCHPath, fileDirI, fileDirE);
1024 path::append(currPCHPath, path::filename(Filename));
1025 return currPCHPath.str();
1026}
1027
1028bool ASTReader::ReadSLocEntry(int ID) {
1029 if (ID == 0)
1030 return false;
1031
1032 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1033 Error("source location entry ID out-of-range for AST file");
1034 return true;
1035 }
1036
1037 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1038 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001039 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001040 unsigned BaseOffset = F->SLocEntryBaseOffset;
1041
1042 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001043 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1044 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001045 Error("incorrectly-formatted source location entry in AST file");
1046 return true;
1047 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001048
Guy Benyei11169dd2012-12-18 14:30:41 +00001049 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001050 StringRef Blob;
1051 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001052 default:
1053 Error("incorrectly-formatted source location entry in AST file");
1054 return true;
1055
1056 case SM_SLOC_FILE_ENTRY: {
1057 // We will detect whether a file changed and return 'Failure' for it, but
1058 // we will also try to fail gracefully by setting up the SLocEntry.
1059 unsigned InputID = Record[4];
1060 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001061 const FileEntry *File = IF.getFile();
1062 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001063
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001064 // Note that we only check if a File was returned. If it was out-of-date
1065 // we have complained but we will continue creating a FileID to recover
1066 // gracefully.
1067 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001068 return true;
1069
1070 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1071 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1072 // This is the module's main file.
1073 IncludeLoc = getImportLocation(F);
1074 }
1075 SrcMgr::CharacteristicKind
1076 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1077 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1078 ID, BaseOffset + Record[0]);
1079 SrcMgr::FileInfo &FileInfo =
1080 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1081 FileInfo.NumCreatedFIDs = Record[5];
1082 if (Record[3])
1083 FileInfo.setHasLineDirectives();
1084
1085 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1086 unsigned NumFileDecls = Record[7];
1087 if (NumFileDecls) {
1088 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1089 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1090 NumFileDecls));
1091 }
1092
1093 const SrcMgr::ContentCache *ContentCache
1094 = SourceMgr.getOrCreateContentCache(File,
1095 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1096 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1097 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1098 unsigned Code = SLocEntryCursor.ReadCode();
1099 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001100 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001101
1102 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1103 Error("AST record has invalid code");
1104 return true;
1105 }
1106
1107 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001108 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00001109 SourceMgr.overrideFileContents(File, Buffer);
1110 }
1111
1112 break;
1113 }
1114
1115 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001116 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 unsigned Offset = Record[0];
1118 SrcMgr::CharacteristicKind
1119 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1120 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1121 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1122 IncludeLoc = getImportLocation(F);
1123 }
1124 unsigned Code = SLocEntryCursor.ReadCode();
1125 Record.clear();
1126 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001127 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001128
1129 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1130 Error("AST record has invalid code");
1131 return true;
1132 }
1133
1134 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001135 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00001136 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
1137 BaseOffset + Offset, IncludeLoc);
1138 break;
1139 }
1140
1141 case SM_SLOC_EXPANSION_ENTRY: {
1142 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1143 SourceMgr.createExpansionLoc(SpellingLoc,
1144 ReadSourceLocation(*F, Record[2]),
1145 ReadSourceLocation(*F, Record[3]),
1146 Record[4],
1147 ID,
1148 BaseOffset + Record[0]);
1149 break;
1150 }
1151 }
1152
1153 return false;
1154}
1155
1156std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1157 if (ID == 0)
1158 return std::make_pair(SourceLocation(), "");
1159
1160 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1161 Error("source location entry ID out-of-range for AST file");
1162 return std::make_pair(SourceLocation(), "");
1163 }
1164
1165 // Find which module file this entry lands in.
1166 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1167 if (M->Kind != MK_Module)
1168 return std::make_pair(SourceLocation(), "");
1169
1170 // FIXME: Can we map this down to a particular submodule? That would be
1171 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001172 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001173}
1174
1175/// \brief Find the location where the module F is imported.
1176SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1177 if (F->ImportLoc.isValid())
1178 return F->ImportLoc;
1179
1180 // Otherwise we have a PCH. It's considered to be "imported" at the first
1181 // location of its includer.
1182 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001183 // Main file is the importer.
1184 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1185 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001186 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001187 return F->ImportedBy[0]->FirstLoc;
1188}
1189
1190/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1191/// specified cursor. Read the abbreviations that are at the top of the block
1192/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001193bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001194 if (Cursor.EnterSubBlock(BlockID)) {
1195 Error("malformed block record in AST file");
1196 return Failure;
1197 }
1198
1199 while (true) {
1200 uint64_t Offset = Cursor.GetCurrentBitNo();
1201 unsigned Code = Cursor.ReadCode();
1202
1203 // We expect all abbrevs to be at the start of the block.
1204 if (Code != llvm::bitc::DEFINE_ABBREV) {
1205 Cursor.JumpToBit(Offset);
1206 return false;
1207 }
1208 Cursor.ReadAbbrevRecord();
1209 }
1210}
1211
Richard Smithe40f2ba2013-08-07 21:41:30 +00001212Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001213 unsigned &Idx) {
1214 Token Tok;
1215 Tok.startToken();
1216 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1217 Tok.setLength(Record[Idx++]);
1218 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1219 Tok.setIdentifierInfo(II);
1220 Tok.setKind((tok::TokenKind)Record[Idx++]);
1221 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1222 return Tok;
1223}
1224
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001225MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001226 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001227
1228 // Keep track of where we are in the stream, then jump back there
1229 // after reading this macro.
1230 SavedStreamPosition SavedPosition(Stream);
1231
1232 Stream.JumpToBit(Offset);
1233 RecordData Record;
1234 SmallVector<IdentifierInfo*, 16> MacroArgs;
1235 MacroInfo *Macro = 0;
1236
Guy Benyei11169dd2012-12-18 14:30:41 +00001237 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001238 // Advance to the next record, but if we get to the end of the block, don't
1239 // pop it (removing all the abbreviations from the cursor) since we want to
1240 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001241 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001242 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1243
1244 switch (Entry.Kind) {
1245 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1246 case llvm::BitstreamEntry::Error:
1247 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001248 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001249 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001250 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001251 case llvm::BitstreamEntry::Record:
1252 // The interesting case.
1253 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001254 }
1255
1256 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001257 Record.clear();
1258 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001259 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001260 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001261 case PP_MACRO_DIRECTIVE_HISTORY:
1262 return Macro;
1263
Guy Benyei11169dd2012-12-18 14:30:41 +00001264 case PP_MACRO_OBJECT_LIKE:
1265 case PP_MACRO_FUNCTION_LIKE: {
1266 // If we already have a macro, that means that we've hit the end
1267 // of the definition of the macro we were looking for. We're
1268 // done.
1269 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001270 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001271
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001272 unsigned NextIndex = 1; // Skip identifier ID.
1273 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001274 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001275 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001276 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001277 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001278 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001279
Guy Benyei11169dd2012-12-18 14:30:41 +00001280 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1281 // Decode function-like macro info.
1282 bool isC99VarArgs = Record[NextIndex++];
1283 bool isGNUVarArgs = Record[NextIndex++];
1284 bool hasCommaPasting = Record[NextIndex++];
1285 MacroArgs.clear();
1286 unsigned NumArgs = Record[NextIndex++];
1287 for (unsigned i = 0; i != NumArgs; ++i)
1288 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1289
1290 // Install function-like macro info.
1291 MI->setIsFunctionLike();
1292 if (isC99VarArgs) MI->setIsC99Varargs();
1293 if (isGNUVarArgs) MI->setIsGNUVarargs();
1294 if (hasCommaPasting) MI->setHasCommaPasting();
1295 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1296 PP.getPreprocessorAllocator());
1297 }
1298
Guy Benyei11169dd2012-12-18 14:30:41 +00001299 // Remember that we saw this macro last so that we add the tokens that
1300 // form its body to it.
1301 Macro = MI;
1302
1303 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1304 Record[NextIndex]) {
1305 // We have a macro definition. Register the association
1306 PreprocessedEntityID
1307 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1308 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001309 PreprocessingRecord::PPEntityID
1310 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1311 MacroDefinition *PPDef =
1312 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1313 if (PPDef)
1314 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001315 }
1316
1317 ++NumMacrosRead;
1318 break;
1319 }
1320
1321 case PP_TOKEN: {
1322 // If we see a TOKEN before a PP_MACRO_*, then the file is
1323 // erroneous, just pretend we didn't see this.
1324 if (Macro == 0) break;
1325
John McCallf413f5e2013-05-03 00:10:13 +00001326 unsigned Idx = 0;
1327 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001328 Macro->AddTokenToBody(Tok);
1329 break;
1330 }
1331 }
1332 }
1333}
1334
1335PreprocessedEntityID
1336ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1337 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1338 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1339 assert(I != M.PreprocessedEntityRemap.end()
1340 && "Invalid index into preprocessed entity index remap");
1341
1342 return LocalID + I->second;
1343}
1344
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001345unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1346 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001347}
1348
1349HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001350HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1351 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1352 FE->getName() };
1353 return ikey;
1354}
Guy Benyei11169dd2012-12-18 14:30:41 +00001355
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001356bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1357 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001358 return false;
1359
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001360 if (strcmp(a.Filename, b.Filename) == 0)
1361 return true;
1362
Guy Benyei11169dd2012-12-18 14:30:41 +00001363 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001364 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001365 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1366 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001367 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001368}
1369
1370std::pair<unsigned, unsigned>
1371HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001372 using namespace llvm::support;
1373 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001374 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001375 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001376}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001377
1378HeaderFileInfoTrait::internal_key_type
1379HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001380 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001381 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001382 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1383 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001384 ikey.Filename = (const char *)d;
1385 return ikey;
1386}
1387
Guy Benyei11169dd2012-12-18 14:30:41 +00001388HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001389HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001390 unsigned DataLen) {
1391 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001392 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001393 HeaderFileInfo HFI;
1394 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001395 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1396 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001397 HFI.isImport = (Flags >> 5) & 0x01;
1398 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1399 HFI.DirInfo = (Flags >> 2) & 0x03;
1400 HFI.Resolved = (Flags >> 1) & 0x01;
1401 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001402 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1403 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1404 M, endian::readNext<uint32_t, little, unaligned>(d));
1405 if (unsigned FrameworkOffset =
1406 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001407 // The framework offset is 1 greater than the actual offset,
1408 // since 0 is used as an indicator for "no framework name".
1409 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1410 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1411 }
1412
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001413 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001414 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001415 if (LocalSMID) {
1416 // This header is part of a module. Associate it with the module to enable
1417 // implicit module import.
1418 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1419 Module *Mod = Reader.getSubmodule(GlobalSMID);
1420 HFI.isModuleHeader = true;
1421 FileManager &FileMgr = Reader.getFileManager();
1422 ModuleMap &ModMap =
1423 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001424 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001425 }
1426 }
1427
Guy Benyei11169dd2012-12-18 14:30:41 +00001428 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1429 (void)End;
1430
1431 // This HeaderFileInfo was externally loaded.
1432 HFI.External = true;
1433 return HFI;
1434}
1435
Richard Smith49f906a2014-03-01 00:08:04 +00001436void
1437ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1438 GlobalMacroID GMacID,
1439 llvm::ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001440 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Richard Smith49f906a2014-03-01 00:08:04 +00001441 SubmoduleID *OverrideData = 0;
1442 if (!Overrides.empty()) {
1443 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1444 OverrideData[0] = Overrides.size();
1445 for (unsigned I = 0; I != Overrides.size(); ++I)
1446 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1447 }
1448 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001449}
1450
1451void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1452 ModuleFile *M,
1453 uint64_t MacroDirectivesOffset) {
1454 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1455 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001456}
1457
1458void ASTReader::ReadDefinedMacros() {
1459 // Note that we are loading defined macros.
1460 Deserializing Macros(this);
1461
1462 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1463 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001464 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001465
1466 // If there was no preprocessor block, skip this file.
1467 if (!MacroCursor.getBitStreamReader())
1468 continue;
1469
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001470 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001471 Cursor.JumpToBit((*I)->MacroStartOffset);
1472
1473 RecordData Record;
1474 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001475 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1476
1477 switch (E.Kind) {
1478 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1479 case llvm::BitstreamEntry::Error:
1480 Error("malformed block record in AST file");
1481 return;
1482 case llvm::BitstreamEntry::EndBlock:
1483 goto NextCursor;
1484
1485 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001486 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001487 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001488 default: // Default behavior: ignore.
1489 break;
1490
1491 case PP_MACRO_OBJECT_LIKE:
1492 case PP_MACRO_FUNCTION_LIKE:
1493 getLocalIdentifier(**I, Record[0]);
1494 break;
1495
1496 case PP_TOKEN:
1497 // Ignore tokens.
1498 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001499 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001500 break;
1501 }
1502 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001503 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001504 }
1505}
1506
1507namespace {
1508 /// \brief Visitor class used to look up identifirs in an AST file.
1509 class IdentifierLookupVisitor {
1510 StringRef Name;
1511 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001512 unsigned &NumIdentifierLookups;
1513 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001514 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001515
Guy Benyei11169dd2012-12-18 14:30:41 +00001516 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001517 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1518 unsigned &NumIdentifierLookups,
1519 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001520 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001521 NumIdentifierLookups(NumIdentifierLookups),
1522 NumIdentifierLookupHits(NumIdentifierLookupHits),
1523 Found()
1524 {
1525 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001526
1527 static bool visit(ModuleFile &M, void *UserData) {
1528 IdentifierLookupVisitor *This
1529 = static_cast<IdentifierLookupVisitor *>(UserData);
1530
1531 // If we've already searched this module file, skip it now.
1532 if (M.Generation <= This->PriorGeneration)
1533 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001534
Guy Benyei11169dd2012-12-18 14:30:41 +00001535 ASTIdentifierLookupTable *IdTable
1536 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1537 if (!IdTable)
1538 return false;
1539
1540 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1541 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001542 ++This->NumIdentifierLookups;
1543 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001544 if (Pos == IdTable->end())
1545 return false;
1546
1547 // Dereferencing the iterator has the effect of building the
1548 // IdentifierInfo node and populating it with the various
1549 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001550 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001551 This->Found = *Pos;
1552 return true;
1553 }
1554
1555 // \brief Retrieve the identifier info found within the module
1556 // files.
1557 IdentifierInfo *getIdentifierInfo() const { return Found; }
1558 };
1559}
1560
1561void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1562 // Note that we are loading an identifier.
1563 Deserializing AnIdentifier(this);
1564
1565 unsigned PriorGeneration = 0;
1566 if (getContext().getLangOpts().Modules)
1567 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001568
1569 // If there is a global index, look there first to determine which modules
1570 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001571 GlobalModuleIndex::HitSet Hits;
1572 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00001573 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001574 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1575 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001576 }
1577 }
1578
Douglas Gregor7211ac12013-01-25 23:32:03 +00001579 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001580 NumIdentifierLookups,
1581 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001582 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001583 markIdentifierUpToDate(&II);
1584}
1585
1586void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1587 if (!II)
1588 return;
1589
1590 II->setOutOfDate(false);
1591
1592 // Update the generation for this identifier.
1593 if (getContext().getLangOpts().Modules)
1594 IdentifierGeneration[II] = CurrentGeneration;
1595}
1596
Richard Smith49f906a2014-03-01 00:08:04 +00001597struct ASTReader::ModuleMacroInfo {
1598 SubmoduleID SubModID;
1599 MacroInfo *MI;
1600 SubmoduleID *Overrides;
1601 // FIXME: Remove this.
1602 ModuleFile *F;
1603
1604 bool isDefine() const { return MI; }
1605
1606 SubmoduleID getSubmoduleID() const { return SubModID; }
1607
1608 llvm::ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
1609 if (!Overrides)
1610 return llvm::ArrayRef<SubmoduleID>();
1611 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1612 }
1613
1614 DefMacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
1615 if (!MI)
1616 return 0;
1617 return PP.AllocateDefMacroDirective(MI, ImportLoc, /*isImported=*/true);
1618 }
1619};
1620
1621ASTReader::ModuleMacroInfo *
1622ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1623 ModuleMacroInfo Info;
1624
1625 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1626 if (ID & 1) {
1627 // Macro undefinition.
1628 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
1629 Info.MI = 0;
1630 } else {
1631 // Macro definition.
1632 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1633 assert(GMacID);
1634
1635 // If this macro has already been loaded, don't do so again.
1636 // FIXME: This is highly dubious. Multiple macro definitions can have the
1637 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1638 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1639 return 0;
1640
1641 Info.MI = getMacro(GMacID);
1642 Info.SubModID = Info.MI->getOwningModuleID();
1643 }
1644 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1645 Info.F = PMInfo.M;
1646
1647 return new (Context) ModuleMacroInfo(Info);
1648}
1649
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001650void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1651 const PendingMacroInfo &PMInfo) {
1652 assert(II);
1653
1654 if (PMInfo.M->Kind != MK_Module) {
1655 installPCHMacroDirectives(II, *PMInfo.M,
1656 PMInfo.PCHMacroData.MacroDirectivesOffset);
1657 return;
1658 }
Richard Smith49f906a2014-03-01 00:08:04 +00001659
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001660 // Module Macro.
1661
Richard Smith49f906a2014-03-01 00:08:04 +00001662 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1663 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001664 return;
1665
Richard Smith49f906a2014-03-01 00:08:04 +00001666 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1667 if (Owner && Owner->NameVisibility == Module::Hidden) {
1668 // Macros in the owning module are hidden. Just remember this macro to
1669 // install if we make this module visible.
1670 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1671 } else {
1672 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001673 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001674}
1675
1676void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1677 ModuleFile &M, uint64_t Offset) {
1678 assert(M.Kind != MK_Module);
1679
1680 BitstreamCursor &Cursor = M.MacroCursor;
1681 SavedStreamPosition SavedPosition(Cursor);
1682 Cursor.JumpToBit(Offset);
1683
1684 llvm::BitstreamEntry Entry =
1685 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1686 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1687 Error("malformed block record in AST file");
1688 return;
1689 }
1690
1691 RecordData Record;
1692 PreprocessorRecordTypes RecType =
1693 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1694 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1695 Error("malformed block record in AST file");
1696 return;
1697 }
1698
1699 // Deserialize the macro directives history in reverse source-order.
1700 MacroDirective *Latest = 0, *Earliest = 0;
1701 unsigned Idx = 0, N = Record.size();
1702 while (Idx < N) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001703 MacroDirective *MD = 0;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001704 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001705 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1706 switch (K) {
1707 case MacroDirective::MD_Define: {
1708 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1709 MacroInfo *MI = getMacro(GMacID);
1710 bool isImported = Record[Idx++];
1711 bool isAmbiguous = Record[Idx++];
1712 DefMacroDirective *DefMD =
1713 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1714 DefMD->setAmbiguous(isAmbiguous);
1715 MD = DefMD;
1716 break;
1717 }
1718 case MacroDirective::MD_Undefine:
1719 MD = PP.AllocateUndefMacroDirective(Loc);
1720 break;
1721 case MacroDirective::MD_Visibility: {
1722 bool isPublic = Record[Idx++];
1723 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1724 break;
1725 }
1726 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001727
1728 if (!Latest)
1729 Latest = MD;
1730 if (Earliest)
1731 Earliest->setPrevious(MD);
1732 Earliest = MD;
1733 }
1734
1735 PP.setLoadedMacroDirective(II, Latest);
1736}
1737
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001738/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001739/// modules.
1740static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001741 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001742 assert(PrevMI && NewMI);
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001743 Module *PrevOwner = 0;
1744 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1745 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001746 SourceManager &SrcMgr = Reader.getSourceManager();
1747 bool PrevInSystem
1748 = PrevOwner? PrevOwner->IsSystem
1749 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1750 bool NewInSystem
1751 = NewOwner? NewOwner->IsSystem
1752 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1753 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001754 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001755 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001756}
1757
Richard Smith49f906a2014-03-01 00:08:04 +00001758void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1759 AmbiguousMacros &Ambig,
1760 llvm::ArrayRef<SubmoduleID> Overrides) {
1761 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1762 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001763
Richard Smith49f906a2014-03-01 00:08:04 +00001764 // If this macro is not yet visible, remove it from the hidden names list.
1765 Module *Owner = getSubmodule(OwnerID);
1766 HiddenNames &Hidden = HiddenNamesMap[Owner];
1767 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1768 if (HI != Hidden.HiddenMacros.end()) {
Richard Smith9d100862014-03-06 03:16:27 +00001769 auto SubOverrides = HI->second->getOverriddenSubmodules();
Richard Smith49f906a2014-03-01 00:08:04 +00001770 Hidden.HiddenMacros.erase(HI);
Richard Smith9d100862014-03-06 03:16:27 +00001771 removeOverriddenMacros(II, Ambig, SubOverrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001772 }
1773
1774 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001775 Ambig.erase(
1776 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1777 return MD->getInfo()->getOwningModuleID() == OwnerID;
1778 }),
1779 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001780 }
1781}
1782
1783ASTReader::AmbiguousMacros *
1784ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1785 llvm::ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001786 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001787 if (!Prev && Overrides.empty())
1788 return 0;
1789
1790 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective() : 0;
1791 if (PrevDef && PrevDef->isAmbiguous()) {
1792 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1793 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1794 Ambig.push_back(PrevDef);
1795
1796 removeOverriddenMacros(II, Ambig, Overrides);
1797
1798 if (!Ambig.empty())
1799 return &Ambig;
1800
1801 AmbiguousMacroDefs.erase(II);
1802 } else {
1803 // There's no ambiguity yet. Maybe we're introducing one.
1804 llvm::SmallVector<DefMacroDirective*, 1> Ambig;
1805 if (PrevDef)
1806 Ambig.push_back(PrevDef);
1807
1808 removeOverriddenMacros(II, Ambig, Overrides);
1809
1810 if (!Ambig.empty()) {
1811 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
1812 Result.swap(Ambig);
1813 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001814 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001815 }
Richard Smith49f906a2014-03-01 00:08:04 +00001816
1817 // We ended up with no ambiguity.
1818 return 0;
1819}
1820
1821void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
1822 Module *Owner) {
1823 assert(II && Owner);
1824
1825 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
1826 if (ImportLoc.isInvalid()) {
1827 // FIXME: If we made macros from this module visible but didn't provide a
1828 // source location for the import, we don't have a location for the macro.
1829 // Use the location at which the containing module file was first imported
1830 // for now.
1831 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00001832 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00001833 }
1834
1835 llvm::SmallVectorImpl<DefMacroDirective*> *Prev =
1836 removeOverriddenMacros(II, MMI->getOverriddenSubmodules());
1837
1838
1839 // Create a synthetic macro definition corresponding to the import (or null
1840 // if this was an undefinition of the macro).
1841 DefMacroDirective *MD = MMI->import(PP, ImportLoc);
1842
1843 // If there's no ambiguity, just install the macro.
1844 if (!Prev) {
1845 if (MD)
1846 PP.appendMacroDirective(II, MD);
1847 else
1848 PP.appendMacroDirective(II, PP.AllocateUndefMacroDirective(ImportLoc));
1849 return;
1850 }
1851 assert(!Prev->empty());
1852
1853 if (!MD) {
1854 // We imported a #undef that didn't remove all prior definitions. The most
1855 // recent prior definition remains, and we install it in the place of the
1856 // imported directive.
1857 MacroInfo *NewMI = Prev->back()->getInfo();
1858 Prev->pop_back();
1859 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc, /*Imported*/true);
1860 }
1861
1862 // We're introducing a macro definition that creates or adds to an ambiguity.
1863 // We can resolve that ambiguity if this macro is token-for-token identical to
1864 // all of the existing definitions.
1865 MacroInfo *NewMI = MD->getInfo();
1866 assert(NewMI && "macro definition with no MacroInfo?");
1867 while (!Prev->empty()) {
1868 MacroInfo *PrevMI = Prev->back()->getInfo();
1869 assert(PrevMI && "macro definition with no MacroInfo?");
1870
1871 // Before marking the macros as ambiguous, check if this is a case where
1872 // both macros are in system headers. If so, we trust that the system
1873 // did not get it wrong. This also handles cases where Clang's own
1874 // headers have a different spelling of certain system macros:
1875 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1876 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
1877 //
1878 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
1879 // overrides the system limits.h's macros, so there's no conflict here.
1880 if (NewMI != PrevMI &&
1881 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
1882 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
1883 break;
1884
1885 // The previous definition is the same as this one (or both are defined in
1886 // system modules so we can assume they're equivalent); we don't need to
1887 // track it any more.
1888 Prev->pop_back();
1889 }
1890
1891 if (!Prev->empty())
1892 MD->setAmbiguous(true);
1893
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001894 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001895}
1896
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001897ASTReader::InputFileInfo
1898ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001899 // Go find this input file.
1900 BitstreamCursor &Cursor = F.InputFilesCursor;
1901 SavedStreamPosition SavedPosition(Cursor);
1902 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1903
1904 unsigned Code = Cursor.ReadCode();
1905 RecordData Record;
1906 StringRef Blob;
1907
1908 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1909 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1910 "invalid record type for input file");
1911 (void)Result;
1912
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001913 std::string Filename;
1914 off_t StoredSize;
1915 time_t StoredTime;
1916 bool Overridden;
1917
Ben Langmuir198c1682014-03-07 07:27:49 +00001918 assert(Record[0] == ID && "Bogus stored ID or offset");
1919 StoredSize = static_cast<off_t>(Record[1]);
1920 StoredTime = static_cast<time_t>(Record[2]);
1921 Overridden = static_cast<bool>(Record[3]);
1922 Filename = Blob;
1923 MaybeAddSystemRootToFilename(F, Filename);
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001924
Hans Wennborg73945142014-03-14 17:45:06 +00001925 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1926 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001927}
1928
1929std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001930 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00001931}
1932
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001933InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001934 // If this ID is bogus, just return an empty input file.
1935 if (ID == 0 || ID > F.InputFilesLoaded.size())
1936 return InputFile();
1937
1938 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001939 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001940 return F.InputFilesLoaded[ID-1];
1941
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001942 if (F.InputFilesLoaded[ID-1].isNotFound())
1943 return InputFile();
1944
Guy Benyei11169dd2012-12-18 14:30:41 +00001945 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001946 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001947 SavedStreamPosition SavedPosition(Cursor);
1948 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1949
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001950 InputFileInfo FI = readInputFileInfo(F, ID);
1951 off_t StoredSize = FI.StoredSize;
1952 time_t StoredTime = FI.StoredTime;
1953 bool Overridden = FI.Overridden;
1954 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001955
Ben Langmuir198c1682014-03-07 07:27:49 +00001956 const FileEntry *File
1957 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1958 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1959
1960 // If we didn't find the file, resolve it relative to the
1961 // original directory from which this AST file was created.
1962 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1963 F.OriginalDir != CurrentDir) {
1964 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1965 F.OriginalDir,
1966 CurrentDir);
1967 if (!Resolved.empty())
1968 File = FileMgr.getFile(Resolved);
1969 }
1970
1971 // For an overridden file, create a virtual file with the stored
1972 // size/timestamp.
1973 if (Overridden && File == 0) {
1974 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1975 }
1976
1977 if (File == 0) {
1978 if (Complain) {
1979 std::string ErrorStr = "could not find file '";
1980 ErrorStr += Filename;
1981 ErrorStr += "' referenced by AST file";
1982 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001983 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001984 // Record that we didn't find the file.
1985 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1986 return InputFile();
1987 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001988
Ben Langmuir198c1682014-03-07 07:27:49 +00001989 // Check if there was a request to override the contents of the file
1990 // that was part of the precompiled header. Overridding such a file
1991 // can lead to problems when lexing using the source locations from the
1992 // PCH.
1993 SourceManager &SM = getSourceManager();
1994 if (!Overridden && SM.isFileOverridden(File)) {
1995 if (Complain)
1996 Error(diag::err_fe_pch_file_overridden, Filename);
1997 // After emitting the diagnostic, recover by disabling the override so
1998 // that the original file will be used.
1999 SM.disableFileContentsOverride(File);
2000 // The FileEntry is a virtual file entry with the size of the contents
2001 // that would override the original contents. Set it to the original's
2002 // size/time.
2003 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2004 StoredSize, StoredTime);
2005 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002006
Ben Langmuir198c1682014-03-07 07:27:49 +00002007 bool IsOutOfDate = false;
2008
2009 // For an overridden file, there is nothing to validate.
2010 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00002011#if !defined(LLVM_ON_WIN32)
Ben Langmuir198c1682014-03-07 07:27:49 +00002012 // In our regression testing, the Windows file system seems to
2013 // have inconsistent modification times that sometimes
2014 // erroneously trigger this error-handling path.
2015 || StoredTime != File->getModificationTime()
Guy Benyei11169dd2012-12-18 14:30:41 +00002016#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002017 )) {
2018 if (Complain) {
2019 // Build a list of the PCH imports that got us here (in reverse).
2020 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2021 while (ImportStack.back()->ImportedBy.size() > 0)
2022 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002023
Ben Langmuir198c1682014-03-07 07:27:49 +00002024 // The top-level PCH is stale.
2025 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2026 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002027
Ben Langmuir198c1682014-03-07 07:27:49 +00002028 // Print the import stack.
2029 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2030 Diag(diag::note_pch_required_by)
2031 << Filename << ImportStack[0]->FileName;
2032 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002033 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002034 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002035 }
2036
Ben Langmuir198c1682014-03-07 07:27:49 +00002037 if (!Diags.isDiagnosticInFlight())
2038 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002039 }
2040
Ben Langmuir198c1682014-03-07 07:27:49 +00002041 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002042 }
2043
Ben Langmuir198c1682014-03-07 07:27:49 +00002044 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2045
2046 // Note that we've loaded this input file.
2047 F.InputFilesLoaded[ID-1] = IF;
2048 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002049}
2050
2051const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2052 ModuleFile &M = ModuleMgr.getPrimaryModule();
2053 std::string Filename = filenameStrRef;
2054 MaybeAddSystemRootToFilename(M, Filename);
2055 const FileEntry *File = FileMgr.getFile(Filename);
2056 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
2057 M.OriginalDir != CurrentDir) {
2058 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2059 M.OriginalDir,
2060 CurrentDir);
2061 if (!resolved.empty())
2062 File = FileMgr.getFile(resolved);
2063 }
2064
2065 return File;
2066}
2067
2068/// \brief If we are loading a relocatable PCH file, and the filename is
2069/// not an absolute path, add the system root to the beginning of the file
2070/// name.
2071void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2072 std::string &Filename) {
2073 // If this is not a relocatable PCH file, there's nothing to do.
2074 if (!M.RelocatablePCH)
2075 return;
2076
2077 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2078 return;
2079
2080 if (isysroot.empty()) {
2081 // If no system root was given, default to '/'
2082 Filename.insert(Filename.begin(), '/');
2083 return;
2084 }
2085
2086 unsigned Length = isysroot.size();
2087 if (isysroot[Length - 1] != '/')
2088 Filename.insert(Filename.begin(), '/');
2089
2090 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2091}
2092
2093ASTReader::ASTReadResult
2094ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002095 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002096 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002097 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002098 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002099
2100 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2101 Error("malformed block record in AST file");
2102 return Failure;
2103 }
2104
2105 // Read all of the records and blocks in the control block.
2106 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002107 while (1) {
2108 llvm::BitstreamEntry Entry = Stream.advance();
2109
2110 switch (Entry.Kind) {
2111 case llvm::BitstreamEntry::Error:
2112 Error("malformed block record in AST file");
2113 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002114 case llvm::BitstreamEntry::EndBlock: {
2115 // Validate input files.
2116 const HeaderSearchOptions &HSOpts =
2117 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002118
2119 // All user input files reside at the index range [0, Record[1]), and
2120 // system input files reside at [Record[1], Record[0]).
2121 // Record is the one from INPUT_FILE_OFFSETS.
2122 unsigned NumInputs = Record[0];
2123 unsigned NumUserInputs = Record[1];
2124
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002125 if (!DisableValidation &&
Ben Langmuir1e258222014-04-08 15:36:28 +00002126 (ValidateSystemInputs || !HSOpts.ModulesValidateOncePerBuildSession ||
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002127 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002128 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002129
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002130 // If we are reading a module, we will create a verification timestamp,
2131 // so we verify all input files. Otherwise, verify only user input
2132 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002133
2134 unsigned N = NumUserInputs;
2135 if (ValidateSystemInputs ||
Ben Langmuircb69b572014-03-07 06:40:32 +00002136 (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
2137 N = NumInputs;
2138
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002139 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002140 InputFile IF = getInputFile(F, I+1, Complain);
2141 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002142 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002143 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002144 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002145
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002146 if (Listener)
2147 Listener->visitModuleFile(F.FileName);
2148
Ben Langmuircb69b572014-03-07 06:40:32 +00002149 if (Listener && Listener->needsInputFileVisitation()) {
2150 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2151 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002152 for (unsigned I = 0; I < N; ++I) {
2153 bool IsSystem = I >= NumUserInputs;
2154 InputFileInfo FI = readInputFileInfo(F, I+1);
2155 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2156 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002157 }
2158
Guy Benyei11169dd2012-12-18 14:30:41 +00002159 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002160 }
2161
Chris Lattnere7b154b2013-01-19 21:39:22 +00002162 case llvm::BitstreamEntry::SubBlock:
2163 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002164 case INPUT_FILES_BLOCK_ID:
2165 F.InputFilesCursor = Stream;
2166 if (Stream.SkipBlock() || // Skip with the main cursor
2167 // Read the abbreviations
2168 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2169 Error("malformed block record in AST file");
2170 return Failure;
2171 }
2172 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002173
Guy Benyei11169dd2012-12-18 14:30:41 +00002174 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002175 if (Stream.SkipBlock()) {
2176 Error("malformed block record in AST file");
2177 return Failure;
2178 }
2179 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002180 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002181
2182 case llvm::BitstreamEntry::Record:
2183 // The interesting case.
2184 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002185 }
2186
2187 // Read and process a record.
2188 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002189 StringRef Blob;
2190 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002191 case METADATA: {
2192 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2193 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002194 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2195 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002196 return VersionMismatch;
2197 }
2198
2199 bool hasErrors = Record[5];
2200 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2201 Diag(diag::err_pch_with_compiler_errors);
2202 return HadErrors;
2203 }
2204
2205 F.RelocatablePCH = Record[4];
2206
2207 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002208 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002209 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2210 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002211 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002212 return VersionMismatch;
2213 }
2214 break;
2215 }
2216
2217 case IMPORTS: {
2218 // Load each of the imported PCH files.
2219 unsigned Idx = 0, N = Record.size();
2220 while (Idx < N) {
2221 // Read information about the AST file.
2222 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2223 // The import location will be the local one for now; we will adjust
2224 // all import locations of module imports after the global source
2225 // location info are setup.
2226 SourceLocation ImportLoc =
2227 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002228 off_t StoredSize = (off_t)Record[Idx++];
2229 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002230 unsigned Length = Record[Idx++];
2231 SmallString<128> ImportedFile(Record.begin() + Idx,
2232 Record.begin() + Idx + Length);
2233 Idx += Length;
2234
2235 // Load the AST file.
2236 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00002237 StoredSize, StoredModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00002238 ClientLoadCapabilities)) {
2239 case Failure: return Failure;
2240 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002241 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002242 case OutOfDate: return OutOfDate;
2243 case VersionMismatch: return VersionMismatch;
2244 case ConfigurationMismatch: return ConfigurationMismatch;
2245 case HadErrors: return HadErrors;
2246 case Success: break;
2247 }
2248 }
2249 break;
2250 }
2251
2252 case LANGUAGE_OPTIONS: {
2253 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2254 if (Listener && &F == *ModuleMgr.begin() &&
2255 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002256 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002257 return ConfigurationMismatch;
2258 break;
2259 }
2260
2261 case TARGET_OPTIONS: {
2262 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2263 if (Listener && &F == *ModuleMgr.begin() &&
2264 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002265 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002266 return ConfigurationMismatch;
2267 break;
2268 }
2269
2270 case DIAGNOSTIC_OPTIONS: {
2271 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2272 if (Listener && &F == *ModuleMgr.begin() &&
2273 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002274 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002275 return ConfigurationMismatch;
2276 break;
2277 }
2278
2279 case FILE_SYSTEM_OPTIONS: {
2280 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2281 if (Listener && &F == *ModuleMgr.begin() &&
2282 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002283 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002284 return ConfigurationMismatch;
2285 break;
2286 }
2287
2288 case HEADER_SEARCH_OPTIONS: {
2289 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2290 if (Listener && &F == *ModuleMgr.begin() &&
2291 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002292 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002293 return ConfigurationMismatch;
2294 break;
2295 }
2296
2297 case PREPROCESSOR_OPTIONS: {
2298 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2299 if (Listener && &F == *ModuleMgr.begin() &&
2300 ParsePreprocessorOptions(Record, Complain, *Listener,
2301 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002302 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002303 return ConfigurationMismatch;
2304 break;
2305 }
2306
2307 case ORIGINAL_FILE:
2308 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002309 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002310 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2311 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2312 break;
2313
2314 case ORIGINAL_FILE_ID:
2315 F.OriginalSourceFileID = FileID::get(Record[0]);
2316 break;
2317
2318 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002319 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002320 break;
2321
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002322 case MODULE_NAME:
2323 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002324 if (Listener)
2325 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002326 break;
2327
2328 case MODULE_MAP_FILE:
2329 F.ModuleMapPath = Blob;
2330
2331 // Try to resolve ModuleName in the current header search context and
2332 // verify that it is found in the same module map file as we saved. If the
2333 // top-level AST file is a main file, skip this check because there is no
2334 // usable header search context.
2335 assert(!F.ModuleName.empty() &&
2336 "MODULE_NAME should come before MOUDLE_MAP_FILE");
2337 if (F.Kind == MK_Module &&
2338 (*ModuleMgr.begin())->Kind != MK_MainFile) {
2339 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2340 if (!M) {
2341 assert(ImportedBy && "top-level import should be verified");
2342 if ((ClientLoadCapabilities & ARR_Missing) == 0)
2343 Diag(diag::err_imported_module_not_found)
2344 << F.ModuleName << ImportedBy->FileName;
2345 return Missing;
2346 }
2347
2348 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
2349 if (StoredModMap == nullptr || StoredModMap != M->ModuleMap) {
2350 assert(M->ModuleMap && "found module is missing module map file");
2351 assert(M->Name == F.ModuleName && "found module with different name");
2352 assert(ImportedBy && "top-level import should be verified");
2353 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2354 Diag(diag::err_imported_module_modmap_changed)
2355 << F.ModuleName << ImportedBy->FileName
2356 << M->ModuleMap->getName() << F.ModuleMapPath;
2357 return OutOfDate;
2358 }
2359 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002360
2361 if (Listener)
2362 Listener->ReadModuleMapFile(F.ModuleMapPath);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002363 break;
2364
Guy Benyei11169dd2012-12-18 14:30:41 +00002365 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002366 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002367 F.InputFilesLoaded.resize(Record[0]);
2368 break;
2369 }
2370 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002371}
2372
Ben Langmuir2c9af442014-04-10 17:57:43 +00002373ASTReader::ASTReadResult
2374ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002375 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002376
2377 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2378 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002379 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002380 }
2381
2382 // Read all of the records and blocks for the AST file.
2383 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002384 while (1) {
2385 llvm::BitstreamEntry Entry = Stream.advance();
2386
2387 switch (Entry.Kind) {
2388 case llvm::BitstreamEntry::Error:
2389 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002390 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002391 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002392 // Outside of C++, we do not store a lookup map for the translation unit.
2393 // Instead, mark it as needing a lookup map to be built if this module
2394 // contains any declarations lexically within it (which it always does!).
2395 // This usually has no cost, since we very rarely need the lookup map for
2396 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002397 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002398 if (DC->hasExternalLexicalStorage() &&
2399 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002400 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002401
Ben Langmuir2c9af442014-04-10 17:57:43 +00002402 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002404 case llvm::BitstreamEntry::SubBlock:
2405 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002406 case DECLTYPES_BLOCK_ID:
2407 // We lazily load the decls block, but we want to set up the
2408 // DeclsCursor cursor to point into it. Clone our current bitcode
2409 // cursor to it, enter the block and read the abbrevs in that block.
2410 // With the main cursor, we just skip over it.
2411 F.DeclsCursor = Stream;
2412 if (Stream.SkipBlock() || // Skip with the main cursor.
2413 // Read the abbrevs.
2414 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2415 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002416 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002417 }
2418 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002419
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 case PREPROCESSOR_BLOCK_ID:
2421 F.MacroCursor = Stream;
2422 if (!PP.getExternalSource())
2423 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002424
Guy Benyei11169dd2012-12-18 14:30:41 +00002425 if (Stream.SkipBlock() ||
2426 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_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 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2431 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002432
Guy Benyei11169dd2012-12-18 14:30:41 +00002433 case PREPROCESSOR_DETAIL_BLOCK_ID:
2434 F.PreprocessorDetailCursor = Stream;
2435 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002436 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002437 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002438 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002439 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002440 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002442 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2443
Guy Benyei11169dd2012-12-18 14:30:41 +00002444 if (!PP.getPreprocessingRecord())
2445 PP.createPreprocessingRecord();
2446 if (!PP.getPreprocessingRecord()->getExternalSource())
2447 PP.getPreprocessingRecord()->SetExternalSource(*this);
2448 break;
2449
2450 case SOURCE_MANAGER_BLOCK_ID:
2451 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002452 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002454
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002456 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2457 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002458 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002459
Guy Benyei11169dd2012-12-18 14:30:41 +00002460 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002461 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002462 if (Stream.SkipBlock() ||
2463 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2464 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002465 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 }
2467 CommentsCursors.push_back(std::make_pair(C, &F));
2468 break;
2469 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002470
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002472 if (Stream.SkipBlock()) {
2473 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002474 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002475 }
2476 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002477 }
2478 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002479
2480 case llvm::BitstreamEntry::Record:
2481 // The interesting case.
2482 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 }
2484
2485 // Read and process a record.
2486 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002487 StringRef Blob;
2488 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002489 default: // Default behavior: ignore.
2490 break;
2491
2492 case TYPE_OFFSET: {
2493 if (F.LocalNumTypes != 0) {
2494 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002495 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002497 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 F.LocalNumTypes = Record[0];
2499 unsigned LocalBaseTypeIndex = Record[1];
2500 F.BaseTypeIndex = getTotalNumTypes();
2501
2502 if (F.LocalNumTypes > 0) {
2503 // Introduce the global -> local mapping for types within this module.
2504 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2505
2506 // Introduce the local -> global mapping for types within this module.
2507 F.TypeRemap.insertOrReplace(
2508 std::make_pair(LocalBaseTypeIndex,
2509 F.BaseTypeIndex - LocalBaseTypeIndex));
2510
2511 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2512 }
2513 break;
2514 }
2515
2516 case DECL_OFFSET: {
2517 if (F.LocalNumDecls != 0) {
2518 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002519 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002520 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002521 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 F.LocalNumDecls = Record[0];
2523 unsigned LocalBaseDeclID = Record[1];
2524 F.BaseDeclID = getTotalNumDecls();
2525
2526 if (F.LocalNumDecls > 0) {
2527 // Introduce the global -> local mapping for declarations within this
2528 // module.
2529 GlobalDeclMap.insert(
2530 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2531
2532 // Introduce the local -> global mapping for declarations within this
2533 // module.
2534 F.DeclRemap.insertOrReplace(
2535 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2536
2537 // Introduce the global -> local mapping for declarations within this
2538 // module.
2539 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2540
2541 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2542 }
2543 break;
2544 }
2545
2546 case TU_UPDATE_LEXICAL: {
2547 DeclContext *TU = Context.getTranslationUnitDecl();
2548 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002549 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002550 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002551 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002552 TU->setHasExternalLexicalStorage(true);
2553 break;
2554 }
2555
2556 case UPDATE_VISIBLE: {
2557 unsigned Idx = 0;
2558 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2559 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002560 ASTDeclContextNameLookupTable::Create(
2561 (const unsigned char *)Blob.data() + Record[Idx++],
2562 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2563 (const unsigned char *)Blob.data(),
2564 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002565 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002566 auto *DC = cast<DeclContext>(D);
2567 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002568 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
Richard Smithcd45dbc2014-04-19 03:48:30 +00002569 // FIXME: There should never be an existing lookup table.
Richard Smith52e3fba2014-03-11 07:17:35 +00002570 delete LookupTable;
2571 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 } else
2573 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2574 break;
2575 }
2576
2577 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002578 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002579 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002580 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2581 (const unsigned char *)F.IdentifierTableData + Record[0],
2582 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2583 (const unsigned char *)F.IdentifierTableData,
2584 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002585
2586 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2587 }
2588 break;
2589
2590 case IDENTIFIER_OFFSET: {
2591 if (F.LocalNumIdentifiers != 0) {
2592 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002593 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002595 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002596 F.LocalNumIdentifiers = Record[0];
2597 unsigned LocalBaseIdentifierID = Record[1];
2598 F.BaseIdentifierID = getTotalNumIdentifiers();
2599
2600 if (F.LocalNumIdentifiers > 0) {
2601 // Introduce the global -> local mapping for identifiers within this
2602 // module.
2603 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2604 &F));
2605
2606 // Introduce the local -> global mapping for identifiers within this
2607 // module.
2608 F.IdentifierRemap.insertOrReplace(
2609 std::make_pair(LocalBaseIdentifierID,
2610 F.BaseIdentifierID - LocalBaseIdentifierID));
2611
2612 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2613 + F.LocalNumIdentifiers);
2614 }
2615 break;
2616 }
2617
Ben Langmuir332aafe2014-01-31 01:06:56 +00002618 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002619 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002620 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 break;
2622
2623 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002624 if (SpecialTypes.empty()) {
2625 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2626 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2627 break;
2628 }
2629
2630 if (SpecialTypes.size() != Record.size()) {
2631 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002632 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002633 }
2634
2635 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2636 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2637 if (!SpecialTypes[I])
2638 SpecialTypes[I] = ID;
2639 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2640 // merge step?
2641 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 break;
2643
2644 case STATISTICS:
2645 TotalNumStatements += Record[0];
2646 TotalNumMacros += Record[1];
2647 TotalLexicalDeclContexts += Record[2];
2648 TotalVisibleDeclContexts += Record[3];
2649 break;
2650
2651 case UNUSED_FILESCOPED_DECLS:
2652 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2653 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2654 break;
2655
2656 case DELEGATING_CTORS:
2657 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2658 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2659 break;
2660
2661 case WEAK_UNDECLARED_IDENTIFIERS:
2662 if (Record.size() % 4 != 0) {
2663 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002664 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 }
2666
2667 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2668 // files. This isn't the way to do it :)
2669 WeakUndeclaredIdentifiers.clear();
2670
2671 // Translate the weak, undeclared identifiers into global IDs.
2672 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2673 WeakUndeclaredIdentifiers.push_back(
2674 getGlobalIdentifierID(F, Record[I++]));
2675 WeakUndeclaredIdentifiers.push_back(
2676 getGlobalIdentifierID(F, Record[I++]));
2677 WeakUndeclaredIdentifiers.push_back(
2678 ReadSourceLocation(F, Record, I).getRawEncoding());
2679 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2680 }
2681 break;
2682
Richard Smith78165b52013-01-10 23:43:47 +00002683 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002685 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 break;
2687
2688 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002689 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 F.LocalNumSelectors = Record[0];
2691 unsigned LocalBaseSelectorID = Record[1];
2692 F.BaseSelectorID = getTotalNumSelectors();
2693
2694 if (F.LocalNumSelectors > 0) {
2695 // Introduce the global -> local mapping for selectors within this
2696 // module.
2697 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2698
2699 // Introduce the local -> global mapping for selectors within this
2700 // module.
2701 F.SelectorRemap.insertOrReplace(
2702 std::make_pair(LocalBaseSelectorID,
2703 F.BaseSelectorID - LocalBaseSelectorID));
2704
2705 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2706 }
2707 break;
2708 }
2709
2710 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002711 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 if (Record[0])
2713 F.SelectorLookupTable
2714 = ASTSelectorLookupTable::Create(
2715 F.SelectorLookupTableData + Record[0],
2716 F.SelectorLookupTableData,
2717 ASTSelectorLookupTrait(*this, F));
2718 TotalNumMethodPoolEntries += Record[1];
2719 break;
2720
2721 case REFERENCED_SELECTOR_POOL:
2722 if (!Record.empty()) {
2723 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2724 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2725 Record[Idx++]));
2726 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2727 getRawEncoding());
2728 }
2729 }
2730 break;
2731
2732 case PP_COUNTER_VALUE:
2733 if (!Record.empty() && Listener)
2734 Listener->ReadCounter(F, Record[0]);
2735 break;
2736
2737 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002738 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002739 F.NumFileSortedDecls = Record[0];
2740 break;
2741
2742 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002743 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002744 F.LocalNumSLocEntries = Record[0];
2745 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002746 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2748 SLocSpaceSize);
2749 // Make our entry in the range map. BaseID is negative and growing, so
2750 // we invert it. Because we invert it, though, we need the other end of
2751 // the range.
2752 unsigned RangeStart =
2753 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2754 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2755 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2756
2757 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2758 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2759 GlobalSLocOffsetMap.insert(
2760 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2761 - SLocSpaceSize,&F));
2762
2763 // Initialize the remapping table.
2764 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002765 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002767 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002768 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2769
2770 TotalNumSLocEntries += F.LocalNumSLocEntries;
2771 break;
2772 }
2773
2774 case MODULE_OFFSET_MAP: {
2775 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002776 const unsigned char *Data = (const unsigned char*)Blob.data();
2777 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002778
2779 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2780 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2781 F.SLocRemap.insert(std::make_pair(0U, 0));
2782 F.SLocRemap.insert(std::make_pair(2U, 1));
2783 }
2784
Guy Benyei11169dd2012-12-18 14:30:41 +00002785 // Continuous range maps we may be updating in our module.
2786 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2787 ContinuousRangeMap<uint32_t, int, 2>::Builder
2788 IdentifierRemap(F.IdentifierRemap);
2789 ContinuousRangeMap<uint32_t, int, 2>::Builder
2790 MacroRemap(F.MacroRemap);
2791 ContinuousRangeMap<uint32_t, int, 2>::Builder
2792 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2793 ContinuousRangeMap<uint32_t, int, 2>::Builder
2794 SubmoduleRemap(F.SubmoduleRemap);
2795 ContinuousRangeMap<uint32_t, int, 2>::Builder
2796 SelectorRemap(F.SelectorRemap);
2797 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2798 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2799
2800 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002801 using namespace llvm::support;
2802 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002803 StringRef Name = StringRef((const char*)Data, Len);
2804 Data += Len;
2805 ModuleFile *OM = ModuleMgr.lookup(Name);
2806 if (!OM) {
2807 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002808 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002809 }
2810
Justin Bogner57ba0b22014-03-28 22:03:24 +00002811 uint32_t SLocOffset =
2812 endian::readNext<uint32_t, little, unaligned>(Data);
2813 uint32_t IdentifierIDOffset =
2814 endian::readNext<uint32_t, little, unaligned>(Data);
2815 uint32_t MacroIDOffset =
2816 endian::readNext<uint32_t, little, unaligned>(Data);
2817 uint32_t PreprocessedEntityIDOffset =
2818 endian::readNext<uint32_t, little, unaligned>(Data);
2819 uint32_t SubmoduleIDOffset =
2820 endian::readNext<uint32_t, little, unaligned>(Data);
2821 uint32_t SelectorIDOffset =
2822 endian::readNext<uint32_t, little, unaligned>(Data);
2823 uint32_t DeclIDOffset =
2824 endian::readNext<uint32_t, little, unaligned>(Data);
2825 uint32_t TypeIndexOffset =
2826 endian::readNext<uint32_t, little, unaligned>(Data);
2827
Guy Benyei11169dd2012-12-18 14:30:41 +00002828 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2829 SLocRemap.insert(std::make_pair(SLocOffset,
2830 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2831 IdentifierRemap.insert(
2832 std::make_pair(IdentifierIDOffset,
2833 OM->BaseIdentifierID - IdentifierIDOffset));
2834 MacroRemap.insert(std::make_pair(MacroIDOffset,
2835 OM->BaseMacroID - MacroIDOffset));
2836 PreprocessedEntityRemap.insert(
2837 std::make_pair(PreprocessedEntityIDOffset,
2838 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2839 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2840 OM->BaseSubmoduleID - SubmoduleIDOffset));
2841 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2842 OM->BaseSelectorID - SelectorIDOffset));
2843 DeclRemap.insert(std::make_pair(DeclIDOffset,
2844 OM->BaseDeclID - DeclIDOffset));
2845
2846 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2847 OM->BaseTypeIndex - TypeIndexOffset));
2848
2849 // Global -> local mappings.
2850 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2851 }
2852 break;
2853 }
2854
2855 case SOURCE_MANAGER_LINE_TABLE:
2856 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002857 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002858 break;
2859
2860 case SOURCE_LOCATION_PRELOADS: {
2861 // Need to transform from the local view (1-based IDs) to the global view,
2862 // which is based off F.SLocEntryBaseID.
2863 if (!F.PreloadSLocEntries.empty()) {
2864 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002865 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002866 }
2867
2868 F.PreloadSLocEntries.swap(Record);
2869 break;
2870 }
2871
2872 case EXT_VECTOR_DECLS:
2873 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2874 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2875 break;
2876
2877 case VTABLE_USES:
2878 if (Record.size() % 3 != 0) {
2879 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002880 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002881 }
2882
2883 // Later tables overwrite earlier ones.
2884 // FIXME: Modules will have some trouble with this. This is clearly not
2885 // the right way to do this.
2886 VTableUses.clear();
2887
2888 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2889 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2890 VTableUses.push_back(
2891 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2892 VTableUses.push_back(Record[Idx++]);
2893 }
2894 break;
2895
2896 case DYNAMIC_CLASSES:
2897 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2898 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2899 break;
2900
2901 case PENDING_IMPLICIT_INSTANTIATIONS:
2902 if (PendingInstantiations.size() % 2 != 0) {
2903 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002904 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002905 }
2906
2907 if (Record.size() % 2 != 0) {
2908 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002909 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002910 }
2911
2912 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2913 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2914 PendingInstantiations.push_back(
2915 ReadSourceLocation(F, Record, I).getRawEncoding());
2916 }
2917 break;
2918
2919 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002920 if (Record.size() != 2) {
2921 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002922 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002923 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002924 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2925 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2926 break;
2927
2928 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002929 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2930 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2931 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002932
2933 unsigned LocalBasePreprocessedEntityID = Record[0];
2934
2935 unsigned StartingID;
2936 if (!PP.getPreprocessingRecord())
2937 PP.createPreprocessingRecord();
2938 if (!PP.getPreprocessingRecord()->getExternalSource())
2939 PP.getPreprocessingRecord()->SetExternalSource(*this);
2940 StartingID
2941 = PP.getPreprocessingRecord()
2942 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2943 F.BasePreprocessedEntityID = StartingID;
2944
2945 if (F.NumPreprocessedEntities > 0) {
2946 // Introduce the global -> local mapping for preprocessed entities in
2947 // this module.
2948 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2949
2950 // Introduce the local -> global mapping for preprocessed entities in
2951 // this module.
2952 F.PreprocessedEntityRemap.insertOrReplace(
2953 std::make_pair(LocalBasePreprocessedEntityID,
2954 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2955 }
2956
2957 break;
2958 }
2959
2960 case DECL_UPDATE_OFFSETS: {
2961 if (Record.size() % 2 != 0) {
2962 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002963 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002964 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002965 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2966 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2967 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2968
2969 // If we've already loaded the decl, perform the updates when we finish
2970 // loading this block.
2971 if (Decl *D = GetExistingDecl(ID))
2972 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2973 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002974 break;
2975 }
2976
2977 case DECL_REPLACEMENTS: {
2978 if (Record.size() % 3 != 0) {
2979 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002980 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 }
2982 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2983 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2984 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2985 break;
2986 }
2987
2988 case OBJC_CATEGORIES_MAP: {
2989 if (F.LocalNumObjCCategoriesInMap != 0) {
2990 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002991 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002992 }
2993
2994 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002995 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002996 break;
2997 }
2998
2999 case OBJC_CATEGORIES:
3000 F.ObjCCategories.swap(Record);
3001 break;
3002
3003 case CXX_BASE_SPECIFIER_OFFSETS: {
3004 if (F.LocalNumCXXBaseSpecifiers != 0) {
3005 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003006 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003007 }
3008
3009 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003010 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3012 break;
3013 }
3014
3015 case DIAG_PRAGMA_MAPPINGS:
3016 if (F.PragmaDiagMappings.empty())
3017 F.PragmaDiagMappings.swap(Record);
3018 else
3019 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3020 Record.begin(), Record.end());
3021 break;
3022
3023 case CUDA_SPECIAL_DECL_REFS:
3024 // Later tables overwrite earlier ones.
3025 // FIXME: Modules will have trouble with this.
3026 CUDASpecialDeclRefs.clear();
3027 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3028 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3029 break;
3030
3031 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003032 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003033 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003034 if (Record[0]) {
3035 F.HeaderFileInfoTable
3036 = HeaderFileInfoLookupTable::Create(
3037 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3038 (const unsigned char *)F.HeaderFileInfoTableData,
3039 HeaderFileInfoTrait(*this, F,
3040 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003041 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003042
3043 PP.getHeaderSearchInfo().SetExternalSource(this);
3044 if (!PP.getHeaderSearchInfo().getExternalLookup())
3045 PP.getHeaderSearchInfo().SetExternalLookup(this);
3046 }
3047 break;
3048 }
3049
3050 case FP_PRAGMA_OPTIONS:
3051 // Later tables overwrite earlier ones.
3052 FPPragmaOptions.swap(Record);
3053 break;
3054
3055 case OPENCL_EXTENSIONS:
3056 // Later tables overwrite earlier ones.
3057 OpenCLExtensions.swap(Record);
3058 break;
3059
3060 case TENTATIVE_DEFINITIONS:
3061 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3062 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3063 break;
3064
3065 case KNOWN_NAMESPACES:
3066 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3067 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3068 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003069
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003070 case UNDEFINED_BUT_USED:
3071 if (UndefinedButUsed.size() % 2 != 0) {
3072 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003073 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003074 }
3075
3076 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003077 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003078 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003079 }
3080 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003081 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3082 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003083 ReadSourceLocation(F, Record, I).getRawEncoding());
3084 }
3085 break;
3086
Guy Benyei11169dd2012-12-18 14:30:41 +00003087 case IMPORTED_MODULES: {
3088 if (F.Kind != MK_Module) {
3089 // If we aren't loading a module (which has its own exports), make
3090 // all of the imported modules visible.
3091 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003092 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3093 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3094 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3095 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003096 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003097 }
3098 }
3099 break;
3100 }
3101
3102 case LOCAL_REDECLARATIONS: {
3103 F.RedeclarationChains.swap(Record);
3104 break;
3105 }
3106
3107 case LOCAL_REDECLARATIONS_MAP: {
3108 if (F.LocalNumRedeclarationsInMap != 0) {
3109 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003110 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 }
3112
3113 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003114 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003115 break;
3116 }
3117
3118 case MERGED_DECLARATIONS: {
3119 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3120 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3121 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3122 for (unsigned N = Record[Idx++]; N > 0; --N)
3123 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3124 }
3125 break;
3126 }
3127
3128 case MACRO_OFFSET: {
3129 if (F.LocalNumMacros != 0) {
3130 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003131 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003132 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003133 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003134 F.LocalNumMacros = Record[0];
3135 unsigned LocalBaseMacroID = Record[1];
3136 F.BaseMacroID = getTotalNumMacros();
3137
3138 if (F.LocalNumMacros > 0) {
3139 // Introduce the global -> local mapping for macros within this module.
3140 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3141
3142 // Introduce the local -> global mapping for macros within this module.
3143 F.MacroRemap.insertOrReplace(
3144 std::make_pair(LocalBaseMacroID,
3145 F.BaseMacroID - LocalBaseMacroID));
3146
3147 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3148 }
3149 break;
3150 }
3151
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003152 case MACRO_TABLE: {
3153 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003154 break;
3155 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003156
3157 case LATE_PARSED_TEMPLATE: {
3158 LateParsedTemplates.append(Record.begin(), Record.end());
3159 break;
3160 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003161 }
3162 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003163}
3164
Douglas Gregorc1489562013-02-12 23:36:21 +00003165/// \brief Move the given method to the back of the global list of methods.
3166static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3167 // Find the entry for this selector in the method pool.
3168 Sema::GlobalMethodPool::iterator Known
3169 = S.MethodPool.find(Method->getSelector());
3170 if (Known == S.MethodPool.end())
3171 return;
3172
3173 // Retrieve the appropriate method list.
3174 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3175 : Known->second.second;
3176 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003177 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003178 if (!Found) {
3179 if (List->Method == Method) {
3180 Found = true;
3181 } else {
3182 // Keep searching.
3183 continue;
3184 }
3185 }
3186
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003187 if (List->getNext())
3188 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003189 else
3190 List->Method = Method;
3191 }
3192}
3193
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003194void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00003195 for (unsigned I = 0, N = Names.HiddenDecls.size(); I != N; ++I) {
3196 Decl *D = Names.HiddenDecls[I];
3197 bool wasHidden = D->Hidden;
3198 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003199
Richard Smith49f906a2014-03-01 00:08:04 +00003200 if (wasHidden && SemaObj) {
3201 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3202 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003203 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003204 }
3205 }
Richard Smith49f906a2014-03-01 00:08:04 +00003206
3207 for (HiddenMacrosMap::const_iterator I = Names.HiddenMacros.begin(),
3208 E = Names.HiddenMacros.end();
3209 I != E; ++I)
3210 installImportedMacro(I->first, I->second, Owner);
Guy Benyei11169dd2012-12-18 14:30:41 +00003211}
3212
Richard Smith49f906a2014-03-01 00:08:04 +00003213void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003214 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003215 SourceLocation ImportLoc,
3216 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003217 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003218 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003219 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003220 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003221 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003222
3223 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003224 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003225 // there is nothing more to do.
3226 continue;
3227 }
Richard Smith49f906a2014-03-01 00:08:04 +00003228
Guy Benyei11169dd2012-12-18 14:30:41 +00003229 if (!Mod->isAvailable()) {
3230 // Modules that aren't available cannot be made visible.
3231 continue;
3232 }
3233
3234 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003235 if (NameVisibility >= Module::MacrosVisible &&
3236 Mod->NameVisibility < Module::MacrosVisible)
3237 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003238 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003239
Guy Benyei11169dd2012-12-18 14:30:41 +00003240 // If we've already deserialized any names from this module,
3241 // mark them as visible.
3242 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3243 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003244 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003245 HiddenNamesMap.erase(Hidden);
3246 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003247
Guy Benyei11169dd2012-12-18 14:30:41 +00003248 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003249 SmallVector<Module *, 16> Exports;
3250 Mod->getExportedModules(Exports);
3251 for (SmallVectorImpl<Module *>::iterator
3252 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3253 Module *Exported = *I;
3254 if (Visited.insert(Exported))
3255 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003256 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003257
3258 // Detect any conflicts.
3259 if (Complain) {
3260 assert(ImportLoc.isValid() && "Missing import location");
3261 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3262 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3263 Diag(ImportLoc, diag::warn_module_conflict)
3264 << Mod->getFullModuleName()
3265 << Mod->Conflicts[I].Other->getFullModuleName()
3266 << Mod->Conflicts[I].Message;
3267 // FIXME: Need note where the other module was imported.
3268 }
3269 }
3270 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003271 }
3272}
3273
Douglas Gregore060e572013-01-25 01:03:03 +00003274bool ASTReader::loadGlobalIndex() {
3275 if (GlobalIndex)
3276 return false;
3277
3278 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3279 !Context.getLangOpts().Modules)
3280 return true;
3281
3282 // Try to load the global index.
3283 TriedLoadingGlobalIndex = true;
3284 StringRef ModuleCachePath
3285 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3286 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003287 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003288 if (!Result.first)
3289 return true;
3290
3291 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003292 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003293 return false;
3294}
3295
3296bool ASTReader::isGlobalIndexUnavailable() const {
3297 return Context.getLangOpts().Modules && UseGlobalIndex &&
3298 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3299}
3300
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003301static void updateModuleTimestamp(ModuleFile &MF) {
3302 // Overwrite the timestamp file contents so that file's mtime changes.
3303 std::string TimestampFilename = MF.getTimestampFilename();
3304 std::string ErrorInfo;
Rafael Espindola04a13be2014-02-24 15:06:52 +00003305 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
Rafael Espindola4fbd3732014-02-24 18:20:21 +00003306 llvm::sys::fs::F_Text);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003307 if (!ErrorInfo.empty())
3308 return;
3309 OS << "Timestamp file\n";
3310}
3311
Guy Benyei11169dd2012-12-18 14:30:41 +00003312ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3313 ModuleKind Type,
3314 SourceLocation ImportLoc,
3315 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003316 llvm::SaveAndRestore<SourceLocation>
3317 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3318
Guy Benyei11169dd2012-12-18 14:30:41 +00003319 // Bump the generation number.
3320 unsigned PreviousGeneration = CurrentGeneration++;
3321
3322 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003323 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003324 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3325 /*ImportedBy=*/0, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003326 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003327 ClientLoadCapabilities)) {
3328 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003329 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003330 case OutOfDate:
3331 case VersionMismatch:
3332 case ConfigurationMismatch:
3333 case HadErrors:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003334 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3335 Context.getLangOpts().Modules
3336 ? &PP.getHeaderSearchInfo().getModuleMap()
3337 : 0);
Douglas Gregore060e572013-01-25 01:03:03 +00003338
3339 // If we find that any modules are unusable, the global index is going
3340 // to be out-of-date. Just remove it.
3341 GlobalIndex.reset();
Douglas Gregor7211ac12013-01-25 23:32:03 +00003342 ModuleMgr.setGlobalIndex(0);
Guy Benyei11169dd2012-12-18 14:30:41 +00003343 return ReadResult;
3344
3345 case Success:
3346 break;
3347 }
3348
3349 // Here comes stuff that we only do once the entire chain is loaded.
3350
3351 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003352 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3353 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003354 M != MEnd; ++M) {
3355 ModuleFile &F = *M->Mod;
3356
3357 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003358 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3359 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003360
3361 // Once read, set the ModuleFile bit base offset and update the size in
3362 // bits of all files we've seen.
3363 F.GlobalBitOffset = TotalModulesSizeInBits;
3364 TotalModulesSizeInBits += F.SizeInBits;
3365 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3366
3367 // Preload SLocEntries.
3368 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3369 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3370 // Load it through the SourceManager and don't call ReadSLocEntry()
3371 // directly because the entry may have already been loaded in which case
3372 // calling ReadSLocEntry() directly would trigger an assertion in
3373 // SourceManager.
3374 SourceMgr.getLoadedSLocEntryByID(Index);
3375 }
3376 }
3377
Douglas Gregor603cd862013-03-22 18:50:14 +00003378 // Setup the import locations and notify the module manager that we've
3379 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003380 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3381 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003382 M != MEnd; ++M) {
3383 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003384
3385 ModuleMgr.moduleFileAccepted(&F);
3386
3387 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003388 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003389 if (!M->ImportedBy)
3390 F.ImportLoc = M->ImportLoc;
3391 else
3392 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3393 M->ImportLoc.getRawEncoding());
3394 }
3395
3396 // Mark all of the identifiers in the identifier table as being out of date,
3397 // so that various accessors know to check the loaded modules when the
3398 // identifier is used.
3399 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3400 IdEnd = PP.getIdentifierTable().end();
3401 Id != IdEnd; ++Id)
3402 Id->second->setOutOfDate(true);
3403
3404 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003405 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3406 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003407 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3408 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003409
3410 switch (Unresolved.Kind) {
3411 case UnresolvedModuleRef::Conflict:
3412 if (ResolvedMod) {
3413 Module::Conflict Conflict;
3414 Conflict.Other = ResolvedMod;
3415 Conflict.Message = Unresolved.String.str();
3416 Unresolved.Mod->Conflicts.push_back(Conflict);
3417 }
3418 continue;
3419
3420 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003421 if (ResolvedMod)
3422 Unresolved.Mod->Imports.push_back(ResolvedMod);
3423 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003424
Douglas Gregorfb912652013-03-20 21:10:35 +00003425 case UnresolvedModuleRef::Export:
3426 if (ResolvedMod || Unresolved.IsWildcard)
3427 Unresolved.Mod->Exports.push_back(
3428 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3429 continue;
3430 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003431 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003432 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003433
3434 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3435 // Might be unnecessary as use declarations are only used to build the
3436 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003437
3438 InitializeContext();
3439
Richard Smith3d8e97e2013-10-18 06:54:39 +00003440 if (SemaObj)
3441 UpdateSema();
3442
Guy Benyei11169dd2012-12-18 14:30:41 +00003443 if (DeserializationListener)
3444 DeserializationListener->ReaderInitialized(this);
3445
3446 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3447 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3448 PrimaryModule.OriginalSourceFileID
3449 = FileID::get(PrimaryModule.SLocEntryBaseID
3450 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3451
3452 // If this AST file is a precompiled preamble, then set the
3453 // preamble file ID of the source manager to the file source file
3454 // from which the preamble was built.
3455 if (Type == MK_Preamble) {
3456 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3457 } else if (Type == MK_MainFile) {
3458 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3459 }
3460 }
3461
3462 // For any Objective-C class definitions we have already loaded, make sure
3463 // that we load any additional categories.
3464 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3465 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3466 ObjCClassesLoaded[I],
3467 PreviousGeneration);
3468 }
Douglas Gregore060e572013-01-25 01:03:03 +00003469
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003470 if (PP.getHeaderSearchInfo()
3471 .getHeaderSearchOpts()
3472 .ModulesValidateOncePerBuildSession) {
3473 // Now we are certain that the module and all modules it depends on are
3474 // up to date. Create or update timestamp files for modules that are
3475 // located in the module cache (not for PCH files that could be anywhere
3476 // in the filesystem).
3477 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3478 ImportedModule &M = Loaded[I];
3479 if (M.Mod->Kind == MK_Module) {
3480 updateModuleTimestamp(*M.Mod);
3481 }
3482 }
3483 }
3484
Guy Benyei11169dd2012-12-18 14:30:41 +00003485 return Success;
3486}
3487
3488ASTReader::ASTReadResult
3489ASTReader::ReadASTCore(StringRef FileName,
3490 ModuleKind Type,
3491 SourceLocation ImportLoc,
3492 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003493 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003494 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003495 unsigned ClientLoadCapabilities) {
3496 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003497 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003498 ModuleManager::AddModuleResult AddResult
3499 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3500 CurrentGeneration, ExpectedSize, ExpectedModTime,
3501 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003502
Douglas Gregor7029ce12013-03-19 00:28:20 +00003503 switch (AddResult) {
3504 case ModuleManager::AlreadyLoaded:
3505 return Success;
3506
3507 case ModuleManager::NewlyLoaded:
3508 // Load module file below.
3509 break;
3510
3511 case ModuleManager::Missing:
3512 // The module file was missing; if the client handle handle, that, return
3513 // it.
3514 if (ClientLoadCapabilities & ARR_Missing)
3515 return Missing;
3516
3517 // Otherwise, return an error.
3518 {
3519 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3520 + ErrorStr;
3521 Error(Msg);
3522 }
3523 return Failure;
3524
3525 case ModuleManager::OutOfDate:
3526 // We couldn't load the module file because it is out-of-date. If the
3527 // client can handle out-of-date, return it.
3528 if (ClientLoadCapabilities & ARR_OutOfDate)
3529 return OutOfDate;
3530
3531 // Otherwise, return an error.
3532 {
3533 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3534 + ErrorStr;
3535 Error(Msg);
3536 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003537 return Failure;
3538 }
3539
Douglas Gregor7029ce12013-03-19 00:28:20 +00003540 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003541
3542 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3543 // module?
3544 if (FileName != "-") {
3545 CurrentDir = llvm::sys::path::parent_path(FileName);
3546 if (CurrentDir.empty()) CurrentDir = ".";
3547 }
3548
3549 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003550 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003551 Stream.init(F.StreamFile);
3552 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3553
3554 // Sniff for the signature.
3555 if (Stream.Read(8) != 'C' ||
3556 Stream.Read(8) != 'P' ||
3557 Stream.Read(8) != 'C' ||
3558 Stream.Read(8) != 'H') {
3559 Diag(diag::err_not_a_pch_file) << FileName;
3560 return Failure;
3561 }
3562
3563 // This is used for compatibility with older PCH formats.
3564 bool HaveReadControlBlock = false;
3565
Chris Lattnerefa77172013-01-20 00:00:22 +00003566 while (1) {
3567 llvm::BitstreamEntry Entry = Stream.advance();
3568
3569 switch (Entry.Kind) {
3570 case llvm::BitstreamEntry::Error:
3571 case llvm::BitstreamEntry::EndBlock:
3572 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003573 Error("invalid record at top-level of AST file");
3574 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003575
3576 case llvm::BitstreamEntry::SubBlock:
3577 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003578 }
3579
Guy Benyei11169dd2012-12-18 14:30:41 +00003580 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003581 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003582 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3583 if (Stream.ReadBlockInfoBlock()) {
3584 Error("malformed BlockInfoBlock in AST file");
3585 return Failure;
3586 }
3587 break;
3588 case CONTROL_BLOCK_ID:
3589 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003590 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003591 case Success:
3592 break;
3593
3594 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003595 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003596 case OutOfDate: return OutOfDate;
3597 case VersionMismatch: return VersionMismatch;
3598 case ConfigurationMismatch: return ConfigurationMismatch;
3599 case HadErrors: return HadErrors;
3600 }
3601 break;
3602 case AST_BLOCK_ID:
3603 if (!HaveReadControlBlock) {
3604 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003605 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003606 return VersionMismatch;
3607 }
3608
3609 // Record that we've loaded this module.
3610 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3611 return Success;
3612
3613 default:
3614 if (Stream.SkipBlock()) {
3615 Error("malformed block record in AST file");
3616 return Failure;
3617 }
3618 break;
3619 }
3620 }
3621
3622 return Success;
3623}
3624
3625void ASTReader::InitializeContext() {
3626 // If there's a listener, notify them that we "read" the translation unit.
3627 if (DeserializationListener)
3628 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3629 Context.getTranslationUnitDecl());
3630
Richard Smithcd45dbc2014-04-19 03:48:30 +00003631 // For any declarations we have already loaded, load any update records.
3632 {
3633 // We're not back to a consistent state until all our pending update
3634 // records have been loaded. There can be interdependencies between them.
3635 Deserializing SomeUpdateRecords(this);
3636 ReadingKindTracker ReadingKind(Read_Decl, *this);
3637
3638 // Make sure we load the declaration update records for the translation
3639 // unit, if there are any.
3640 // FIXME: Is this necessary any more?
3641 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3642 Context.getTranslationUnitDecl());
3643
3644 for (auto &Update : PendingUpdateRecords)
3645 loadDeclUpdateRecords(Update.first, Update.second);
3646 PendingUpdateRecords.clear();
3647 }
3648
Guy Benyei11169dd2012-12-18 14:30:41 +00003649 // FIXME: Find a better way to deal with collisions between these
3650 // built-in types. Right now, we just ignore the problem.
3651
3652 // Load the special types.
3653 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3654 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3655 if (!Context.CFConstantStringTypeDecl)
3656 Context.setCFConstantStringType(GetType(String));
3657 }
3658
3659 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3660 QualType FileType = GetType(File);
3661 if (FileType.isNull()) {
3662 Error("FILE type is NULL");
3663 return;
3664 }
3665
3666 if (!Context.FILEDecl) {
3667 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3668 Context.setFILEDecl(Typedef->getDecl());
3669 else {
3670 const TagType *Tag = FileType->getAs<TagType>();
3671 if (!Tag) {
3672 Error("Invalid FILE type in AST file");
3673 return;
3674 }
3675 Context.setFILEDecl(Tag->getDecl());
3676 }
3677 }
3678 }
3679
3680 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3681 QualType Jmp_bufType = GetType(Jmp_buf);
3682 if (Jmp_bufType.isNull()) {
3683 Error("jmp_buf type is NULL");
3684 return;
3685 }
3686
3687 if (!Context.jmp_bufDecl) {
3688 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3689 Context.setjmp_bufDecl(Typedef->getDecl());
3690 else {
3691 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3692 if (!Tag) {
3693 Error("Invalid jmp_buf type in AST file");
3694 return;
3695 }
3696 Context.setjmp_bufDecl(Tag->getDecl());
3697 }
3698 }
3699 }
3700
3701 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3702 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3703 if (Sigjmp_bufType.isNull()) {
3704 Error("sigjmp_buf type is NULL");
3705 return;
3706 }
3707
3708 if (!Context.sigjmp_bufDecl) {
3709 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3710 Context.setsigjmp_bufDecl(Typedef->getDecl());
3711 else {
3712 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3713 assert(Tag && "Invalid sigjmp_buf type in AST file");
3714 Context.setsigjmp_bufDecl(Tag->getDecl());
3715 }
3716 }
3717 }
3718
3719 if (unsigned ObjCIdRedef
3720 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3721 if (Context.ObjCIdRedefinitionType.isNull())
3722 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3723 }
3724
3725 if (unsigned ObjCClassRedef
3726 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3727 if (Context.ObjCClassRedefinitionType.isNull())
3728 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3729 }
3730
3731 if (unsigned ObjCSelRedef
3732 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3733 if (Context.ObjCSelRedefinitionType.isNull())
3734 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3735 }
3736
3737 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3738 QualType Ucontext_tType = GetType(Ucontext_t);
3739 if (Ucontext_tType.isNull()) {
3740 Error("ucontext_t type is NULL");
3741 return;
3742 }
3743
3744 if (!Context.ucontext_tDecl) {
3745 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3746 Context.setucontext_tDecl(Typedef->getDecl());
3747 else {
3748 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3749 assert(Tag && "Invalid ucontext_t type in AST file");
3750 Context.setucontext_tDecl(Tag->getDecl());
3751 }
3752 }
3753 }
3754 }
3755
3756 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3757
3758 // If there were any CUDA special declarations, deserialize them.
3759 if (!CUDASpecialDeclRefs.empty()) {
3760 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3761 Context.setcudaConfigureCallDecl(
3762 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3763 }
Richard Smith56be7542014-03-21 00:33:59 +00003764
Guy Benyei11169dd2012-12-18 14:30:41 +00003765 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00003766 // FIXME: This does not make macro-only imports visible again. It also doesn't
3767 // make #includes mapped to module imports visible.
3768 for (auto &Import : ImportedModules) {
3769 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003770 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00003771 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00003772 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003773 }
3774 ImportedModules.clear();
3775}
3776
3777void ASTReader::finalizeForWriting() {
3778 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3779 HiddenEnd = HiddenNamesMap.end();
3780 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003781 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003782 }
3783 HiddenNamesMap.clear();
3784}
3785
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003786/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3787/// cursor into the start of the given block ID, returning false on success and
3788/// true on failure.
3789static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003790 while (1) {
3791 llvm::BitstreamEntry Entry = Cursor.advance();
3792 switch (Entry.Kind) {
3793 case llvm::BitstreamEntry::Error:
3794 case llvm::BitstreamEntry::EndBlock:
3795 return true;
3796
3797 case llvm::BitstreamEntry::Record:
3798 // Ignore top-level records.
3799 Cursor.skipRecord(Entry.ID);
3800 break;
3801
3802 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003803 if (Entry.ID == BlockID) {
3804 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003805 return true;
3806 // Found it!
3807 return false;
3808 }
3809
3810 if (Cursor.SkipBlock())
3811 return true;
3812 }
3813 }
3814}
3815
Guy Benyei11169dd2012-12-18 14:30:41 +00003816/// \brief Retrieve the name of the original source file name
3817/// directly from the AST file, without actually loading the AST
3818/// file.
3819std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3820 FileManager &FileMgr,
3821 DiagnosticsEngine &Diags) {
3822 // Open the AST file.
3823 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003824 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003825 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3826 if (!Buffer) {
3827 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3828 return std::string();
3829 }
3830
3831 // Initialize the stream
3832 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003833 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003834 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3835 (const unsigned char *)Buffer->getBufferEnd());
3836 Stream.init(StreamFile);
3837
3838 // Sniff for the signature.
3839 if (Stream.Read(8) != 'C' ||
3840 Stream.Read(8) != 'P' ||
3841 Stream.Read(8) != 'C' ||
3842 Stream.Read(8) != 'H') {
3843 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3844 return std::string();
3845 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003846
Chris Lattnere7b154b2013-01-19 21:39:22 +00003847 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003848 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003849 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3850 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003851 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003852
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003853 // Scan for ORIGINAL_FILE inside the control block.
3854 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003855 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003856 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003857 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3858 return std::string();
3859
3860 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3861 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3862 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003863 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003864
Guy Benyei11169dd2012-12-18 14:30:41 +00003865 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003866 StringRef Blob;
3867 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3868 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003869 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003870}
3871
3872namespace {
3873 class SimplePCHValidator : public ASTReaderListener {
3874 const LangOptions &ExistingLangOpts;
3875 const TargetOptions &ExistingTargetOpts;
3876 const PreprocessorOptions &ExistingPPOpts;
3877 FileManager &FileMgr;
3878
3879 public:
3880 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3881 const TargetOptions &ExistingTargetOpts,
3882 const PreprocessorOptions &ExistingPPOpts,
3883 FileManager &FileMgr)
3884 : ExistingLangOpts(ExistingLangOpts),
3885 ExistingTargetOpts(ExistingTargetOpts),
3886 ExistingPPOpts(ExistingPPOpts),
3887 FileMgr(FileMgr)
3888 {
3889 }
3890
Craig Topper3e89dfe2014-03-13 02:13:41 +00003891 bool ReadLanguageOptions(const LangOptions &LangOpts,
3892 bool Complain) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003893 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3894 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003895 bool ReadTargetOptions(const TargetOptions &TargetOpts,
3896 bool Complain) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003897 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3898 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003899 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3900 bool Complain,
3901 std::string &SuggestedPredefines) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003902 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003903 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003904 }
3905 };
3906}
3907
3908bool ASTReader::readASTFileControlBlock(StringRef Filename,
3909 FileManager &FileMgr,
3910 ASTReaderListener &Listener) {
3911 // Open the AST file.
3912 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003913 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003914 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3915 if (!Buffer) {
3916 return true;
3917 }
3918
3919 // Initialize the stream
3920 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003921 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003922 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3923 (const unsigned char *)Buffer->getBufferEnd());
3924 Stream.init(StreamFile);
3925
3926 // Sniff for the signature.
3927 if (Stream.Read(8) != 'C' ||
3928 Stream.Read(8) != 'P' ||
3929 Stream.Read(8) != 'C' ||
3930 Stream.Read(8) != 'H') {
3931 return true;
3932 }
3933
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003934 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003935 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003936 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003937
3938 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00003939 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003940 BitstreamCursor InputFilesCursor;
3941 if (NeedsInputFiles) {
3942 InputFilesCursor = Stream;
3943 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
3944 return true;
3945
3946 // Read the abbreviations
3947 while (true) {
3948 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
3949 unsigned Code = InputFilesCursor.ReadCode();
3950
3951 // We expect all abbrevs to be at the start of the block.
3952 if (Code != llvm::bitc::DEFINE_ABBREV) {
3953 InputFilesCursor.JumpToBit(Offset);
3954 break;
3955 }
3956 InputFilesCursor.ReadAbbrevRecord();
3957 }
3958 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003959
3960 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00003961 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003962 while (1) {
3963 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3964 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3965 return false;
3966
3967 if (Entry.Kind != llvm::BitstreamEntry::Record)
3968 return true;
3969
Guy Benyei11169dd2012-12-18 14:30:41 +00003970 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003971 StringRef Blob;
3972 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003973 switch ((ControlRecordTypes)RecCode) {
3974 case METADATA: {
3975 if (Record[0] != VERSION_MAJOR)
3976 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003977
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003978 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003979 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003980
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003981 break;
3982 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00003983 case MODULE_NAME:
3984 Listener.ReadModuleName(Blob);
3985 break;
3986 case MODULE_MAP_FILE:
3987 Listener.ReadModuleMapFile(Blob);
3988 break;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003989 case LANGUAGE_OPTIONS:
3990 if (ParseLanguageOptions(Record, false, Listener))
3991 return true;
3992 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003993
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003994 case TARGET_OPTIONS:
3995 if (ParseTargetOptions(Record, false, Listener))
3996 return true;
3997 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003998
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003999 case DIAGNOSTIC_OPTIONS:
4000 if (ParseDiagnosticOptions(Record, false, Listener))
4001 return true;
4002 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004003
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004004 case FILE_SYSTEM_OPTIONS:
4005 if (ParseFileSystemOptions(Record, false, Listener))
4006 return true;
4007 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004008
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004009 case HEADER_SEARCH_OPTIONS:
4010 if (ParseHeaderSearchOptions(Record, false, Listener))
4011 return true;
4012 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004013
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004014 case PREPROCESSOR_OPTIONS: {
4015 std::string IgnoredSuggestedPredefines;
4016 if (ParsePreprocessorOptions(Record, false, Listener,
4017 IgnoredSuggestedPredefines))
4018 return true;
4019 break;
4020 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004021
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004022 case INPUT_FILE_OFFSETS: {
4023 if (!NeedsInputFiles)
4024 break;
4025
4026 unsigned NumInputFiles = Record[0];
4027 unsigned NumUserFiles = Record[1];
4028 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
4029 for (unsigned I = 0; I != NumInputFiles; ++I) {
4030 // Go find this input file.
4031 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004032
4033 if (isSystemFile && !NeedsSystemInputFiles)
4034 break; // the rest are system input files
4035
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004036 BitstreamCursor &Cursor = InputFilesCursor;
4037 SavedStreamPosition SavedPosition(Cursor);
4038 Cursor.JumpToBit(InputFileOffs[I]);
4039
4040 unsigned Code = Cursor.ReadCode();
4041 RecordData Record;
4042 StringRef Blob;
4043 bool shouldContinue = false;
4044 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4045 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004046 bool Overridden = static_cast<bool>(Record[3]);
4047 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004048 break;
4049 }
4050 if (!shouldContinue)
4051 break;
4052 }
4053 break;
4054 }
4055
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004056 default:
4057 // No other validation to perform.
4058 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004059 }
4060 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004061}
4062
4063
4064bool ASTReader::isAcceptableASTFile(StringRef Filename,
4065 FileManager &FileMgr,
4066 const LangOptions &LangOpts,
4067 const TargetOptions &TargetOpts,
4068 const PreprocessorOptions &PPOpts) {
4069 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4070 return !readASTFileControlBlock(Filename, FileMgr, validator);
4071}
4072
Ben Langmuir2c9af442014-04-10 17:57:43 +00004073ASTReader::ASTReadResult
4074ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004075 // Enter the submodule block.
4076 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4077 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004078 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004079 }
4080
4081 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4082 bool First = true;
4083 Module *CurrentModule = 0;
4084 RecordData Record;
4085 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004086 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4087
4088 switch (Entry.Kind) {
4089 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4090 case llvm::BitstreamEntry::Error:
4091 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004092 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004093 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004094 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004095 case llvm::BitstreamEntry::Record:
4096 // The interesting case.
4097 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004098 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004099
Guy Benyei11169dd2012-12-18 14:30:41 +00004100 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004101 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004102 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004103 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004104 default: // Default behavior: ignore.
4105 break;
4106
4107 case SUBMODULE_DEFINITION: {
4108 if (First) {
4109 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004110 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004111 }
4112
Douglas Gregor8d932422013-03-20 03:59:18 +00004113 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004115 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004116 }
4117
Chris Lattner0e6c9402013-01-20 02:38:54 +00004118 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004119 unsigned Idx = 0;
4120 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4121 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4122 bool IsFramework = Record[Idx++];
4123 bool IsExplicit = Record[Idx++];
4124 bool IsSystem = Record[Idx++];
4125 bool IsExternC = Record[Idx++];
4126 bool InferSubmodules = Record[Idx++];
4127 bool InferExplicitSubmodules = Record[Idx++];
4128 bool InferExportWildcard = Record[Idx++];
4129 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004130
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004131 Module *ParentModule = nullptr;
4132 const FileEntry *ModuleMap = nullptr;
4133 if (Parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004134 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004135 ModuleMap = ParentModule->ModuleMap;
4136 }
4137
4138 if (!F.ModuleMapPath.empty())
4139 ModuleMap = FileMgr.getFile(F.ModuleMapPath);
4140
Guy Benyei11169dd2012-12-18 14:30:41 +00004141 // Retrieve this (sub)module from the module map, creating it if
4142 // necessary.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004143 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, ModuleMap,
Guy Benyei11169dd2012-12-18 14:30:41 +00004144 IsFramework,
4145 IsExplicit).first;
4146 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4147 if (GlobalIndex >= SubmodulesLoaded.size() ||
4148 SubmodulesLoaded[GlobalIndex]) {
4149 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004150 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004151 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004152
Douglas Gregor7029ce12013-03-19 00:28:20 +00004153 if (!ParentModule) {
4154 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4155 if (CurFile != F.File) {
4156 if (!Diags.isDiagnosticInFlight()) {
4157 Diag(diag::err_module_file_conflict)
4158 << CurrentModule->getTopLevelModuleName()
4159 << CurFile->getName()
4160 << F.File->getName();
4161 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004162 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004163 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004164 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004165
4166 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004167 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004168
Guy Benyei11169dd2012-12-18 14:30:41 +00004169 CurrentModule->IsFromModuleFile = true;
4170 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004171 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004172 CurrentModule->InferSubmodules = InferSubmodules;
4173 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4174 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004175 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004176 if (DeserializationListener)
4177 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4178
4179 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004180
Douglas Gregorfb912652013-03-20 21:10:35 +00004181 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004182 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004183 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004184 CurrentModule->UnresolvedConflicts.clear();
4185 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004186 break;
4187 }
4188
4189 case SUBMODULE_UMBRELLA_HEADER: {
4190 if (First) {
4191 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004192 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004193 }
4194
4195 if (!CurrentModule)
4196 break;
4197
Chris Lattner0e6c9402013-01-20 02:38:54 +00004198 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004199 if (!CurrentModule->getUmbrellaHeader())
4200 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4201 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004202 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4203 Error("mismatched umbrella headers in submodule");
4204 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004205 }
4206 }
4207 break;
4208 }
4209
4210 case SUBMODULE_HEADER: {
4211 if (First) {
4212 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004213 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004214 }
4215
4216 if (!CurrentModule)
4217 break;
4218
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004219 // We lazily associate headers with their modules via the HeaderInfoTable.
4220 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4221 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004222 break;
4223 }
4224
4225 case SUBMODULE_EXCLUDED_HEADER: {
4226 if (First) {
4227 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004228 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004229 }
4230
4231 if (!CurrentModule)
4232 break;
4233
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004234 // We lazily associate headers with their modules via the HeaderInfoTable.
4235 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4236 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004237 break;
4238 }
4239
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004240 case SUBMODULE_PRIVATE_HEADER: {
4241 if (First) {
4242 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004243 return Failure;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004244 }
4245
4246 if (!CurrentModule)
4247 break;
4248
4249 // We lazily associate headers with their modules via the HeaderInfoTable.
4250 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4251 // of complete filenames or remove it entirely.
4252 break;
4253 }
4254
Guy Benyei11169dd2012-12-18 14:30:41 +00004255 case SUBMODULE_TOPHEADER: {
4256 if (First) {
4257 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004258 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004259 }
4260
4261 if (!CurrentModule)
4262 break;
4263
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004264 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004265 break;
4266 }
4267
4268 case SUBMODULE_UMBRELLA_DIR: {
4269 if (First) {
4270 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004271 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004272 }
4273
4274 if (!CurrentModule)
4275 break;
4276
Guy Benyei11169dd2012-12-18 14:30:41 +00004277 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004278 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 if (!CurrentModule->getUmbrellaDir())
4280 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4281 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004282 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4283 Error("mismatched umbrella directories in submodule");
4284 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004285 }
4286 }
4287 break;
4288 }
4289
4290 case SUBMODULE_METADATA: {
4291 if (!First) {
4292 Error("submodule metadata record not at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004293 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004294 }
4295 First = false;
4296
4297 F.BaseSubmoduleID = getTotalNumSubmodules();
4298 F.LocalNumSubmodules = Record[0];
4299 unsigned LocalBaseSubmoduleID = Record[1];
4300 if (F.LocalNumSubmodules > 0) {
4301 // Introduce the global -> local mapping for submodules within this
4302 // module.
4303 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4304
4305 // Introduce the local -> global mapping for submodules within this
4306 // module.
4307 F.SubmoduleRemap.insertOrReplace(
4308 std::make_pair(LocalBaseSubmoduleID,
4309 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4310
4311 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4312 }
4313 break;
4314 }
4315
4316 case SUBMODULE_IMPORTS: {
4317 if (First) {
4318 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004319 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004320 }
4321
4322 if (!CurrentModule)
4323 break;
4324
4325 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004326 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004327 Unresolved.File = &F;
4328 Unresolved.Mod = CurrentModule;
4329 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004330 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004331 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004332 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004333 }
4334 break;
4335 }
4336
4337 case SUBMODULE_EXPORTS: {
4338 if (First) {
4339 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004340 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004341 }
4342
4343 if (!CurrentModule)
4344 break;
4345
4346 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004347 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004348 Unresolved.File = &F;
4349 Unresolved.Mod = CurrentModule;
4350 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004351 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004352 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004353 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004354 }
4355
4356 // Once we've loaded the set of exports, there's no reason to keep
4357 // the parsed, unresolved exports around.
4358 CurrentModule->UnresolvedExports.clear();
4359 break;
4360 }
4361 case SUBMODULE_REQUIRES: {
4362 if (First) {
4363 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004364 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004365 }
4366
4367 if (!CurrentModule)
4368 break;
4369
Richard Smitha3feee22013-10-28 22:18:19 +00004370 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004371 Context.getTargetInfo());
4372 break;
4373 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004374
4375 case SUBMODULE_LINK_LIBRARY:
4376 if (First) {
4377 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004378 return Failure;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004379 }
4380
4381 if (!CurrentModule)
4382 break;
4383
4384 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004385 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004386 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004387
4388 case SUBMODULE_CONFIG_MACRO:
4389 if (First) {
4390 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004391 return Failure;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004392 }
4393
4394 if (!CurrentModule)
4395 break;
4396
4397 CurrentModule->ConfigMacros.push_back(Blob.str());
4398 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004399
4400 case SUBMODULE_CONFLICT: {
4401 if (First) {
4402 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004403 return Failure;
Douglas Gregorfb912652013-03-20 21:10:35 +00004404 }
4405
4406 if (!CurrentModule)
4407 break;
4408
4409 UnresolvedModuleRef Unresolved;
4410 Unresolved.File = &F;
4411 Unresolved.Mod = CurrentModule;
4412 Unresolved.ID = Record[0];
4413 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4414 Unresolved.IsWildcard = false;
4415 Unresolved.String = Blob;
4416 UnresolvedModuleRefs.push_back(Unresolved);
4417 break;
4418 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004419 }
4420 }
4421}
4422
4423/// \brief Parse the record that corresponds to a LangOptions data
4424/// structure.
4425///
4426/// This routine parses the language options from the AST file and then gives
4427/// them to the AST listener if one is set.
4428///
4429/// \returns true if the listener deems the file unacceptable, false otherwise.
4430bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4431 bool Complain,
4432 ASTReaderListener &Listener) {
4433 LangOptions LangOpts;
4434 unsigned Idx = 0;
4435#define LANGOPT(Name, Bits, Default, Description) \
4436 LangOpts.Name = Record[Idx++];
4437#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4438 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4439#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004440#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4441#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004442
4443 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4444 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4445 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4446
4447 unsigned Length = Record[Idx++];
4448 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4449 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004450
4451 Idx += Length;
4452
4453 // Comment options.
4454 for (unsigned N = Record[Idx++]; N; --N) {
4455 LangOpts.CommentOpts.BlockCommandNames.push_back(
4456 ReadString(Record, Idx));
4457 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004458 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004459
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 return Listener.ReadLanguageOptions(LangOpts, Complain);
4461}
4462
4463bool ASTReader::ParseTargetOptions(const RecordData &Record,
4464 bool Complain,
4465 ASTReaderListener &Listener) {
4466 unsigned Idx = 0;
4467 TargetOptions TargetOpts;
4468 TargetOpts.Triple = ReadString(Record, Idx);
4469 TargetOpts.CPU = ReadString(Record, Idx);
4470 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004471 TargetOpts.LinkerVersion = ReadString(Record, Idx);
4472 for (unsigned N = Record[Idx++]; N; --N) {
4473 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4474 }
4475 for (unsigned N = Record[Idx++]; N; --N) {
4476 TargetOpts.Features.push_back(ReadString(Record, Idx));
4477 }
4478
4479 return Listener.ReadTargetOptions(TargetOpts, Complain);
4480}
4481
4482bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4483 ASTReaderListener &Listener) {
4484 DiagnosticOptions DiagOpts;
4485 unsigned Idx = 0;
4486#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
4487#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4488 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
4489#include "clang/Basic/DiagnosticOptions.def"
4490
4491 for (unsigned N = Record[Idx++]; N; --N) {
4492 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
4493 }
4494
4495 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4496}
4497
4498bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4499 ASTReaderListener &Listener) {
4500 FileSystemOptions FSOpts;
4501 unsigned Idx = 0;
4502 FSOpts.WorkingDir = ReadString(Record, Idx);
4503 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4504}
4505
4506bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4507 bool Complain,
4508 ASTReaderListener &Listener) {
4509 HeaderSearchOptions HSOpts;
4510 unsigned Idx = 0;
4511 HSOpts.Sysroot = ReadString(Record, Idx);
4512
4513 // Include entries.
4514 for (unsigned N = Record[Idx++]; N; --N) {
4515 std::string Path = ReadString(Record, Idx);
4516 frontend::IncludeDirGroup Group
4517 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004518 bool IsFramework = Record[Idx++];
4519 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004521 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004522 }
4523
4524 // System header prefixes.
4525 for (unsigned N = Record[Idx++]; N; --N) {
4526 std::string Prefix = ReadString(Record, Idx);
4527 bool IsSystemHeader = Record[Idx++];
4528 HSOpts.SystemHeaderPrefixes.push_back(
4529 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4530 }
4531
4532 HSOpts.ResourceDir = ReadString(Record, Idx);
4533 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004534 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004535 HSOpts.DisableModuleHash = Record[Idx++];
4536 HSOpts.UseBuiltinIncludes = Record[Idx++];
4537 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4538 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4539 HSOpts.UseLibcxx = Record[Idx++];
4540
4541 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4542}
4543
4544bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4545 bool Complain,
4546 ASTReaderListener &Listener,
4547 std::string &SuggestedPredefines) {
4548 PreprocessorOptions PPOpts;
4549 unsigned Idx = 0;
4550
4551 // Macro definitions/undefs
4552 for (unsigned N = Record[Idx++]; N; --N) {
4553 std::string Macro = ReadString(Record, Idx);
4554 bool IsUndef = Record[Idx++];
4555 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4556 }
4557
4558 // Includes
4559 for (unsigned N = Record[Idx++]; N; --N) {
4560 PPOpts.Includes.push_back(ReadString(Record, Idx));
4561 }
4562
4563 // Macro Includes
4564 for (unsigned N = Record[Idx++]; N; --N) {
4565 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4566 }
4567
4568 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004569 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004570 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4571 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4572 PPOpts.ObjCXXARCStandardLibrary =
4573 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4574 SuggestedPredefines.clear();
4575 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4576 SuggestedPredefines);
4577}
4578
4579std::pair<ModuleFile *, unsigned>
4580ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4581 GlobalPreprocessedEntityMapType::iterator
4582 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4583 assert(I != GlobalPreprocessedEntityMap.end() &&
4584 "Corrupted global preprocessed entity map");
4585 ModuleFile *M = I->second;
4586 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4587 return std::make_pair(M, LocalIndex);
4588}
4589
4590std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4591ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4592 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4593 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4594 Mod.NumPreprocessedEntities);
4595
4596 return std::make_pair(PreprocessingRecord::iterator(),
4597 PreprocessingRecord::iterator());
4598}
4599
4600std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4601ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4602 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4603 ModuleDeclIterator(this, &Mod,
4604 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4605}
4606
4607PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4608 PreprocessedEntityID PPID = Index+1;
4609 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4610 ModuleFile &M = *PPInfo.first;
4611 unsigned LocalIndex = PPInfo.second;
4612 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4613
Guy Benyei11169dd2012-12-18 14:30:41 +00004614 if (!PP.getPreprocessingRecord()) {
4615 Error("no preprocessing record");
4616 return 0;
4617 }
4618
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004619 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4620 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4621
4622 llvm::BitstreamEntry Entry =
4623 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4624 if (Entry.Kind != llvm::BitstreamEntry::Record)
4625 return 0;
4626
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 // Read the record.
4628 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4629 ReadSourceLocation(M, PPOffs.End));
4630 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004631 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004632 RecordData Record;
4633 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004634 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4635 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004636 switch (RecType) {
4637 case PPD_MACRO_EXPANSION: {
4638 bool isBuiltin = Record[0];
4639 IdentifierInfo *Name = 0;
4640 MacroDefinition *Def = 0;
4641 if (isBuiltin)
4642 Name = getLocalIdentifier(M, Record[1]);
4643 else {
4644 PreprocessedEntityID
4645 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4646 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4647 }
4648
4649 MacroExpansion *ME;
4650 if (isBuiltin)
4651 ME = new (PPRec) MacroExpansion(Name, Range);
4652 else
4653 ME = new (PPRec) MacroExpansion(Def, Range);
4654
4655 return ME;
4656 }
4657
4658 case PPD_MACRO_DEFINITION: {
4659 // Decode the identifier info and then check again; if the macro is
4660 // still defined and associated with the identifier,
4661 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4662 MacroDefinition *MD
4663 = new (PPRec) MacroDefinition(II, Range);
4664
4665 if (DeserializationListener)
4666 DeserializationListener->MacroDefinitionRead(PPID, MD);
4667
4668 return MD;
4669 }
4670
4671 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004672 const char *FullFileNameStart = Blob.data() + Record[0];
4673 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004674 const FileEntry *File = 0;
4675 if (!FullFileName.empty())
4676 File = PP.getFileManager().getFile(FullFileName);
4677
4678 // FIXME: Stable encoding
4679 InclusionDirective::InclusionKind Kind
4680 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4681 InclusionDirective *ID
4682 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004683 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004684 Record[1], Record[3],
4685 File,
4686 Range);
4687 return ID;
4688 }
4689 }
4690
4691 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4692}
4693
4694/// \brief \arg SLocMapI points at a chunk of a module that contains no
4695/// preprocessed entities or the entities it contains are not the ones we are
4696/// looking for. Find the next module that contains entities and return the ID
4697/// of the first entry.
4698PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4699 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4700 ++SLocMapI;
4701 for (GlobalSLocOffsetMapType::const_iterator
4702 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4703 ModuleFile &M = *SLocMapI->second;
4704 if (M.NumPreprocessedEntities)
4705 return M.BasePreprocessedEntityID;
4706 }
4707
4708 return getTotalNumPreprocessedEntities();
4709}
4710
4711namespace {
4712
4713template <unsigned PPEntityOffset::*PPLoc>
4714struct PPEntityComp {
4715 const ASTReader &Reader;
4716 ModuleFile &M;
4717
4718 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4719
4720 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4721 SourceLocation LHS = getLoc(L);
4722 SourceLocation RHS = getLoc(R);
4723 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4724 }
4725
4726 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4727 SourceLocation LHS = getLoc(L);
4728 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4729 }
4730
4731 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4732 SourceLocation RHS = getLoc(R);
4733 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4734 }
4735
4736 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4737 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4738 }
4739};
4740
4741}
4742
4743/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4744PreprocessedEntityID
4745ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4746 if (SourceMgr.isLocalSourceLocation(BLoc))
4747 return getTotalNumPreprocessedEntities();
4748
4749 GlobalSLocOffsetMapType::const_iterator
4750 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004751 BLoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004752 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4753 "Corrupted global sloc offset map");
4754
4755 if (SLocMapI->second->NumPreprocessedEntities == 0)
4756 return findNextPreprocessedEntity(SLocMapI);
4757
4758 ModuleFile &M = *SLocMapI->second;
4759 typedef const PPEntityOffset *pp_iterator;
4760 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4761 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4762
4763 size_t Count = M.NumPreprocessedEntities;
4764 size_t Half;
4765 pp_iterator First = pp_begin;
4766 pp_iterator PPI;
4767
4768 // Do a binary search manually instead of using std::lower_bound because
4769 // The end locations of entities may be unordered (when a macro expansion
4770 // is inside another macro argument), but for this case it is not important
4771 // whether we get the first macro expansion or its containing macro.
4772 while (Count > 0) {
4773 Half = Count/2;
4774 PPI = First;
4775 std::advance(PPI, Half);
4776 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4777 BLoc)){
4778 First = PPI;
4779 ++First;
4780 Count = Count - Half - 1;
4781 } else
4782 Count = Half;
4783 }
4784
4785 if (PPI == pp_end)
4786 return findNextPreprocessedEntity(SLocMapI);
4787
4788 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4789}
4790
4791/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4792PreprocessedEntityID
4793ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4794 if (SourceMgr.isLocalSourceLocation(ELoc))
4795 return getTotalNumPreprocessedEntities();
4796
4797 GlobalSLocOffsetMapType::const_iterator
4798 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004799 ELoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004800 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4801 "Corrupted global sloc offset map");
4802
4803 if (SLocMapI->second->NumPreprocessedEntities == 0)
4804 return findNextPreprocessedEntity(SLocMapI);
4805
4806 ModuleFile &M = *SLocMapI->second;
4807 typedef const PPEntityOffset *pp_iterator;
4808 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4809 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4810 pp_iterator PPI =
4811 std::upper_bound(pp_begin, pp_end, ELoc,
4812 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4813
4814 if (PPI == pp_end)
4815 return findNextPreprocessedEntity(SLocMapI);
4816
4817 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4818}
4819
4820/// \brief Returns a pair of [Begin, End) indices of preallocated
4821/// preprocessed entities that \arg Range encompasses.
4822std::pair<unsigned, unsigned>
4823 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4824 if (Range.isInvalid())
4825 return std::make_pair(0,0);
4826 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4827
4828 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4829 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4830 return std::make_pair(BeginID, EndID);
4831}
4832
4833/// \brief Optionally returns true or false if the preallocated preprocessed
4834/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004835Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004836 FileID FID) {
4837 if (FID.isInvalid())
4838 return false;
4839
4840 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4841 ModuleFile &M = *PPInfo.first;
4842 unsigned LocalIndex = PPInfo.second;
4843 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4844
4845 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4846 if (Loc.isInvalid())
4847 return false;
4848
4849 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4850 return true;
4851 else
4852 return false;
4853}
4854
4855namespace {
4856 /// \brief Visitor used to search for information about a header file.
4857 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004858 const FileEntry *FE;
4859
David Blaikie05785d12013-02-20 22:23:23 +00004860 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004861
4862 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004863 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4864 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004865
4866 static bool visit(ModuleFile &M, void *UserData) {
4867 HeaderFileInfoVisitor *This
4868 = static_cast<HeaderFileInfoVisitor *>(UserData);
4869
Guy Benyei11169dd2012-12-18 14:30:41 +00004870 HeaderFileInfoLookupTable *Table
4871 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4872 if (!Table)
4873 return false;
4874
4875 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004876 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004877 if (Pos == Table->end())
4878 return false;
4879
4880 This->HFI = *Pos;
4881 return true;
4882 }
4883
David Blaikie05785d12013-02-20 22:23:23 +00004884 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004885 };
4886}
4887
4888HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004889 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004890 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004891 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004892 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004893
4894 return HeaderFileInfo();
4895}
4896
4897void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4898 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004899 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004900 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4901 ModuleFile &F = *(*I);
4902 unsigned Idx = 0;
4903 DiagStates.clear();
4904 assert(!Diag.DiagStates.empty());
4905 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4906 while (Idx < F.PragmaDiagMappings.size()) {
4907 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4908 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4909 if (DiagStateID != 0) {
4910 Diag.DiagStatePoints.push_back(
4911 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4912 FullSourceLoc(Loc, SourceMgr)));
4913 continue;
4914 }
4915
4916 assert(DiagStateID == 0);
4917 // A new DiagState was created here.
4918 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4919 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4920 DiagStates.push_back(NewState);
4921 Diag.DiagStatePoints.push_back(
4922 DiagnosticsEngine::DiagStatePoint(NewState,
4923 FullSourceLoc(Loc, SourceMgr)));
4924 while (1) {
4925 assert(Idx < F.PragmaDiagMappings.size() &&
4926 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4927 if (Idx >= F.PragmaDiagMappings.size()) {
4928 break; // Something is messed up but at least avoid infinite loop in
4929 // release build.
4930 }
4931 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4932 if (DiagID == (unsigned)-1) {
4933 break; // no more diag/map pairs for this location.
4934 }
4935 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4936 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4937 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4938 }
4939 }
4940 }
4941}
4942
4943/// \brief Get the correct cursor and offset for loading a type.
4944ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4945 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4946 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4947 ModuleFile *M = I->second;
4948 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4949}
4950
4951/// \brief Read and return the type with the given index..
4952///
4953/// The index is the type ID, shifted and minus the number of predefs. This
4954/// routine actually reads the record corresponding to the type at the given
4955/// location. It is a helper routine for GetType, which deals with reading type
4956/// IDs.
4957QualType ASTReader::readTypeRecord(unsigned Index) {
4958 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004959 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004960
4961 // Keep track of where we are in the stream, then jump back there
4962 // after reading this type.
4963 SavedStreamPosition SavedPosition(DeclsCursor);
4964
4965 ReadingKindTracker ReadingKind(Read_Type, *this);
4966
4967 // Note that we are loading a type record.
4968 Deserializing AType(this);
4969
4970 unsigned Idx = 0;
4971 DeclsCursor.JumpToBit(Loc.Offset);
4972 RecordData Record;
4973 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004974 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004975 case TYPE_EXT_QUAL: {
4976 if (Record.size() != 2) {
4977 Error("Incorrect encoding of extended qualifier type");
4978 return QualType();
4979 }
4980 QualType Base = readType(*Loc.F, Record, Idx);
4981 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4982 return Context.getQualifiedType(Base, Quals);
4983 }
4984
4985 case TYPE_COMPLEX: {
4986 if (Record.size() != 1) {
4987 Error("Incorrect encoding of complex type");
4988 return QualType();
4989 }
4990 QualType ElemType = readType(*Loc.F, Record, Idx);
4991 return Context.getComplexType(ElemType);
4992 }
4993
4994 case TYPE_POINTER: {
4995 if (Record.size() != 1) {
4996 Error("Incorrect encoding of pointer type");
4997 return QualType();
4998 }
4999 QualType PointeeType = readType(*Loc.F, Record, Idx);
5000 return Context.getPointerType(PointeeType);
5001 }
5002
Reid Kleckner8a365022013-06-24 17:51:48 +00005003 case TYPE_DECAYED: {
5004 if (Record.size() != 1) {
5005 Error("Incorrect encoding of decayed type");
5006 return QualType();
5007 }
5008 QualType OriginalType = readType(*Loc.F, Record, Idx);
5009 QualType DT = Context.getAdjustedParameterType(OriginalType);
5010 if (!isa<DecayedType>(DT))
5011 Error("Decayed type does not decay");
5012 return DT;
5013 }
5014
Reid Kleckner0503a872013-12-05 01:23:43 +00005015 case TYPE_ADJUSTED: {
5016 if (Record.size() != 2) {
5017 Error("Incorrect encoding of adjusted type");
5018 return QualType();
5019 }
5020 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5021 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5022 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5023 }
5024
Guy Benyei11169dd2012-12-18 14:30:41 +00005025 case TYPE_BLOCK_POINTER: {
5026 if (Record.size() != 1) {
5027 Error("Incorrect encoding of block pointer type");
5028 return QualType();
5029 }
5030 QualType PointeeType = readType(*Loc.F, Record, Idx);
5031 return Context.getBlockPointerType(PointeeType);
5032 }
5033
5034 case TYPE_LVALUE_REFERENCE: {
5035 if (Record.size() != 2) {
5036 Error("Incorrect encoding of lvalue reference type");
5037 return QualType();
5038 }
5039 QualType PointeeType = readType(*Loc.F, Record, Idx);
5040 return Context.getLValueReferenceType(PointeeType, Record[1]);
5041 }
5042
5043 case TYPE_RVALUE_REFERENCE: {
5044 if (Record.size() != 1) {
5045 Error("Incorrect encoding of rvalue reference type");
5046 return QualType();
5047 }
5048 QualType PointeeType = readType(*Loc.F, Record, Idx);
5049 return Context.getRValueReferenceType(PointeeType);
5050 }
5051
5052 case TYPE_MEMBER_POINTER: {
5053 if (Record.size() != 2) {
5054 Error("Incorrect encoding of member pointer type");
5055 return QualType();
5056 }
5057 QualType PointeeType = readType(*Loc.F, Record, Idx);
5058 QualType ClassType = readType(*Loc.F, Record, Idx);
5059 if (PointeeType.isNull() || ClassType.isNull())
5060 return QualType();
5061
5062 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5063 }
5064
5065 case TYPE_CONSTANT_ARRAY: {
5066 QualType ElementType = readType(*Loc.F, Record, Idx);
5067 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5068 unsigned IndexTypeQuals = Record[2];
5069 unsigned Idx = 3;
5070 llvm::APInt Size = ReadAPInt(Record, Idx);
5071 return Context.getConstantArrayType(ElementType, Size,
5072 ASM, IndexTypeQuals);
5073 }
5074
5075 case TYPE_INCOMPLETE_ARRAY: {
5076 QualType ElementType = readType(*Loc.F, Record, Idx);
5077 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5078 unsigned IndexTypeQuals = Record[2];
5079 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5080 }
5081
5082 case TYPE_VARIABLE_ARRAY: {
5083 QualType ElementType = readType(*Loc.F, Record, Idx);
5084 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5085 unsigned IndexTypeQuals = Record[2];
5086 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5087 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5088 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5089 ASM, IndexTypeQuals,
5090 SourceRange(LBLoc, RBLoc));
5091 }
5092
5093 case TYPE_VECTOR: {
5094 if (Record.size() != 3) {
5095 Error("incorrect encoding of vector type in AST file");
5096 return QualType();
5097 }
5098
5099 QualType ElementType = readType(*Loc.F, Record, Idx);
5100 unsigned NumElements = Record[1];
5101 unsigned VecKind = Record[2];
5102 return Context.getVectorType(ElementType, NumElements,
5103 (VectorType::VectorKind)VecKind);
5104 }
5105
5106 case TYPE_EXT_VECTOR: {
5107 if (Record.size() != 3) {
5108 Error("incorrect encoding of extended vector type in AST file");
5109 return QualType();
5110 }
5111
5112 QualType ElementType = readType(*Loc.F, Record, Idx);
5113 unsigned NumElements = Record[1];
5114 return Context.getExtVectorType(ElementType, NumElements);
5115 }
5116
5117 case TYPE_FUNCTION_NO_PROTO: {
5118 if (Record.size() != 6) {
5119 Error("incorrect encoding of no-proto function type");
5120 return QualType();
5121 }
5122 QualType ResultType = readType(*Loc.F, Record, Idx);
5123 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5124 (CallingConv)Record[4], Record[5]);
5125 return Context.getFunctionNoProtoType(ResultType, Info);
5126 }
5127
5128 case TYPE_FUNCTION_PROTO: {
5129 QualType ResultType = readType(*Loc.F, Record, Idx);
5130
5131 FunctionProtoType::ExtProtoInfo EPI;
5132 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5133 /*hasregparm*/ Record[2],
5134 /*regparm*/ Record[3],
5135 static_cast<CallingConv>(Record[4]),
5136 /*produces*/ Record[5]);
5137
5138 unsigned Idx = 6;
5139 unsigned NumParams = Record[Idx++];
5140 SmallVector<QualType, 16> ParamTypes;
5141 for (unsigned I = 0; I != NumParams; ++I)
5142 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5143
5144 EPI.Variadic = Record[Idx++];
5145 EPI.HasTrailingReturn = Record[Idx++];
5146 EPI.TypeQuals = Record[Idx++];
5147 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005148 SmallVector<QualType, 8> ExceptionStorage;
5149 readExceptionSpec(*Loc.F, ExceptionStorage, EPI, Record, Idx);
Jordan Rose5c382722013-03-08 21:51:21 +00005150 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 }
5152
5153 case TYPE_UNRESOLVED_USING: {
5154 unsigned Idx = 0;
5155 return Context.getTypeDeclType(
5156 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5157 }
5158
5159 case TYPE_TYPEDEF: {
5160 if (Record.size() != 2) {
5161 Error("incorrect encoding of typedef type");
5162 return QualType();
5163 }
5164 unsigned Idx = 0;
5165 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5166 QualType Canonical = readType(*Loc.F, Record, Idx);
5167 if (!Canonical.isNull())
5168 Canonical = Context.getCanonicalType(Canonical);
5169 return Context.getTypedefType(Decl, Canonical);
5170 }
5171
5172 case TYPE_TYPEOF_EXPR:
5173 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5174
5175 case TYPE_TYPEOF: {
5176 if (Record.size() != 1) {
5177 Error("incorrect encoding of typeof(type) in AST file");
5178 return QualType();
5179 }
5180 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5181 return Context.getTypeOfType(UnderlyingType);
5182 }
5183
5184 case TYPE_DECLTYPE: {
5185 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5186 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5187 }
5188
5189 case TYPE_UNARY_TRANSFORM: {
5190 QualType BaseType = readType(*Loc.F, Record, Idx);
5191 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5192 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5193 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5194 }
5195
Richard Smith74aeef52013-04-26 16:15:35 +00005196 case TYPE_AUTO: {
5197 QualType Deduced = readType(*Loc.F, Record, Idx);
5198 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005199 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005200 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005201 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005202
5203 case TYPE_RECORD: {
5204 if (Record.size() != 2) {
5205 Error("incorrect encoding of record type");
5206 return QualType();
5207 }
5208 unsigned Idx = 0;
5209 bool IsDependent = Record[Idx++];
5210 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5211 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5212 QualType T = Context.getRecordType(RD);
5213 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5214 return T;
5215 }
5216
5217 case TYPE_ENUM: {
5218 if (Record.size() != 2) {
5219 Error("incorrect encoding of enum type");
5220 return QualType();
5221 }
5222 unsigned Idx = 0;
5223 bool IsDependent = Record[Idx++];
5224 QualType T
5225 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5226 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5227 return T;
5228 }
5229
5230 case TYPE_ATTRIBUTED: {
5231 if (Record.size() != 3) {
5232 Error("incorrect encoding of attributed type");
5233 return QualType();
5234 }
5235 QualType modifiedType = readType(*Loc.F, Record, Idx);
5236 QualType equivalentType = readType(*Loc.F, Record, Idx);
5237 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5238 return Context.getAttributedType(kind, modifiedType, equivalentType);
5239 }
5240
5241 case TYPE_PAREN: {
5242 if (Record.size() != 1) {
5243 Error("incorrect encoding of paren type");
5244 return QualType();
5245 }
5246 QualType InnerType = readType(*Loc.F, Record, Idx);
5247 return Context.getParenType(InnerType);
5248 }
5249
5250 case TYPE_PACK_EXPANSION: {
5251 if (Record.size() != 2) {
5252 Error("incorrect encoding of pack expansion type");
5253 return QualType();
5254 }
5255 QualType Pattern = readType(*Loc.F, Record, Idx);
5256 if (Pattern.isNull())
5257 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005258 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005259 if (Record[1])
5260 NumExpansions = Record[1] - 1;
5261 return Context.getPackExpansionType(Pattern, NumExpansions);
5262 }
5263
5264 case TYPE_ELABORATED: {
5265 unsigned Idx = 0;
5266 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5267 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5268 QualType NamedType = readType(*Loc.F, Record, Idx);
5269 return Context.getElaboratedType(Keyword, NNS, NamedType);
5270 }
5271
5272 case TYPE_OBJC_INTERFACE: {
5273 unsigned Idx = 0;
5274 ObjCInterfaceDecl *ItfD
5275 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5276 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5277 }
5278
5279 case TYPE_OBJC_OBJECT: {
5280 unsigned Idx = 0;
5281 QualType Base = readType(*Loc.F, Record, Idx);
5282 unsigned NumProtos = Record[Idx++];
5283 SmallVector<ObjCProtocolDecl*, 4> Protos;
5284 for (unsigned I = 0; I != NumProtos; ++I)
5285 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5286 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5287 }
5288
5289 case TYPE_OBJC_OBJECT_POINTER: {
5290 unsigned Idx = 0;
5291 QualType Pointee = readType(*Loc.F, Record, Idx);
5292 return Context.getObjCObjectPointerType(Pointee);
5293 }
5294
5295 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5296 unsigned Idx = 0;
5297 QualType Parm = readType(*Loc.F, Record, Idx);
5298 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005299 return Context.getSubstTemplateTypeParmType(
5300 cast<TemplateTypeParmType>(Parm),
5301 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005302 }
5303
5304 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5305 unsigned Idx = 0;
5306 QualType Parm = readType(*Loc.F, Record, Idx);
5307 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5308 return Context.getSubstTemplateTypeParmPackType(
5309 cast<TemplateTypeParmType>(Parm),
5310 ArgPack);
5311 }
5312
5313 case TYPE_INJECTED_CLASS_NAME: {
5314 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5315 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5316 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5317 // for AST reading, too much interdependencies.
Richard Smithf17fdbd2014-04-24 02:25:27 +00005318 const Type *T;
5319 if (const Type *Existing = D->getTypeForDecl())
5320 T = Existing;
5321 else if (auto *Prev = D->getPreviousDecl())
5322 T = Prev->getTypeForDecl();
5323 else
5324 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5325 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005326 }
5327
5328 case TYPE_TEMPLATE_TYPE_PARM: {
5329 unsigned Idx = 0;
5330 unsigned Depth = Record[Idx++];
5331 unsigned Index = Record[Idx++];
5332 bool Pack = Record[Idx++];
5333 TemplateTypeParmDecl *D
5334 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5335 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5336 }
5337
5338 case TYPE_DEPENDENT_NAME: {
5339 unsigned Idx = 0;
5340 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5341 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5342 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5343 QualType Canon = readType(*Loc.F, Record, Idx);
5344 if (!Canon.isNull())
5345 Canon = Context.getCanonicalType(Canon);
5346 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5347 }
5348
5349 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5350 unsigned Idx = 0;
5351 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5352 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5353 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5354 unsigned NumArgs = Record[Idx++];
5355 SmallVector<TemplateArgument, 8> Args;
5356 Args.reserve(NumArgs);
5357 while (NumArgs--)
5358 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5359 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5360 Args.size(), Args.data());
5361 }
5362
5363 case TYPE_DEPENDENT_SIZED_ARRAY: {
5364 unsigned Idx = 0;
5365
5366 // ArrayType
5367 QualType ElementType = readType(*Loc.F, Record, Idx);
5368 ArrayType::ArraySizeModifier ASM
5369 = (ArrayType::ArraySizeModifier)Record[Idx++];
5370 unsigned IndexTypeQuals = Record[Idx++];
5371
5372 // DependentSizedArrayType
5373 Expr *NumElts = ReadExpr(*Loc.F);
5374 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5375
5376 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5377 IndexTypeQuals, Brackets);
5378 }
5379
5380 case TYPE_TEMPLATE_SPECIALIZATION: {
5381 unsigned Idx = 0;
5382 bool IsDependent = Record[Idx++];
5383 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5384 SmallVector<TemplateArgument, 8> Args;
5385 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5386 QualType Underlying = readType(*Loc.F, Record, Idx);
5387 QualType T;
5388 if (Underlying.isNull())
5389 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5390 Args.size());
5391 else
5392 T = Context.getTemplateSpecializationType(Name, Args.data(),
5393 Args.size(), Underlying);
5394 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5395 return T;
5396 }
5397
5398 case TYPE_ATOMIC: {
5399 if (Record.size() != 1) {
5400 Error("Incorrect encoding of atomic type");
5401 return QualType();
5402 }
5403 QualType ValueType = readType(*Loc.F, Record, Idx);
5404 return Context.getAtomicType(ValueType);
5405 }
5406 }
5407 llvm_unreachable("Invalid TypeCode!");
5408}
5409
Richard Smith564417a2014-03-20 21:47:22 +00005410void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5411 SmallVectorImpl<QualType> &Exceptions,
5412 FunctionProtoType::ExtProtoInfo &EPI,
5413 const RecordData &Record, unsigned &Idx) {
5414 ExceptionSpecificationType EST =
5415 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5416 EPI.ExceptionSpecType = EST;
5417 if (EST == EST_Dynamic) {
5418 EPI.NumExceptions = Record[Idx++];
5419 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5420 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5421 EPI.Exceptions = Exceptions.data();
5422 } else if (EST == EST_ComputedNoexcept) {
5423 EPI.NoexceptExpr = ReadExpr(ModuleFile);
5424 } else if (EST == EST_Uninstantiated) {
5425 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5426 EPI.ExceptionSpecTemplate =
5427 ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5428 } else if (EST == EST_Unevaluated) {
5429 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5430 }
5431}
5432
Guy Benyei11169dd2012-12-18 14:30:41 +00005433class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5434 ASTReader &Reader;
5435 ModuleFile &F;
5436 const ASTReader::RecordData &Record;
5437 unsigned &Idx;
5438
5439 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5440 unsigned &I) {
5441 return Reader.ReadSourceLocation(F, R, I);
5442 }
5443
5444 template<typename T>
5445 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5446 return Reader.ReadDeclAs<T>(F, Record, Idx);
5447 }
5448
5449public:
5450 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5451 const ASTReader::RecordData &Record, unsigned &Idx)
5452 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5453 { }
5454
5455 // We want compile-time assurance that we've enumerated all of
5456 // these, so unfortunately we have to declare them first, then
5457 // define them out-of-line.
5458#define ABSTRACT_TYPELOC(CLASS, PARENT)
5459#define TYPELOC(CLASS, PARENT) \
5460 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5461#include "clang/AST/TypeLocNodes.def"
5462
5463 void VisitFunctionTypeLoc(FunctionTypeLoc);
5464 void VisitArrayTypeLoc(ArrayTypeLoc);
5465};
5466
5467void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5468 // nothing to do
5469}
5470void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5471 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5472 if (TL.needsExtraLocalData()) {
5473 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5474 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5475 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5476 TL.setModeAttr(Record[Idx++]);
5477 }
5478}
5479void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5480 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5481}
5482void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5483 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5484}
Reid Kleckner8a365022013-06-24 17:51:48 +00005485void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5486 // nothing to do
5487}
Reid Kleckner0503a872013-12-05 01:23:43 +00005488void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5489 // nothing to do
5490}
Guy Benyei11169dd2012-12-18 14:30:41 +00005491void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5492 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5493}
5494void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5495 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5496}
5497void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5498 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5499}
5500void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5501 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5502 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5503}
5504void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5505 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5506 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5507 if (Record[Idx++])
5508 TL.setSizeExpr(Reader.ReadExpr(F));
5509 else
5510 TL.setSizeExpr(0);
5511}
5512void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5513 VisitArrayTypeLoc(TL);
5514}
5515void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5516 VisitArrayTypeLoc(TL);
5517}
5518void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5519 VisitArrayTypeLoc(TL);
5520}
5521void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5522 DependentSizedArrayTypeLoc TL) {
5523 VisitArrayTypeLoc(TL);
5524}
5525void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5526 DependentSizedExtVectorTypeLoc TL) {
5527 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5528}
5529void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5530 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5531}
5532void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5533 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5534}
5535void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5536 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5537 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5538 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5539 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005540 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5541 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005542 }
5543}
5544void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5545 VisitFunctionTypeLoc(TL);
5546}
5547void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5548 VisitFunctionTypeLoc(TL);
5549}
5550void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5551 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5552}
5553void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5554 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5555}
5556void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5557 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5558 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5559 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5560}
5561void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5562 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5563 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5564 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5565 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5566}
5567void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5568 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5569}
5570void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5571 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5572 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5573 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5574 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5575}
5576void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5577 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5578}
5579void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5580 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5581}
5582void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5583 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5584}
5585void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5586 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5587 if (TL.hasAttrOperand()) {
5588 SourceRange range;
5589 range.setBegin(ReadSourceLocation(Record, Idx));
5590 range.setEnd(ReadSourceLocation(Record, Idx));
5591 TL.setAttrOperandParensRange(range);
5592 }
5593 if (TL.hasAttrExprOperand()) {
5594 if (Record[Idx++])
5595 TL.setAttrExprOperand(Reader.ReadExpr(F));
5596 else
5597 TL.setAttrExprOperand(0);
5598 } else if (TL.hasAttrEnumOperand())
5599 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5600}
5601void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5602 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5603}
5604void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5605 SubstTemplateTypeParmTypeLoc TL) {
5606 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5607}
5608void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5609 SubstTemplateTypeParmPackTypeLoc TL) {
5610 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5611}
5612void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5613 TemplateSpecializationTypeLoc TL) {
5614 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5615 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5616 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5617 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5618 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5619 TL.setArgLocInfo(i,
5620 Reader.GetTemplateArgumentLocInfo(F,
5621 TL.getTypePtr()->getArg(i).getKind(),
5622 Record, Idx));
5623}
5624void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5625 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5626 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5627}
5628void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5629 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5630 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5631}
5632void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5633 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5634}
5635void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5636 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5637 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5638 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5639}
5640void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5641 DependentTemplateSpecializationTypeLoc TL) {
5642 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5643 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5644 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5645 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5646 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5647 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5648 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5649 TL.setArgLocInfo(I,
5650 Reader.GetTemplateArgumentLocInfo(F,
5651 TL.getTypePtr()->getArg(I).getKind(),
5652 Record, Idx));
5653}
5654void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5655 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5656}
5657void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5658 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5659}
5660void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5661 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5662 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5663 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5664 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5665 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5666}
5667void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5668 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5669}
5670void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5671 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5672 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5673 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5674}
5675
5676TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5677 const RecordData &Record,
5678 unsigned &Idx) {
5679 QualType InfoTy = readType(F, Record, Idx);
5680 if (InfoTy.isNull())
5681 return 0;
5682
5683 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5684 TypeLocReader TLR(*this, F, Record, Idx);
5685 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5686 TLR.Visit(TL);
5687 return TInfo;
5688}
5689
5690QualType ASTReader::GetType(TypeID ID) {
5691 unsigned FastQuals = ID & Qualifiers::FastMask;
5692 unsigned Index = ID >> Qualifiers::FastWidth;
5693
5694 if (Index < NUM_PREDEF_TYPE_IDS) {
5695 QualType T;
5696 switch ((PredefinedTypeIDs)Index) {
5697 case PREDEF_TYPE_NULL_ID: return QualType();
5698 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5699 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5700
5701 case PREDEF_TYPE_CHAR_U_ID:
5702 case PREDEF_TYPE_CHAR_S_ID:
5703 // FIXME: Check that the signedness of CharTy is correct!
5704 T = Context.CharTy;
5705 break;
5706
5707 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5708 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5709 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5710 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5711 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5712 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5713 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5714 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5715 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5716 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5717 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5718 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5719 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5720 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5721 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5722 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5723 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5724 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5725 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5726 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5727 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5728 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5729 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5730 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5731 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5732 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5733 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5734 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005735 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5736 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5737 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5738 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5739 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5740 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005741 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005742 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005743 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5744
5745 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5746 T = Context.getAutoRRefDeductType();
5747 break;
5748
5749 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5750 T = Context.ARCUnbridgedCastTy;
5751 break;
5752
5753 case PREDEF_TYPE_VA_LIST_TAG:
5754 T = Context.getVaListTagType();
5755 break;
5756
5757 case PREDEF_TYPE_BUILTIN_FN:
5758 T = Context.BuiltinFnTy;
5759 break;
5760 }
5761
5762 assert(!T.isNull() && "Unknown predefined type");
5763 return T.withFastQualifiers(FastQuals);
5764 }
5765
5766 Index -= NUM_PREDEF_TYPE_IDS;
5767 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5768 if (TypesLoaded[Index].isNull()) {
5769 TypesLoaded[Index] = readTypeRecord(Index);
5770 if (TypesLoaded[Index].isNull())
5771 return QualType();
5772
5773 TypesLoaded[Index]->setFromAST();
5774 if (DeserializationListener)
5775 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5776 TypesLoaded[Index]);
5777 }
5778
5779 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5780}
5781
5782QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5783 return GetType(getGlobalTypeID(F, LocalID));
5784}
5785
5786serialization::TypeID
5787ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5788 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5789 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5790
5791 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5792 return LocalID;
5793
5794 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5795 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5796 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5797
5798 unsigned GlobalIndex = LocalIndex + I->second;
5799 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5800}
5801
5802TemplateArgumentLocInfo
5803ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5804 TemplateArgument::ArgKind Kind,
5805 const RecordData &Record,
5806 unsigned &Index) {
5807 switch (Kind) {
5808 case TemplateArgument::Expression:
5809 return ReadExpr(F);
5810 case TemplateArgument::Type:
5811 return GetTypeSourceInfo(F, Record, Index);
5812 case TemplateArgument::Template: {
5813 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5814 Index);
5815 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5816 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5817 SourceLocation());
5818 }
5819 case TemplateArgument::TemplateExpansion: {
5820 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5821 Index);
5822 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5823 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5824 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5825 EllipsisLoc);
5826 }
5827 case TemplateArgument::Null:
5828 case TemplateArgument::Integral:
5829 case TemplateArgument::Declaration:
5830 case TemplateArgument::NullPtr:
5831 case TemplateArgument::Pack:
5832 // FIXME: Is this right?
5833 return TemplateArgumentLocInfo();
5834 }
5835 llvm_unreachable("unexpected template argument loc");
5836}
5837
5838TemplateArgumentLoc
5839ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5840 const RecordData &Record, unsigned &Index) {
5841 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5842
5843 if (Arg.getKind() == TemplateArgument::Expression) {
5844 if (Record[Index++]) // bool InfoHasSameExpr.
5845 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5846 }
5847 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5848 Record, Index));
5849}
5850
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005851const ASTTemplateArgumentListInfo*
5852ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5853 const RecordData &Record,
5854 unsigned &Index) {
5855 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5856 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5857 unsigned NumArgsAsWritten = Record[Index++];
5858 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5859 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5860 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5861 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5862}
5863
Guy Benyei11169dd2012-12-18 14:30:41 +00005864Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5865 return GetDecl(ID);
5866}
5867
Richard Smithcd45dbc2014-04-19 03:48:30 +00005868uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5869 const RecordData &Record,
5870 unsigned &Idx) {
5871 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5872 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005873 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005874 }
5875
Guy Benyei11169dd2012-12-18 14:30:41 +00005876 unsigned LocalID = Record[Idx++];
5877 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5878}
5879
5880CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5881 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005882 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005883 SavedStreamPosition SavedPosition(Cursor);
5884 Cursor.JumpToBit(Loc.Offset);
5885 ReadingKindTracker ReadingKind(Read_Decl, *this);
5886 RecordData Record;
5887 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005888 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005889 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005890 Error("malformed AST file: missing C++ base specifiers");
Guy Benyei11169dd2012-12-18 14:30:41 +00005891 return 0;
5892 }
5893
5894 unsigned Idx = 0;
5895 unsigned NumBases = Record[Idx++];
5896 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5897 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5898 for (unsigned I = 0; I != NumBases; ++I)
5899 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5900 return Bases;
5901}
5902
5903serialization::DeclID
5904ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5905 if (LocalID < NUM_PREDEF_DECL_IDS)
5906 return LocalID;
5907
5908 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5909 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5910 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5911
5912 return LocalID + I->second;
5913}
5914
5915bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5916 ModuleFile &M) const {
5917 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5918 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5919 return &M == I->second;
5920}
5921
Douglas Gregor9f782892013-01-21 15:25:38 +00005922ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005923 if (!D->isFromASTFile())
5924 return 0;
5925 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5926 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5927 return I->second;
5928}
5929
5930SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5931 if (ID < NUM_PREDEF_DECL_IDS)
5932 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00005933
Guy Benyei11169dd2012-12-18 14:30:41 +00005934 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5935
5936 if (Index > DeclsLoaded.size()) {
5937 Error("declaration ID out-of-range for AST file");
5938 return SourceLocation();
5939 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00005940
Guy Benyei11169dd2012-12-18 14:30:41 +00005941 if (Decl *D = DeclsLoaded[Index])
5942 return D->getLocation();
5943
5944 unsigned RawLocation = 0;
5945 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5946 return ReadSourceLocation(*Rec.F, RawLocation);
5947}
5948
Richard Smithcd45dbc2014-04-19 03:48:30 +00005949Decl *ASTReader::GetExistingDecl(DeclID ID) {
5950 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005951 switch ((PredefinedDeclIDs)ID) {
5952 case PREDEF_DECL_NULL_ID:
5953 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005954
Guy Benyei11169dd2012-12-18 14:30:41 +00005955 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5956 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00005957
Guy Benyei11169dd2012-12-18 14:30:41 +00005958 case PREDEF_DECL_OBJC_ID_ID:
5959 return Context.getObjCIdDecl();
5960
5961 case PREDEF_DECL_OBJC_SEL_ID:
5962 return Context.getObjCSelDecl();
5963
5964 case PREDEF_DECL_OBJC_CLASS_ID:
5965 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00005966
Guy Benyei11169dd2012-12-18 14:30:41 +00005967 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5968 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00005969
Guy Benyei11169dd2012-12-18 14:30:41 +00005970 case PREDEF_DECL_INT_128_ID:
5971 return Context.getInt128Decl();
5972
5973 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5974 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00005975
Guy Benyei11169dd2012-12-18 14:30:41 +00005976 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5977 return Context.getObjCInstanceTypeDecl();
5978
5979 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5980 return Context.getBuiltinVaListDecl();
5981 }
5982 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00005983
Guy Benyei11169dd2012-12-18 14:30:41 +00005984 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5985
5986 if (Index >= DeclsLoaded.size()) {
5987 assert(0 && "declaration ID out-of-range for AST file");
5988 Error("declaration ID out-of-range for AST file");
5989 return 0;
5990 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00005991
5992 return DeclsLoaded[Index];
5993}
5994
5995Decl *ASTReader::GetDecl(DeclID ID) {
5996 if (ID < NUM_PREDEF_DECL_IDS)
5997 return GetExistingDecl(ID);
5998
5999 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6000
6001 if (Index >= DeclsLoaded.size()) {
6002 assert(0 && "declaration ID out-of-range for AST file");
6003 Error("declaration ID out-of-range for AST file");
6004 return 0;
6005 }
6006
Guy Benyei11169dd2012-12-18 14:30:41 +00006007 if (!DeclsLoaded[Index]) {
6008 ReadDeclRecord(ID);
6009 if (DeserializationListener)
6010 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6011 }
6012
6013 return DeclsLoaded[Index];
6014}
6015
6016DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6017 DeclID GlobalID) {
6018 if (GlobalID < NUM_PREDEF_DECL_IDS)
6019 return GlobalID;
6020
6021 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6022 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6023 ModuleFile *Owner = I->second;
6024
6025 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6026 = M.GlobalToLocalDeclIDs.find(Owner);
6027 if (Pos == M.GlobalToLocalDeclIDs.end())
6028 return 0;
6029
6030 return GlobalID - Owner->BaseDeclID + Pos->second;
6031}
6032
6033serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6034 const RecordData &Record,
6035 unsigned &Idx) {
6036 if (Idx >= Record.size()) {
6037 Error("Corrupted AST file");
6038 return 0;
6039 }
6040
6041 return getGlobalDeclID(F, Record[Idx++]);
6042}
6043
6044/// \brief Resolve the offset of a statement into a statement.
6045///
6046/// This operation will read a new statement from the external
6047/// source each time it is called, and is meant to be used via a
6048/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6049Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6050 // Switch case IDs are per Decl.
6051 ClearSwitchCaseIDs();
6052
6053 // Offset here is a global offset across the entire chain.
6054 RecordLocation Loc = getLocalBitOffset(Offset);
6055 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6056 return ReadStmtFromStream(*Loc.F);
6057}
6058
6059namespace {
6060 class FindExternalLexicalDeclsVisitor {
6061 ASTReader &Reader;
6062 const DeclContext *DC;
6063 bool (*isKindWeWant)(Decl::Kind);
6064
6065 SmallVectorImpl<Decl*> &Decls;
6066 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6067
6068 public:
6069 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6070 bool (*isKindWeWant)(Decl::Kind),
6071 SmallVectorImpl<Decl*> &Decls)
6072 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6073 {
6074 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6075 PredefsVisited[I] = false;
6076 }
6077
6078 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6079 if (Preorder)
6080 return false;
6081
6082 FindExternalLexicalDeclsVisitor *This
6083 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6084
6085 ModuleFile::DeclContextInfosMap::iterator Info
6086 = M.DeclContextInfos.find(This->DC);
6087 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6088 return false;
6089
6090 // Load all of the declaration IDs
6091 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6092 *IDE = ID + Info->second.NumLexicalDecls;
6093 ID != IDE; ++ID) {
6094 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6095 continue;
6096
6097 // Don't add predefined declarations to the lexical context more
6098 // than once.
6099 if (ID->second < NUM_PREDEF_DECL_IDS) {
6100 if (This->PredefsVisited[ID->second])
6101 continue;
6102
6103 This->PredefsVisited[ID->second] = true;
6104 }
6105
6106 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6107 if (!This->DC->isDeclInLexicalTraversal(D))
6108 This->Decls.push_back(D);
6109 }
6110 }
6111
6112 return false;
6113 }
6114 };
6115}
6116
6117ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6118 bool (*isKindWeWant)(Decl::Kind),
6119 SmallVectorImpl<Decl*> &Decls) {
6120 // There might be lexical decls in multiple modules, for the TU at
6121 // least. Walk all of the modules in the order they were loaded.
6122 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6123 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6124 ++NumLexicalDeclContextsRead;
6125 return ELR_Success;
6126}
6127
6128namespace {
6129
6130class DeclIDComp {
6131 ASTReader &Reader;
6132 ModuleFile &Mod;
6133
6134public:
6135 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6136
6137 bool operator()(LocalDeclID L, LocalDeclID R) const {
6138 SourceLocation LHS = getLocation(L);
6139 SourceLocation RHS = getLocation(R);
6140 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6141 }
6142
6143 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6144 SourceLocation RHS = getLocation(R);
6145 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6146 }
6147
6148 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6149 SourceLocation LHS = getLocation(L);
6150 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6151 }
6152
6153 SourceLocation getLocation(LocalDeclID ID) const {
6154 return Reader.getSourceManager().getFileLoc(
6155 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6156 }
6157};
6158
6159}
6160
6161void ASTReader::FindFileRegionDecls(FileID File,
6162 unsigned Offset, unsigned Length,
6163 SmallVectorImpl<Decl *> &Decls) {
6164 SourceManager &SM = getSourceManager();
6165
6166 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6167 if (I == FileDeclIDs.end())
6168 return;
6169
6170 FileDeclsInfo &DInfo = I->second;
6171 if (DInfo.Decls.empty())
6172 return;
6173
6174 SourceLocation
6175 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6176 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6177
6178 DeclIDComp DIDComp(*this, *DInfo.Mod);
6179 ArrayRef<serialization::LocalDeclID>::iterator
6180 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6181 BeginLoc, DIDComp);
6182 if (BeginIt != DInfo.Decls.begin())
6183 --BeginIt;
6184
6185 // If we are pointing at a top-level decl inside an objc container, we need
6186 // to backtrack until we find it otherwise we will fail to report that the
6187 // region overlaps with an objc container.
6188 while (BeginIt != DInfo.Decls.begin() &&
6189 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6190 ->isTopLevelDeclInObjCContainer())
6191 --BeginIt;
6192
6193 ArrayRef<serialization::LocalDeclID>::iterator
6194 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6195 EndLoc, DIDComp);
6196 if (EndIt != DInfo.Decls.end())
6197 ++EndIt;
6198
6199 for (ArrayRef<serialization::LocalDeclID>::iterator
6200 DIt = BeginIt; DIt != EndIt; ++DIt)
6201 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6202}
6203
6204namespace {
6205 /// \brief ModuleFile visitor used to perform name lookup into a
6206 /// declaration context.
6207 class DeclContextNameLookupVisitor {
6208 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006209 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006210 DeclarationName Name;
6211 SmallVectorImpl<NamedDecl *> &Decls;
6212
6213 public:
6214 DeclContextNameLookupVisitor(ASTReader &Reader,
6215 SmallVectorImpl<const DeclContext *> &Contexts,
6216 DeclarationName Name,
6217 SmallVectorImpl<NamedDecl *> &Decls)
6218 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6219
6220 static bool visit(ModuleFile &M, void *UserData) {
6221 DeclContextNameLookupVisitor *This
6222 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6223
6224 // Check whether we have any visible declaration information for
6225 // this context in this module.
6226 ModuleFile::DeclContextInfosMap::iterator Info;
6227 bool FoundInfo = false;
6228 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6229 Info = M.DeclContextInfos.find(This->Contexts[I]);
6230 if (Info != M.DeclContextInfos.end() &&
6231 Info->second.NameLookupTableData) {
6232 FoundInfo = true;
6233 break;
6234 }
6235 }
6236
6237 if (!FoundInfo)
6238 return false;
6239
6240 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006241 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006242 Info->second.NameLookupTableData;
6243 ASTDeclContextNameLookupTable::iterator Pos
6244 = LookupTable->find(This->Name);
6245 if (Pos == LookupTable->end())
6246 return false;
6247
6248 bool FoundAnything = false;
6249 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6250 for (; Data.first != Data.second; ++Data.first) {
6251 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6252 if (!ND)
6253 continue;
6254
6255 if (ND->getDeclName() != This->Name) {
6256 // A name might be null because the decl's redeclarable part is
6257 // currently read before reading its name. The lookup is triggered by
6258 // building that decl (likely indirectly), and so it is later in the
6259 // sense of "already existing" and can be ignored here.
6260 continue;
6261 }
6262
6263 // Record this declaration.
6264 FoundAnything = true;
6265 This->Decls.push_back(ND);
6266 }
6267
6268 return FoundAnything;
6269 }
6270 };
6271}
6272
Douglas Gregor9f782892013-01-21 15:25:38 +00006273/// \brief Retrieve the "definitive" module file for the definition of the
6274/// given declaration context, if there is one.
6275///
6276/// The "definitive" module file is the only place where we need to look to
6277/// find information about the declarations within the given declaration
6278/// context. For example, C++ and Objective-C classes, C structs/unions, and
6279/// Objective-C protocols, categories, and extensions are all defined in a
6280/// single place in the source code, so they have definitive module files
6281/// associated with them. C++ namespaces, on the other hand, can have
6282/// definitions in multiple different module files.
6283///
6284/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6285/// NDEBUG checking.
6286static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6287 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006288 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6289 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006290
6291 return 0;
6292}
6293
Richard Smith9ce12e32013-02-07 03:30:24 +00006294bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006295ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6296 DeclarationName Name) {
6297 assert(DC->hasExternalVisibleStorage() &&
6298 "DeclContext has no visible decls in storage");
6299 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006300 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006301
6302 SmallVector<NamedDecl *, 64> Decls;
6303
6304 // Compute the declaration contexts we need to look into. Multiple such
6305 // declaration contexts occur when two declaration contexts from disjoint
6306 // modules get merged, e.g., when two namespaces with the same name are
6307 // independently defined in separate modules.
6308 SmallVector<const DeclContext *, 2> Contexts;
6309 Contexts.push_back(DC);
6310
6311 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006312 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006313 if (Merged != MergedDecls.end()) {
6314 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6315 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6316 }
6317 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006318 if (isa<CXXRecordDecl>(DC)) {
6319 auto Merged = MergedLookups.find(DC);
6320 if (Merged != MergedLookups.end())
6321 Contexts.insert(Contexts.end(), Merged->second.begin(),
6322 Merged->second.end());
6323 }
6324
Guy Benyei11169dd2012-12-18 14:30:41 +00006325 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006326
6327 // If we can definitively determine which module file to look into,
6328 // only look there. Otherwise, look in all module files.
6329 ModuleFile *Definitive;
6330 if (Contexts.size() == 1 &&
6331 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6332 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6333 } else {
6334 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6335 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006336 ++NumVisibleDeclContextsRead;
6337 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006338 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006339}
6340
6341namespace {
6342 /// \brief ModuleFile visitor used to retrieve all visible names in a
6343 /// declaration context.
6344 class DeclContextAllNamesVisitor {
6345 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006346 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006347 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006348 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006349
6350 public:
6351 DeclContextAllNamesVisitor(ASTReader &Reader,
6352 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006353 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006354 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006355
6356 static bool visit(ModuleFile &M, void *UserData) {
6357 DeclContextAllNamesVisitor *This
6358 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6359
6360 // Check whether we have any visible declaration information for
6361 // this context in this module.
6362 ModuleFile::DeclContextInfosMap::iterator Info;
6363 bool FoundInfo = false;
6364 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6365 Info = M.DeclContextInfos.find(This->Contexts[I]);
6366 if (Info != M.DeclContextInfos.end() &&
6367 Info->second.NameLookupTableData) {
6368 FoundInfo = true;
6369 break;
6370 }
6371 }
6372
6373 if (!FoundInfo)
6374 return false;
6375
Richard Smith52e3fba2014-03-11 07:17:35 +00006376 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006377 Info->second.NameLookupTableData;
6378 bool FoundAnything = false;
6379 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006380 I = LookupTable->data_begin(), E = LookupTable->data_end();
6381 I != E;
6382 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006383 ASTDeclContextNameLookupTrait::data_type Data = *I;
6384 for (; Data.first != Data.second; ++Data.first) {
6385 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6386 *Data.first);
6387 if (!ND)
6388 continue;
6389
6390 // Record this declaration.
6391 FoundAnything = true;
6392 This->Decls[ND->getDeclName()].push_back(ND);
6393 }
6394 }
6395
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006396 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006397 }
6398 };
6399}
6400
6401void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6402 if (!DC->hasExternalVisibleStorage())
6403 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006404 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006405
6406 // Compute the declaration contexts we need to look into. Multiple such
6407 // declaration contexts occur when two declaration contexts from disjoint
6408 // modules get merged, e.g., when two namespaces with the same name are
6409 // independently defined in separate modules.
6410 SmallVector<const DeclContext *, 2> Contexts;
6411 Contexts.push_back(DC);
6412
6413 if (DC->isNamespace()) {
6414 MergedDeclsMap::iterator Merged
6415 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6416 if (Merged != MergedDecls.end()) {
6417 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6418 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6419 }
6420 }
6421
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006422 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6423 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006424 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6425 ++NumVisibleDeclContextsRead;
6426
Craig Topper79be4cd2013-07-05 04:33:53 +00006427 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006428 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6429 }
6430 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6431}
6432
6433/// \brief Under non-PCH compilation the consumer receives the objc methods
6434/// before receiving the implementation, and codegen depends on this.
6435/// We simulate this by deserializing and passing to consumer the methods of the
6436/// implementation before passing the deserialized implementation decl.
6437static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6438 ASTConsumer *Consumer) {
6439 assert(ImplD && Consumer);
6440
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006441 for (auto *I : ImplD->methods())
6442 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006443
6444 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6445}
6446
6447void ASTReader::PassInterestingDeclsToConsumer() {
6448 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006449
6450 if (PassingDeclsToConsumer)
6451 return;
6452
6453 // Guard variable to avoid recursively redoing the process of passing
6454 // decls to consumer.
6455 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6456 true);
6457
Guy Benyei11169dd2012-12-18 14:30:41 +00006458 while (!InterestingDecls.empty()) {
6459 Decl *D = InterestingDecls.front();
6460 InterestingDecls.pop_front();
6461
6462 PassInterestingDeclToConsumer(D);
6463 }
6464}
6465
6466void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6467 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6468 PassObjCImplDeclToConsumer(ImplD, Consumer);
6469 else
6470 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6471}
6472
6473void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6474 this->Consumer = Consumer;
6475
6476 if (!Consumer)
6477 return;
6478
Ben Langmuir332aafe2014-01-31 01:06:56 +00006479 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006480 // Force deserialization of this decl, which will cause it to be queued for
6481 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006482 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006483 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006484 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006485
6486 PassInterestingDeclsToConsumer();
6487}
6488
6489void ASTReader::PrintStats() {
6490 std::fprintf(stderr, "*** AST File Statistics:\n");
6491
6492 unsigned NumTypesLoaded
6493 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6494 QualType());
6495 unsigned NumDeclsLoaded
6496 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6497 (Decl *)0);
6498 unsigned NumIdentifiersLoaded
6499 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6500 IdentifiersLoaded.end(),
6501 (IdentifierInfo *)0);
6502 unsigned NumMacrosLoaded
6503 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6504 MacrosLoaded.end(),
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006505 (MacroInfo *)0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006506 unsigned NumSelectorsLoaded
6507 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6508 SelectorsLoaded.end(),
6509 Selector());
6510
6511 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6512 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6513 NumSLocEntriesRead, TotalNumSLocEntries,
6514 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6515 if (!TypesLoaded.empty())
6516 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6517 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6518 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6519 if (!DeclsLoaded.empty())
6520 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6521 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6522 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6523 if (!IdentifiersLoaded.empty())
6524 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6525 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6526 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6527 if (!MacrosLoaded.empty())
6528 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6529 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6530 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6531 if (!SelectorsLoaded.empty())
6532 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6533 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6534 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6535 if (TotalNumStatements)
6536 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6537 NumStatementsRead, TotalNumStatements,
6538 ((float)NumStatementsRead/TotalNumStatements * 100));
6539 if (TotalNumMacros)
6540 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6541 NumMacrosRead, TotalNumMacros,
6542 ((float)NumMacrosRead/TotalNumMacros * 100));
6543 if (TotalLexicalDeclContexts)
6544 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6545 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6546 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6547 * 100));
6548 if (TotalVisibleDeclContexts)
6549 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6550 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6551 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6552 * 100));
6553 if (TotalNumMethodPoolEntries) {
6554 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6555 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6556 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6557 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006558 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006559 if (NumMethodPoolLookups) {
6560 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6561 NumMethodPoolHits, NumMethodPoolLookups,
6562 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6563 }
6564 if (NumMethodPoolTableLookups) {
6565 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6566 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6567 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6568 * 100.0));
6569 }
6570
Douglas Gregor00a50f72013-01-25 00:38:33 +00006571 if (NumIdentifierLookupHits) {
6572 std::fprintf(stderr,
6573 " %u / %u identifier table lookups succeeded (%f%%)\n",
6574 NumIdentifierLookupHits, NumIdentifierLookups,
6575 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6576 }
6577
Douglas Gregore060e572013-01-25 01:03:03 +00006578 if (GlobalIndex) {
6579 std::fprintf(stderr, "\n");
6580 GlobalIndex->printStats();
6581 }
6582
Guy Benyei11169dd2012-12-18 14:30:41 +00006583 std::fprintf(stderr, "\n");
6584 dump();
6585 std::fprintf(stderr, "\n");
6586}
6587
6588template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6589static void
6590dumpModuleIDMap(StringRef Name,
6591 const ContinuousRangeMap<Key, ModuleFile *,
6592 InitialCapacity> &Map) {
6593 if (Map.begin() == Map.end())
6594 return;
6595
6596 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6597 llvm::errs() << Name << ":\n";
6598 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6599 I != IEnd; ++I) {
6600 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6601 << "\n";
6602 }
6603}
6604
6605void ASTReader::dump() {
6606 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6607 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6608 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6609 dumpModuleIDMap("Global type map", GlobalTypeMap);
6610 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6611 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6612 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6613 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6614 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6615 dumpModuleIDMap("Global preprocessed entity map",
6616 GlobalPreprocessedEntityMap);
6617
6618 llvm::errs() << "\n*** PCH/Modules Loaded:";
6619 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6620 MEnd = ModuleMgr.end();
6621 M != MEnd; ++M)
6622 (*M)->dump();
6623}
6624
6625/// Return the amount of memory used by memory buffers, breaking down
6626/// by heap-backed versus mmap'ed memory.
6627void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6628 for (ModuleConstIterator I = ModuleMgr.begin(),
6629 E = ModuleMgr.end(); I != E; ++I) {
6630 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6631 size_t bytes = buf->getBufferSize();
6632 switch (buf->getBufferKind()) {
6633 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6634 sizes.malloc_bytes += bytes;
6635 break;
6636 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6637 sizes.mmap_bytes += bytes;
6638 break;
6639 }
6640 }
6641 }
6642}
6643
6644void ASTReader::InitializeSema(Sema &S) {
6645 SemaObj = &S;
6646 S.addExternalSource(this);
6647
6648 // Makes sure any declarations that were deserialized "too early"
6649 // still get added to the identifier's declaration chains.
6650 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006651 pushExternalDeclIntoScope(PreloadedDecls[I],
6652 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006653 }
6654 PreloadedDecls.clear();
6655
Richard Smith3d8e97e2013-10-18 06:54:39 +00006656 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006657 if (!FPPragmaOptions.empty()) {
6658 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6659 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6660 }
6661
Richard Smith3d8e97e2013-10-18 06:54:39 +00006662 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006663 if (!OpenCLExtensions.empty()) {
6664 unsigned I = 0;
6665#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6666#include "clang/Basic/OpenCLExtensions.def"
6667
6668 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6669 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006670
6671 UpdateSema();
6672}
6673
6674void ASTReader::UpdateSema() {
6675 assert(SemaObj && "no Sema to update");
6676
6677 // Load the offsets of the declarations that Sema references.
6678 // They will be lazily deserialized when needed.
6679 if (!SemaDeclRefs.empty()) {
6680 assert(SemaDeclRefs.size() % 2 == 0);
6681 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6682 if (!SemaObj->StdNamespace)
6683 SemaObj->StdNamespace = SemaDeclRefs[I];
6684 if (!SemaObj->StdBadAlloc)
6685 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6686 }
6687 SemaDeclRefs.clear();
6688 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006689}
6690
6691IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6692 // Note that we are loading an identifier.
6693 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006694 StringRef Name(NameStart, NameEnd - NameStart);
6695
6696 // If there is a global index, look there first to determine which modules
6697 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006698 GlobalModuleIndex::HitSet Hits;
6699 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00006700 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006701 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6702 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006703 }
6704 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006705 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006706 NumIdentifierLookups,
6707 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006708 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006709 IdentifierInfo *II = Visitor.getIdentifierInfo();
6710 markIdentifierUpToDate(II);
6711 return II;
6712}
6713
6714namespace clang {
6715 /// \brief An identifier-lookup iterator that enumerates all of the
6716 /// identifiers stored within a set of AST files.
6717 class ASTIdentifierIterator : public IdentifierIterator {
6718 /// \brief The AST reader whose identifiers are being enumerated.
6719 const ASTReader &Reader;
6720
6721 /// \brief The current index into the chain of AST files stored in
6722 /// the AST reader.
6723 unsigned Index;
6724
6725 /// \brief The current position within the identifier lookup table
6726 /// of the current AST file.
6727 ASTIdentifierLookupTable::key_iterator Current;
6728
6729 /// \brief The end position within the identifier lookup table of
6730 /// the current AST file.
6731 ASTIdentifierLookupTable::key_iterator End;
6732
6733 public:
6734 explicit ASTIdentifierIterator(const ASTReader &Reader);
6735
Craig Topper3e89dfe2014-03-13 02:13:41 +00006736 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006737 };
6738}
6739
6740ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6741 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6742 ASTIdentifierLookupTable *IdTable
6743 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6744 Current = IdTable->key_begin();
6745 End = IdTable->key_end();
6746}
6747
6748StringRef ASTIdentifierIterator::Next() {
6749 while (Current == End) {
6750 // If we have exhausted all of our AST files, we're done.
6751 if (Index == 0)
6752 return StringRef();
6753
6754 --Index;
6755 ASTIdentifierLookupTable *IdTable
6756 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6757 IdentifierLookupTable;
6758 Current = IdTable->key_begin();
6759 End = IdTable->key_end();
6760 }
6761
6762 // We have any identifiers remaining in the current AST file; return
6763 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006764 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006765 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006766 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006767}
6768
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006769IdentifierIterator *ASTReader::getIdentifiers() {
6770 if (!loadGlobalIndex())
6771 return GlobalIndex->createIdentifierIterator();
6772
Guy Benyei11169dd2012-12-18 14:30:41 +00006773 return new ASTIdentifierIterator(*this);
6774}
6775
6776namespace clang { namespace serialization {
6777 class ReadMethodPoolVisitor {
6778 ASTReader &Reader;
6779 Selector Sel;
6780 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006781 unsigned InstanceBits;
6782 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006783 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6784 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006785
6786 public:
6787 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6788 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006789 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6790 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006791
6792 static bool visit(ModuleFile &M, void *UserData) {
6793 ReadMethodPoolVisitor *This
6794 = static_cast<ReadMethodPoolVisitor *>(UserData);
6795
6796 if (!M.SelectorLookupTable)
6797 return false;
6798
6799 // If we've already searched this module file, skip it now.
6800 if (M.Generation <= This->PriorGeneration)
6801 return true;
6802
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006803 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006804 ASTSelectorLookupTable *PoolTable
6805 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6806 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6807 if (Pos == PoolTable->end())
6808 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006809
6810 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006811 ++This->Reader.NumSelectorsRead;
6812 // FIXME: Not quite happy with the statistics here. We probably should
6813 // disable this tracking when called via LoadSelector.
6814 // Also, should entries without methods count as misses?
6815 ++This->Reader.NumMethodPoolEntriesRead;
6816 ASTSelectorLookupTrait::data_type Data = *Pos;
6817 if (This->Reader.DeserializationListener)
6818 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6819 This->Sel);
6820
6821 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6822 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006823 This->InstanceBits = Data.InstanceBits;
6824 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006825 return true;
6826 }
6827
6828 /// \brief Retrieve the instance methods found by this visitor.
6829 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6830 return InstanceMethods;
6831 }
6832
6833 /// \brief Retrieve the instance methods found by this visitor.
6834 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6835 return FactoryMethods;
6836 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006837
6838 unsigned getInstanceBits() const { return InstanceBits; }
6839 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006840 };
6841} } // end namespace clang::serialization
6842
6843/// \brief Add the given set of methods to the method list.
6844static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6845 ObjCMethodList &List) {
6846 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6847 S.addMethodToGlobalList(&List, Methods[I]);
6848 }
6849}
6850
6851void ASTReader::ReadMethodPool(Selector Sel) {
6852 // Get the selector generation and update it to the current generation.
6853 unsigned &Generation = SelectorGeneration[Sel];
6854 unsigned PriorGeneration = Generation;
6855 Generation = CurrentGeneration;
6856
6857 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006858 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006859 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6860 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6861
6862 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006863 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006864 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006865
6866 ++NumMethodPoolHits;
6867
Guy Benyei11169dd2012-12-18 14:30:41 +00006868 if (!getSema())
6869 return;
6870
6871 Sema &S = *getSema();
6872 Sema::GlobalMethodPool::iterator Pos
6873 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6874
6875 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6876 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006877 Pos->second.first.setBits(Visitor.getInstanceBits());
6878 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00006879}
6880
6881void ASTReader::ReadKnownNamespaces(
6882 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6883 Namespaces.clear();
6884
6885 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6886 if (NamespaceDecl *Namespace
6887 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6888 Namespaces.push_back(Namespace);
6889 }
6890}
6891
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006892void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00006893 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006894 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6895 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00006896 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006897 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00006898 Undefined.insert(std::make_pair(D, Loc));
6899 }
6900}
Nick Lewycky8334af82013-01-26 00:35:08 +00006901
Guy Benyei11169dd2012-12-18 14:30:41 +00006902void ASTReader::ReadTentativeDefinitions(
6903 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6904 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6905 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6906 if (Var)
6907 TentativeDefs.push_back(Var);
6908 }
6909 TentativeDefinitions.clear();
6910}
6911
6912void ASTReader::ReadUnusedFileScopedDecls(
6913 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6914 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6915 DeclaratorDecl *D
6916 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6917 if (D)
6918 Decls.push_back(D);
6919 }
6920 UnusedFileScopedDecls.clear();
6921}
6922
6923void ASTReader::ReadDelegatingConstructors(
6924 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6925 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6926 CXXConstructorDecl *D
6927 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6928 if (D)
6929 Decls.push_back(D);
6930 }
6931 DelegatingCtorDecls.clear();
6932}
6933
6934void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6935 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6936 TypedefNameDecl *D
6937 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6938 if (D)
6939 Decls.push_back(D);
6940 }
6941 ExtVectorDecls.clear();
6942}
6943
6944void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6945 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6946 CXXRecordDecl *D
6947 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6948 if (D)
6949 Decls.push_back(D);
6950 }
6951 DynamicClasses.clear();
6952}
6953
6954void
Richard Smith78165b52013-01-10 23:43:47 +00006955ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6956 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6957 NamedDecl *D
6958 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006959 if (D)
6960 Decls.push_back(D);
6961 }
Richard Smith78165b52013-01-10 23:43:47 +00006962 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006963}
6964
6965void ASTReader::ReadReferencedSelectors(
6966 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6967 if (ReferencedSelectorsData.empty())
6968 return;
6969
6970 // If there are @selector references added them to its pool. This is for
6971 // implementation of -Wselector.
6972 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6973 unsigned I = 0;
6974 while (I < DataSize) {
6975 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6976 SourceLocation SelLoc
6977 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6978 Sels.push_back(std::make_pair(Sel, SelLoc));
6979 }
6980 ReferencedSelectorsData.clear();
6981}
6982
6983void ASTReader::ReadWeakUndeclaredIdentifiers(
6984 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6985 if (WeakUndeclaredIdentifiers.empty())
6986 return;
6987
6988 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6989 IdentifierInfo *WeakId
6990 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6991 IdentifierInfo *AliasId
6992 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6993 SourceLocation Loc
6994 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6995 bool Used = WeakUndeclaredIdentifiers[I++];
6996 WeakInfo WI(AliasId, Loc);
6997 WI.setUsed(Used);
6998 WeakIDs.push_back(std::make_pair(WeakId, WI));
6999 }
7000 WeakUndeclaredIdentifiers.clear();
7001}
7002
7003void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7004 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7005 ExternalVTableUse VT;
7006 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7007 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7008 VT.DefinitionRequired = VTableUses[Idx++];
7009 VTables.push_back(VT);
7010 }
7011
7012 VTableUses.clear();
7013}
7014
7015void ASTReader::ReadPendingInstantiations(
7016 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7017 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7018 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7019 SourceLocation Loc
7020 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7021
7022 Pending.push_back(std::make_pair(D, Loc));
7023 }
7024 PendingInstantiations.clear();
7025}
7026
Richard Smithe40f2ba2013-08-07 21:41:30 +00007027void ASTReader::ReadLateParsedTemplates(
7028 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7029 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7030 /* In loop */) {
7031 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7032
7033 LateParsedTemplate *LT = new LateParsedTemplate;
7034 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7035
7036 ModuleFile *F = getOwningModuleFile(LT->D);
7037 assert(F && "No module");
7038
7039 unsigned TokN = LateParsedTemplates[Idx++];
7040 LT->Toks.reserve(TokN);
7041 for (unsigned T = 0; T < TokN; ++T)
7042 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7043
7044 LPTMap[FD] = LT;
7045 }
7046
7047 LateParsedTemplates.clear();
7048}
7049
Guy Benyei11169dd2012-12-18 14:30:41 +00007050void ASTReader::LoadSelector(Selector Sel) {
7051 // It would be complicated to avoid reading the methods anyway. So don't.
7052 ReadMethodPool(Sel);
7053}
7054
7055void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7056 assert(ID && "Non-zero identifier ID required");
7057 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7058 IdentifiersLoaded[ID - 1] = II;
7059 if (DeserializationListener)
7060 DeserializationListener->IdentifierRead(ID, II);
7061}
7062
7063/// \brief Set the globally-visible declarations associated with the given
7064/// identifier.
7065///
7066/// If the AST reader is currently in a state where the given declaration IDs
7067/// cannot safely be resolved, they are queued until it is safe to resolve
7068/// them.
7069///
7070/// \param II an IdentifierInfo that refers to one or more globally-visible
7071/// declarations.
7072///
7073/// \param DeclIDs the set of declaration IDs with the name @p II that are
7074/// visible at global scope.
7075///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007076/// \param Decls if non-null, this vector will be populated with the set of
7077/// deserialized declarations. These declarations will not be pushed into
7078/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007079void
7080ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7081 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007082 SmallVectorImpl<Decl *> *Decls) {
7083 if (NumCurrentElementsDeserializing && !Decls) {
7084 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007085 return;
7086 }
7087
7088 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7089 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7090 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007091 // If we're simply supposed to record the declarations, do so now.
7092 if (Decls) {
7093 Decls->push_back(D);
7094 continue;
7095 }
7096
Guy Benyei11169dd2012-12-18 14:30:41 +00007097 // Introduce this declaration into the translation-unit scope
7098 // and add it to the declaration chain for this identifier, so
7099 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007100 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007101 } else {
7102 // Queue this declaration so that it will be added to the
7103 // translation unit scope and identifier's declaration chain
7104 // once a Sema object is known.
7105 PreloadedDecls.push_back(D);
7106 }
7107 }
7108}
7109
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007110IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007111 if (ID == 0)
7112 return 0;
7113
7114 if (IdentifiersLoaded.empty()) {
7115 Error("no identifier table in AST file");
7116 return 0;
7117 }
7118
7119 ID -= 1;
7120 if (!IdentifiersLoaded[ID]) {
7121 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7122 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7123 ModuleFile *M = I->second;
7124 unsigned Index = ID - M->BaseIdentifierID;
7125 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7126
7127 // All of the strings in the AST file are preceded by a 16-bit length.
7128 // Extract that 16-bit length to avoid having to execute strlen().
7129 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7130 // unsigned integers. This is important to avoid integer overflow when
7131 // we cast them to 'unsigned'.
7132 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7133 unsigned StrLen = (((unsigned) StrLenPtr[0])
7134 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007135 IdentifiersLoaded[ID]
7136 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007137 if (DeserializationListener)
7138 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7139 }
7140
7141 return IdentifiersLoaded[ID];
7142}
7143
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007144IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7145 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007146}
7147
7148IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7149 if (LocalID < NUM_PREDEF_IDENT_IDS)
7150 return LocalID;
7151
7152 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7153 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7154 assert(I != M.IdentifierRemap.end()
7155 && "Invalid index into identifier index remap");
7156
7157 return LocalID + I->second;
7158}
7159
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007160MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007161 if (ID == 0)
7162 return 0;
7163
7164 if (MacrosLoaded.empty()) {
7165 Error("no macro table in AST file");
7166 return 0;
7167 }
7168
7169 ID -= NUM_PREDEF_MACRO_IDS;
7170 if (!MacrosLoaded[ID]) {
7171 GlobalMacroMapType::iterator I
7172 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7173 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7174 ModuleFile *M = I->second;
7175 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007176 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7177
7178 if (DeserializationListener)
7179 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7180 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007181 }
7182
7183 return MacrosLoaded[ID];
7184}
7185
7186MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7187 if (LocalID < NUM_PREDEF_MACRO_IDS)
7188 return LocalID;
7189
7190 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7191 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7192 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7193
7194 return LocalID + I->second;
7195}
7196
7197serialization::SubmoduleID
7198ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7199 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7200 return LocalID;
7201
7202 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7203 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7204 assert(I != M.SubmoduleRemap.end()
7205 && "Invalid index into submodule index remap");
7206
7207 return LocalID + I->second;
7208}
7209
7210Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7211 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7212 assert(GlobalID == 0 && "Unhandled global submodule ID");
7213 return 0;
7214 }
7215
7216 if (GlobalID > SubmodulesLoaded.size()) {
7217 Error("submodule ID out of range in AST file");
7218 return 0;
7219 }
7220
7221 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7222}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007223
7224Module *ASTReader::getModule(unsigned ID) {
7225 return getSubmodule(ID);
7226}
7227
Guy Benyei11169dd2012-12-18 14:30:41 +00007228Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7229 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7230}
7231
7232Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7233 if (ID == 0)
7234 return Selector();
7235
7236 if (ID > SelectorsLoaded.size()) {
7237 Error("selector ID out of range in AST file");
7238 return Selector();
7239 }
7240
7241 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
7242 // Load this selector from the selector table.
7243 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7244 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7245 ModuleFile &M = *I->second;
7246 ASTSelectorLookupTrait Trait(*this, M);
7247 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7248 SelectorsLoaded[ID - 1] =
7249 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7250 if (DeserializationListener)
7251 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7252 }
7253
7254 return SelectorsLoaded[ID - 1];
7255}
7256
7257Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7258 return DecodeSelector(ID);
7259}
7260
7261uint32_t ASTReader::GetNumExternalSelectors() {
7262 // ID 0 (the null selector) is considered an external selector.
7263 return getTotalNumSelectors() + 1;
7264}
7265
7266serialization::SelectorID
7267ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7268 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7269 return LocalID;
7270
7271 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7272 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7273 assert(I != M.SelectorRemap.end()
7274 && "Invalid index into selector index remap");
7275
7276 return LocalID + I->second;
7277}
7278
7279DeclarationName
7280ASTReader::ReadDeclarationName(ModuleFile &F,
7281 const RecordData &Record, unsigned &Idx) {
7282 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7283 switch (Kind) {
7284 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007285 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007286
7287 case DeclarationName::ObjCZeroArgSelector:
7288 case DeclarationName::ObjCOneArgSelector:
7289 case DeclarationName::ObjCMultiArgSelector:
7290 return DeclarationName(ReadSelector(F, Record, Idx));
7291
7292 case DeclarationName::CXXConstructorName:
7293 return Context.DeclarationNames.getCXXConstructorName(
7294 Context.getCanonicalType(readType(F, Record, Idx)));
7295
7296 case DeclarationName::CXXDestructorName:
7297 return Context.DeclarationNames.getCXXDestructorName(
7298 Context.getCanonicalType(readType(F, Record, Idx)));
7299
7300 case DeclarationName::CXXConversionFunctionName:
7301 return Context.DeclarationNames.getCXXConversionFunctionName(
7302 Context.getCanonicalType(readType(F, Record, Idx)));
7303
7304 case DeclarationName::CXXOperatorName:
7305 return Context.DeclarationNames.getCXXOperatorName(
7306 (OverloadedOperatorKind)Record[Idx++]);
7307
7308 case DeclarationName::CXXLiteralOperatorName:
7309 return Context.DeclarationNames.getCXXLiteralOperatorName(
7310 GetIdentifierInfo(F, Record, Idx));
7311
7312 case DeclarationName::CXXUsingDirective:
7313 return DeclarationName::getUsingDirectiveName();
7314 }
7315
7316 llvm_unreachable("Invalid NameKind!");
7317}
7318
7319void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7320 DeclarationNameLoc &DNLoc,
7321 DeclarationName Name,
7322 const RecordData &Record, unsigned &Idx) {
7323 switch (Name.getNameKind()) {
7324 case DeclarationName::CXXConstructorName:
7325 case DeclarationName::CXXDestructorName:
7326 case DeclarationName::CXXConversionFunctionName:
7327 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7328 break;
7329
7330 case DeclarationName::CXXOperatorName:
7331 DNLoc.CXXOperatorName.BeginOpNameLoc
7332 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7333 DNLoc.CXXOperatorName.EndOpNameLoc
7334 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7335 break;
7336
7337 case DeclarationName::CXXLiteralOperatorName:
7338 DNLoc.CXXLiteralOperatorName.OpNameLoc
7339 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7340 break;
7341
7342 case DeclarationName::Identifier:
7343 case DeclarationName::ObjCZeroArgSelector:
7344 case DeclarationName::ObjCOneArgSelector:
7345 case DeclarationName::ObjCMultiArgSelector:
7346 case DeclarationName::CXXUsingDirective:
7347 break;
7348 }
7349}
7350
7351void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7352 DeclarationNameInfo &NameInfo,
7353 const RecordData &Record, unsigned &Idx) {
7354 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7355 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7356 DeclarationNameLoc DNLoc;
7357 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7358 NameInfo.setInfo(DNLoc);
7359}
7360
7361void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7362 const RecordData &Record, unsigned &Idx) {
7363 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7364 unsigned NumTPLists = Record[Idx++];
7365 Info.NumTemplParamLists = NumTPLists;
7366 if (NumTPLists) {
7367 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7368 for (unsigned i=0; i != NumTPLists; ++i)
7369 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7370 }
7371}
7372
7373TemplateName
7374ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7375 unsigned &Idx) {
7376 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7377 switch (Kind) {
7378 case TemplateName::Template:
7379 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7380
7381 case TemplateName::OverloadedTemplate: {
7382 unsigned size = Record[Idx++];
7383 UnresolvedSet<8> Decls;
7384 while (size--)
7385 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7386
7387 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7388 }
7389
7390 case TemplateName::QualifiedTemplate: {
7391 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7392 bool hasTemplKeyword = Record[Idx++];
7393 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7394 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7395 }
7396
7397 case TemplateName::DependentTemplate: {
7398 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7399 if (Record[Idx++]) // isIdentifier
7400 return Context.getDependentTemplateName(NNS,
7401 GetIdentifierInfo(F, Record,
7402 Idx));
7403 return Context.getDependentTemplateName(NNS,
7404 (OverloadedOperatorKind)Record[Idx++]);
7405 }
7406
7407 case TemplateName::SubstTemplateTemplateParm: {
7408 TemplateTemplateParmDecl *param
7409 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7410 if (!param) return TemplateName();
7411 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7412 return Context.getSubstTemplateTemplateParm(param, replacement);
7413 }
7414
7415 case TemplateName::SubstTemplateTemplateParmPack: {
7416 TemplateTemplateParmDecl *Param
7417 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7418 if (!Param)
7419 return TemplateName();
7420
7421 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7422 if (ArgPack.getKind() != TemplateArgument::Pack)
7423 return TemplateName();
7424
7425 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7426 }
7427 }
7428
7429 llvm_unreachable("Unhandled template name kind!");
7430}
7431
7432TemplateArgument
7433ASTReader::ReadTemplateArgument(ModuleFile &F,
7434 const RecordData &Record, unsigned &Idx) {
7435 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7436 switch (Kind) {
7437 case TemplateArgument::Null:
7438 return TemplateArgument();
7439 case TemplateArgument::Type:
7440 return TemplateArgument(readType(F, Record, Idx));
7441 case TemplateArgument::Declaration: {
7442 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7443 bool ForReferenceParam = Record[Idx++];
7444 return TemplateArgument(D, ForReferenceParam);
7445 }
7446 case TemplateArgument::NullPtr:
7447 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7448 case TemplateArgument::Integral: {
7449 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7450 QualType T = readType(F, Record, Idx);
7451 return TemplateArgument(Context, Value, T);
7452 }
7453 case TemplateArgument::Template:
7454 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7455 case TemplateArgument::TemplateExpansion: {
7456 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007457 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007458 if (unsigned NumExpansions = Record[Idx++])
7459 NumTemplateExpansions = NumExpansions - 1;
7460 return TemplateArgument(Name, NumTemplateExpansions);
7461 }
7462 case TemplateArgument::Expression:
7463 return TemplateArgument(ReadExpr(F));
7464 case TemplateArgument::Pack: {
7465 unsigned NumArgs = Record[Idx++];
7466 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7467 for (unsigned I = 0; I != NumArgs; ++I)
7468 Args[I] = ReadTemplateArgument(F, Record, Idx);
7469 return TemplateArgument(Args, NumArgs);
7470 }
7471 }
7472
7473 llvm_unreachable("Unhandled template argument kind!");
7474}
7475
7476TemplateParameterList *
7477ASTReader::ReadTemplateParameterList(ModuleFile &F,
7478 const RecordData &Record, unsigned &Idx) {
7479 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7480 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7481 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7482
7483 unsigned NumParams = Record[Idx++];
7484 SmallVector<NamedDecl *, 16> Params;
7485 Params.reserve(NumParams);
7486 while (NumParams--)
7487 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7488
7489 TemplateParameterList* TemplateParams =
7490 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7491 Params.data(), Params.size(), RAngleLoc);
7492 return TemplateParams;
7493}
7494
7495void
7496ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007497ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007498 ModuleFile &F, const RecordData &Record,
7499 unsigned &Idx) {
7500 unsigned NumTemplateArgs = Record[Idx++];
7501 TemplArgs.reserve(NumTemplateArgs);
7502 while (NumTemplateArgs--)
7503 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7504}
7505
7506/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007507void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007508 const RecordData &Record, unsigned &Idx) {
7509 unsigned NumDecls = Record[Idx++];
7510 Set.reserve(Context, NumDecls);
7511 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007512 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007513 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007514 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007515 }
7516}
7517
7518CXXBaseSpecifier
7519ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7520 const RecordData &Record, unsigned &Idx) {
7521 bool isVirtual = static_cast<bool>(Record[Idx++]);
7522 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7523 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7524 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7525 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7526 SourceRange Range = ReadSourceRange(F, Record, Idx);
7527 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7528 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7529 EllipsisLoc);
7530 Result.setInheritConstructors(inheritConstructors);
7531 return Result;
7532}
7533
7534std::pair<CXXCtorInitializer **, unsigned>
7535ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7536 unsigned &Idx) {
7537 CXXCtorInitializer **CtorInitializers = 0;
7538 unsigned NumInitializers = Record[Idx++];
7539 if (NumInitializers) {
7540 CtorInitializers
7541 = new (Context) CXXCtorInitializer*[NumInitializers];
7542 for (unsigned i=0; i != NumInitializers; ++i) {
7543 TypeSourceInfo *TInfo = 0;
7544 bool IsBaseVirtual = false;
7545 FieldDecl *Member = 0;
7546 IndirectFieldDecl *IndirectMember = 0;
7547
7548 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7549 switch (Type) {
7550 case CTOR_INITIALIZER_BASE:
7551 TInfo = GetTypeSourceInfo(F, Record, Idx);
7552 IsBaseVirtual = Record[Idx++];
7553 break;
7554
7555 case CTOR_INITIALIZER_DELEGATING:
7556 TInfo = GetTypeSourceInfo(F, Record, Idx);
7557 break;
7558
7559 case CTOR_INITIALIZER_MEMBER:
7560 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7561 break;
7562
7563 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7564 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7565 break;
7566 }
7567
7568 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7569 Expr *Init = ReadExpr(F);
7570 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7571 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7572 bool IsWritten = Record[Idx++];
7573 unsigned SourceOrderOrNumArrayIndices;
7574 SmallVector<VarDecl *, 8> Indices;
7575 if (IsWritten) {
7576 SourceOrderOrNumArrayIndices = Record[Idx++];
7577 } else {
7578 SourceOrderOrNumArrayIndices = Record[Idx++];
7579 Indices.reserve(SourceOrderOrNumArrayIndices);
7580 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7581 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7582 }
7583
7584 CXXCtorInitializer *BOMInit;
7585 if (Type == CTOR_INITIALIZER_BASE) {
7586 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7587 LParenLoc, Init, RParenLoc,
7588 MemberOrEllipsisLoc);
7589 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7590 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7591 Init, RParenLoc);
7592 } else if (IsWritten) {
7593 if (Member)
7594 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7595 LParenLoc, Init, RParenLoc);
7596 else
7597 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7598 MemberOrEllipsisLoc, LParenLoc,
7599 Init, RParenLoc);
7600 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007601 if (IndirectMember) {
7602 assert(Indices.empty() && "Indirect field improperly initialized");
7603 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7604 MemberOrEllipsisLoc, LParenLoc,
7605 Init, RParenLoc);
7606 } else {
7607 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7608 LParenLoc, Init, RParenLoc,
7609 Indices.data(), Indices.size());
7610 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007611 }
7612
7613 if (IsWritten)
7614 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7615 CtorInitializers[i] = BOMInit;
7616 }
7617 }
7618
7619 return std::make_pair(CtorInitializers, NumInitializers);
7620}
7621
7622NestedNameSpecifier *
7623ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7624 const RecordData &Record, unsigned &Idx) {
7625 unsigned N = Record[Idx++];
7626 NestedNameSpecifier *NNS = 0, *Prev = 0;
7627 for (unsigned I = 0; I != N; ++I) {
7628 NestedNameSpecifier::SpecifierKind Kind
7629 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7630 switch (Kind) {
7631 case NestedNameSpecifier::Identifier: {
7632 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7633 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7634 break;
7635 }
7636
7637 case NestedNameSpecifier::Namespace: {
7638 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7639 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7640 break;
7641 }
7642
7643 case NestedNameSpecifier::NamespaceAlias: {
7644 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7645 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7646 break;
7647 }
7648
7649 case NestedNameSpecifier::TypeSpec:
7650 case NestedNameSpecifier::TypeSpecWithTemplate: {
7651 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7652 if (!T)
7653 return 0;
7654
7655 bool Template = Record[Idx++];
7656 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7657 break;
7658 }
7659
7660 case NestedNameSpecifier::Global: {
7661 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7662 // No associated value, and there can't be a prefix.
7663 break;
7664 }
7665 }
7666 Prev = NNS;
7667 }
7668 return NNS;
7669}
7670
7671NestedNameSpecifierLoc
7672ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7673 unsigned &Idx) {
7674 unsigned N = Record[Idx++];
7675 NestedNameSpecifierLocBuilder Builder;
7676 for (unsigned I = 0; I != N; ++I) {
7677 NestedNameSpecifier::SpecifierKind Kind
7678 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7679 switch (Kind) {
7680 case NestedNameSpecifier::Identifier: {
7681 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7682 SourceRange Range = ReadSourceRange(F, Record, Idx);
7683 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7684 break;
7685 }
7686
7687 case NestedNameSpecifier::Namespace: {
7688 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7689 SourceRange Range = ReadSourceRange(F, Record, Idx);
7690 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7691 break;
7692 }
7693
7694 case NestedNameSpecifier::NamespaceAlias: {
7695 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7696 SourceRange Range = ReadSourceRange(F, Record, Idx);
7697 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7698 break;
7699 }
7700
7701 case NestedNameSpecifier::TypeSpec:
7702 case NestedNameSpecifier::TypeSpecWithTemplate: {
7703 bool Template = Record[Idx++];
7704 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7705 if (!T)
7706 return NestedNameSpecifierLoc();
7707 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7708
7709 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7710 Builder.Extend(Context,
7711 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7712 T->getTypeLoc(), ColonColonLoc);
7713 break;
7714 }
7715
7716 case NestedNameSpecifier::Global: {
7717 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7718 Builder.MakeGlobal(Context, ColonColonLoc);
7719 break;
7720 }
7721 }
7722 }
7723
7724 return Builder.getWithLocInContext(Context);
7725}
7726
7727SourceRange
7728ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7729 unsigned &Idx) {
7730 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7731 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7732 return SourceRange(beg, end);
7733}
7734
7735/// \brief Read an integral value
7736llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7737 unsigned BitWidth = Record[Idx++];
7738 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7739 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7740 Idx += NumWords;
7741 return Result;
7742}
7743
7744/// \brief Read a signed integral value
7745llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7746 bool isUnsigned = Record[Idx++];
7747 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7748}
7749
7750/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007751llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7752 const llvm::fltSemantics &Sem,
7753 unsigned &Idx) {
7754 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007755}
7756
7757// \brief Read a string
7758std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7759 unsigned Len = Record[Idx++];
7760 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7761 Idx += Len;
7762 return Result;
7763}
7764
7765VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7766 unsigned &Idx) {
7767 unsigned Major = Record[Idx++];
7768 unsigned Minor = Record[Idx++];
7769 unsigned Subminor = Record[Idx++];
7770 if (Minor == 0)
7771 return VersionTuple(Major);
7772 if (Subminor == 0)
7773 return VersionTuple(Major, Minor - 1);
7774 return VersionTuple(Major, Minor - 1, Subminor - 1);
7775}
7776
7777CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7778 const RecordData &Record,
7779 unsigned &Idx) {
7780 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7781 return CXXTemporary::Create(Context, Decl);
7782}
7783
7784DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007785 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007786}
7787
7788DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7789 return Diags.Report(Loc, DiagID);
7790}
7791
7792/// \brief Retrieve the identifier table associated with the
7793/// preprocessor.
7794IdentifierTable &ASTReader::getIdentifierTable() {
7795 return PP.getIdentifierTable();
7796}
7797
7798/// \brief Record that the given ID maps to the given switch-case
7799/// statement.
7800void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7801 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7802 "Already have a SwitchCase with this ID");
7803 (*CurrSwitchCaseStmts)[ID] = SC;
7804}
7805
7806/// \brief Retrieve the switch-case statement with the given ID.
7807SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7808 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7809 return (*CurrSwitchCaseStmts)[ID];
7810}
7811
7812void ASTReader::ClearSwitchCaseIDs() {
7813 CurrSwitchCaseStmts->clear();
7814}
7815
7816void ASTReader::ReadComments() {
7817 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007818 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007819 serialization::ModuleFile *> >::iterator
7820 I = CommentsCursors.begin(),
7821 E = CommentsCursors.end();
7822 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007823 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007824 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007825 serialization::ModuleFile &F = *I->second;
7826 SavedStreamPosition SavedPosition(Cursor);
7827
7828 RecordData Record;
7829 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007830 llvm::BitstreamEntry Entry =
7831 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007832
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007833 switch (Entry.Kind) {
7834 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7835 case llvm::BitstreamEntry::Error:
7836 Error("malformed block record in AST file");
7837 return;
7838 case llvm::BitstreamEntry::EndBlock:
7839 goto NextCursor;
7840 case llvm::BitstreamEntry::Record:
7841 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007842 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007843 }
7844
7845 // Read a record.
7846 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007847 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007848 case COMMENTS_RAW_COMMENT: {
7849 unsigned Idx = 0;
7850 SourceRange SR = ReadSourceRange(F, Record, Idx);
7851 RawComment::CommentKind Kind =
7852 (RawComment::CommentKind) Record[Idx++];
7853 bool IsTrailingComment = Record[Idx++];
7854 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00007855 Comments.push_back(new (Context) RawComment(
7856 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7857 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00007858 break;
7859 }
7860 }
7861 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007862 NextCursor:
7863 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00007864 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007865}
7866
Richard Smithcd45dbc2014-04-19 03:48:30 +00007867std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
7868 // If we know the owning module, use it.
7869 if (Module *M = D->getOwningModule())
7870 return M->getFullModuleName();
7871
7872 // Otherwise, use the name of the top-level module the decl is within.
7873 if (ModuleFile *M = getOwningModuleFile(D))
7874 return M->ModuleName;
7875
7876 // Not from a module.
7877 return "";
7878}
7879
Guy Benyei11169dd2012-12-18 14:30:41 +00007880void ASTReader::finishPendingActions() {
7881 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00007882 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
7883 !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007884 // If any identifiers with corresponding top-level declarations have
7885 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00007886 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
7887 TopLevelDeclsMap;
7888 TopLevelDeclsMap TopLevelDecls;
7889
Guy Benyei11169dd2012-12-18 14:30:41 +00007890 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007891 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00007892 SmallVector<uint32_t, 4> DeclIDs =
7893 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00007894 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00007895
7896 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007897 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00007898
Guy Benyei11169dd2012-12-18 14:30:41 +00007899 // Load pending declaration chains.
7900 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7901 loadPendingDeclChain(PendingDeclChains[I]);
7902 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
7903 }
7904 PendingDeclChains.clear();
7905
Douglas Gregor6168bd22013-02-18 15:53:43 +00007906 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00007907 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
7908 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007909 IdentifierInfo *II = TLD->first;
7910 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007911 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00007912 }
7913 }
7914
Guy Benyei11169dd2012-12-18 14:30:41 +00007915 // Load any pending macro definitions.
7916 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007917 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
7918 SmallVector<PendingMacroInfo, 2> GlobalIDs;
7919 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
7920 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00007921 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00007922 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007923 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7924 if (Info.M->Kind != MK_Module)
7925 resolvePendingMacro(II, Info);
7926 }
7927 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00007928 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007929 ++IDIdx) {
7930 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7931 if (Info.M->Kind == MK_Module)
7932 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00007933 }
7934 }
7935 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00007936
7937 // Wire up the DeclContexts for Decls that we delayed setting until
7938 // recursive loading is completed.
7939 while (!PendingDeclContextInfos.empty()) {
7940 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7941 PendingDeclContextInfos.pop_front();
7942 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7943 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7944 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7945 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00007946
Richard Smithcd45dbc2014-04-19 03:48:30 +00007947 // Trigger the import of the full definition of each class that had any
7948 // odr-merging problems, so we can produce better diagnostics for them.
7949 for (auto &Merge : PendingOdrMergeFailures) {
7950 Merge.first->buildLookup();
7951 Merge.first->decls_begin();
7952 Merge.first->bases_begin();
7953 Merge.first->vbases_begin();
7954 for (auto *RD : Merge.second) {
7955 RD->decls_begin();
7956 RD->bases_begin();
7957 RD->vbases_begin();
7958 }
7959 }
7960
Richard Smith2b9e3e32013-10-18 06:05:18 +00007961 // For each declaration from a merged context, check that the canonical
7962 // definition of that context also contains a declaration of the same
7963 // entity.
7964 while (!PendingOdrMergeChecks.empty()) {
7965 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
7966
7967 // FIXME: Skip over implicit declarations for now. This matters for things
7968 // like implicitly-declared special member functions. This isn't entirely
7969 // correct; we can end up with multiple unmerged declarations of the same
7970 // implicit entity.
7971 if (D->isImplicit())
7972 continue;
7973
7974 DeclContext *CanonDef = D->getDeclContext();
7975 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
7976
7977 bool Found = false;
7978 const Decl *DCanon = D->getCanonicalDecl();
7979
7980 llvm::SmallVector<const NamedDecl*, 4> Candidates;
7981 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
7982 !Found && I != E; ++I) {
Aaron Ballman86c93902014-03-06 23:45:36 +00007983 for (auto RI : (*I)->redecls()) {
7984 if (RI->getLexicalDeclContext() == CanonDef) {
Richard Smith2b9e3e32013-10-18 06:05:18 +00007985 // This declaration is present in the canonical definition. If it's
7986 // in the same redecl chain, it's the one we're looking for.
Aaron Ballman86c93902014-03-06 23:45:36 +00007987 if (RI->getCanonicalDecl() == DCanon)
Richard Smith2b9e3e32013-10-18 06:05:18 +00007988 Found = true;
7989 else
Aaron Ballman86c93902014-03-06 23:45:36 +00007990 Candidates.push_back(cast<NamedDecl>(RI));
Richard Smith2b9e3e32013-10-18 06:05:18 +00007991 break;
7992 }
7993 }
7994 }
7995
7996 if (!Found) {
7997 D->setInvalidDecl();
7998
Richard Smithcd45dbc2014-04-19 03:48:30 +00007999 std::string CanonDefModule =
8000 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008001 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008002 << D << getOwningModuleNameForDiagnostic(D)
8003 << CanonDef << CanonDefModule.empty() << CanonDefModule;
Richard Smith2b9e3e32013-10-18 06:05:18 +00008004
8005 if (Candidates.empty())
8006 Diag(cast<Decl>(CanonDef)->getLocation(),
8007 diag::note_module_odr_violation_no_possible_decls) << D;
8008 else {
8009 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8010 Diag(Candidates[I]->getLocation(),
8011 diag::note_module_odr_violation_possible_decl)
8012 << Candidates[I];
8013 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008014
8015 DiagnosedOdrMergeFailures.insert(CanonDef);
Richard Smith2b9e3e32013-10-18 06:05:18 +00008016 }
8017 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008018 }
8019
8020 // If we deserialized any C++ or Objective-C class definitions, any
8021 // Objective-C protocol definitions, or any redeclarable templates, make sure
8022 // that all redeclarations point to the definitions. Note that this can only
8023 // happen now, after the redeclaration chains have been fully wired.
8024 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
8025 DEnd = PendingDefinitions.end();
8026 D != DEnd; ++D) {
8027 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008028 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008029 // Make sure that the TagType points at the definition.
8030 const_cast<TagType*>(TagT)->decl = TD;
8031 }
8032
Aaron Ballman86c93902014-03-06 23:45:36 +00008033 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
8034 for (auto R : RD->redecls())
8035 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei11169dd2012-12-18 14:30:41 +00008036
8037 }
8038
8039 continue;
8040 }
8041
Aaron Ballman86c93902014-03-06 23:45:36 +00008042 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008043 // Make sure that the ObjCInterfaceType points at the definition.
8044 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8045 ->Decl = ID;
8046
Aaron Ballman86c93902014-03-06 23:45:36 +00008047 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008048 R->Data = ID->Data;
8049
8050 continue;
8051 }
8052
Aaron Ballman86c93902014-03-06 23:45:36 +00008053 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
8054 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008055 R->Data = PD->Data;
8056
8057 continue;
8058 }
8059
Aaron Ballman86c93902014-03-06 23:45:36 +00008060 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
8061 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008062 R->Common = RTD->Common;
8063 }
8064 PendingDefinitions.clear();
8065
8066 // Load the bodies of any functions or methods we've encountered. We do
8067 // this now (delayed) so that we can be sure that the declaration chains
8068 // have been fully wired up.
8069 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8070 PBEnd = PendingBodies.end();
8071 PB != PBEnd; ++PB) {
8072 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8073 // FIXME: Check for =delete/=default?
8074 // FIXME: Complain about ODR violations here?
8075 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8076 FD->setLazyBody(PB->second);
8077 continue;
8078 }
8079
8080 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8081 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8082 MD->setLazyBody(PB->second);
8083 }
8084 PendingBodies.clear();
Richard Smithcd45dbc2014-04-19 03:48:30 +00008085
8086 // Issue any pending ODR-failure diagnostics.
8087 for (auto &Merge : PendingOdrMergeFailures) {
8088 if (!DiagnosedOdrMergeFailures.insert(Merge.first))
8089 continue;
8090
8091 bool Diagnosed = false;
8092 for (auto *RD : Merge.second) {
8093 // Multiple different declarations got merged together; tell the user
8094 // where they came from.
8095 if (Merge.first != RD) {
8096 // FIXME: Walk the definition, figure out what's different,
8097 // and diagnose that.
8098 if (!Diagnosed) {
8099 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8100 Diag(Merge.first->getLocation(),
8101 diag::err_module_odr_violation_different_definitions)
8102 << Merge.first << Module.empty() << Module;
8103 Diagnosed = true;
8104 }
8105
8106 Diag(RD->getLocation(),
8107 diag::note_module_odr_violation_different_definitions)
8108 << getOwningModuleNameForDiagnostic(RD);
8109 }
8110 }
8111
8112 if (!Diagnosed) {
8113 // All definitions are updates to the same declaration. This happens if a
8114 // module instantiates the declaration of a class template specialization
8115 // and two or more other modules instantiate its definition.
8116 //
8117 // FIXME: Indicate which modules had instantiations of this definition.
8118 // FIXME: How can this even happen?
8119 Diag(Merge.first->getLocation(),
8120 diag::err_module_odr_violation_different_instantiations)
8121 << Merge.first;
8122 }
8123 }
8124 PendingOdrMergeFailures.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008125}
8126
8127void ASTReader::FinishedDeserializing() {
8128 assert(NumCurrentElementsDeserializing &&
8129 "FinishedDeserializing not paired with StartedDeserializing");
8130 if (NumCurrentElementsDeserializing == 1) {
8131 // We decrease NumCurrentElementsDeserializing only after pending actions
8132 // are finished, to avoid recursively re-calling finishPendingActions().
8133 finishPendingActions();
8134 }
8135 --NumCurrentElementsDeserializing;
8136
Richard Smith04d05b52014-03-23 00:27:18 +00008137 if (NumCurrentElementsDeserializing == 0 && Consumer) {
8138 // We are not in recursive loading, so it's safe to pass the "interesting"
8139 // decls to the consumer.
8140 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008141 }
8142}
8143
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008144void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008145 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008146
8147 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8148 SemaObj->TUScope->AddDecl(D);
8149 } else if (SemaObj->TUScope) {
8150 // Adding the decl to IdResolver may have failed because it was already in
8151 // (even though it was not added in scope). If it is already in, make sure
8152 // it gets in the scope as well.
8153 if (std::find(SemaObj->IdResolver.begin(Name),
8154 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8155 SemaObj->TUScope->AddDecl(D);
8156 }
8157}
8158
Guy Benyei11169dd2012-12-18 14:30:41 +00008159ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
8160 StringRef isysroot, bool DisableValidation,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008161 bool AllowASTWithCompilerErrors,
8162 bool AllowConfigurationMismatch,
Ben Langmuir3d4417c2014-02-07 17:31:11 +00008163 bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008164 bool UseGlobalIndex)
Guy Benyei11169dd2012-12-18 14:30:41 +00008165 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
8166 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
8167 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
8168 Consumer(0), ModuleMgr(PP.getFileManager()),
8169 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregor00a50f72013-01-25 00:38:33 +00008170 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008171 AllowConfigurationMismatch(AllowConfigurationMismatch),
Ben Langmuir3d4417c2014-02-07 17:31:11 +00008172 ValidateSystemInputs(ValidateSystemInputs),
Douglas Gregorc1bbec82013-01-25 00:45:27 +00008173 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei11169dd2012-12-18 14:30:41 +00008174 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
8175 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregor00a50f72013-01-25 00:38:33 +00008176 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
8177 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
8178 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008179 NumMethodPoolLookups(0), NumMethodPoolHits(0),
8180 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
8181 TotalNumMethodPoolEntries(0),
Guy Benyei11169dd2012-12-18 14:30:41 +00008182 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8183 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8184 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8185 PassingDeclsToConsumer(false),
Richard Smith629ff362013-07-31 00:26:46 +00008186 NumCXXBaseSpecifiersLoaded(0), ReadingKind(Read_None)
Guy Benyei11169dd2012-12-18 14:30:41 +00008187{
8188 SourceMgr.setExternalSLocEntrySource(this);
8189}
8190
8191ASTReader::~ASTReader() {
8192 for (DeclContextVisibleUpdatesPending::iterator
8193 I = PendingVisibleUpdates.begin(),
8194 E = PendingVisibleUpdates.end();
8195 I != E; ++I) {
8196 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8197 F = I->second.end();
8198 J != F; ++J)
8199 delete J->first;
8200 }
8201}