blob: c16bc336da1878cecfe9da10d27ba3b1171ebef6 [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}
73bool ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
74 bool Complain) {
75 return First->ReadLanguageOptions(LangOpts, Complain) ||
76 Second->ReadLanguageOptions(LangOpts, Complain);
77}
78bool
79ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
80 bool Complain) {
81 return First->ReadTargetOptions(TargetOpts, Complain) ||
82 Second->ReadTargetOptions(TargetOpts, Complain);
83}
84bool ChainedASTReaderListener::ReadDiagnosticOptions(
85 const DiagnosticOptions &DiagOpts, bool Complain) {
86 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
87 Second->ReadDiagnosticOptions(DiagOpts, Complain);
88}
89bool
90ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
91 bool Complain) {
92 return First->ReadFileSystemOptions(FSOpts, Complain) ||
93 Second->ReadFileSystemOptions(FSOpts, Complain);
94}
95
96bool ChainedASTReaderListener::ReadHeaderSearchOptions(
97 const HeaderSearchOptions &HSOpts, bool Complain) {
98 return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
99 Second->ReadHeaderSearchOptions(HSOpts, Complain);
100}
101bool ChainedASTReaderListener::ReadPreprocessorOptions(
102 const PreprocessorOptions &PPOpts, bool Complain,
103 std::string &SuggestedPredefines) {
104 return First->ReadPreprocessorOptions(PPOpts, Complain,
105 SuggestedPredefines) ||
106 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
107}
108void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
109 unsigned Value) {
110 First->ReadCounter(M, Value);
111 Second->ReadCounter(M, Value);
112}
113bool ChainedASTReaderListener::needsInputFileVisitation() {
114 return First->needsInputFileVisitation() ||
115 Second->needsInputFileVisitation();
116}
117bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
118 return First->needsSystemInputFileVisitation() ||
119 Second->needsSystemInputFileVisitation();
120}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000121void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
122 First->visitModuleFile(Filename);
123 Second->visitModuleFile(Filename);
124}
Ben Langmuircb69b572014-03-07 06:40:32 +0000125bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000126 bool isSystem,
127 bool isOverridden) {
128 return First->visitInputFile(Filename, isSystem, isOverridden) ||
129 Second->visitInputFile(Filename, isSystem, isOverridden);
Ben Langmuircb69b572014-03-07 06:40:32 +0000130}
131
Guy Benyei11169dd2012-12-18 14:30:41 +0000132//===----------------------------------------------------------------------===//
133// PCH validator implementation
134//===----------------------------------------------------------------------===//
135
136ASTReaderListener::~ASTReaderListener() {}
137
138/// \brief Compare the given set of language options against an existing set of
139/// language options.
140///
141/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
142///
143/// \returns true if the languagae options mis-match, false otherwise.
144static bool checkLanguageOptions(const LangOptions &LangOpts,
145 const LangOptions &ExistingLangOpts,
146 DiagnosticsEngine *Diags) {
147#define LANGOPT(Name, Bits, Default, Description) \
148 if (ExistingLangOpts.Name != LangOpts.Name) { \
149 if (Diags) \
150 Diags->Report(diag::err_pch_langopt_mismatch) \
151 << Description << LangOpts.Name << ExistingLangOpts.Name; \
152 return true; \
153 }
154
155#define VALUE_LANGOPT(Name, Bits, Default, Description) \
156 if (ExistingLangOpts.Name != LangOpts.Name) { \
157 if (Diags) \
158 Diags->Report(diag::err_pch_langopt_value_mismatch) \
159 << Description; \
160 return true; \
161 }
162
163#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
164 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
165 if (Diags) \
166 Diags->Report(diag::err_pch_langopt_value_mismatch) \
167 << Description; \
168 return true; \
169 }
170
171#define BENIGN_LANGOPT(Name, Bits, Default, Description)
172#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
173#include "clang/Basic/LangOptions.def"
174
175 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
176 if (Diags)
177 Diags->Report(diag::err_pch_langopt_value_mismatch)
178 << "target Objective-C runtime";
179 return true;
180 }
181
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000182 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
183 LangOpts.CommentOpts.BlockCommandNames) {
184 if (Diags)
185 Diags->Report(diag::err_pch_langopt_value_mismatch)
186 << "block command names";
187 return true;
188 }
189
Guy Benyei11169dd2012-12-18 14:30:41 +0000190 return false;
191}
192
193/// \brief Compare the given set of target options against an existing set of
194/// target options.
195///
196/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
197///
198/// \returns true if the target options mis-match, false otherwise.
199static bool checkTargetOptions(const TargetOptions &TargetOpts,
200 const TargetOptions &ExistingTargetOpts,
201 DiagnosticsEngine *Diags) {
202#define CHECK_TARGET_OPT(Field, Name) \
203 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
204 if (Diags) \
205 Diags->Report(diag::err_pch_targetopt_mismatch) \
206 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
207 return true; \
208 }
209
210 CHECK_TARGET_OPT(Triple, "target");
211 CHECK_TARGET_OPT(CPU, "target CPU");
212 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000213 CHECK_TARGET_OPT(LinkerVersion, "target linker version");
214#undef CHECK_TARGET_OPT
215
216 // Compare feature sets.
217 SmallVector<StringRef, 4> ExistingFeatures(
218 ExistingTargetOpts.FeaturesAsWritten.begin(),
219 ExistingTargetOpts.FeaturesAsWritten.end());
220 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
221 TargetOpts.FeaturesAsWritten.end());
222 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
223 std::sort(ReadFeatures.begin(), ReadFeatures.end());
224
225 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
226 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
227 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
228 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
229 ++ExistingIdx;
230 ++ReadIdx;
231 continue;
232 }
233
234 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
235 if (Diags)
236 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
237 << false << ReadFeatures[ReadIdx];
238 return true;
239 }
240
241 if (Diags)
242 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
243 << true << ExistingFeatures[ExistingIdx];
244 return true;
245 }
246
247 if (ExistingIdx < ExistingN) {
248 if (Diags)
249 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
250 << true << ExistingFeatures[ExistingIdx];
251 return true;
252 }
253
254 if (ReadIdx < ReadN) {
255 if (Diags)
256 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
257 << false << ReadFeatures[ReadIdx];
258 return true;
259 }
260
261 return false;
262}
263
264bool
265PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
266 bool Complain) {
267 const LangOptions &ExistingLangOpts = PP.getLangOpts();
268 return checkLanguageOptions(LangOpts, ExistingLangOpts,
269 Complain? &Reader.Diags : 0);
270}
271
272bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
273 bool Complain) {
274 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
275 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
276 Complain? &Reader.Diags : 0);
277}
278
279namespace {
280 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
281 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000282 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
283 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000284}
285
286/// \brief Collect the macro definitions provided by the given preprocessor
287/// options.
288static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
289 MacroDefinitionsMap &Macros,
290 SmallVectorImpl<StringRef> *MacroNames = 0){
291 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
292 StringRef Macro = PPOpts.Macros[I].first;
293 bool IsUndef = PPOpts.Macros[I].second;
294
295 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
296 StringRef MacroName = MacroPair.first;
297 StringRef MacroBody = MacroPair.second;
298
299 // For an #undef'd macro, we only care about the name.
300 if (IsUndef) {
301 if (MacroNames && !Macros.count(MacroName))
302 MacroNames->push_back(MacroName);
303
304 Macros[MacroName] = std::make_pair("", true);
305 continue;
306 }
307
308 // For a #define'd macro, figure out the actual definition.
309 if (MacroName.size() == Macro.size())
310 MacroBody = "1";
311 else {
312 // Note: GCC drops anything following an end-of-line character.
313 StringRef::size_type End = MacroBody.find_first_of("\n\r");
314 MacroBody = MacroBody.substr(0, End);
315 }
316
317 if (MacroNames && !Macros.count(MacroName))
318 MacroNames->push_back(MacroName);
319 Macros[MacroName] = std::make_pair(MacroBody, false);
320 }
321}
322
323/// \brief Check the preprocessor options deserialized from the control block
324/// against the preprocessor options in an existing preprocessor.
325///
326/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
327static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
328 const PreprocessorOptions &ExistingPPOpts,
329 DiagnosticsEngine *Diags,
330 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000331 std::string &SuggestedPredefines,
332 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000333 // Check macro definitions.
334 MacroDefinitionsMap ASTFileMacros;
335 collectMacroDefinitions(PPOpts, ASTFileMacros);
336 MacroDefinitionsMap ExistingMacros;
337 SmallVector<StringRef, 4> ExistingMacroNames;
338 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
339
340 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
341 // Dig out the macro definition in the existing preprocessor options.
342 StringRef MacroName = ExistingMacroNames[I];
343 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
344
345 // Check whether we know anything about this macro name or not.
346 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
347 = ASTFileMacros.find(MacroName);
348 if (Known == ASTFileMacros.end()) {
349 // FIXME: Check whether this identifier was referenced anywhere in the
350 // AST file. If so, we should reject the AST file. Unfortunately, this
351 // information isn't in the control block. What shall we do about it?
352
353 if (Existing.second) {
354 SuggestedPredefines += "#undef ";
355 SuggestedPredefines += MacroName.str();
356 SuggestedPredefines += '\n';
357 } else {
358 SuggestedPredefines += "#define ";
359 SuggestedPredefines += MacroName.str();
360 SuggestedPredefines += ' ';
361 SuggestedPredefines += Existing.first.str();
362 SuggestedPredefines += '\n';
363 }
364 continue;
365 }
366
367 // If the macro was defined in one but undef'd in the other, we have a
368 // conflict.
369 if (Existing.second != Known->second.second) {
370 if (Diags) {
371 Diags->Report(diag::err_pch_macro_def_undef)
372 << MacroName << Known->second.second;
373 }
374 return true;
375 }
376
377 // If the macro was #undef'd in both, or if the macro bodies are identical,
378 // it's fine.
379 if (Existing.second || Existing.first == Known->second.first)
380 continue;
381
382 // The macro bodies differ; complain.
383 if (Diags) {
384 Diags->Report(diag::err_pch_macro_def_conflict)
385 << MacroName << Known->second.first << Existing.first;
386 }
387 return true;
388 }
389
390 // Check whether we're using predefines.
391 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
392 if (Diags) {
393 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
394 }
395 return true;
396 }
397
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000398 // Detailed record is important since it is used for the module cache hash.
399 if (LangOpts.Modules &&
400 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
401 if (Diags) {
402 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
403 }
404 return true;
405 }
406
Guy Benyei11169dd2012-12-18 14:30:41 +0000407 // Compute the #include and #include_macros lines we need.
408 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
409 StringRef File = ExistingPPOpts.Includes[I];
410 if (File == ExistingPPOpts.ImplicitPCHInclude)
411 continue;
412
413 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
414 != PPOpts.Includes.end())
415 continue;
416
417 SuggestedPredefines += "#include \"";
418 SuggestedPredefines +=
419 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
420 SuggestedPredefines += "\"\n";
421 }
422
423 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
424 StringRef File = ExistingPPOpts.MacroIncludes[I];
425 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
426 File)
427 != PPOpts.MacroIncludes.end())
428 continue;
429
430 SuggestedPredefines += "#__include_macros \"";
431 SuggestedPredefines +=
432 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
433 SuggestedPredefines += "\"\n##\n";
434 }
435
436 return false;
437}
438
439bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
440 bool Complain,
441 std::string &SuggestedPredefines) {
442 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
443
444 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
445 Complain? &Reader.Diags : 0,
446 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000447 SuggestedPredefines,
448 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000449}
450
Guy Benyei11169dd2012-12-18 14:30:41 +0000451void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
452 PP.setCounterValue(Value);
453}
454
455//===----------------------------------------------------------------------===//
456// AST reader implementation
457//===----------------------------------------------------------------------===//
458
459void
460ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
461 DeserializationListener = Listener;
462}
463
464
465
466unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
467 return serialization::ComputeHash(Sel);
468}
469
470
471std::pair<unsigned, unsigned>
472ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000473 using namespace llvm::support;
474 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
475 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000476 return std::make_pair(KeyLen, DataLen);
477}
478
479ASTSelectorLookupTrait::internal_key_type
480ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000481 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000482 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000483 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
484 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
485 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000486 if (N == 0)
487 return SelTable.getNullarySelector(FirstII);
488 else if (N == 1)
489 return SelTable.getUnarySelector(FirstII);
490
491 SmallVector<IdentifierInfo *, 16> Args;
492 Args.push_back(FirstII);
493 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000494 Args.push_back(Reader.getLocalIdentifier(
495 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000496
497 return SelTable.getSelector(N, Args.data());
498}
499
500ASTSelectorLookupTrait::data_type
501ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
502 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000503 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000504
505 data_type Result;
506
Justin Bogner57ba0b22014-03-28 22:03:24 +0000507 Result.ID = Reader.getGlobalSelectorID(
508 F, endian::readNext<uint32_t, little, unaligned>(d));
509 unsigned NumInstanceMethodsAndBits =
510 endian::readNext<uint16_t, little, unaligned>(d);
511 unsigned NumFactoryMethodsAndBits =
512 endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000513 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
514 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
515 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
516 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000517
518 // Load instance methods
519 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000520 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
521 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000522 Result.Instance.push_back(Method);
523 }
524
525 // Load factory methods
526 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000527 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
528 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000529 Result.Factory.push_back(Method);
530 }
531
532 return Result;
533}
534
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000535unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
536 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000537}
538
539std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000540ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000541 using namespace llvm::support;
542 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
543 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000544 return std::make_pair(KeyLen, DataLen);
545}
546
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000547ASTIdentifierLookupTraitBase::internal_key_type
548ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000549 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000550 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000551}
552
Douglas Gregordcf25082013-02-11 18:16:18 +0000553/// \brief Whether the given identifier is "interesting".
554static bool isInterestingIdentifier(IdentifierInfo &II) {
555 return II.isPoisoned() ||
556 II.isExtensionToken() ||
557 II.getObjCOrBuiltinID() ||
558 II.hasRevertedTokenIDToIdentifier() ||
559 II.hadMacroDefinition() ||
560 II.getFETokenInfo<void>();
561}
562
Guy Benyei11169dd2012-12-18 14:30:41 +0000563IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
564 const unsigned char* d,
565 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000566 using namespace llvm::support;
567 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000568 bool IsInteresting = RawID & 0x01;
569
570 // Wipe out the "is interesting" bit.
571 RawID = RawID >> 1;
572
573 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
574 if (!IsInteresting) {
575 // For uninteresting identifiers, just build the IdentifierInfo
576 // and associate it with the persistent ID.
577 IdentifierInfo *II = KnownII;
578 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000579 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000580 KnownII = II;
581 }
582 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000583 if (!II->isFromAST()) {
584 bool WasInteresting = isInterestingIdentifier(*II);
585 II->setIsFromAST();
586 if (WasInteresting)
587 II->setChangedSinceDeserialization();
588 }
589 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000590 return II;
591 }
592
Justin Bogner57ba0b22014-03-28 22:03:24 +0000593 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
594 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000595 bool CPlusPlusOperatorKeyword = Bits & 0x01;
596 Bits >>= 1;
597 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
598 Bits >>= 1;
599 bool Poisoned = Bits & 0x01;
600 Bits >>= 1;
601 bool ExtensionToken = Bits & 0x01;
602 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000603 bool hasSubmoduleMacros = Bits & 0x01;
604 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000605 bool hadMacroDefinition = Bits & 0x01;
606 Bits >>= 1;
607
608 assert(Bits == 0 && "Extra bits in the identifier?");
609 DataLen -= 8;
610
611 // Build the IdentifierInfo itself and link the identifier ID with
612 // the new IdentifierInfo.
613 IdentifierInfo *II = KnownII;
614 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000615 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000616 KnownII = II;
617 }
618 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000619 if (!II->isFromAST()) {
620 bool WasInteresting = isInterestingIdentifier(*II);
621 II->setIsFromAST();
622 if (WasInteresting)
623 II->setChangedSinceDeserialization();
624 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000625
626 // Set or check the various bits in the IdentifierInfo structure.
627 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000628 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000629 II->RevertTokenIDToIdentifier();
630 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
631 assert(II->isExtensionToken() == ExtensionToken &&
632 "Incorrect extension token flag");
633 (void)ExtensionToken;
634 if (Poisoned)
635 II->setIsPoisoned(true);
636 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
637 "Incorrect C++ operator keyword flag");
638 (void)CPlusPlusOperatorKeyword;
639
640 // If this identifier is a macro, deserialize the macro
641 // definition.
642 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000643 uint32_t MacroDirectivesOffset =
644 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000645 DataLen -= 4;
646 SmallVector<uint32_t, 8> LocalMacroIDs;
647 if (hasSubmoduleMacros) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000648 while (uint32_t LocalMacroID =
649 endian::readNext<uint32_t, little, unaligned>(d)) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000650 DataLen -= 4;
651 LocalMacroIDs.push_back(LocalMacroID);
652 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000653 DataLen -= 4;
654 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000655
656 if (F.Kind == MK_Module) {
Richard Smith49f906a2014-03-01 00:08:04 +0000657 // Macro definitions are stored from newest to oldest, so reverse them
658 // before registering them.
659 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000660 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000661 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
662 unsigned Size = 1;
663
664 static const uint32_t HasOverridesFlag = 0x80000000U;
665 if (I + 1 != E && (I[1] & HasOverridesFlag))
666 Size += 1 + (I[1] & ~HasOverridesFlag);
667
668 MacroSizes.push_back(Size);
669 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000670 }
Richard Smith49f906a2014-03-01 00:08:04 +0000671
672 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
673 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
674 SE = MacroSizes.rend();
675 SI != SE; ++SI) {
676 I -= *SI;
677
678 uint32_t LocalMacroID = *I;
679 llvm::ArrayRef<uint32_t> Overrides;
680 if (*SI != 1)
681 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
682 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
683 }
684 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000685 } else {
686 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
687 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000688 }
689
690 Reader.SetIdentifierInfo(ID, II);
691
692 // Read all of the declarations visible at global scope with this
693 // name.
694 if (DataLen > 0) {
695 SmallVector<uint32_t, 4> DeclIDs;
696 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000697 DeclIDs.push_back(Reader.getGlobalDeclID(
698 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000699 Reader.SetGloballyVisibleDecls(II, DeclIDs);
700 }
701
702 return II;
703}
704
705unsigned
706ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
707 llvm::FoldingSetNodeID ID;
708 ID.AddInteger(Key.Kind);
709
710 switch (Key.Kind) {
711 case DeclarationName::Identifier:
712 case DeclarationName::CXXLiteralOperatorName:
713 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
714 break;
715 case DeclarationName::ObjCZeroArgSelector:
716 case DeclarationName::ObjCOneArgSelector:
717 case DeclarationName::ObjCMultiArgSelector:
718 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
719 break;
720 case DeclarationName::CXXOperatorName:
721 ID.AddInteger((OverloadedOperatorKind)Key.Data);
722 break;
723 case DeclarationName::CXXConstructorName:
724 case DeclarationName::CXXDestructorName:
725 case DeclarationName::CXXConversionFunctionName:
726 case DeclarationName::CXXUsingDirective:
727 break;
728 }
729
730 return ID.ComputeHash();
731}
732
733ASTDeclContextNameLookupTrait::internal_key_type
734ASTDeclContextNameLookupTrait::GetInternalKey(
735 const external_key_type& Name) const {
736 DeclNameKey Key;
737 Key.Kind = Name.getNameKind();
738 switch (Name.getNameKind()) {
739 case DeclarationName::Identifier:
740 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
741 break;
742 case DeclarationName::ObjCZeroArgSelector:
743 case DeclarationName::ObjCOneArgSelector:
744 case DeclarationName::ObjCMultiArgSelector:
745 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
746 break;
747 case DeclarationName::CXXOperatorName:
748 Key.Data = Name.getCXXOverloadedOperator();
749 break;
750 case DeclarationName::CXXLiteralOperatorName:
751 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
752 break;
753 case DeclarationName::CXXConstructorName:
754 case DeclarationName::CXXDestructorName:
755 case DeclarationName::CXXConversionFunctionName:
756 case DeclarationName::CXXUsingDirective:
757 Key.Data = 0;
758 break;
759 }
760
761 return Key;
762}
763
764std::pair<unsigned, unsigned>
765ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000766 using namespace llvm::support;
767 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
768 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000769 return std::make_pair(KeyLen, DataLen);
770}
771
772ASTDeclContextNameLookupTrait::internal_key_type
773ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000774 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000775
776 DeclNameKey Key;
777 Key.Kind = (DeclarationName::NameKind)*d++;
778 switch (Key.Kind) {
779 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000780 Key.Data = (uint64_t)Reader.getLocalIdentifier(
781 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000782 break;
783 case DeclarationName::ObjCZeroArgSelector:
784 case DeclarationName::ObjCOneArgSelector:
785 case DeclarationName::ObjCMultiArgSelector:
786 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000787 (uint64_t)Reader.getLocalSelector(
788 F, endian::readNext<uint32_t, little, unaligned>(
789 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000790 break;
791 case DeclarationName::CXXOperatorName:
792 Key.Data = *d++; // OverloadedOperatorKind
793 break;
794 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000795 Key.Data = (uint64_t)Reader.getLocalIdentifier(
796 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000797 break;
798 case DeclarationName::CXXConstructorName:
799 case DeclarationName::CXXDestructorName:
800 case DeclarationName::CXXConversionFunctionName:
801 case DeclarationName::CXXUsingDirective:
802 Key.Data = 0;
803 break;
804 }
805
806 return Key;
807}
808
809ASTDeclContextNameLookupTrait::data_type
810ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
811 const unsigned char* d,
812 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000813 using namespace llvm::support;
814 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000815 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
816 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000817 return std::make_pair(Start, Start + NumDecls);
818}
819
820bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000821 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000822 const std::pair<uint64_t, uint64_t> &Offsets,
823 DeclContextInfo &Info) {
824 SavedStreamPosition SavedPosition(Cursor);
825 // First the lexical decls.
826 if (Offsets.first != 0) {
827 Cursor.JumpToBit(Offsets.first);
828
829 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000830 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000831 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000832 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000833 if (RecCode != DECL_CONTEXT_LEXICAL) {
834 Error("Expected lexical block");
835 return true;
836 }
837
Chris Lattner0e6c9402013-01-20 02:38:54 +0000838 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
839 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000840 }
841
842 // Now the lookup table.
843 if (Offsets.second != 0) {
844 Cursor.JumpToBit(Offsets.second);
845
846 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000847 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000848 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000849 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000850 if (RecCode != DECL_CONTEXT_VISIBLE) {
851 Error("Expected visible lookup table block");
852 return true;
853 }
Richard Smith52e3fba2014-03-11 07:17:35 +0000854 Info.NameLookupTableData
855 = ASTDeclContextNameLookupTable::Create(
856 (const unsigned char *)Blob.data() + Record[0],
857 (const unsigned char *)Blob.data(),
858 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000859 }
860
861 return false;
862}
863
864void ASTReader::Error(StringRef Msg) {
865 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000866 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
867 Diag(diag::note_module_cache_path)
868 << PP.getHeaderSearchInfo().getModuleCachePath();
869 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000870}
871
872void ASTReader::Error(unsigned DiagID,
873 StringRef Arg1, StringRef Arg2) {
874 if (Diags.isDiagnosticInFlight())
875 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
876 else
877 Diag(DiagID) << Arg1 << Arg2;
878}
879
880//===----------------------------------------------------------------------===//
881// Source Manager Deserialization
882//===----------------------------------------------------------------------===//
883
884/// \brief Read the line table in the source manager block.
885/// \returns true if there was an error.
886bool ASTReader::ParseLineTable(ModuleFile &F,
887 SmallVectorImpl<uint64_t> &Record) {
888 unsigned Idx = 0;
889 LineTableInfo &LineTable = SourceMgr.getLineTable();
890
891 // Parse the file names
892 std::map<int, int> FileIDs;
893 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
894 // Extract the file name
895 unsigned FilenameLen = Record[Idx++];
896 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
897 Idx += FilenameLen;
898 MaybeAddSystemRootToFilename(F, Filename);
899 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
900 }
901
902 // Parse the line entries
903 std::vector<LineEntry> Entries;
904 while (Idx < Record.size()) {
905 int FID = Record[Idx++];
906 assert(FID >= 0 && "Serialized line entries for non-local file.");
907 // Remap FileID from 1-based old view.
908 FID += F.SLocEntryBaseID - 1;
909
910 // Extract the line entries
911 unsigned NumEntries = Record[Idx++];
912 assert(NumEntries && "Numentries is 00000");
913 Entries.clear();
914 Entries.reserve(NumEntries);
915 for (unsigned I = 0; I != NumEntries; ++I) {
916 unsigned FileOffset = Record[Idx++];
917 unsigned LineNo = Record[Idx++];
918 int FilenameID = FileIDs[Record[Idx++]];
919 SrcMgr::CharacteristicKind FileKind
920 = (SrcMgr::CharacteristicKind)Record[Idx++];
921 unsigned IncludeOffset = Record[Idx++];
922 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
923 FileKind, IncludeOffset));
924 }
925 LineTable.AddEntry(FileID::get(FID), Entries);
926 }
927
928 return false;
929}
930
931/// \brief Read a source manager block
932bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
933 using namespace SrcMgr;
934
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000935 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000936
937 // Set the source-location entry cursor to the current position in
938 // the stream. This cursor will be used to read the contents of the
939 // source manager block initially, and then lazily read
940 // source-location entries as needed.
941 SLocEntryCursor = F.Stream;
942
943 // The stream itself is going to skip over the source manager block.
944 if (F.Stream.SkipBlock()) {
945 Error("malformed block record in AST file");
946 return true;
947 }
948
949 // Enter the source manager block.
950 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
951 Error("malformed source manager block record in AST file");
952 return true;
953 }
954
955 RecordData Record;
956 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +0000957 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
958
959 switch (E.Kind) {
960 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
961 case llvm::BitstreamEntry::Error:
962 Error("malformed block record in AST file");
963 return true;
964 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +0000965 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +0000966 case llvm::BitstreamEntry::Record:
967 // The interesting case.
968 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000969 }
Chris Lattnere7b154b2013-01-19 21:39:22 +0000970
Guy Benyei11169dd2012-12-18 14:30:41 +0000971 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +0000972 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +0000973 StringRef Blob;
974 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000975 default: // Default behavior: ignore.
976 break;
977
978 case SM_SLOC_FILE_ENTRY:
979 case SM_SLOC_BUFFER_ENTRY:
980 case SM_SLOC_EXPANSION_ENTRY:
981 // Once we hit one of the source location entries, we're done.
982 return false;
983 }
984 }
985}
986
987/// \brief If a header file is not found at the path that we expect it to be
988/// and the PCH file was moved from its original location, try to resolve the
989/// file by assuming that header+PCH were moved together and the header is in
990/// the same place relative to the PCH.
991static std::string
992resolveFileRelativeToOriginalDir(const std::string &Filename,
993 const std::string &OriginalDir,
994 const std::string &CurrDir) {
995 assert(OriginalDir != CurrDir &&
996 "No point trying to resolve the file if the PCH dir didn't change");
997 using namespace llvm::sys;
998 SmallString<128> filePath(Filename);
999 fs::make_absolute(filePath);
1000 assert(path::is_absolute(OriginalDir));
1001 SmallString<128> currPCHPath(CurrDir);
1002
1003 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1004 fileDirE = path::end(path::parent_path(filePath));
1005 path::const_iterator origDirI = path::begin(OriginalDir),
1006 origDirE = path::end(OriginalDir);
1007 // Skip the common path components from filePath and OriginalDir.
1008 while (fileDirI != fileDirE && origDirI != origDirE &&
1009 *fileDirI == *origDirI) {
1010 ++fileDirI;
1011 ++origDirI;
1012 }
1013 for (; origDirI != origDirE; ++origDirI)
1014 path::append(currPCHPath, "..");
1015 path::append(currPCHPath, fileDirI, fileDirE);
1016 path::append(currPCHPath, path::filename(Filename));
1017 return currPCHPath.str();
1018}
1019
1020bool ASTReader::ReadSLocEntry(int ID) {
1021 if (ID == 0)
1022 return false;
1023
1024 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1025 Error("source location entry ID out-of-range for AST file");
1026 return true;
1027 }
1028
1029 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1030 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001031 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001032 unsigned BaseOffset = F->SLocEntryBaseOffset;
1033
1034 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001035 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1036 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001037 Error("incorrectly-formatted source location entry in AST file");
1038 return true;
1039 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001040
Guy Benyei11169dd2012-12-18 14:30:41 +00001041 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001042 StringRef Blob;
1043 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001044 default:
1045 Error("incorrectly-formatted source location entry in AST file");
1046 return true;
1047
1048 case SM_SLOC_FILE_ENTRY: {
1049 // We will detect whether a file changed and return 'Failure' for it, but
1050 // we will also try to fail gracefully by setting up the SLocEntry.
1051 unsigned InputID = Record[4];
1052 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001053 const FileEntry *File = IF.getFile();
1054 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001055
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001056 // Note that we only check if a File was returned. If it was out-of-date
1057 // we have complained but we will continue creating a FileID to recover
1058 // gracefully.
1059 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001060 return true;
1061
1062 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1063 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1064 // This is the module's main file.
1065 IncludeLoc = getImportLocation(F);
1066 }
1067 SrcMgr::CharacteristicKind
1068 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1069 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1070 ID, BaseOffset + Record[0]);
1071 SrcMgr::FileInfo &FileInfo =
1072 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1073 FileInfo.NumCreatedFIDs = Record[5];
1074 if (Record[3])
1075 FileInfo.setHasLineDirectives();
1076
1077 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1078 unsigned NumFileDecls = Record[7];
1079 if (NumFileDecls) {
1080 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1081 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1082 NumFileDecls));
1083 }
1084
1085 const SrcMgr::ContentCache *ContentCache
1086 = SourceMgr.getOrCreateContentCache(File,
1087 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1088 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1089 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1090 unsigned Code = SLocEntryCursor.ReadCode();
1091 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001092 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001093
1094 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1095 Error("AST record has invalid code");
1096 return true;
1097 }
1098
1099 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001100 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00001101 SourceMgr.overrideFileContents(File, Buffer);
1102 }
1103
1104 break;
1105 }
1106
1107 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001108 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001109 unsigned Offset = Record[0];
1110 SrcMgr::CharacteristicKind
1111 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1112 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1113 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1114 IncludeLoc = getImportLocation(F);
1115 }
1116 unsigned Code = SLocEntryCursor.ReadCode();
1117 Record.clear();
1118 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001119 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001120
1121 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1122 Error("AST record has invalid code");
1123 return true;
1124 }
1125
1126 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001127 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00001128 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
1129 BaseOffset + Offset, IncludeLoc);
1130 break;
1131 }
1132
1133 case SM_SLOC_EXPANSION_ENTRY: {
1134 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1135 SourceMgr.createExpansionLoc(SpellingLoc,
1136 ReadSourceLocation(*F, Record[2]),
1137 ReadSourceLocation(*F, Record[3]),
1138 Record[4],
1139 ID,
1140 BaseOffset + Record[0]);
1141 break;
1142 }
1143 }
1144
1145 return false;
1146}
1147
1148std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1149 if (ID == 0)
1150 return std::make_pair(SourceLocation(), "");
1151
1152 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1153 Error("source location entry ID out-of-range for AST file");
1154 return std::make_pair(SourceLocation(), "");
1155 }
1156
1157 // Find which module file this entry lands in.
1158 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1159 if (M->Kind != MK_Module)
1160 return std::make_pair(SourceLocation(), "");
1161
1162 // FIXME: Can we map this down to a particular submodule? That would be
1163 // ideal.
1164 return std::make_pair(M->ImportLoc, llvm::sys::path::stem(M->FileName));
1165}
1166
1167/// \brief Find the location where the module F is imported.
1168SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1169 if (F->ImportLoc.isValid())
1170 return F->ImportLoc;
1171
1172 // Otherwise we have a PCH. It's considered to be "imported" at the first
1173 // location of its includer.
1174 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1175 // Main file is the importer. We assume that it is the first entry in the
1176 // entry table. We can't ask the manager, because at the time of PCH loading
1177 // the main file entry doesn't exist yet.
1178 // The very first entry is the invalid instantiation loc, which takes up
1179 // offsets 0 and 1.
1180 return SourceLocation::getFromRawEncoding(2U);
1181 }
1182 //return F->Loaders[0]->FirstLoc;
1183 return F->ImportedBy[0]->FirstLoc;
1184}
1185
1186/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1187/// specified cursor. Read the abbreviations that are at the top of the block
1188/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001189bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001190 if (Cursor.EnterSubBlock(BlockID)) {
1191 Error("malformed block record in AST file");
1192 return Failure;
1193 }
1194
1195 while (true) {
1196 uint64_t Offset = Cursor.GetCurrentBitNo();
1197 unsigned Code = Cursor.ReadCode();
1198
1199 // We expect all abbrevs to be at the start of the block.
1200 if (Code != llvm::bitc::DEFINE_ABBREV) {
1201 Cursor.JumpToBit(Offset);
1202 return false;
1203 }
1204 Cursor.ReadAbbrevRecord();
1205 }
1206}
1207
Richard Smithe40f2ba2013-08-07 21:41:30 +00001208Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001209 unsigned &Idx) {
1210 Token Tok;
1211 Tok.startToken();
1212 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1213 Tok.setLength(Record[Idx++]);
1214 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1215 Tok.setIdentifierInfo(II);
1216 Tok.setKind((tok::TokenKind)Record[Idx++]);
1217 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1218 return Tok;
1219}
1220
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001221MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001222 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001223
1224 // Keep track of where we are in the stream, then jump back there
1225 // after reading this macro.
1226 SavedStreamPosition SavedPosition(Stream);
1227
1228 Stream.JumpToBit(Offset);
1229 RecordData Record;
1230 SmallVector<IdentifierInfo*, 16> MacroArgs;
1231 MacroInfo *Macro = 0;
1232
Guy Benyei11169dd2012-12-18 14:30:41 +00001233 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001234 // Advance to the next record, but if we get to the end of the block, don't
1235 // pop it (removing all the abbreviations from the cursor) since we want to
1236 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001237 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001238 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1239
1240 switch (Entry.Kind) {
1241 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1242 case llvm::BitstreamEntry::Error:
1243 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001244 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001245 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001246 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001247 case llvm::BitstreamEntry::Record:
1248 // The interesting case.
1249 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001250 }
1251
1252 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001253 Record.clear();
1254 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001255 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001256 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001257 case PP_MACRO_DIRECTIVE_HISTORY:
1258 return Macro;
1259
Guy Benyei11169dd2012-12-18 14:30:41 +00001260 case PP_MACRO_OBJECT_LIKE:
1261 case PP_MACRO_FUNCTION_LIKE: {
1262 // If we already have a macro, that means that we've hit the end
1263 // of the definition of the macro we were looking for. We're
1264 // done.
1265 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001266 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001267
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001268 unsigned NextIndex = 1; // Skip identifier ID.
1269 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001270 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001271 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001272 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001273 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001274 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001275
Guy Benyei11169dd2012-12-18 14:30:41 +00001276 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1277 // Decode function-like macro info.
1278 bool isC99VarArgs = Record[NextIndex++];
1279 bool isGNUVarArgs = Record[NextIndex++];
1280 bool hasCommaPasting = Record[NextIndex++];
1281 MacroArgs.clear();
1282 unsigned NumArgs = Record[NextIndex++];
1283 for (unsigned i = 0; i != NumArgs; ++i)
1284 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1285
1286 // Install function-like macro info.
1287 MI->setIsFunctionLike();
1288 if (isC99VarArgs) MI->setIsC99Varargs();
1289 if (isGNUVarArgs) MI->setIsGNUVarargs();
1290 if (hasCommaPasting) MI->setHasCommaPasting();
1291 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1292 PP.getPreprocessorAllocator());
1293 }
1294
Guy Benyei11169dd2012-12-18 14:30:41 +00001295 // Remember that we saw this macro last so that we add the tokens that
1296 // form its body to it.
1297 Macro = MI;
1298
1299 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1300 Record[NextIndex]) {
1301 // We have a macro definition. Register the association
1302 PreprocessedEntityID
1303 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1304 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001305 PreprocessingRecord::PPEntityID
1306 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1307 MacroDefinition *PPDef =
1308 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1309 if (PPDef)
1310 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 }
1312
1313 ++NumMacrosRead;
1314 break;
1315 }
1316
1317 case PP_TOKEN: {
1318 // If we see a TOKEN before a PP_MACRO_*, then the file is
1319 // erroneous, just pretend we didn't see this.
1320 if (Macro == 0) break;
1321
John McCallf413f5e2013-05-03 00:10:13 +00001322 unsigned Idx = 0;
1323 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001324 Macro->AddTokenToBody(Tok);
1325 break;
1326 }
1327 }
1328 }
1329}
1330
1331PreprocessedEntityID
1332ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1333 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1334 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1335 assert(I != M.PreprocessedEntityRemap.end()
1336 && "Invalid index into preprocessed entity index remap");
1337
1338 return LocalID + I->second;
1339}
1340
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001341unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1342 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001343}
1344
1345HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001346HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1347 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1348 FE->getName() };
1349 return ikey;
1350}
Guy Benyei11169dd2012-12-18 14:30:41 +00001351
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001352bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1353 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001354 return false;
1355
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001356 if (strcmp(a.Filename, b.Filename) == 0)
1357 return true;
1358
Guy Benyei11169dd2012-12-18 14:30:41 +00001359 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001360 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001361 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1362 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001363 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001364}
1365
1366std::pair<unsigned, unsigned>
1367HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001368 using namespace llvm::support;
1369 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001370 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001371 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001372}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001373
1374HeaderFileInfoTrait::internal_key_type
1375HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001376 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001377 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001378 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1379 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001380 ikey.Filename = (const char *)d;
1381 return ikey;
1382}
1383
Guy Benyei11169dd2012-12-18 14:30:41 +00001384HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001385HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001386 unsigned DataLen) {
1387 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001388 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001389 HeaderFileInfo HFI;
1390 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001391 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1392 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001393 HFI.isImport = (Flags >> 5) & 0x01;
1394 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1395 HFI.DirInfo = (Flags >> 2) & 0x03;
1396 HFI.Resolved = (Flags >> 1) & 0x01;
1397 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001398 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1399 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1400 M, endian::readNext<uint32_t, little, unaligned>(d));
1401 if (unsigned FrameworkOffset =
1402 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001403 // The framework offset is 1 greater than the actual offset,
1404 // since 0 is used as an indicator for "no framework name".
1405 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1406 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1407 }
1408
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001409 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001410 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001411 if (LocalSMID) {
1412 // This header is part of a module. Associate it with the module to enable
1413 // implicit module import.
1414 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1415 Module *Mod = Reader.getSubmodule(GlobalSMID);
1416 HFI.isModuleHeader = true;
1417 FileManager &FileMgr = Reader.getFileManager();
1418 ModuleMap &ModMap =
1419 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001420 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001421 }
1422 }
1423
Guy Benyei11169dd2012-12-18 14:30:41 +00001424 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1425 (void)End;
1426
1427 // This HeaderFileInfo was externally loaded.
1428 HFI.External = true;
1429 return HFI;
1430}
1431
Richard Smith49f906a2014-03-01 00:08:04 +00001432void
1433ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1434 GlobalMacroID GMacID,
1435 llvm::ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001436 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Richard Smith49f906a2014-03-01 00:08:04 +00001437 SubmoduleID *OverrideData = 0;
1438 if (!Overrides.empty()) {
1439 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1440 OverrideData[0] = Overrides.size();
1441 for (unsigned I = 0; I != Overrides.size(); ++I)
1442 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1443 }
1444 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001445}
1446
1447void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1448 ModuleFile *M,
1449 uint64_t MacroDirectivesOffset) {
1450 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1451 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001452}
1453
1454void ASTReader::ReadDefinedMacros() {
1455 // Note that we are loading defined macros.
1456 Deserializing Macros(this);
1457
1458 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1459 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001460 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001461
1462 // If there was no preprocessor block, skip this file.
1463 if (!MacroCursor.getBitStreamReader())
1464 continue;
1465
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001466 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001467 Cursor.JumpToBit((*I)->MacroStartOffset);
1468
1469 RecordData Record;
1470 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001471 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1472
1473 switch (E.Kind) {
1474 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1475 case llvm::BitstreamEntry::Error:
1476 Error("malformed block record in AST file");
1477 return;
1478 case llvm::BitstreamEntry::EndBlock:
1479 goto NextCursor;
1480
1481 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001482 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001483 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001484 default: // Default behavior: ignore.
1485 break;
1486
1487 case PP_MACRO_OBJECT_LIKE:
1488 case PP_MACRO_FUNCTION_LIKE:
1489 getLocalIdentifier(**I, Record[0]);
1490 break;
1491
1492 case PP_TOKEN:
1493 // Ignore tokens.
1494 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001495 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001496 break;
1497 }
1498 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001499 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001500 }
1501}
1502
1503namespace {
1504 /// \brief Visitor class used to look up identifirs in an AST file.
1505 class IdentifierLookupVisitor {
1506 StringRef Name;
1507 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001508 unsigned &NumIdentifierLookups;
1509 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001510 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001511
Guy Benyei11169dd2012-12-18 14:30:41 +00001512 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001513 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1514 unsigned &NumIdentifierLookups,
1515 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001516 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001517 NumIdentifierLookups(NumIdentifierLookups),
1518 NumIdentifierLookupHits(NumIdentifierLookupHits),
1519 Found()
1520 {
1521 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001522
1523 static bool visit(ModuleFile &M, void *UserData) {
1524 IdentifierLookupVisitor *This
1525 = static_cast<IdentifierLookupVisitor *>(UserData);
1526
1527 // If we've already searched this module file, skip it now.
1528 if (M.Generation <= This->PriorGeneration)
1529 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001530
Guy Benyei11169dd2012-12-18 14:30:41 +00001531 ASTIdentifierLookupTable *IdTable
1532 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1533 if (!IdTable)
1534 return false;
1535
1536 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1537 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001538 ++This->NumIdentifierLookups;
1539 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001540 if (Pos == IdTable->end())
1541 return false;
1542
1543 // Dereferencing the iterator has the effect of building the
1544 // IdentifierInfo node and populating it with the various
1545 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001546 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001547 This->Found = *Pos;
1548 return true;
1549 }
1550
1551 // \brief Retrieve the identifier info found within the module
1552 // files.
1553 IdentifierInfo *getIdentifierInfo() const { return Found; }
1554 };
1555}
1556
1557void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1558 // Note that we are loading an identifier.
1559 Deserializing AnIdentifier(this);
1560
1561 unsigned PriorGeneration = 0;
1562 if (getContext().getLangOpts().Modules)
1563 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001564
1565 // If there is a global index, look there first to determine which modules
1566 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001567 GlobalModuleIndex::HitSet Hits;
1568 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00001569 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001570 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1571 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001572 }
1573 }
1574
Douglas Gregor7211ac12013-01-25 23:32:03 +00001575 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001576 NumIdentifierLookups,
1577 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001578 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001579 markIdentifierUpToDate(&II);
1580}
1581
1582void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1583 if (!II)
1584 return;
1585
1586 II->setOutOfDate(false);
1587
1588 // Update the generation for this identifier.
1589 if (getContext().getLangOpts().Modules)
1590 IdentifierGeneration[II] = CurrentGeneration;
1591}
1592
Richard Smith49f906a2014-03-01 00:08:04 +00001593struct ASTReader::ModuleMacroInfo {
1594 SubmoduleID SubModID;
1595 MacroInfo *MI;
1596 SubmoduleID *Overrides;
1597 // FIXME: Remove this.
1598 ModuleFile *F;
1599
1600 bool isDefine() const { return MI; }
1601
1602 SubmoduleID getSubmoduleID() const { return SubModID; }
1603
1604 llvm::ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
1605 if (!Overrides)
1606 return llvm::ArrayRef<SubmoduleID>();
1607 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1608 }
1609
1610 DefMacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
1611 if (!MI)
1612 return 0;
1613 return PP.AllocateDefMacroDirective(MI, ImportLoc, /*isImported=*/true);
1614 }
1615};
1616
1617ASTReader::ModuleMacroInfo *
1618ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1619 ModuleMacroInfo Info;
1620
1621 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1622 if (ID & 1) {
1623 // Macro undefinition.
1624 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
1625 Info.MI = 0;
1626 } else {
1627 // Macro definition.
1628 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1629 assert(GMacID);
1630
1631 // If this macro has already been loaded, don't do so again.
1632 // FIXME: This is highly dubious. Multiple macro definitions can have the
1633 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1634 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1635 return 0;
1636
1637 Info.MI = getMacro(GMacID);
1638 Info.SubModID = Info.MI->getOwningModuleID();
1639 }
1640 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1641 Info.F = PMInfo.M;
1642
1643 return new (Context) ModuleMacroInfo(Info);
1644}
1645
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001646void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1647 const PendingMacroInfo &PMInfo) {
1648 assert(II);
1649
1650 if (PMInfo.M->Kind != MK_Module) {
1651 installPCHMacroDirectives(II, *PMInfo.M,
1652 PMInfo.PCHMacroData.MacroDirectivesOffset);
1653 return;
1654 }
Richard Smith49f906a2014-03-01 00:08:04 +00001655
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001656 // Module Macro.
1657
Richard Smith49f906a2014-03-01 00:08:04 +00001658 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1659 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001660 return;
1661
Richard Smith49f906a2014-03-01 00:08:04 +00001662 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1663 if (Owner && Owner->NameVisibility == Module::Hidden) {
1664 // Macros in the owning module are hidden. Just remember this macro to
1665 // install if we make this module visible.
1666 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1667 } else {
1668 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001669 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001670}
1671
1672void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1673 ModuleFile &M, uint64_t Offset) {
1674 assert(M.Kind != MK_Module);
1675
1676 BitstreamCursor &Cursor = M.MacroCursor;
1677 SavedStreamPosition SavedPosition(Cursor);
1678 Cursor.JumpToBit(Offset);
1679
1680 llvm::BitstreamEntry Entry =
1681 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1682 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1683 Error("malformed block record in AST file");
1684 return;
1685 }
1686
1687 RecordData Record;
1688 PreprocessorRecordTypes RecType =
1689 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1690 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1691 Error("malformed block record in AST file");
1692 return;
1693 }
1694
1695 // Deserialize the macro directives history in reverse source-order.
1696 MacroDirective *Latest = 0, *Earliest = 0;
1697 unsigned Idx = 0, N = Record.size();
1698 while (Idx < N) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001699 MacroDirective *MD = 0;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001700 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001701 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1702 switch (K) {
1703 case MacroDirective::MD_Define: {
1704 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1705 MacroInfo *MI = getMacro(GMacID);
1706 bool isImported = Record[Idx++];
1707 bool isAmbiguous = Record[Idx++];
1708 DefMacroDirective *DefMD =
1709 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1710 DefMD->setAmbiguous(isAmbiguous);
1711 MD = DefMD;
1712 break;
1713 }
1714 case MacroDirective::MD_Undefine:
1715 MD = PP.AllocateUndefMacroDirective(Loc);
1716 break;
1717 case MacroDirective::MD_Visibility: {
1718 bool isPublic = Record[Idx++];
1719 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1720 break;
1721 }
1722 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001723
1724 if (!Latest)
1725 Latest = MD;
1726 if (Earliest)
1727 Earliest->setPrevious(MD);
1728 Earliest = MD;
1729 }
1730
1731 PP.setLoadedMacroDirective(II, Latest);
1732}
1733
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001734/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001735/// modules.
1736static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001737 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001738 assert(PrevMI && NewMI);
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001739 Module *PrevOwner = 0;
1740 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1741 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001742 SourceManager &SrcMgr = Reader.getSourceManager();
1743 bool PrevInSystem
1744 = PrevOwner? PrevOwner->IsSystem
1745 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1746 bool NewInSystem
1747 = NewOwner? NewOwner->IsSystem
1748 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1749 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001750 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001751 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001752}
1753
Richard Smith49f906a2014-03-01 00:08:04 +00001754void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1755 AmbiguousMacros &Ambig,
1756 llvm::ArrayRef<SubmoduleID> Overrides) {
1757 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1758 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001759
Richard Smith49f906a2014-03-01 00:08:04 +00001760 // If this macro is not yet visible, remove it from the hidden names list.
1761 Module *Owner = getSubmodule(OwnerID);
1762 HiddenNames &Hidden = HiddenNamesMap[Owner];
1763 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1764 if (HI != Hidden.HiddenMacros.end()) {
Richard Smith9d100862014-03-06 03:16:27 +00001765 auto SubOverrides = HI->second->getOverriddenSubmodules();
Richard Smith49f906a2014-03-01 00:08:04 +00001766 Hidden.HiddenMacros.erase(HI);
Richard Smith9d100862014-03-06 03:16:27 +00001767 removeOverriddenMacros(II, Ambig, SubOverrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001768 }
1769
1770 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001771 Ambig.erase(
1772 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1773 return MD->getInfo()->getOwningModuleID() == OwnerID;
1774 }),
1775 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001776 }
1777}
1778
1779ASTReader::AmbiguousMacros *
1780ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1781 llvm::ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001782 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001783 if (!Prev && Overrides.empty())
1784 return 0;
1785
1786 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective() : 0;
1787 if (PrevDef && PrevDef->isAmbiguous()) {
1788 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1789 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1790 Ambig.push_back(PrevDef);
1791
1792 removeOverriddenMacros(II, Ambig, Overrides);
1793
1794 if (!Ambig.empty())
1795 return &Ambig;
1796
1797 AmbiguousMacroDefs.erase(II);
1798 } else {
1799 // There's no ambiguity yet. Maybe we're introducing one.
1800 llvm::SmallVector<DefMacroDirective*, 1> Ambig;
1801 if (PrevDef)
1802 Ambig.push_back(PrevDef);
1803
1804 removeOverriddenMacros(II, Ambig, Overrides);
1805
1806 if (!Ambig.empty()) {
1807 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
1808 Result.swap(Ambig);
1809 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001810 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001811 }
Richard Smith49f906a2014-03-01 00:08:04 +00001812
1813 // We ended up with no ambiguity.
1814 return 0;
1815}
1816
1817void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
1818 Module *Owner) {
1819 assert(II && Owner);
1820
1821 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
1822 if (ImportLoc.isInvalid()) {
1823 // FIXME: If we made macros from this module visible but didn't provide a
1824 // source location for the import, we don't have a location for the macro.
1825 // Use the location at which the containing module file was first imported
1826 // for now.
1827 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00001828 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00001829 }
1830
1831 llvm::SmallVectorImpl<DefMacroDirective*> *Prev =
1832 removeOverriddenMacros(II, MMI->getOverriddenSubmodules());
1833
1834
1835 // Create a synthetic macro definition corresponding to the import (or null
1836 // if this was an undefinition of the macro).
1837 DefMacroDirective *MD = MMI->import(PP, ImportLoc);
1838
1839 // If there's no ambiguity, just install the macro.
1840 if (!Prev) {
1841 if (MD)
1842 PP.appendMacroDirective(II, MD);
1843 else
1844 PP.appendMacroDirective(II, PP.AllocateUndefMacroDirective(ImportLoc));
1845 return;
1846 }
1847 assert(!Prev->empty());
1848
1849 if (!MD) {
1850 // We imported a #undef that didn't remove all prior definitions. The most
1851 // recent prior definition remains, and we install it in the place of the
1852 // imported directive.
1853 MacroInfo *NewMI = Prev->back()->getInfo();
1854 Prev->pop_back();
1855 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc, /*Imported*/true);
1856 }
1857
1858 // We're introducing a macro definition that creates or adds to an ambiguity.
1859 // We can resolve that ambiguity if this macro is token-for-token identical to
1860 // all of the existing definitions.
1861 MacroInfo *NewMI = MD->getInfo();
1862 assert(NewMI && "macro definition with no MacroInfo?");
1863 while (!Prev->empty()) {
1864 MacroInfo *PrevMI = Prev->back()->getInfo();
1865 assert(PrevMI && "macro definition with no MacroInfo?");
1866
1867 // Before marking the macros as ambiguous, check if this is a case where
1868 // both macros are in system headers. If so, we trust that the system
1869 // did not get it wrong. This also handles cases where Clang's own
1870 // headers have a different spelling of certain system macros:
1871 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1872 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
1873 //
1874 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
1875 // overrides the system limits.h's macros, so there's no conflict here.
1876 if (NewMI != PrevMI &&
1877 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
1878 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
1879 break;
1880
1881 // The previous definition is the same as this one (or both are defined in
1882 // system modules so we can assume they're equivalent); we don't need to
1883 // track it any more.
1884 Prev->pop_back();
1885 }
1886
1887 if (!Prev->empty())
1888 MD->setAmbiguous(true);
1889
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001890 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001891}
1892
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001893ASTReader::InputFileInfo
1894ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001895 // Go find this input file.
1896 BitstreamCursor &Cursor = F.InputFilesCursor;
1897 SavedStreamPosition SavedPosition(Cursor);
1898 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1899
1900 unsigned Code = Cursor.ReadCode();
1901 RecordData Record;
1902 StringRef Blob;
1903
1904 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1905 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1906 "invalid record type for input file");
1907 (void)Result;
1908
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001909 std::string Filename;
1910 off_t StoredSize;
1911 time_t StoredTime;
1912 bool Overridden;
1913
Ben Langmuir198c1682014-03-07 07:27:49 +00001914 assert(Record[0] == ID && "Bogus stored ID or offset");
1915 StoredSize = static_cast<off_t>(Record[1]);
1916 StoredTime = static_cast<time_t>(Record[2]);
1917 Overridden = static_cast<bool>(Record[3]);
1918 Filename = Blob;
1919 MaybeAddSystemRootToFilename(F, Filename);
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001920
Hans Wennborg73945142014-03-14 17:45:06 +00001921 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1922 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001923}
1924
1925std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001926 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00001927}
1928
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001929InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001930 // If this ID is bogus, just return an empty input file.
1931 if (ID == 0 || ID > F.InputFilesLoaded.size())
1932 return InputFile();
1933
1934 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001935 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001936 return F.InputFilesLoaded[ID-1];
1937
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001938 if (F.InputFilesLoaded[ID-1].isNotFound())
1939 return InputFile();
1940
Guy Benyei11169dd2012-12-18 14:30:41 +00001941 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001942 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001943 SavedStreamPosition SavedPosition(Cursor);
1944 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1945
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001946 InputFileInfo FI = readInputFileInfo(F, ID);
1947 off_t StoredSize = FI.StoredSize;
1948 time_t StoredTime = FI.StoredTime;
1949 bool Overridden = FI.Overridden;
1950 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001951
Ben Langmuir198c1682014-03-07 07:27:49 +00001952 const FileEntry *File
1953 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1954 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1955
1956 // If we didn't find the file, resolve it relative to the
1957 // original directory from which this AST file was created.
1958 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1959 F.OriginalDir != CurrentDir) {
1960 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1961 F.OriginalDir,
1962 CurrentDir);
1963 if (!Resolved.empty())
1964 File = FileMgr.getFile(Resolved);
1965 }
1966
1967 // For an overridden file, create a virtual file with the stored
1968 // size/timestamp.
1969 if (Overridden && File == 0) {
1970 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1971 }
1972
1973 if (File == 0) {
1974 if (Complain) {
1975 std::string ErrorStr = "could not find file '";
1976 ErrorStr += Filename;
1977 ErrorStr += "' referenced by AST file";
1978 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001979 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001980 // Record that we didn't find the file.
1981 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1982 return InputFile();
1983 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001984
Ben Langmuir198c1682014-03-07 07:27:49 +00001985 // Check if there was a request to override the contents of the file
1986 // that was part of the precompiled header. Overridding such a file
1987 // can lead to problems when lexing using the source locations from the
1988 // PCH.
1989 SourceManager &SM = getSourceManager();
1990 if (!Overridden && SM.isFileOverridden(File)) {
1991 if (Complain)
1992 Error(diag::err_fe_pch_file_overridden, Filename);
1993 // After emitting the diagnostic, recover by disabling the override so
1994 // that the original file will be used.
1995 SM.disableFileContentsOverride(File);
1996 // The FileEntry is a virtual file entry with the size of the contents
1997 // that would override the original contents. Set it to the original's
1998 // size/time.
1999 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2000 StoredSize, StoredTime);
2001 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002002
Ben Langmuir198c1682014-03-07 07:27:49 +00002003 bool IsOutOfDate = false;
2004
2005 // For an overridden file, there is nothing to validate.
2006 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00002007#if !defined(LLVM_ON_WIN32)
Ben Langmuir198c1682014-03-07 07:27:49 +00002008 // In our regression testing, the Windows file system seems to
2009 // have inconsistent modification times that sometimes
2010 // erroneously trigger this error-handling path.
2011 || StoredTime != File->getModificationTime()
Guy Benyei11169dd2012-12-18 14:30:41 +00002012#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002013 )) {
2014 if (Complain) {
2015 // Build a list of the PCH imports that got us here (in reverse).
2016 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2017 while (ImportStack.back()->ImportedBy.size() > 0)
2018 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002019
Ben Langmuir198c1682014-03-07 07:27:49 +00002020 // The top-level PCH is stale.
2021 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2022 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002023
Ben Langmuir198c1682014-03-07 07:27:49 +00002024 // Print the import stack.
2025 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2026 Diag(diag::note_pch_required_by)
2027 << Filename << ImportStack[0]->FileName;
2028 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002029 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002030 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002031 }
2032
Ben Langmuir198c1682014-03-07 07:27:49 +00002033 if (!Diags.isDiagnosticInFlight())
2034 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002035 }
2036
Ben Langmuir198c1682014-03-07 07:27:49 +00002037 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002038 }
2039
Ben Langmuir198c1682014-03-07 07:27:49 +00002040 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2041
2042 // Note that we've loaded this input file.
2043 F.InputFilesLoaded[ID-1] = IF;
2044 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002045}
2046
2047const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2048 ModuleFile &M = ModuleMgr.getPrimaryModule();
2049 std::string Filename = filenameStrRef;
2050 MaybeAddSystemRootToFilename(M, Filename);
2051 const FileEntry *File = FileMgr.getFile(Filename);
2052 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
2053 M.OriginalDir != CurrentDir) {
2054 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2055 M.OriginalDir,
2056 CurrentDir);
2057 if (!resolved.empty())
2058 File = FileMgr.getFile(resolved);
2059 }
2060
2061 return File;
2062}
2063
2064/// \brief If we are loading a relocatable PCH file, and the filename is
2065/// not an absolute path, add the system root to the beginning of the file
2066/// name.
2067void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2068 std::string &Filename) {
2069 // If this is not a relocatable PCH file, there's nothing to do.
2070 if (!M.RelocatablePCH)
2071 return;
2072
2073 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2074 return;
2075
2076 if (isysroot.empty()) {
2077 // If no system root was given, default to '/'
2078 Filename.insert(Filename.begin(), '/');
2079 return;
2080 }
2081
2082 unsigned Length = isysroot.size();
2083 if (isysroot[Length - 1] != '/')
2084 Filename.insert(Filename.begin(), '/');
2085
2086 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2087}
2088
2089ASTReader::ASTReadResult
2090ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002091 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei11169dd2012-12-18 14:30:41 +00002092 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002093 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002094
2095 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2096 Error("malformed block record in AST file");
2097 return Failure;
2098 }
2099
2100 // Read all of the records and blocks in the control block.
2101 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002102 while (1) {
2103 llvm::BitstreamEntry Entry = Stream.advance();
2104
2105 switch (Entry.Kind) {
2106 case llvm::BitstreamEntry::Error:
2107 Error("malformed block record in AST file");
2108 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002109 case llvm::BitstreamEntry::EndBlock: {
2110 // Validate input files.
2111 const HeaderSearchOptions &HSOpts =
2112 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002113
2114 // All user input files reside at the index range [0, Record[1]), and
2115 // system input files reside at [Record[1], Record[0]).
2116 // Record is the one from INPUT_FILE_OFFSETS.
2117 unsigned NumInputs = Record[0];
2118 unsigned NumUserInputs = Record[1];
2119
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002120 if (!DisableValidation &&
Ben Langmuir1e258222014-04-08 15:36:28 +00002121 (ValidateSystemInputs || !HSOpts.ModulesValidateOncePerBuildSession ||
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002122 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002123 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002124
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002125 // If we are reading a module, we will create a verification timestamp,
2126 // so we verify all input files. Otherwise, verify only user input
2127 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002128
2129 unsigned N = NumUserInputs;
2130 if (ValidateSystemInputs ||
Ben Langmuircb69b572014-03-07 06:40:32 +00002131 (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
2132 N = NumInputs;
2133
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002134 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002135 InputFile IF = getInputFile(F, I+1, Complain);
2136 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002137 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002138 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002139 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002140
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002141 if (Listener)
2142 Listener->visitModuleFile(F.FileName);
2143
Ben Langmuircb69b572014-03-07 06:40:32 +00002144 if (Listener && Listener->needsInputFileVisitation()) {
2145 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2146 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002147 for (unsigned I = 0; I < N; ++I) {
2148 bool IsSystem = I >= NumUserInputs;
2149 InputFileInfo FI = readInputFileInfo(F, I+1);
2150 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2151 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002152 }
2153
Guy Benyei11169dd2012-12-18 14:30:41 +00002154 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002155 }
2156
Chris Lattnere7b154b2013-01-19 21:39:22 +00002157 case llvm::BitstreamEntry::SubBlock:
2158 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002159 case INPUT_FILES_BLOCK_ID:
2160 F.InputFilesCursor = Stream;
2161 if (Stream.SkipBlock() || // Skip with the main cursor
2162 // Read the abbreviations
2163 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2164 Error("malformed block record in AST file");
2165 return Failure;
2166 }
2167 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002168
Guy Benyei11169dd2012-12-18 14:30:41 +00002169 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002170 if (Stream.SkipBlock()) {
2171 Error("malformed block record in AST file");
2172 return Failure;
2173 }
2174 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002175 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002176
2177 case llvm::BitstreamEntry::Record:
2178 // The interesting case.
2179 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002180 }
2181
2182 // Read and process a record.
2183 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002184 StringRef Blob;
2185 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002186 case METADATA: {
2187 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2188 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002189 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2190 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002191 return VersionMismatch;
2192 }
2193
2194 bool hasErrors = Record[5];
2195 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2196 Diag(diag::err_pch_with_compiler_errors);
2197 return HadErrors;
2198 }
2199
2200 F.RelocatablePCH = Record[4];
2201
2202 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002203 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002204 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2205 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002206 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002207 return VersionMismatch;
2208 }
2209 break;
2210 }
2211
2212 case IMPORTS: {
2213 // Load each of the imported PCH files.
2214 unsigned Idx = 0, N = Record.size();
2215 while (Idx < N) {
2216 // Read information about the AST file.
2217 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2218 // The import location will be the local one for now; we will adjust
2219 // all import locations of module imports after the global source
2220 // location info are setup.
2221 SourceLocation ImportLoc =
2222 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002223 off_t StoredSize = (off_t)Record[Idx++];
2224 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002225 unsigned Length = Record[Idx++];
2226 SmallString<128> ImportedFile(Record.begin() + Idx,
2227 Record.begin() + Idx + Length);
2228 Idx += Length;
2229
2230 // Load the AST file.
2231 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00002232 StoredSize, StoredModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00002233 ClientLoadCapabilities)) {
2234 case Failure: return Failure;
2235 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002236 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002237 case OutOfDate: return OutOfDate;
2238 case VersionMismatch: return VersionMismatch;
2239 case ConfigurationMismatch: return ConfigurationMismatch;
2240 case HadErrors: return HadErrors;
2241 case Success: break;
2242 }
2243 }
2244 break;
2245 }
2246
2247 case LANGUAGE_OPTIONS: {
2248 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2249 if (Listener && &F == *ModuleMgr.begin() &&
2250 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002251 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002252 return ConfigurationMismatch;
2253 break;
2254 }
2255
2256 case TARGET_OPTIONS: {
2257 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2258 if (Listener && &F == *ModuleMgr.begin() &&
2259 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002260 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002261 return ConfigurationMismatch;
2262 break;
2263 }
2264
2265 case DIAGNOSTIC_OPTIONS: {
2266 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2267 if (Listener && &F == *ModuleMgr.begin() &&
2268 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002269 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002270 return ConfigurationMismatch;
2271 break;
2272 }
2273
2274 case FILE_SYSTEM_OPTIONS: {
2275 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2276 if (Listener && &F == *ModuleMgr.begin() &&
2277 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002278 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002279 return ConfigurationMismatch;
2280 break;
2281 }
2282
2283 case HEADER_SEARCH_OPTIONS: {
2284 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2285 if (Listener && &F == *ModuleMgr.begin() &&
2286 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002287 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 return ConfigurationMismatch;
2289 break;
2290 }
2291
2292 case PREPROCESSOR_OPTIONS: {
2293 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2294 if (Listener && &F == *ModuleMgr.begin() &&
2295 ParsePreprocessorOptions(Record, Complain, *Listener,
2296 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002297 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002298 return ConfigurationMismatch;
2299 break;
2300 }
2301
2302 case ORIGINAL_FILE:
2303 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002304 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002305 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2306 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2307 break;
2308
2309 case ORIGINAL_FILE_ID:
2310 F.OriginalSourceFileID = FileID::get(Record[0]);
2311 break;
2312
2313 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002314 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002315 break;
2316
2317 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002318 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002319 F.InputFilesLoaded.resize(Record[0]);
2320 break;
2321 }
2322 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002323}
2324
2325bool ASTReader::ReadASTBlock(ModuleFile &F) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002326 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002327
2328 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2329 Error("malformed block record in AST file");
2330 return true;
2331 }
2332
2333 // Read all of the records and blocks for the AST file.
2334 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002335 while (1) {
2336 llvm::BitstreamEntry Entry = Stream.advance();
2337
2338 switch (Entry.Kind) {
2339 case llvm::BitstreamEntry::Error:
2340 Error("error at end of module block in AST file");
2341 return true;
2342 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002343 // Outside of C++, we do not store a lookup map for the translation unit.
2344 // Instead, mark it as needing a lookup map to be built if this module
2345 // contains any declarations lexically within it (which it always does!).
2346 // This usually has no cost, since we very rarely need the lookup map for
2347 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002348 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002349 if (DC->hasExternalLexicalStorage() &&
2350 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002351 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002352
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 return false;
2354 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002355 case llvm::BitstreamEntry::SubBlock:
2356 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002357 case DECLTYPES_BLOCK_ID:
2358 // We lazily load the decls block, but we want to set up the
2359 // DeclsCursor cursor to point into it. Clone our current bitcode
2360 // cursor to it, enter the block and read the abbrevs in that block.
2361 // With the main cursor, we just skip over it.
2362 F.DeclsCursor = Stream;
2363 if (Stream.SkipBlock() || // Skip with the main cursor.
2364 // Read the abbrevs.
2365 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2366 Error("malformed block record in AST file");
2367 return true;
2368 }
2369 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002370
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 case PREPROCESSOR_BLOCK_ID:
2372 F.MacroCursor = Stream;
2373 if (!PP.getExternalSource())
2374 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002375
Guy Benyei11169dd2012-12-18 14:30:41 +00002376 if (Stream.SkipBlock() ||
2377 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2378 Error("malformed block record in AST file");
2379 return true;
2380 }
2381 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2382 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002383
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 case PREPROCESSOR_DETAIL_BLOCK_ID:
2385 F.PreprocessorDetailCursor = Stream;
2386 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002387 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002388 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002389 Error("malformed preprocessor detail record in AST file");
2390 return true;
2391 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002393 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2394
Guy Benyei11169dd2012-12-18 14:30:41 +00002395 if (!PP.getPreprocessingRecord())
2396 PP.createPreprocessingRecord();
2397 if (!PP.getPreprocessingRecord()->getExternalSource())
2398 PP.getPreprocessingRecord()->SetExternalSource(*this);
2399 break;
2400
2401 case SOURCE_MANAGER_BLOCK_ID:
2402 if (ReadSourceManagerBlock(F))
2403 return true;
2404 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002405
Guy Benyei11169dd2012-12-18 14:30:41 +00002406 case SUBMODULE_BLOCK_ID:
2407 if (ReadSubmoduleBlock(F))
2408 return true;
2409 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002410
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002412 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002413 if (Stream.SkipBlock() ||
2414 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2415 Error("malformed comments block in AST file");
2416 return true;
2417 }
2418 CommentsCursors.push_back(std::make_pair(C, &F));
2419 break;
2420 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002421
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002423 if (Stream.SkipBlock()) {
2424 Error("malformed block record in AST file");
2425 return true;
2426 }
2427 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002428 }
2429 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002430
2431 case llvm::BitstreamEntry::Record:
2432 // The interesting case.
2433 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 }
2435
2436 // Read and process a record.
2437 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002438 StringRef Blob;
2439 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002440 default: // Default behavior: ignore.
2441 break;
2442
2443 case TYPE_OFFSET: {
2444 if (F.LocalNumTypes != 0) {
2445 Error("duplicate TYPE_OFFSET record in AST file");
2446 return true;
2447 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002448 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002449 F.LocalNumTypes = Record[0];
2450 unsigned LocalBaseTypeIndex = Record[1];
2451 F.BaseTypeIndex = getTotalNumTypes();
2452
2453 if (F.LocalNumTypes > 0) {
2454 // Introduce the global -> local mapping for types within this module.
2455 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2456
2457 // Introduce the local -> global mapping for types within this module.
2458 F.TypeRemap.insertOrReplace(
2459 std::make_pair(LocalBaseTypeIndex,
2460 F.BaseTypeIndex - LocalBaseTypeIndex));
2461
2462 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2463 }
2464 break;
2465 }
2466
2467 case DECL_OFFSET: {
2468 if (F.LocalNumDecls != 0) {
2469 Error("duplicate DECL_OFFSET record in AST file");
2470 return true;
2471 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002472 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002473 F.LocalNumDecls = Record[0];
2474 unsigned LocalBaseDeclID = Record[1];
2475 F.BaseDeclID = getTotalNumDecls();
2476
2477 if (F.LocalNumDecls > 0) {
2478 // Introduce the global -> local mapping for declarations within this
2479 // module.
2480 GlobalDeclMap.insert(
2481 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2482
2483 // Introduce the local -> global mapping for declarations within this
2484 // module.
2485 F.DeclRemap.insertOrReplace(
2486 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2487
2488 // Introduce the global -> local mapping for declarations within this
2489 // module.
2490 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2491
2492 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2493 }
2494 break;
2495 }
2496
2497 case TU_UPDATE_LEXICAL: {
2498 DeclContext *TU = Context.getTranslationUnitDecl();
2499 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002500 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002502 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 TU->setHasExternalLexicalStorage(true);
2504 break;
2505 }
2506
2507 case UPDATE_VISIBLE: {
2508 unsigned Idx = 0;
2509 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2510 ASTDeclContextNameLookupTable *Table =
2511 ASTDeclContextNameLookupTable::Create(
Chris Lattner0e6c9402013-01-20 02:38:54 +00002512 (const unsigned char *)Blob.data() + Record[Idx++],
2513 (const unsigned char *)Blob.data(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002514 ASTDeclContextNameLookupTrait(*this, F));
2515 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2516 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith52e3fba2014-03-11 07:17:35 +00002517 F.DeclContextInfos[TU].NameLookupTableData = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 TU->setHasExternalVisibleStorage(true);
Richard Smithd9174792014-03-11 03:10:46 +00002519 } else if (Decl *D = DeclsLoaded[ID - NUM_PREDEF_DECL_IDS]) {
2520 auto *DC = cast<DeclContext>(D);
2521 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002522 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2523 delete LookupTable;
2524 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 } else
2526 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2527 break;
2528 }
2529
2530 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002531 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 if (Record[0]) {
2533 F.IdentifierLookupTable
2534 = ASTIdentifierLookupTable::Create(
2535 (const unsigned char *)F.IdentifierTableData + Record[0],
2536 (const unsigned char *)F.IdentifierTableData,
2537 ASTIdentifierLookupTrait(*this, F));
2538
2539 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2540 }
2541 break;
2542
2543 case IDENTIFIER_OFFSET: {
2544 if (F.LocalNumIdentifiers != 0) {
2545 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2546 return true;
2547 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002548 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002549 F.LocalNumIdentifiers = Record[0];
2550 unsigned LocalBaseIdentifierID = Record[1];
2551 F.BaseIdentifierID = getTotalNumIdentifiers();
2552
2553 if (F.LocalNumIdentifiers > 0) {
2554 // Introduce the global -> local mapping for identifiers within this
2555 // module.
2556 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2557 &F));
2558
2559 // Introduce the local -> global mapping for identifiers within this
2560 // module.
2561 F.IdentifierRemap.insertOrReplace(
2562 std::make_pair(LocalBaseIdentifierID,
2563 F.BaseIdentifierID - LocalBaseIdentifierID));
2564
2565 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2566 + F.LocalNumIdentifiers);
2567 }
2568 break;
2569 }
2570
Ben Langmuir332aafe2014-01-31 01:06:56 +00002571 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002573 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 break;
2575
2576 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002577 if (SpecialTypes.empty()) {
2578 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2579 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2580 break;
2581 }
2582
2583 if (SpecialTypes.size() != Record.size()) {
2584 Error("invalid special-types record");
2585 return true;
2586 }
2587
2588 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2589 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2590 if (!SpecialTypes[I])
2591 SpecialTypes[I] = ID;
2592 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2593 // merge step?
2594 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 break;
2596
2597 case STATISTICS:
2598 TotalNumStatements += Record[0];
2599 TotalNumMacros += Record[1];
2600 TotalLexicalDeclContexts += Record[2];
2601 TotalVisibleDeclContexts += Record[3];
2602 break;
2603
2604 case UNUSED_FILESCOPED_DECLS:
2605 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2606 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2607 break;
2608
2609 case DELEGATING_CTORS:
2610 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2611 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2612 break;
2613
2614 case WEAK_UNDECLARED_IDENTIFIERS:
2615 if (Record.size() % 4 != 0) {
2616 Error("invalid weak identifiers record");
2617 return true;
2618 }
2619
2620 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2621 // files. This isn't the way to do it :)
2622 WeakUndeclaredIdentifiers.clear();
2623
2624 // Translate the weak, undeclared identifiers into global IDs.
2625 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2626 WeakUndeclaredIdentifiers.push_back(
2627 getGlobalIdentifierID(F, Record[I++]));
2628 WeakUndeclaredIdentifiers.push_back(
2629 getGlobalIdentifierID(F, Record[I++]));
2630 WeakUndeclaredIdentifiers.push_back(
2631 ReadSourceLocation(F, Record, I).getRawEncoding());
2632 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2633 }
2634 break;
2635
Richard Smith78165b52013-01-10 23:43:47 +00002636 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002638 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002639 break;
2640
2641 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002642 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002643 F.LocalNumSelectors = Record[0];
2644 unsigned LocalBaseSelectorID = Record[1];
2645 F.BaseSelectorID = getTotalNumSelectors();
2646
2647 if (F.LocalNumSelectors > 0) {
2648 // Introduce the global -> local mapping for selectors within this
2649 // module.
2650 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2651
2652 // Introduce the local -> global mapping for selectors within this
2653 // module.
2654 F.SelectorRemap.insertOrReplace(
2655 std::make_pair(LocalBaseSelectorID,
2656 F.BaseSelectorID - LocalBaseSelectorID));
2657
2658 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2659 }
2660 break;
2661 }
2662
2663 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002664 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 if (Record[0])
2666 F.SelectorLookupTable
2667 = ASTSelectorLookupTable::Create(
2668 F.SelectorLookupTableData + Record[0],
2669 F.SelectorLookupTableData,
2670 ASTSelectorLookupTrait(*this, F));
2671 TotalNumMethodPoolEntries += Record[1];
2672 break;
2673
2674 case REFERENCED_SELECTOR_POOL:
2675 if (!Record.empty()) {
2676 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2677 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2678 Record[Idx++]));
2679 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2680 getRawEncoding());
2681 }
2682 }
2683 break;
2684
2685 case PP_COUNTER_VALUE:
2686 if (!Record.empty() && Listener)
2687 Listener->ReadCounter(F, Record[0]);
2688 break;
2689
2690 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002691 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002692 F.NumFileSortedDecls = Record[0];
2693 break;
2694
2695 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002696 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 F.LocalNumSLocEntries = Record[0];
2698 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002699 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Guy Benyei11169dd2012-12-18 14:30:41 +00002700 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2701 SLocSpaceSize);
2702 // Make our entry in the range map. BaseID is negative and growing, so
2703 // we invert it. Because we invert it, though, we need the other end of
2704 // the range.
2705 unsigned RangeStart =
2706 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2707 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2708 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2709
2710 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2711 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2712 GlobalSLocOffsetMap.insert(
2713 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2714 - SLocSpaceSize,&F));
2715
2716 // Initialize the remapping table.
2717 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002718 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002720 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2722
2723 TotalNumSLocEntries += F.LocalNumSLocEntries;
2724 break;
2725 }
2726
2727 case MODULE_OFFSET_MAP: {
2728 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002729 const unsigned char *Data = (const unsigned char*)Blob.data();
2730 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002731
2732 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2733 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2734 F.SLocRemap.insert(std::make_pair(0U, 0));
2735 F.SLocRemap.insert(std::make_pair(2U, 1));
2736 }
2737
Guy Benyei11169dd2012-12-18 14:30:41 +00002738 // Continuous range maps we may be updating in our module.
2739 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2740 ContinuousRangeMap<uint32_t, int, 2>::Builder
2741 IdentifierRemap(F.IdentifierRemap);
2742 ContinuousRangeMap<uint32_t, int, 2>::Builder
2743 MacroRemap(F.MacroRemap);
2744 ContinuousRangeMap<uint32_t, int, 2>::Builder
2745 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2746 ContinuousRangeMap<uint32_t, int, 2>::Builder
2747 SubmoduleRemap(F.SubmoduleRemap);
2748 ContinuousRangeMap<uint32_t, int, 2>::Builder
2749 SelectorRemap(F.SelectorRemap);
2750 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2751 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2752
2753 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002754 using namespace llvm::support;
2755 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002756 StringRef Name = StringRef((const char*)Data, Len);
2757 Data += Len;
2758 ModuleFile *OM = ModuleMgr.lookup(Name);
2759 if (!OM) {
2760 Error("SourceLocation remap refers to unknown module");
2761 return true;
2762 }
2763
Justin Bogner57ba0b22014-03-28 22:03:24 +00002764 uint32_t SLocOffset =
2765 endian::readNext<uint32_t, little, unaligned>(Data);
2766 uint32_t IdentifierIDOffset =
2767 endian::readNext<uint32_t, little, unaligned>(Data);
2768 uint32_t MacroIDOffset =
2769 endian::readNext<uint32_t, little, unaligned>(Data);
2770 uint32_t PreprocessedEntityIDOffset =
2771 endian::readNext<uint32_t, little, unaligned>(Data);
2772 uint32_t SubmoduleIDOffset =
2773 endian::readNext<uint32_t, little, unaligned>(Data);
2774 uint32_t SelectorIDOffset =
2775 endian::readNext<uint32_t, little, unaligned>(Data);
2776 uint32_t DeclIDOffset =
2777 endian::readNext<uint32_t, little, unaligned>(Data);
2778 uint32_t TypeIndexOffset =
2779 endian::readNext<uint32_t, little, unaligned>(Data);
2780
Guy Benyei11169dd2012-12-18 14:30:41 +00002781 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2782 SLocRemap.insert(std::make_pair(SLocOffset,
2783 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2784 IdentifierRemap.insert(
2785 std::make_pair(IdentifierIDOffset,
2786 OM->BaseIdentifierID - IdentifierIDOffset));
2787 MacroRemap.insert(std::make_pair(MacroIDOffset,
2788 OM->BaseMacroID - MacroIDOffset));
2789 PreprocessedEntityRemap.insert(
2790 std::make_pair(PreprocessedEntityIDOffset,
2791 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2792 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2793 OM->BaseSubmoduleID - SubmoduleIDOffset));
2794 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2795 OM->BaseSelectorID - SelectorIDOffset));
2796 DeclRemap.insert(std::make_pair(DeclIDOffset,
2797 OM->BaseDeclID - DeclIDOffset));
2798
2799 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2800 OM->BaseTypeIndex - TypeIndexOffset));
2801
2802 // Global -> local mappings.
2803 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2804 }
2805 break;
2806 }
2807
2808 case SOURCE_MANAGER_LINE_TABLE:
2809 if (ParseLineTable(F, Record))
2810 return true;
2811 break;
2812
2813 case SOURCE_LOCATION_PRELOADS: {
2814 // Need to transform from the local view (1-based IDs) to the global view,
2815 // which is based off F.SLocEntryBaseID.
2816 if (!F.PreloadSLocEntries.empty()) {
2817 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2818 return true;
2819 }
2820
2821 F.PreloadSLocEntries.swap(Record);
2822 break;
2823 }
2824
2825 case EXT_VECTOR_DECLS:
2826 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2827 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2828 break;
2829
2830 case VTABLE_USES:
2831 if (Record.size() % 3 != 0) {
2832 Error("Invalid VTABLE_USES record");
2833 return true;
2834 }
2835
2836 // Later tables overwrite earlier ones.
2837 // FIXME: Modules will have some trouble with this. This is clearly not
2838 // the right way to do this.
2839 VTableUses.clear();
2840
2841 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2842 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2843 VTableUses.push_back(
2844 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2845 VTableUses.push_back(Record[Idx++]);
2846 }
2847 break;
2848
2849 case DYNAMIC_CLASSES:
2850 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2851 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2852 break;
2853
2854 case PENDING_IMPLICIT_INSTANTIATIONS:
2855 if (PendingInstantiations.size() % 2 != 0) {
2856 Error("Invalid existing PendingInstantiations");
2857 return true;
2858 }
2859
2860 if (Record.size() % 2 != 0) {
2861 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2862 return true;
2863 }
2864
2865 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2866 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2867 PendingInstantiations.push_back(
2868 ReadSourceLocation(F, Record, I).getRawEncoding());
2869 }
2870 break;
2871
2872 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002873 if (Record.size() != 2) {
2874 Error("Invalid SEMA_DECL_REFS block");
2875 return true;
2876 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002877 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2878 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2879 break;
2880
2881 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002882 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2883 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2884 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002885
2886 unsigned LocalBasePreprocessedEntityID = Record[0];
2887
2888 unsigned StartingID;
2889 if (!PP.getPreprocessingRecord())
2890 PP.createPreprocessingRecord();
2891 if (!PP.getPreprocessingRecord()->getExternalSource())
2892 PP.getPreprocessingRecord()->SetExternalSource(*this);
2893 StartingID
2894 = PP.getPreprocessingRecord()
2895 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2896 F.BasePreprocessedEntityID = StartingID;
2897
2898 if (F.NumPreprocessedEntities > 0) {
2899 // Introduce the global -> local mapping for preprocessed entities in
2900 // this module.
2901 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2902
2903 // Introduce the local -> global mapping for preprocessed entities in
2904 // this module.
2905 F.PreprocessedEntityRemap.insertOrReplace(
2906 std::make_pair(LocalBasePreprocessedEntityID,
2907 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2908 }
2909
2910 break;
2911 }
2912
2913 case DECL_UPDATE_OFFSETS: {
2914 if (Record.size() % 2 != 0) {
2915 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2916 return true;
2917 }
Richard Smith04d05b52014-03-23 00:27:18 +00002918 // FIXME: If we've already loaded the decl, perform the updates now.
Guy Benyei11169dd2012-12-18 14:30:41 +00002919 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2920 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2921 .push_back(std::make_pair(&F, Record[I+1]));
2922 break;
2923 }
2924
2925 case DECL_REPLACEMENTS: {
2926 if (Record.size() % 3 != 0) {
2927 Error("invalid DECL_REPLACEMENTS block in AST file");
2928 return true;
2929 }
2930 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2931 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2932 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2933 break;
2934 }
2935
2936 case OBJC_CATEGORIES_MAP: {
2937 if (F.LocalNumObjCCategoriesInMap != 0) {
2938 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2939 return true;
2940 }
2941
2942 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002943 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 break;
2945 }
2946
2947 case OBJC_CATEGORIES:
2948 F.ObjCCategories.swap(Record);
2949 break;
2950
2951 case CXX_BASE_SPECIFIER_OFFSETS: {
2952 if (F.LocalNumCXXBaseSpecifiers != 0) {
2953 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2954 return true;
2955 }
2956
2957 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002958 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002959 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2960 break;
2961 }
2962
2963 case DIAG_PRAGMA_MAPPINGS:
2964 if (F.PragmaDiagMappings.empty())
2965 F.PragmaDiagMappings.swap(Record);
2966 else
2967 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2968 Record.begin(), Record.end());
2969 break;
2970
2971 case CUDA_SPECIAL_DECL_REFS:
2972 // Later tables overwrite earlier ones.
2973 // FIXME: Modules will have trouble with this.
2974 CUDASpecialDeclRefs.clear();
2975 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2976 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2977 break;
2978
2979 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002980 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002982 if (Record[0]) {
2983 F.HeaderFileInfoTable
2984 = HeaderFileInfoLookupTable::Create(
2985 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2986 (const unsigned char *)F.HeaderFileInfoTableData,
2987 HeaderFileInfoTrait(*this, F,
2988 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002989 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002990
2991 PP.getHeaderSearchInfo().SetExternalSource(this);
2992 if (!PP.getHeaderSearchInfo().getExternalLookup())
2993 PP.getHeaderSearchInfo().SetExternalLookup(this);
2994 }
2995 break;
2996 }
2997
2998 case FP_PRAGMA_OPTIONS:
2999 // Later tables overwrite earlier ones.
3000 FPPragmaOptions.swap(Record);
3001 break;
3002
3003 case OPENCL_EXTENSIONS:
3004 // Later tables overwrite earlier ones.
3005 OpenCLExtensions.swap(Record);
3006 break;
3007
3008 case TENTATIVE_DEFINITIONS:
3009 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3010 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3011 break;
3012
3013 case KNOWN_NAMESPACES:
3014 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3015 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3016 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003017
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003018 case UNDEFINED_BUT_USED:
3019 if (UndefinedButUsed.size() % 2 != 0) {
3020 Error("Invalid existing UndefinedButUsed");
Nick Lewycky8334af82013-01-26 00:35:08 +00003021 return true;
3022 }
3023
3024 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003025 Error("invalid undefined-but-used record");
Nick Lewycky8334af82013-01-26 00:35:08 +00003026 return true;
3027 }
3028 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003029 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3030 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003031 ReadSourceLocation(F, Record, I).getRawEncoding());
3032 }
3033 break;
3034
Guy Benyei11169dd2012-12-18 14:30:41 +00003035 case IMPORTED_MODULES: {
3036 if (F.Kind != MK_Module) {
3037 // If we aren't loading a module (which has its own exports), make
3038 // all of the imported modules visible.
3039 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003040 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3041 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3042 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3043 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003044 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 }
3046 }
3047 break;
3048 }
3049
3050 case LOCAL_REDECLARATIONS: {
3051 F.RedeclarationChains.swap(Record);
3052 break;
3053 }
3054
3055 case LOCAL_REDECLARATIONS_MAP: {
3056 if (F.LocalNumRedeclarationsInMap != 0) {
3057 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
3058 return true;
3059 }
3060
3061 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003062 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003063 break;
3064 }
3065
3066 case MERGED_DECLARATIONS: {
3067 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3068 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3069 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3070 for (unsigned N = Record[Idx++]; N > 0; --N)
3071 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3072 }
3073 break;
3074 }
3075
3076 case MACRO_OFFSET: {
3077 if (F.LocalNumMacros != 0) {
3078 Error("duplicate MACRO_OFFSET record in AST file");
3079 return true;
3080 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003081 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003082 F.LocalNumMacros = Record[0];
3083 unsigned LocalBaseMacroID = Record[1];
3084 F.BaseMacroID = getTotalNumMacros();
3085
3086 if (F.LocalNumMacros > 0) {
3087 // Introduce the global -> local mapping for macros within this module.
3088 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3089
3090 // Introduce the local -> global mapping for macros within this module.
3091 F.MacroRemap.insertOrReplace(
3092 std::make_pair(LocalBaseMacroID,
3093 F.BaseMacroID - LocalBaseMacroID));
3094
3095 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3096 }
3097 break;
3098 }
3099
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003100 case MACRO_TABLE: {
3101 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003102 break;
3103 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003104
3105 case LATE_PARSED_TEMPLATE: {
3106 LateParsedTemplates.append(Record.begin(), Record.end());
3107 break;
3108 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003109 }
3110 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003111}
3112
Douglas Gregorc1489562013-02-12 23:36:21 +00003113/// \brief Move the given method to the back of the global list of methods.
3114static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3115 // Find the entry for this selector in the method pool.
3116 Sema::GlobalMethodPool::iterator Known
3117 = S.MethodPool.find(Method->getSelector());
3118 if (Known == S.MethodPool.end())
3119 return;
3120
3121 // Retrieve the appropriate method list.
3122 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3123 : Known->second.second;
3124 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003125 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003126 if (!Found) {
3127 if (List->Method == Method) {
3128 Found = true;
3129 } else {
3130 // Keep searching.
3131 continue;
3132 }
3133 }
3134
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003135 if (List->getNext())
3136 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003137 else
3138 List->Method = Method;
3139 }
3140}
3141
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003142void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00003143 for (unsigned I = 0, N = Names.HiddenDecls.size(); I != N; ++I) {
3144 Decl *D = Names.HiddenDecls[I];
3145 bool wasHidden = D->Hidden;
3146 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003147
Richard Smith49f906a2014-03-01 00:08:04 +00003148 if (wasHidden && SemaObj) {
3149 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3150 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003151 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 }
3153 }
Richard Smith49f906a2014-03-01 00:08:04 +00003154
3155 for (HiddenMacrosMap::const_iterator I = Names.HiddenMacros.begin(),
3156 E = Names.HiddenMacros.end();
3157 I != E; ++I)
3158 installImportedMacro(I->first, I->second, Owner);
Guy Benyei11169dd2012-12-18 14:30:41 +00003159}
3160
Richard Smith49f906a2014-03-01 00:08:04 +00003161void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003162 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003163 SourceLocation ImportLoc,
3164 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003165 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003166 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003167 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003168 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003169 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003170
3171 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003172 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003173 // there is nothing more to do.
3174 continue;
3175 }
Richard Smith49f906a2014-03-01 00:08:04 +00003176
Guy Benyei11169dd2012-12-18 14:30:41 +00003177 if (!Mod->isAvailable()) {
3178 // Modules that aren't available cannot be made visible.
3179 continue;
3180 }
3181
3182 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003183 if (NameVisibility >= Module::MacrosVisible &&
3184 Mod->NameVisibility < Module::MacrosVisible)
3185 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003186 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003187
Guy Benyei11169dd2012-12-18 14:30:41 +00003188 // If we've already deserialized any names from this module,
3189 // mark them as visible.
3190 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3191 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003192 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003193 HiddenNamesMap.erase(Hidden);
3194 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003195
Guy Benyei11169dd2012-12-18 14:30:41 +00003196 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003197 SmallVector<Module *, 16> Exports;
3198 Mod->getExportedModules(Exports);
3199 for (SmallVectorImpl<Module *>::iterator
3200 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3201 Module *Exported = *I;
3202 if (Visited.insert(Exported))
3203 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003204 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003205
3206 // Detect any conflicts.
3207 if (Complain) {
3208 assert(ImportLoc.isValid() && "Missing import location");
3209 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3210 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3211 Diag(ImportLoc, diag::warn_module_conflict)
3212 << Mod->getFullModuleName()
3213 << Mod->Conflicts[I].Other->getFullModuleName()
3214 << Mod->Conflicts[I].Message;
3215 // FIXME: Need note where the other module was imported.
3216 }
3217 }
3218 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003219 }
3220}
3221
Douglas Gregore060e572013-01-25 01:03:03 +00003222bool ASTReader::loadGlobalIndex() {
3223 if (GlobalIndex)
3224 return false;
3225
3226 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3227 !Context.getLangOpts().Modules)
3228 return true;
3229
3230 // Try to load the global index.
3231 TriedLoadingGlobalIndex = true;
3232 StringRef ModuleCachePath
3233 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3234 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003235 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003236 if (!Result.first)
3237 return true;
3238
3239 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003240 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003241 return false;
3242}
3243
3244bool ASTReader::isGlobalIndexUnavailable() const {
3245 return Context.getLangOpts().Modules && UseGlobalIndex &&
3246 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3247}
3248
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003249static void updateModuleTimestamp(ModuleFile &MF) {
3250 // Overwrite the timestamp file contents so that file's mtime changes.
3251 std::string TimestampFilename = MF.getTimestampFilename();
3252 std::string ErrorInfo;
Rafael Espindola04a13be2014-02-24 15:06:52 +00003253 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
Rafael Espindola4fbd3732014-02-24 18:20:21 +00003254 llvm::sys::fs::F_Text);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003255 if (!ErrorInfo.empty())
3256 return;
3257 OS << "Timestamp file\n";
3258}
3259
Guy Benyei11169dd2012-12-18 14:30:41 +00003260ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3261 ModuleKind Type,
3262 SourceLocation ImportLoc,
3263 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003264 llvm::SaveAndRestore<SourceLocation>
3265 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3266
Guy Benyei11169dd2012-12-18 14:30:41 +00003267 // Bump the generation number.
3268 unsigned PreviousGeneration = CurrentGeneration++;
3269
3270 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003271 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003272 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3273 /*ImportedBy=*/0, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003274 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003275 ClientLoadCapabilities)) {
3276 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003277 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003278 case OutOfDate:
3279 case VersionMismatch:
3280 case ConfigurationMismatch:
3281 case HadErrors:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003282 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3283 Context.getLangOpts().Modules
3284 ? &PP.getHeaderSearchInfo().getModuleMap()
3285 : 0);
Douglas Gregore060e572013-01-25 01:03:03 +00003286
3287 // If we find that any modules are unusable, the global index is going
3288 // to be out-of-date. Just remove it.
3289 GlobalIndex.reset();
Douglas Gregor7211ac12013-01-25 23:32:03 +00003290 ModuleMgr.setGlobalIndex(0);
Guy Benyei11169dd2012-12-18 14:30:41 +00003291 return ReadResult;
3292
3293 case Success:
3294 break;
3295 }
3296
3297 // Here comes stuff that we only do once the entire chain is loaded.
3298
3299 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003300 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3301 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003302 M != MEnd; ++M) {
3303 ModuleFile &F = *M->Mod;
3304
3305 // Read the AST block.
3306 if (ReadASTBlock(F))
3307 return Failure;
3308
3309 // Once read, set the ModuleFile bit base offset and update the size in
3310 // bits of all files we've seen.
3311 F.GlobalBitOffset = TotalModulesSizeInBits;
3312 TotalModulesSizeInBits += F.SizeInBits;
3313 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3314
3315 // Preload SLocEntries.
3316 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3317 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3318 // Load it through the SourceManager and don't call ReadSLocEntry()
3319 // directly because the entry may have already been loaded in which case
3320 // calling ReadSLocEntry() directly would trigger an assertion in
3321 // SourceManager.
3322 SourceMgr.getLoadedSLocEntryByID(Index);
3323 }
3324 }
3325
Douglas Gregor603cd862013-03-22 18:50:14 +00003326 // Setup the import locations and notify the module manager that we've
3327 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003328 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3329 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003330 M != MEnd; ++M) {
3331 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003332
3333 ModuleMgr.moduleFileAccepted(&F);
3334
3335 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003336 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003337 if (!M->ImportedBy)
3338 F.ImportLoc = M->ImportLoc;
3339 else
3340 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3341 M->ImportLoc.getRawEncoding());
3342 }
3343
3344 // Mark all of the identifiers in the identifier table as being out of date,
3345 // so that various accessors know to check the loaded modules when the
3346 // identifier is used.
3347 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3348 IdEnd = PP.getIdentifierTable().end();
3349 Id != IdEnd; ++Id)
3350 Id->second->setOutOfDate(true);
3351
3352 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003353 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3354 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003355 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3356 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003357
3358 switch (Unresolved.Kind) {
3359 case UnresolvedModuleRef::Conflict:
3360 if (ResolvedMod) {
3361 Module::Conflict Conflict;
3362 Conflict.Other = ResolvedMod;
3363 Conflict.Message = Unresolved.String.str();
3364 Unresolved.Mod->Conflicts.push_back(Conflict);
3365 }
3366 continue;
3367
3368 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003369 if (ResolvedMod)
3370 Unresolved.Mod->Imports.push_back(ResolvedMod);
3371 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003372
Douglas Gregorfb912652013-03-20 21:10:35 +00003373 case UnresolvedModuleRef::Export:
3374 if (ResolvedMod || Unresolved.IsWildcard)
3375 Unresolved.Mod->Exports.push_back(
3376 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3377 continue;
3378 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003379 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003380 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003381
3382 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3383 // Might be unnecessary as use declarations are only used to build the
3384 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003385
3386 InitializeContext();
3387
Richard Smith3d8e97e2013-10-18 06:54:39 +00003388 if (SemaObj)
3389 UpdateSema();
3390
Guy Benyei11169dd2012-12-18 14:30:41 +00003391 if (DeserializationListener)
3392 DeserializationListener->ReaderInitialized(this);
3393
3394 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3395 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3396 PrimaryModule.OriginalSourceFileID
3397 = FileID::get(PrimaryModule.SLocEntryBaseID
3398 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3399
3400 // If this AST file is a precompiled preamble, then set the
3401 // preamble file ID of the source manager to the file source file
3402 // from which the preamble was built.
3403 if (Type == MK_Preamble) {
3404 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3405 } else if (Type == MK_MainFile) {
3406 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3407 }
3408 }
3409
3410 // For any Objective-C class definitions we have already loaded, make sure
3411 // that we load any additional categories.
3412 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3413 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3414 ObjCClassesLoaded[I],
3415 PreviousGeneration);
3416 }
Douglas Gregore060e572013-01-25 01:03:03 +00003417
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003418 if (PP.getHeaderSearchInfo()
3419 .getHeaderSearchOpts()
3420 .ModulesValidateOncePerBuildSession) {
3421 // Now we are certain that the module and all modules it depends on are
3422 // up to date. Create or update timestamp files for modules that are
3423 // located in the module cache (not for PCH files that could be anywhere
3424 // in the filesystem).
3425 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3426 ImportedModule &M = Loaded[I];
3427 if (M.Mod->Kind == MK_Module) {
3428 updateModuleTimestamp(*M.Mod);
3429 }
3430 }
3431 }
3432
Guy Benyei11169dd2012-12-18 14:30:41 +00003433 return Success;
3434}
3435
3436ASTReader::ASTReadResult
3437ASTReader::ReadASTCore(StringRef FileName,
3438 ModuleKind Type,
3439 SourceLocation ImportLoc,
3440 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003441 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003442 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003443 unsigned ClientLoadCapabilities) {
3444 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003445 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003446 ModuleManager::AddModuleResult AddResult
3447 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3448 CurrentGeneration, ExpectedSize, ExpectedModTime,
3449 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003450
Douglas Gregor7029ce12013-03-19 00:28:20 +00003451 switch (AddResult) {
3452 case ModuleManager::AlreadyLoaded:
3453 return Success;
3454
3455 case ModuleManager::NewlyLoaded:
3456 // Load module file below.
3457 break;
3458
3459 case ModuleManager::Missing:
3460 // The module file was missing; if the client handle handle, that, return
3461 // it.
3462 if (ClientLoadCapabilities & ARR_Missing)
3463 return Missing;
3464
3465 // Otherwise, return an error.
3466 {
3467 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3468 + ErrorStr;
3469 Error(Msg);
3470 }
3471 return Failure;
3472
3473 case ModuleManager::OutOfDate:
3474 // We couldn't load the module file because it is out-of-date. If the
3475 // client can handle out-of-date, return it.
3476 if (ClientLoadCapabilities & ARR_OutOfDate)
3477 return OutOfDate;
3478
3479 // Otherwise, return an error.
3480 {
3481 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3482 + ErrorStr;
3483 Error(Msg);
3484 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003485 return Failure;
3486 }
3487
Douglas Gregor7029ce12013-03-19 00:28:20 +00003488 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003489
3490 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3491 // module?
3492 if (FileName != "-") {
3493 CurrentDir = llvm::sys::path::parent_path(FileName);
3494 if (CurrentDir.empty()) CurrentDir = ".";
3495 }
3496
3497 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003498 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003499 Stream.init(F.StreamFile);
3500 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3501
3502 // Sniff for the signature.
3503 if (Stream.Read(8) != 'C' ||
3504 Stream.Read(8) != 'P' ||
3505 Stream.Read(8) != 'C' ||
3506 Stream.Read(8) != 'H') {
3507 Diag(diag::err_not_a_pch_file) << FileName;
3508 return Failure;
3509 }
3510
3511 // This is used for compatibility with older PCH formats.
3512 bool HaveReadControlBlock = false;
3513
Chris Lattnerefa77172013-01-20 00:00:22 +00003514 while (1) {
3515 llvm::BitstreamEntry Entry = Stream.advance();
3516
3517 switch (Entry.Kind) {
3518 case llvm::BitstreamEntry::Error:
3519 case llvm::BitstreamEntry::EndBlock:
3520 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003521 Error("invalid record at top-level of AST file");
3522 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003523
3524 case llvm::BitstreamEntry::SubBlock:
3525 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003526 }
3527
Guy Benyei11169dd2012-12-18 14:30:41 +00003528 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003529 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003530 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3531 if (Stream.ReadBlockInfoBlock()) {
3532 Error("malformed BlockInfoBlock in AST file");
3533 return Failure;
3534 }
3535 break;
3536 case CONTROL_BLOCK_ID:
3537 HaveReadControlBlock = true;
3538 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
3539 case Success:
3540 break;
3541
3542 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003543 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003544 case OutOfDate: return OutOfDate;
3545 case VersionMismatch: return VersionMismatch;
3546 case ConfigurationMismatch: return ConfigurationMismatch;
3547 case HadErrors: return HadErrors;
3548 }
3549 break;
3550 case AST_BLOCK_ID:
3551 if (!HaveReadControlBlock) {
3552 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003553 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003554 return VersionMismatch;
3555 }
3556
3557 // Record that we've loaded this module.
3558 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3559 return Success;
3560
3561 default:
3562 if (Stream.SkipBlock()) {
3563 Error("malformed block record in AST file");
3564 return Failure;
3565 }
3566 break;
3567 }
3568 }
3569
3570 return Success;
3571}
3572
3573void ASTReader::InitializeContext() {
3574 // If there's a listener, notify them that we "read" the translation unit.
3575 if (DeserializationListener)
3576 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3577 Context.getTranslationUnitDecl());
3578
3579 // Make sure we load the declaration update records for the translation unit,
3580 // if there are any.
3581 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3582 Context.getTranslationUnitDecl());
3583
3584 // FIXME: Find a better way to deal with collisions between these
3585 // built-in types. Right now, we just ignore the problem.
3586
3587 // Load the special types.
3588 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3589 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3590 if (!Context.CFConstantStringTypeDecl)
3591 Context.setCFConstantStringType(GetType(String));
3592 }
3593
3594 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3595 QualType FileType = GetType(File);
3596 if (FileType.isNull()) {
3597 Error("FILE type is NULL");
3598 return;
3599 }
3600
3601 if (!Context.FILEDecl) {
3602 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3603 Context.setFILEDecl(Typedef->getDecl());
3604 else {
3605 const TagType *Tag = FileType->getAs<TagType>();
3606 if (!Tag) {
3607 Error("Invalid FILE type in AST file");
3608 return;
3609 }
3610 Context.setFILEDecl(Tag->getDecl());
3611 }
3612 }
3613 }
3614
3615 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3616 QualType Jmp_bufType = GetType(Jmp_buf);
3617 if (Jmp_bufType.isNull()) {
3618 Error("jmp_buf type is NULL");
3619 return;
3620 }
3621
3622 if (!Context.jmp_bufDecl) {
3623 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3624 Context.setjmp_bufDecl(Typedef->getDecl());
3625 else {
3626 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3627 if (!Tag) {
3628 Error("Invalid jmp_buf type in AST file");
3629 return;
3630 }
3631 Context.setjmp_bufDecl(Tag->getDecl());
3632 }
3633 }
3634 }
3635
3636 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3637 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3638 if (Sigjmp_bufType.isNull()) {
3639 Error("sigjmp_buf type is NULL");
3640 return;
3641 }
3642
3643 if (!Context.sigjmp_bufDecl) {
3644 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3645 Context.setsigjmp_bufDecl(Typedef->getDecl());
3646 else {
3647 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3648 assert(Tag && "Invalid sigjmp_buf type in AST file");
3649 Context.setsigjmp_bufDecl(Tag->getDecl());
3650 }
3651 }
3652 }
3653
3654 if (unsigned ObjCIdRedef
3655 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3656 if (Context.ObjCIdRedefinitionType.isNull())
3657 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3658 }
3659
3660 if (unsigned ObjCClassRedef
3661 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3662 if (Context.ObjCClassRedefinitionType.isNull())
3663 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3664 }
3665
3666 if (unsigned ObjCSelRedef
3667 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3668 if (Context.ObjCSelRedefinitionType.isNull())
3669 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3670 }
3671
3672 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3673 QualType Ucontext_tType = GetType(Ucontext_t);
3674 if (Ucontext_tType.isNull()) {
3675 Error("ucontext_t type is NULL");
3676 return;
3677 }
3678
3679 if (!Context.ucontext_tDecl) {
3680 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3681 Context.setucontext_tDecl(Typedef->getDecl());
3682 else {
3683 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3684 assert(Tag && "Invalid ucontext_t type in AST file");
3685 Context.setucontext_tDecl(Tag->getDecl());
3686 }
3687 }
3688 }
3689 }
3690
3691 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3692
3693 // If there were any CUDA special declarations, deserialize them.
3694 if (!CUDASpecialDeclRefs.empty()) {
3695 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3696 Context.setcudaConfigureCallDecl(
3697 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3698 }
Richard Smith56be7542014-03-21 00:33:59 +00003699
Guy Benyei11169dd2012-12-18 14:30:41 +00003700 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00003701 // FIXME: This does not make macro-only imports visible again. It also doesn't
3702 // make #includes mapped to module imports visible.
3703 for (auto &Import : ImportedModules) {
3704 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003705 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00003706 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00003707 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003708 }
3709 ImportedModules.clear();
3710}
3711
3712void ASTReader::finalizeForWriting() {
3713 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3714 HiddenEnd = HiddenNamesMap.end();
3715 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003716 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003717 }
3718 HiddenNamesMap.clear();
3719}
3720
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003721/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3722/// cursor into the start of the given block ID, returning false on success and
3723/// true on failure.
3724static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003725 while (1) {
3726 llvm::BitstreamEntry Entry = Cursor.advance();
3727 switch (Entry.Kind) {
3728 case llvm::BitstreamEntry::Error:
3729 case llvm::BitstreamEntry::EndBlock:
3730 return true;
3731
3732 case llvm::BitstreamEntry::Record:
3733 // Ignore top-level records.
3734 Cursor.skipRecord(Entry.ID);
3735 break;
3736
3737 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003738 if (Entry.ID == BlockID) {
3739 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003740 return true;
3741 // Found it!
3742 return false;
3743 }
3744
3745 if (Cursor.SkipBlock())
3746 return true;
3747 }
3748 }
3749}
3750
Guy Benyei11169dd2012-12-18 14:30:41 +00003751/// \brief Retrieve the name of the original source file name
3752/// directly from the AST file, without actually loading the AST
3753/// file.
3754std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3755 FileManager &FileMgr,
3756 DiagnosticsEngine &Diags) {
3757 // Open the AST file.
3758 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003759 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003760 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3761 if (!Buffer) {
3762 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3763 return std::string();
3764 }
3765
3766 // Initialize the stream
3767 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003768 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003769 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3770 (const unsigned char *)Buffer->getBufferEnd());
3771 Stream.init(StreamFile);
3772
3773 // Sniff for the signature.
3774 if (Stream.Read(8) != 'C' ||
3775 Stream.Read(8) != 'P' ||
3776 Stream.Read(8) != 'C' ||
3777 Stream.Read(8) != 'H') {
3778 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3779 return std::string();
3780 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003781
Chris Lattnere7b154b2013-01-19 21:39:22 +00003782 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003783 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003784 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3785 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003786 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003787
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003788 // Scan for ORIGINAL_FILE inside the control block.
3789 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003790 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003791 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003792 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3793 return std::string();
3794
3795 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3796 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3797 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003798 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003799
Guy Benyei11169dd2012-12-18 14:30:41 +00003800 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003801 StringRef Blob;
3802 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3803 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003804 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003805}
3806
3807namespace {
3808 class SimplePCHValidator : public ASTReaderListener {
3809 const LangOptions &ExistingLangOpts;
3810 const TargetOptions &ExistingTargetOpts;
3811 const PreprocessorOptions &ExistingPPOpts;
3812 FileManager &FileMgr;
3813
3814 public:
3815 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3816 const TargetOptions &ExistingTargetOpts,
3817 const PreprocessorOptions &ExistingPPOpts,
3818 FileManager &FileMgr)
3819 : ExistingLangOpts(ExistingLangOpts),
3820 ExistingTargetOpts(ExistingTargetOpts),
3821 ExistingPPOpts(ExistingPPOpts),
3822 FileMgr(FileMgr)
3823 {
3824 }
3825
Craig Topper3e89dfe2014-03-13 02:13:41 +00003826 bool ReadLanguageOptions(const LangOptions &LangOpts,
3827 bool Complain) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003828 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3829 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003830 bool ReadTargetOptions(const TargetOptions &TargetOpts,
3831 bool Complain) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003832 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3833 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003834 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3835 bool Complain,
3836 std::string &SuggestedPredefines) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003837 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003838 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003839 }
3840 };
3841}
3842
3843bool ASTReader::readASTFileControlBlock(StringRef Filename,
3844 FileManager &FileMgr,
3845 ASTReaderListener &Listener) {
3846 // Open the AST file.
3847 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003848 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003849 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3850 if (!Buffer) {
3851 return true;
3852 }
3853
3854 // Initialize the stream
3855 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003856 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003857 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3858 (const unsigned char *)Buffer->getBufferEnd());
3859 Stream.init(StreamFile);
3860
3861 // Sniff for the signature.
3862 if (Stream.Read(8) != 'C' ||
3863 Stream.Read(8) != 'P' ||
3864 Stream.Read(8) != 'C' ||
3865 Stream.Read(8) != 'H') {
3866 return true;
3867 }
3868
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003869 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003870 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003871 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003872
3873 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00003874 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003875 BitstreamCursor InputFilesCursor;
3876 if (NeedsInputFiles) {
3877 InputFilesCursor = Stream;
3878 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
3879 return true;
3880
3881 // Read the abbreviations
3882 while (true) {
3883 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
3884 unsigned Code = InputFilesCursor.ReadCode();
3885
3886 // We expect all abbrevs to be at the start of the block.
3887 if (Code != llvm::bitc::DEFINE_ABBREV) {
3888 InputFilesCursor.JumpToBit(Offset);
3889 break;
3890 }
3891 InputFilesCursor.ReadAbbrevRecord();
3892 }
3893 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003894
3895 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00003896 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003897 while (1) {
3898 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3899 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3900 return false;
3901
3902 if (Entry.Kind != llvm::BitstreamEntry::Record)
3903 return true;
3904
Guy Benyei11169dd2012-12-18 14:30:41 +00003905 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003906 StringRef Blob;
3907 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003908 switch ((ControlRecordTypes)RecCode) {
3909 case METADATA: {
3910 if (Record[0] != VERSION_MAJOR)
3911 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003912
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003913 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003914 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003915
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003916 break;
3917 }
3918 case LANGUAGE_OPTIONS:
3919 if (ParseLanguageOptions(Record, false, Listener))
3920 return true;
3921 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003922
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003923 case TARGET_OPTIONS:
3924 if (ParseTargetOptions(Record, false, Listener))
3925 return true;
3926 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003927
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003928 case DIAGNOSTIC_OPTIONS:
3929 if (ParseDiagnosticOptions(Record, false, Listener))
3930 return true;
3931 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003932
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003933 case FILE_SYSTEM_OPTIONS:
3934 if (ParseFileSystemOptions(Record, false, Listener))
3935 return true;
3936 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003937
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003938 case HEADER_SEARCH_OPTIONS:
3939 if (ParseHeaderSearchOptions(Record, false, Listener))
3940 return true;
3941 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003942
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003943 case PREPROCESSOR_OPTIONS: {
3944 std::string IgnoredSuggestedPredefines;
3945 if (ParsePreprocessorOptions(Record, false, Listener,
3946 IgnoredSuggestedPredefines))
3947 return true;
3948 break;
3949 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003950
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003951 case INPUT_FILE_OFFSETS: {
3952 if (!NeedsInputFiles)
3953 break;
3954
3955 unsigned NumInputFiles = Record[0];
3956 unsigned NumUserFiles = Record[1];
3957 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
3958 for (unsigned I = 0; I != NumInputFiles; ++I) {
3959 // Go find this input file.
3960 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00003961
3962 if (isSystemFile && !NeedsSystemInputFiles)
3963 break; // the rest are system input files
3964
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003965 BitstreamCursor &Cursor = InputFilesCursor;
3966 SavedStreamPosition SavedPosition(Cursor);
3967 Cursor.JumpToBit(InputFileOffs[I]);
3968
3969 unsigned Code = Cursor.ReadCode();
3970 RecordData Record;
3971 StringRef Blob;
3972 bool shouldContinue = false;
3973 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
3974 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00003975 bool Overridden = static_cast<bool>(Record[3]);
3976 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003977 break;
3978 }
3979 if (!shouldContinue)
3980 break;
3981 }
3982 break;
3983 }
3984
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003985 default:
3986 // No other validation to perform.
3987 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003988 }
3989 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003990}
3991
3992
3993bool ASTReader::isAcceptableASTFile(StringRef Filename,
3994 FileManager &FileMgr,
3995 const LangOptions &LangOpts,
3996 const TargetOptions &TargetOpts,
3997 const PreprocessorOptions &PPOpts) {
3998 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3999 return !readASTFileControlBlock(Filename, FileMgr, validator);
4000}
4001
4002bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
4003 // Enter the submodule block.
4004 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4005 Error("malformed submodule block record in AST file");
4006 return true;
4007 }
4008
4009 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4010 bool First = true;
4011 Module *CurrentModule = 0;
4012 RecordData Record;
4013 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004014 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4015
4016 switch (Entry.Kind) {
4017 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4018 case llvm::BitstreamEntry::Error:
4019 Error("malformed block record in AST file");
4020 return true;
4021 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004022 return false;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004023 case llvm::BitstreamEntry::Record:
4024 // The interesting case.
4025 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004026 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004027
Guy Benyei11169dd2012-12-18 14:30:41 +00004028 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004029 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004030 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004031 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004032 default: // Default behavior: ignore.
4033 break;
4034
4035 case SUBMODULE_DEFINITION: {
4036 if (First) {
4037 Error("missing submodule metadata record at beginning of block");
4038 return true;
4039 }
4040
Douglas Gregor8d932422013-03-20 03:59:18 +00004041 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004042 Error("malformed module definition");
4043 return true;
4044 }
4045
Chris Lattner0e6c9402013-01-20 02:38:54 +00004046 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004047 unsigned Idx = 0;
4048 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4049 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4050 bool IsFramework = Record[Idx++];
4051 bool IsExplicit = Record[Idx++];
4052 bool IsSystem = Record[Idx++];
4053 bool IsExternC = Record[Idx++];
4054 bool InferSubmodules = Record[Idx++];
4055 bool InferExplicitSubmodules = Record[Idx++];
4056 bool InferExportWildcard = Record[Idx++];
4057 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004058
Guy Benyei11169dd2012-12-18 14:30:41 +00004059 Module *ParentModule = 0;
4060 if (Parent)
4061 ParentModule = getSubmodule(Parent);
4062
4063 // Retrieve this (sub)module from the module map, creating it if
4064 // necessary.
4065 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
4066 IsFramework,
4067 IsExplicit).first;
4068 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4069 if (GlobalIndex >= SubmodulesLoaded.size() ||
4070 SubmodulesLoaded[GlobalIndex]) {
4071 Error("too many submodules");
4072 return true;
4073 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004074
Douglas Gregor7029ce12013-03-19 00:28:20 +00004075 if (!ParentModule) {
4076 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4077 if (CurFile != F.File) {
4078 if (!Diags.isDiagnosticInFlight()) {
4079 Diag(diag::err_module_file_conflict)
4080 << CurrentModule->getTopLevelModuleName()
4081 << CurFile->getName()
4082 << F.File->getName();
4083 }
4084 return true;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004085 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004086 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004087
4088 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004089 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004090
Guy Benyei11169dd2012-12-18 14:30:41 +00004091 CurrentModule->IsFromModuleFile = true;
4092 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004093 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004094 CurrentModule->InferSubmodules = InferSubmodules;
4095 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4096 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004097 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004098 if (DeserializationListener)
4099 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4100
4101 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004102
Douglas Gregorfb912652013-03-20 21:10:35 +00004103 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004104 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004105 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004106 CurrentModule->UnresolvedConflicts.clear();
4107 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004108 break;
4109 }
4110
4111 case SUBMODULE_UMBRELLA_HEADER: {
4112 if (First) {
4113 Error("missing submodule metadata record at beginning of block");
4114 return true;
4115 }
4116
4117 if (!CurrentModule)
4118 break;
4119
Chris Lattner0e6c9402013-01-20 02:38:54 +00004120 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004121 if (!CurrentModule->getUmbrellaHeader())
4122 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4123 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
4124 Error("mismatched umbrella headers in submodule");
4125 return true;
4126 }
4127 }
4128 break;
4129 }
4130
4131 case SUBMODULE_HEADER: {
4132 if (First) {
4133 Error("missing submodule metadata record at beginning of block");
4134 return true;
4135 }
4136
4137 if (!CurrentModule)
4138 break;
4139
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004140 // We lazily associate headers with their modules via the HeaderInfoTable.
4141 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4142 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004143 break;
4144 }
4145
4146 case SUBMODULE_EXCLUDED_HEADER: {
4147 if (First) {
4148 Error("missing submodule metadata record at beginning of block");
4149 return true;
4150 }
4151
4152 if (!CurrentModule)
4153 break;
4154
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004155 // We lazily associate headers with their modules via the HeaderInfoTable.
4156 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4157 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004158 break;
4159 }
4160
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004161 case SUBMODULE_PRIVATE_HEADER: {
4162 if (First) {
4163 Error("missing submodule metadata record at beginning of block");
4164 return true;
4165 }
4166
4167 if (!CurrentModule)
4168 break;
4169
4170 // We lazily associate headers with their modules via the HeaderInfoTable.
4171 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4172 // of complete filenames or remove it entirely.
4173 break;
4174 }
4175
Guy Benyei11169dd2012-12-18 14:30:41 +00004176 case SUBMODULE_TOPHEADER: {
4177 if (First) {
4178 Error("missing submodule metadata record at beginning of block");
4179 return true;
4180 }
4181
4182 if (!CurrentModule)
4183 break;
4184
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004185 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004186 break;
4187 }
4188
4189 case SUBMODULE_UMBRELLA_DIR: {
4190 if (First) {
4191 Error("missing submodule metadata record at beginning of block");
4192 return true;
4193 }
4194
4195 if (!CurrentModule)
4196 break;
4197
Guy Benyei11169dd2012-12-18 14:30:41 +00004198 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004199 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004200 if (!CurrentModule->getUmbrellaDir())
4201 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4202 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
4203 Error("mismatched umbrella directories in submodule");
4204 return true;
4205 }
4206 }
4207 break;
4208 }
4209
4210 case SUBMODULE_METADATA: {
4211 if (!First) {
4212 Error("submodule metadata record not at beginning of block");
4213 return true;
4214 }
4215 First = false;
4216
4217 F.BaseSubmoduleID = getTotalNumSubmodules();
4218 F.LocalNumSubmodules = Record[0];
4219 unsigned LocalBaseSubmoduleID = Record[1];
4220 if (F.LocalNumSubmodules > 0) {
4221 // Introduce the global -> local mapping for submodules within this
4222 // module.
4223 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4224
4225 // Introduce the local -> global mapping for submodules within this
4226 // module.
4227 F.SubmoduleRemap.insertOrReplace(
4228 std::make_pair(LocalBaseSubmoduleID,
4229 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4230
4231 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4232 }
4233 break;
4234 }
4235
4236 case SUBMODULE_IMPORTS: {
4237 if (First) {
4238 Error("missing submodule metadata record at beginning of block");
4239 return true;
4240 }
4241
4242 if (!CurrentModule)
4243 break;
4244
4245 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004246 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004247 Unresolved.File = &F;
4248 Unresolved.Mod = CurrentModule;
4249 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004250 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004251 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004252 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004253 }
4254 break;
4255 }
4256
4257 case SUBMODULE_EXPORTS: {
4258 if (First) {
4259 Error("missing submodule metadata record at beginning of block");
4260 return true;
4261 }
4262
4263 if (!CurrentModule)
4264 break;
4265
4266 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004267 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 Unresolved.File = &F;
4269 Unresolved.Mod = CurrentModule;
4270 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004271 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004272 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004273 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004274 }
4275
4276 // Once we've loaded the set of exports, there's no reason to keep
4277 // the parsed, unresolved exports around.
4278 CurrentModule->UnresolvedExports.clear();
4279 break;
4280 }
4281 case SUBMODULE_REQUIRES: {
4282 if (First) {
4283 Error("missing submodule metadata record at beginning of block");
4284 return true;
4285 }
4286
4287 if (!CurrentModule)
4288 break;
4289
Richard Smitha3feee22013-10-28 22:18:19 +00004290 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004291 Context.getTargetInfo());
4292 break;
4293 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004294
4295 case SUBMODULE_LINK_LIBRARY:
4296 if (First) {
4297 Error("missing submodule metadata record at beginning of block");
4298 return true;
4299 }
4300
4301 if (!CurrentModule)
4302 break;
4303
4304 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004305 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004306 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004307
4308 case SUBMODULE_CONFIG_MACRO:
4309 if (First) {
4310 Error("missing submodule metadata record at beginning of block");
4311 return true;
4312 }
4313
4314 if (!CurrentModule)
4315 break;
4316
4317 CurrentModule->ConfigMacros.push_back(Blob.str());
4318 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004319
4320 case SUBMODULE_CONFLICT: {
4321 if (First) {
4322 Error("missing submodule metadata record at beginning of block");
4323 return true;
4324 }
4325
4326 if (!CurrentModule)
4327 break;
4328
4329 UnresolvedModuleRef Unresolved;
4330 Unresolved.File = &F;
4331 Unresolved.Mod = CurrentModule;
4332 Unresolved.ID = Record[0];
4333 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4334 Unresolved.IsWildcard = false;
4335 Unresolved.String = Blob;
4336 UnresolvedModuleRefs.push_back(Unresolved);
4337 break;
4338 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 }
4340 }
4341}
4342
4343/// \brief Parse the record that corresponds to a LangOptions data
4344/// structure.
4345///
4346/// This routine parses the language options from the AST file and then gives
4347/// them to the AST listener if one is set.
4348///
4349/// \returns true if the listener deems the file unacceptable, false otherwise.
4350bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4351 bool Complain,
4352 ASTReaderListener &Listener) {
4353 LangOptions LangOpts;
4354 unsigned Idx = 0;
4355#define LANGOPT(Name, Bits, Default, Description) \
4356 LangOpts.Name = Record[Idx++];
4357#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4358 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4359#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004360#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4361#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004362
4363 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4364 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4365 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4366
4367 unsigned Length = Record[Idx++];
4368 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4369 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004370
4371 Idx += Length;
4372
4373 // Comment options.
4374 for (unsigned N = Record[Idx++]; N; --N) {
4375 LangOpts.CommentOpts.BlockCommandNames.push_back(
4376 ReadString(Record, Idx));
4377 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004378 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004379
Guy Benyei11169dd2012-12-18 14:30:41 +00004380 return Listener.ReadLanguageOptions(LangOpts, Complain);
4381}
4382
4383bool ASTReader::ParseTargetOptions(const RecordData &Record,
4384 bool Complain,
4385 ASTReaderListener &Listener) {
4386 unsigned Idx = 0;
4387 TargetOptions TargetOpts;
4388 TargetOpts.Triple = ReadString(Record, Idx);
4389 TargetOpts.CPU = ReadString(Record, Idx);
4390 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004391 TargetOpts.LinkerVersion = ReadString(Record, Idx);
4392 for (unsigned N = Record[Idx++]; N; --N) {
4393 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4394 }
4395 for (unsigned N = Record[Idx++]; N; --N) {
4396 TargetOpts.Features.push_back(ReadString(Record, Idx));
4397 }
4398
4399 return Listener.ReadTargetOptions(TargetOpts, Complain);
4400}
4401
4402bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4403 ASTReaderListener &Listener) {
4404 DiagnosticOptions DiagOpts;
4405 unsigned Idx = 0;
4406#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
4407#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4408 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
4409#include "clang/Basic/DiagnosticOptions.def"
4410
4411 for (unsigned N = Record[Idx++]; N; --N) {
4412 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
4413 }
4414
4415 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4416}
4417
4418bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4419 ASTReaderListener &Listener) {
4420 FileSystemOptions FSOpts;
4421 unsigned Idx = 0;
4422 FSOpts.WorkingDir = ReadString(Record, Idx);
4423 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4424}
4425
4426bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4427 bool Complain,
4428 ASTReaderListener &Listener) {
4429 HeaderSearchOptions HSOpts;
4430 unsigned Idx = 0;
4431 HSOpts.Sysroot = ReadString(Record, Idx);
4432
4433 // Include entries.
4434 for (unsigned N = Record[Idx++]; N; --N) {
4435 std::string Path = ReadString(Record, Idx);
4436 frontend::IncludeDirGroup Group
4437 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004438 bool IsFramework = Record[Idx++];
4439 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004440 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004441 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004442 }
4443
4444 // System header prefixes.
4445 for (unsigned N = Record[Idx++]; N; --N) {
4446 std::string Prefix = ReadString(Record, Idx);
4447 bool IsSystemHeader = Record[Idx++];
4448 HSOpts.SystemHeaderPrefixes.push_back(
4449 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4450 }
4451
4452 HSOpts.ResourceDir = ReadString(Record, Idx);
4453 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004454 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004455 HSOpts.DisableModuleHash = Record[Idx++];
4456 HSOpts.UseBuiltinIncludes = Record[Idx++];
4457 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4458 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4459 HSOpts.UseLibcxx = Record[Idx++];
4460
4461 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4462}
4463
4464bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4465 bool Complain,
4466 ASTReaderListener &Listener,
4467 std::string &SuggestedPredefines) {
4468 PreprocessorOptions PPOpts;
4469 unsigned Idx = 0;
4470
4471 // Macro definitions/undefs
4472 for (unsigned N = Record[Idx++]; N; --N) {
4473 std::string Macro = ReadString(Record, Idx);
4474 bool IsUndef = Record[Idx++];
4475 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4476 }
4477
4478 // Includes
4479 for (unsigned N = Record[Idx++]; N; --N) {
4480 PPOpts.Includes.push_back(ReadString(Record, Idx));
4481 }
4482
4483 // Macro Includes
4484 for (unsigned N = Record[Idx++]; N; --N) {
4485 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4486 }
4487
4488 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004489 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4491 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4492 PPOpts.ObjCXXARCStandardLibrary =
4493 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4494 SuggestedPredefines.clear();
4495 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4496 SuggestedPredefines);
4497}
4498
4499std::pair<ModuleFile *, unsigned>
4500ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4501 GlobalPreprocessedEntityMapType::iterator
4502 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4503 assert(I != GlobalPreprocessedEntityMap.end() &&
4504 "Corrupted global preprocessed entity map");
4505 ModuleFile *M = I->second;
4506 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4507 return std::make_pair(M, LocalIndex);
4508}
4509
4510std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4511ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4512 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4513 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4514 Mod.NumPreprocessedEntities);
4515
4516 return std::make_pair(PreprocessingRecord::iterator(),
4517 PreprocessingRecord::iterator());
4518}
4519
4520std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4521ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4522 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4523 ModuleDeclIterator(this, &Mod,
4524 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4525}
4526
4527PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4528 PreprocessedEntityID PPID = Index+1;
4529 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4530 ModuleFile &M = *PPInfo.first;
4531 unsigned LocalIndex = PPInfo.second;
4532 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4533
Guy Benyei11169dd2012-12-18 14:30:41 +00004534 if (!PP.getPreprocessingRecord()) {
4535 Error("no preprocessing record");
4536 return 0;
4537 }
4538
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004539 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4540 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4541
4542 llvm::BitstreamEntry Entry =
4543 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4544 if (Entry.Kind != llvm::BitstreamEntry::Record)
4545 return 0;
4546
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 // Read the record.
4548 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4549 ReadSourceLocation(M, PPOffs.End));
4550 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004551 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004552 RecordData Record;
4553 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004554 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4555 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004556 switch (RecType) {
4557 case PPD_MACRO_EXPANSION: {
4558 bool isBuiltin = Record[0];
4559 IdentifierInfo *Name = 0;
4560 MacroDefinition *Def = 0;
4561 if (isBuiltin)
4562 Name = getLocalIdentifier(M, Record[1]);
4563 else {
4564 PreprocessedEntityID
4565 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4566 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4567 }
4568
4569 MacroExpansion *ME;
4570 if (isBuiltin)
4571 ME = new (PPRec) MacroExpansion(Name, Range);
4572 else
4573 ME = new (PPRec) MacroExpansion(Def, Range);
4574
4575 return ME;
4576 }
4577
4578 case PPD_MACRO_DEFINITION: {
4579 // Decode the identifier info and then check again; if the macro is
4580 // still defined and associated with the identifier,
4581 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4582 MacroDefinition *MD
4583 = new (PPRec) MacroDefinition(II, Range);
4584
4585 if (DeserializationListener)
4586 DeserializationListener->MacroDefinitionRead(PPID, MD);
4587
4588 return MD;
4589 }
4590
4591 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004592 const char *FullFileNameStart = Blob.data() + Record[0];
4593 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004594 const FileEntry *File = 0;
4595 if (!FullFileName.empty())
4596 File = PP.getFileManager().getFile(FullFileName);
4597
4598 // FIXME: Stable encoding
4599 InclusionDirective::InclusionKind Kind
4600 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4601 InclusionDirective *ID
4602 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004603 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004604 Record[1], Record[3],
4605 File,
4606 Range);
4607 return ID;
4608 }
4609 }
4610
4611 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4612}
4613
4614/// \brief \arg SLocMapI points at a chunk of a module that contains no
4615/// preprocessed entities or the entities it contains are not the ones we are
4616/// looking for. Find the next module that contains entities and return the ID
4617/// of the first entry.
4618PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4619 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4620 ++SLocMapI;
4621 for (GlobalSLocOffsetMapType::const_iterator
4622 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4623 ModuleFile &M = *SLocMapI->second;
4624 if (M.NumPreprocessedEntities)
4625 return M.BasePreprocessedEntityID;
4626 }
4627
4628 return getTotalNumPreprocessedEntities();
4629}
4630
4631namespace {
4632
4633template <unsigned PPEntityOffset::*PPLoc>
4634struct PPEntityComp {
4635 const ASTReader &Reader;
4636 ModuleFile &M;
4637
4638 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4639
4640 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4641 SourceLocation LHS = getLoc(L);
4642 SourceLocation RHS = getLoc(R);
4643 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4644 }
4645
4646 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4647 SourceLocation LHS = getLoc(L);
4648 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4649 }
4650
4651 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4652 SourceLocation RHS = getLoc(R);
4653 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4654 }
4655
4656 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4657 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4658 }
4659};
4660
4661}
4662
4663/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4664PreprocessedEntityID
4665ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4666 if (SourceMgr.isLocalSourceLocation(BLoc))
4667 return getTotalNumPreprocessedEntities();
4668
4669 GlobalSLocOffsetMapType::const_iterator
4670 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004671 BLoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004672 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4673 "Corrupted global sloc offset map");
4674
4675 if (SLocMapI->second->NumPreprocessedEntities == 0)
4676 return findNextPreprocessedEntity(SLocMapI);
4677
4678 ModuleFile &M = *SLocMapI->second;
4679 typedef const PPEntityOffset *pp_iterator;
4680 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4681 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4682
4683 size_t Count = M.NumPreprocessedEntities;
4684 size_t Half;
4685 pp_iterator First = pp_begin;
4686 pp_iterator PPI;
4687
4688 // Do a binary search manually instead of using std::lower_bound because
4689 // The end locations of entities may be unordered (when a macro expansion
4690 // is inside another macro argument), but for this case it is not important
4691 // whether we get the first macro expansion or its containing macro.
4692 while (Count > 0) {
4693 Half = Count/2;
4694 PPI = First;
4695 std::advance(PPI, Half);
4696 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4697 BLoc)){
4698 First = PPI;
4699 ++First;
4700 Count = Count - Half - 1;
4701 } else
4702 Count = Half;
4703 }
4704
4705 if (PPI == pp_end)
4706 return findNextPreprocessedEntity(SLocMapI);
4707
4708 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4709}
4710
4711/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4712PreprocessedEntityID
4713ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4714 if (SourceMgr.isLocalSourceLocation(ELoc))
4715 return getTotalNumPreprocessedEntities();
4716
4717 GlobalSLocOffsetMapType::const_iterator
4718 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004719 ELoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004720 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4721 "Corrupted global sloc offset map");
4722
4723 if (SLocMapI->second->NumPreprocessedEntities == 0)
4724 return findNextPreprocessedEntity(SLocMapI);
4725
4726 ModuleFile &M = *SLocMapI->second;
4727 typedef const PPEntityOffset *pp_iterator;
4728 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4729 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4730 pp_iterator PPI =
4731 std::upper_bound(pp_begin, pp_end, ELoc,
4732 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4733
4734 if (PPI == pp_end)
4735 return findNextPreprocessedEntity(SLocMapI);
4736
4737 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4738}
4739
4740/// \brief Returns a pair of [Begin, End) indices of preallocated
4741/// preprocessed entities that \arg Range encompasses.
4742std::pair<unsigned, unsigned>
4743 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4744 if (Range.isInvalid())
4745 return std::make_pair(0,0);
4746 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4747
4748 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4749 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4750 return std::make_pair(BeginID, EndID);
4751}
4752
4753/// \brief Optionally returns true or false if the preallocated preprocessed
4754/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004755Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004756 FileID FID) {
4757 if (FID.isInvalid())
4758 return false;
4759
4760 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4761 ModuleFile &M = *PPInfo.first;
4762 unsigned LocalIndex = PPInfo.second;
4763 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4764
4765 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4766 if (Loc.isInvalid())
4767 return false;
4768
4769 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4770 return true;
4771 else
4772 return false;
4773}
4774
4775namespace {
4776 /// \brief Visitor used to search for information about a header file.
4777 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004778 const FileEntry *FE;
4779
David Blaikie05785d12013-02-20 22:23:23 +00004780 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004781
4782 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004783 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4784 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004785
4786 static bool visit(ModuleFile &M, void *UserData) {
4787 HeaderFileInfoVisitor *This
4788 = static_cast<HeaderFileInfoVisitor *>(UserData);
4789
Guy Benyei11169dd2012-12-18 14:30:41 +00004790 HeaderFileInfoLookupTable *Table
4791 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4792 if (!Table)
4793 return false;
4794
4795 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004796 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004797 if (Pos == Table->end())
4798 return false;
4799
4800 This->HFI = *Pos;
4801 return true;
4802 }
4803
David Blaikie05785d12013-02-20 22:23:23 +00004804 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004805 };
4806}
4807
4808HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004809 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004810 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004811 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004812 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004813
4814 return HeaderFileInfo();
4815}
4816
4817void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4818 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004819 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004820 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4821 ModuleFile &F = *(*I);
4822 unsigned Idx = 0;
4823 DiagStates.clear();
4824 assert(!Diag.DiagStates.empty());
4825 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4826 while (Idx < F.PragmaDiagMappings.size()) {
4827 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4828 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4829 if (DiagStateID != 0) {
4830 Diag.DiagStatePoints.push_back(
4831 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4832 FullSourceLoc(Loc, SourceMgr)));
4833 continue;
4834 }
4835
4836 assert(DiagStateID == 0);
4837 // A new DiagState was created here.
4838 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4839 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4840 DiagStates.push_back(NewState);
4841 Diag.DiagStatePoints.push_back(
4842 DiagnosticsEngine::DiagStatePoint(NewState,
4843 FullSourceLoc(Loc, SourceMgr)));
4844 while (1) {
4845 assert(Idx < F.PragmaDiagMappings.size() &&
4846 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4847 if (Idx >= F.PragmaDiagMappings.size()) {
4848 break; // Something is messed up but at least avoid infinite loop in
4849 // release build.
4850 }
4851 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4852 if (DiagID == (unsigned)-1) {
4853 break; // no more diag/map pairs for this location.
4854 }
4855 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4856 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4857 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4858 }
4859 }
4860 }
4861}
4862
4863/// \brief Get the correct cursor and offset for loading a type.
4864ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4865 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4866 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4867 ModuleFile *M = I->second;
4868 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4869}
4870
4871/// \brief Read and return the type with the given index..
4872///
4873/// The index is the type ID, shifted and minus the number of predefs. This
4874/// routine actually reads the record corresponding to the type at the given
4875/// location. It is a helper routine for GetType, which deals with reading type
4876/// IDs.
4877QualType ASTReader::readTypeRecord(unsigned Index) {
4878 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004879 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004880
4881 // Keep track of where we are in the stream, then jump back there
4882 // after reading this type.
4883 SavedStreamPosition SavedPosition(DeclsCursor);
4884
4885 ReadingKindTracker ReadingKind(Read_Type, *this);
4886
4887 // Note that we are loading a type record.
4888 Deserializing AType(this);
4889
4890 unsigned Idx = 0;
4891 DeclsCursor.JumpToBit(Loc.Offset);
4892 RecordData Record;
4893 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004894 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004895 case TYPE_EXT_QUAL: {
4896 if (Record.size() != 2) {
4897 Error("Incorrect encoding of extended qualifier type");
4898 return QualType();
4899 }
4900 QualType Base = readType(*Loc.F, Record, Idx);
4901 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4902 return Context.getQualifiedType(Base, Quals);
4903 }
4904
4905 case TYPE_COMPLEX: {
4906 if (Record.size() != 1) {
4907 Error("Incorrect encoding of complex type");
4908 return QualType();
4909 }
4910 QualType ElemType = readType(*Loc.F, Record, Idx);
4911 return Context.getComplexType(ElemType);
4912 }
4913
4914 case TYPE_POINTER: {
4915 if (Record.size() != 1) {
4916 Error("Incorrect encoding of pointer type");
4917 return QualType();
4918 }
4919 QualType PointeeType = readType(*Loc.F, Record, Idx);
4920 return Context.getPointerType(PointeeType);
4921 }
4922
Reid Kleckner8a365022013-06-24 17:51:48 +00004923 case TYPE_DECAYED: {
4924 if (Record.size() != 1) {
4925 Error("Incorrect encoding of decayed type");
4926 return QualType();
4927 }
4928 QualType OriginalType = readType(*Loc.F, Record, Idx);
4929 QualType DT = Context.getAdjustedParameterType(OriginalType);
4930 if (!isa<DecayedType>(DT))
4931 Error("Decayed type does not decay");
4932 return DT;
4933 }
4934
Reid Kleckner0503a872013-12-05 01:23:43 +00004935 case TYPE_ADJUSTED: {
4936 if (Record.size() != 2) {
4937 Error("Incorrect encoding of adjusted type");
4938 return QualType();
4939 }
4940 QualType OriginalTy = readType(*Loc.F, Record, Idx);
4941 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
4942 return Context.getAdjustedType(OriginalTy, AdjustedTy);
4943 }
4944
Guy Benyei11169dd2012-12-18 14:30:41 +00004945 case TYPE_BLOCK_POINTER: {
4946 if (Record.size() != 1) {
4947 Error("Incorrect encoding of block pointer type");
4948 return QualType();
4949 }
4950 QualType PointeeType = readType(*Loc.F, Record, Idx);
4951 return Context.getBlockPointerType(PointeeType);
4952 }
4953
4954 case TYPE_LVALUE_REFERENCE: {
4955 if (Record.size() != 2) {
4956 Error("Incorrect encoding of lvalue reference type");
4957 return QualType();
4958 }
4959 QualType PointeeType = readType(*Loc.F, Record, Idx);
4960 return Context.getLValueReferenceType(PointeeType, Record[1]);
4961 }
4962
4963 case TYPE_RVALUE_REFERENCE: {
4964 if (Record.size() != 1) {
4965 Error("Incorrect encoding of rvalue reference type");
4966 return QualType();
4967 }
4968 QualType PointeeType = readType(*Loc.F, Record, Idx);
4969 return Context.getRValueReferenceType(PointeeType);
4970 }
4971
4972 case TYPE_MEMBER_POINTER: {
4973 if (Record.size() != 2) {
4974 Error("Incorrect encoding of member pointer type");
4975 return QualType();
4976 }
4977 QualType PointeeType = readType(*Loc.F, Record, Idx);
4978 QualType ClassType = readType(*Loc.F, Record, Idx);
4979 if (PointeeType.isNull() || ClassType.isNull())
4980 return QualType();
4981
4982 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4983 }
4984
4985 case TYPE_CONSTANT_ARRAY: {
4986 QualType ElementType = readType(*Loc.F, Record, Idx);
4987 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4988 unsigned IndexTypeQuals = Record[2];
4989 unsigned Idx = 3;
4990 llvm::APInt Size = ReadAPInt(Record, Idx);
4991 return Context.getConstantArrayType(ElementType, Size,
4992 ASM, IndexTypeQuals);
4993 }
4994
4995 case TYPE_INCOMPLETE_ARRAY: {
4996 QualType ElementType = readType(*Loc.F, Record, Idx);
4997 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4998 unsigned IndexTypeQuals = Record[2];
4999 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5000 }
5001
5002 case TYPE_VARIABLE_ARRAY: {
5003 QualType ElementType = readType(*Loc.F, Record, Idx);
5004 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5005 unsigned IndexTypeQuals = Record[2];
5006 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5007 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5008 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5009 ASM, IndexTypeQuals,
5010 SourceRange(LBLoc, RBLoc));
5011 }
5012
5013 case TYPE_VECTOR: {
5014 if (Record.size() != 3) {
5015 Error("incorrect encoding of vector type in AST file");
5016 return QualType();
5017 }
5018
5019 QualType ElementType = readType(*Loc.F, Record, Idx);
5020 unsigned NumElements = Record[1];
5021 unsigned VecKind = Record[2];
5022 return Context.getVectorType(ElementType, NumElements,
5023 (VectorType::VectorKind)VecKind);
5024 }
5025
5026 case TYPE_EXT_VECTOR: {
5027 if (Record.size() != 3) {
5028 Error("incorrect encoding of extended vector type in AST file");
5029 return QualType();
5030 }
5031
5032 QualType ElementType = readType(*Loc.F, Record, Idx);
5033 unsigned NumElements = Record[1];
5034 return Context.getExtVectorType(ElementType, NumElements);
5035 }
5036
5037 case TYPE_FUNCTION_NO_PROTO: {
5038 if (Record.size() != 6) {
5039 Error("incorrect encoding of no-proto function type");
5040 return QualType();
5041 }
5042 QualType ResultType = readType(*Loc.F, Record, Idx);
5043 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5044 (CallingConv)Record[4], Record[5]);
5045 return Context.getFunctionNoProtoType(ResultType, Info);
5046 }
5047
5048 case TYPE_FUNCTION_PROTO: {
5049 QualType ResultType = readType(*Loc.F, Record, Idx);
5050
5051 FunctionProtoType::ExtProtoInfo EPI;
5052 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5053 /*hasregparm*/ Record[2],
5054 /*regparm*/ Record[3],
5055 static_cast<CallingConv>(Record[4]),
5056 /*produces*/ Record[5]);
5057
5058 unsigned Idx = 6;
5059 unsigned NumParams = Record[Idx++];
5060 SmallVector<QualType, 16> ParamTypes;
5061 for (unsigned I = 0; I != NumParams; ++I)
5062 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5063
5064 EPI.Variadic = Record[Idx++];
5065 EPI.HasTrailingReturn = Record[Idx++];
5066 EPI.TypeQuals = Record[Idx++];
5067 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005068 SmallVector<QualType, 8> ExceptionStorage;
5069 readExceptionSpec(*Loc.F, ExceptionStorage, EPI, Record, Idx);
Jordan Rose5c382722013-03-08 21:51:21 +00005070 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 }
5072
5073 case TYPE_UNRESOLVED_USING: {
5074 unsigned Idx = 0;
5075 return Context.getTypeDeclType(
5076 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5077 }
5078
5079 case TYPE_TYPEDEF: {
5080 if (Record.size() != 2) {
5081 Error("incorrect encoding of typedef type");
5082 return QualType();
5083 }
5084 unsigned Idx = 0;
5085 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5086 QualType Canonical = readType(*Loc.F, Record, Idx);
5087 if (!Canonical.isNull())
5088 Canonical = Context.getCanonicalType(Canonical);
5089 return Context.getTypedefType(Decl, Canonical);
5090 }
5091
5092 case TYPE_TYPEOF_EXPR:
5093 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5094
5095 case TYPE_TYPEOF: {
5096 if (Record.size() != 1) {
5097 Error("incorrect encoding of typeof(type) in AST file");
5098 return QualType();
5099 }
5100 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5101 return Context.getTypeOfType(UnderlyingType);
5102 }
5103
5104 case TYPE_DECLTYPE: {
5105 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5106 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5107 }
5108
5109 case TYPE_UNARY_TRANSFORM: {
5110 QualType BaseType = readType(*Loc.F, Record, Idx);
5111 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5112 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5113 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5114 }
5115
Richard Smith74aeef52013-04-26 16:15:35 +00005116 case TYPE_AUTO: {
5117 QualType Deduced = readType(*Loc.F, Record, Idx);
5118 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005119 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005120 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005121 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005122
5123 case TYPE_RECORD: {
5124 if (Record.size() != 2) {
5125 Error("incorrect encoding of record type");
5126 return QualType();
5127 }
5128 unsigned Idx = 0;
5129 bool IsDependent = Record[Idx++];
5130 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5131 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5132 QualType T = Context.getRecordType(RD);
5133 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5134 return T;
5135 }
5136
5137 case TYPE_ENUM: {
5138 if (Record.size() != 2) {
5139 Error("incorrect encoding of enum type");
5140 return QualType();
5141 }
5142 unsigned Idx = 0;
5143 bool IsDependent = Record[Idx++];
5144 QualType T
5145 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5146 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5147 return T;
5148 }
5149
5150 case TYPE_ATTRIBUTED: {
5151 if (Record.size() != 3) {
5152 Error("incorrect encoding of attributed type");
5153 return QualType();
5154 }
5155 QualType modifiedType = readType(*Loc.F, Record, Idx);
5156 QualType equivalentType = readType(*Loc.F, Record, Idx);
5157 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5158 return Context.getAttributedType(kind, modifiedType, equivalentType);
5159 }
5160
5161 case TYPE_PAREN: {
5162 if (Record.size() != 1) {
5163 Error("incorrect encoding of paren type");
5164 return QualType();
5165 }
5166 QualType InnerType = readType(*Loc.F, Record, Idx);
5167 return Context.getParenType(InnerType);
5168 }
5169
5170 case TYPE_PACK_EXPANSION: {
5171 if (Record.size() != 2) {
5172 Error("incorrect encoding of pack expansion type");
5173 return QualType();
5174 }
5175 QualType Pattern = readType(*Loc.F, Record, Idx);
5176 if (Pattern.isNull())
5177 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005178 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005179 if (Record[1])
5180 NumExpansions = Record[1] - 1;
5181 return Context.getPackExpansionType(Pattern, NumExpansions);
5182 }
5183
5184 case TYPE_ELABORATED: {
5185 unsigned Idx = 0;
5186 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5187 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5188 QualType NamedType = readType(*Loc.F, Record, Idx);
5189 return Context.getElaboratedType(Keyword, NNS, NamedType);
5190 }
5191
5192 case TYPE_OBJC_INTERFACE: {
5193 unsigned Idx = 0;
5194 ObjCInterfaceDecl *ItfD
5195 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5196 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5197 }
5198
5199 case TYPE_OBJC_OBJECT: {
5200 unsigned Idx = 0;
5201 QualType Base = readType(*Loc.F, Record, Idx);
5202 unsigned NumProtos = Record[Idx++];
5203 SmallVector<ObjCProtocolDecl*, 4> Protos;
5204 for (unsigned I = 0; I != NumProtos; ++I)
5205 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5206 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5207 }
5208
5209 case TYPE_OBJC_OBJECT_POINTER: {
5210 unsigned Idx = 0;
5211 QualType Pointee = readType(*Loc.F, Record, Idx);
5212 return Context.getObjCObjectPointerType(Pointee);
5213 }
5214
5215 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5216 unsigned Idx = 0;
5217 QualType Parm = readType(*Loc.F, Record, Idx);
5218 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005219 return Context.getSubstTemplateTypeParmType(
5220 cast<TemplateTypeParmType>(Parm),
5221 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005222 }
5223
5224 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5225 unsigned Idx = 0;
5226 QualType Parm = readType(*Loc.F, Record, Idx);
5227 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5228 return Context.getSubstTemplateTypeParmPackType(
5229 cast<TemplateTypeParmType>(Parm),
5230 ArgPack);
5231 }
5232
5233 case TYPE_INJECTED_CLASS_NAME: {
5234 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5235 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5236 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5237 // for AST reading, too much interdependencies.
5238 return
5239 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
5240 }
5241
5242 case TYPE_TEMPLATE_TYPE_PARM: {
5243 unsigned Idx = 0;
5244 unsigned Depth = Record[Idx++];
5245 unsigned Index = Record[Idx++];
5246 bool Pack = Record[Idx++];
5247 TemplateTypeParmDecl *D
5248 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5249 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5250 }
5251
5252 case TYPE_DEPENDENT_NAME: {
5253 unsigned Idx = 0;
5254 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5255 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5256 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5257 QualType Canon = readType(*Loc.F, Record, Idx);
5258 if (!Canon.isNull())
5259 Canon = Context.getCanonicalType(Canon);
5260 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5261 }
5262
5263 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5264 unsigned Idx = 0;
5265 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5266 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5267 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5268 unsigned NumArgs = Record[Idx++];
5269 SmallVector<TemplateArgument, 8> Args;
5270 Args.reserve(NumArgs);
5271 while (NumArgs--)
5272 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5273 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5274 Args.size(), Args.data());
5275 }
5276
5277 case TYPE_DEPENDENT_SIZED_ARRAY: {
5278 unsigned Idx = 0;
5279
5280 // ArrayType
5281 QualType ElementType = readType(*Loc.F, Record, Idx);
5282 ArrayType::ArraySizeModifier ASM
5283 = (ArrayType::ArraySizeModifier)Record[Idx++];
5284 unsigned IndexTypeQuals = Record[Idx++];
5285
5286 // DependentSizedArrayType
5287 Expr *NumElts = ReadExpr(*Loc.F);
5288 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5289
5290 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5291 IndexTypeQuals, Brackets);
5292 }
5293
5294 case TYPE_TEMPLATE_SPECIALIZATION: {
5295 unsigned Idx = 0;
5296 bool IsDependent = Record[Idx++];
5297 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5298 SmallVector<TemplateArgument, 8> Args;
5299 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5300 QualType Underlying = readType(*Loc.F, Record, Idx);
5301 QualType T;
5302 if (Underlying.isNull())
5303 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5304 Args.size());
5305 else
5306 T = Context.getTemplateSpecializationType(Name, Args.data(),
5307 Args.size(), Underlying);
5308 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5309 return T;
5310 }
5311
5312 case TYPE_ATOMIC: {
5313 if (Record.size() != 1) {
5314 Error("Incorrect encoding of atomic type");
5315 return QualType();
5316 }
5317 QualType ValueType = readType(*Loc.F, Record, Idx);
5318 return Context.getAtomicType(ValueType);
5319 }
5320 }
5321 llvm_unreachable("Invalid TypeCode!");
5322}
5323
Richard Smith564417a2014-03-20 21:47:22 +00005324void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5325 SmallVectorImpl<QualType> &Exceptions,
5326 FunctionProtoType::ExtProtoInfo &EPI,
5327 const RecordData &Record, unsigned &Idx) {
5328 ExceptionSpecificationType EST =
5329 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5330 EPI.ExceptionSpecType = EST;
5331 if (EST == EST_Dynamic) {
5332 EPI.NumExceptions = Record[Idx++];
5333 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5334 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5335 EPI.Exceptions = Exceptions.data();
5336 } else if (EST == EST_ComputedNoexcept) {
5337 EPI.NoexceptExpr = ReadExpr(ModuleFile);
5338 } else if (EST == EST_Uninstantiated) {
5339 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5340 EPI.ExceptionSpecTemplate =
5341 ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5342 } else if (EST == EST_Unevaluated) {
5343 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5344 }
5345}
5346
Guy Benyei11169dd2012-12-18 14:30:41 +00005347class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5348 ASTReader &Reader;
5349 ModuleFile &F;
5350 const ASTReader::RecordData &Record;
5351 unsigned &Idx;
5352
5353 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5354 unsigned &I) {
5355 return Reader.ReadSourceLocation(F, R, I);
5356 }
5357
5358 template<typename T>
5359 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5360 return Reader.ReadDeclAs<T>(F, Record, Idx);
5361 }
5362
5363public:
5364 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5365 const ASTReader::RecordData &Record, unsigned &Idx)
5366 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5367 { }
5368
5369 // We want compile-time assurance that we've enumerated all of
5370 // these, so unfortunately we have to declare them first, then
5371 // define them out-of-line.
5372#define ABSTRACT_TYPELOC(CLASS, PARENT)
5373#define TYPELOC(CLASS, PARENT) \
5374 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5375#include "clang/AST/TypeLocNodes.def"
5376
5377 void VisitFunctionTypeLoc(FunctionTypeLoc);
5378 void VisitArrayTypeLoc(ArrayTypeLoc);
5379};
5380
5381void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5382 // nothing to do
5383}
5384void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5385 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5386 if (TL.needsExtraLocalData()) {
5387 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5388 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5389 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5390 TL.setModeAttr(Record[Idx++]);
5391 }
5392}
5393void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5394 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5395}
5396void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5397 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5398}
Reid Kleckner8a365022013-06-24 17:51:48 +00005399void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5400 // nothing to do
5401}
Reid Kleckner0503a872013-12-05 01:23:43 +00005402void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5403 // nothing to do
5404}
Guy Benyei11169dd2012-12-18 14:30:41 +00005405void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5406 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5407}
5408void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5409 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5410}
5411void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5412 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5413}
5414void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5415 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5416 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5417}
5418void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5419 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5420 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5421 if (Record[Idx++])
5422 TL.setSizeExpr(Reader.ReadExpr(F));
5423 else
5424 TL.setSizeExpr(0);
5425}
5426void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5427 VisitArrayTypeLoc(TL);
5428}
5429void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5430 VisitArrayTypeLoc(TL);
5431}
5432void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5433 VisitArrayTypeLoc(TL);
5434}
5435void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5436 DependentSizedArrayTypeLoc TL) {
5437 VisitArrayTypeLoc(TL);
5438}
5439void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5440 DependentSizedExtVectorTypeLoc TL) {
5441 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5442}
5443void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5444 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5445}
5446void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5447 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5448}
5449void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5450 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5451 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5452 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5453 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005454 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5455 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005456 }
5457}
5458void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5459 VisitFunctionTypeLoc(TL);
5460}
5461void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5462 VisitFunctionTypeLoc(TL);
5463}
5464void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5465 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5466}
5467void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5468 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5469}
5470void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5471 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5472 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5473 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5474}
5475void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5476 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5477 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5478 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5479 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5480}
5481void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5482 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5483}
5484void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5485 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5486 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5487 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5488 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5489}
5490void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5491 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5492}
5493void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5494 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5495}
5496void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5497 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5498}
5499void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5500 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5501 if (TL.hasAttrOperand()) {
5502 SourceRange range;
5503 range.setBegin(ReadSourceLocation(Record, Idx));
5504 range.setEnd(ReadSourceLocation(Record, Idx));
5505 TL.setAttrOperandParensRange(range);
5506 }
5507 if (TL.hasAttrExprOperand()) {
5508 if (Record[Idx++])
5509 TL.setAttrExprOperand(Reader.ReadExpr(F));
5510 else
5511 TL.setAttrExprOperand(0);
5512 } else if (TL.hasAttrEnumOperand())
5513 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5514}
5515void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5516 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5517}
5518void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5519 SubstTemplateTypeParmTypeLoc TL) {
5520 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5521}
5522void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5523 SubstTemplateTypeParmPackTypeLoc TL) {
5524 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5525}
5526void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5527 TemplateSpecializationTypeLoc TL) {
5528 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5529 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5530 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5531 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5532 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5533 TL.setArgLocInfo(i,
5534 Reader.GetTemplateArgumentLocInfo(F,
5535 TL.getTypePtr()->getArg(i).getKind(),
5536 Record, Idx));
5537}
5538void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5539 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5540 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5541}
5542void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5543 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5544 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5545}
5546void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5547 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5548}
5549void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5550 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5551 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5552 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5553}
5554void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5555 DependentTemplateSpecializationTypeLoc TL) {
5556 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5557 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5558 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5559 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5560 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5561 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5562 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5563 TL.setArgLocInfo(I,
5564 Reader.GetTemplateArgumentLocInfo(F,
5565 TL.getTypePtr()->getArg(I).getKind(),
5566 Record, Idx));
5567}
5568void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5569 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5570}
5571void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5572 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5573}
5574void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5575 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5576 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5577 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5578 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5579 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5580}
5581void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5582 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5583}
5584void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5585 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5586 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5587 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5588}
5589
5590TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5591 const RecordData &Record,
5592 unsigned &Idx) {
5593 QualType InfoTy = readType(F, Record, Idx);
5594 if (InfoTy.isNull())
5595 return 0;
5596
5597 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5598 TypeLocReader TLR(*this, F, Record, Idx);
5599 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5600 TLR.Visit(TL);
5601 return TInfo;
5602}
5603
5604QualType ASTReader::GetType(TypeID ID) {
5605 unsigned FastQuals = ID & Qualifiers::FastMask;
5606 unsigned Index = ID >> Qualifiers::FastWidth;
5607
5608 if (Index < NUM_PREDEF_TYPE_IDS) {
5609 QualType T;
5610 switch ((PredefinedTypeIDs)Index) {
5611 case PREDEF_TYPE_NULL_ID: return QualType();
5612 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5613 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5614
5615 case PREDEF_TYPE_CHAR_U_ID:
5616 case PREDEF_TYPE_CHAR_S_ID:
5617 // FIXME: Check that the signedness of CharTy is correct!
5618 T = Context.CharTy;
5619 break;
5620
5621 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5622 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5623 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5624 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5625 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5626 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5627 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5628 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5629 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5630 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5631 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5632 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5633 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5634 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5635 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5636 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5637 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5638 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5639 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5640 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5641 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5642 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5643 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5644 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5645 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5646 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5647 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5648 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005649 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5650 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5651 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5652 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5653 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5654 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005655 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005656 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005657 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5658
5659 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5660 T = Context.getAutoRRefDeductType();
5661 break;
5662
5663 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5664 T = Context.ARCUnbridgedCastTy;
5665 break;
5666
5667 case PREDEF_TYPE_VA_LIST_TAG:
5668 T = Context.getVaListTagType();
5669 break;
5670
5671 case PREDEF_TYPE_BUILTIN_FN:
5672 T = Context.BuiltinFnTy;
5673 break;
5674 }
5675
5676 assert(!T.isNull() && "Unknown predefined type");
5677 return T.withFastQualifiers(FastQuals);
5678 }
5679
5680 Index -= NUM_PREDEF_TYPE_IDS;
5681 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5682 if (TypesLoaded[Index].isNull()) {
5683 TypesLoaded[Index] = readTypeRecord(Index);
5684 if (TypesLoaded[Index].isNull())
5685 return QualType();
5686
5687 TypesLoaded[Index]->setFromAST();
5688 if (DeserializationListener)
5689 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5690 TypesLoaded[Index]);
5691 }
5692
5693 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5694}
5695
5696QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5697 return GetType(getGlobalTypeID(F, LocalID));
5698}
5699
5700serialization::TypeID
5701ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5702 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5703 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5704
5705 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5706 return LocalID;
5707
5708 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5709 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5710 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5711
5712 unsigned GlobalIndex = LocalIndex + I->second;
5713 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5714}
5715
5716TemplateArgumentLocInfo
5717ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5718 TemplateArgument::ArgKind Kind,
5719 const RecordData &Record,
5720 unsigned &Index) {
5721 switch (Kind) {
5722 case TemplateArgument::Expression:
5723 return ReadExpr(F);
5724 case TemplateArgument::Type:
5725 return GetTypeSourceInfo(F, Record, Index);
5726 case TemplateArgument::Template: {
5727 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5728 Index);
5729 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5730 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5731 SourceLocation());
5732 }
5733 case TemplateArgument::TemplateExpansion: {
5734 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5735 Index);
5736 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5737 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5738 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5739 EllipsisLoc);
5740 }
5741 case TemplateArgument::Null:
5742 case TemplateArgument::Integral:
5743 case TemplateArgument::Declaration:
5744 case TemplateArgument::NullPtr:
5745 case TemplateArgument::Pack:
5746 // FIXME: Is this right?
5747 return TemplateArgumentLocInfo();
5748 }
5749 llvm_unreachable("unexpected template argument loc");
5750}
5751
5752TemplateArgumentLoc
5753ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5754 const RecordData &Record, unsigned &Index) {
5755 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5756
5757 if (Arg.getKind() == TemplateArgument::Expression) {
5758 if (Record[Index++]) // bool InfoHasSameExpr.
5759 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5760 }
5761 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5762 Record, Index));
5763}
5764
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005765const ASTTemplateArgumentListInfo*
5766ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5767 const RecordData &Record,
5768 unsigned &Index) {
5769 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5770 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5771 unsigned NumArgsAsWritten = Record[Index++];
5772 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5773 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5774 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5775 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5776}
5777
Guy Benyei11169dd2012-12-18 14:30:41 +00005778Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5779 return GetDecl(ID);
5780}
5781
5782uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5783 unsigned &Idx){
5784 if (Idx >= Record.size())
5785 return 0;
5786
5787 unsigned LocalID = Record[Idx++];
5788 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5789}
5790
5791CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5792 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005793 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005794 SavedStreamPosition SavedPosition(Cursor);
5795 Cursor.JumpToBit(Loc.Offset);
5796 ReadingKindTracker ReadingKind(Read_Decl, *this);
5797 RecordData Record;
5798 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005799 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005800 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5801 Error("Malformed AST file: missing C++ base specifiers");
5802 return 0;
5803 }
5804
5805 unsigned Idx = 0;
5806 unsigned NumBases = Record[Idx++];
5807 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5808 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5809 for (unsigned I = 0; I != NumBases; ++I)
5810 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5811 return Bases;
5812}
5813
5814serialization::DeclID
5815ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5816 if (LocalID < NUM_PREDEF_DECL_IDS)
5817 return LocalID;
5818
5819 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5820 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5821 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5822
5823 return LocalID + I->second;
5824}
5825
5826bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5827 ModuleFile &M) const {
5828 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5829 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5830 return &M == I->second;
5831}
5832
Douglas Gregor9f782892013-01-21 15:25:38 +00005833ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005834 if (!D->isFromASTFile())
5835 return 0;
5836 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5837 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5838 return I->second;
5839}
5840
5841SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5842 if (ID < NUM_PREDEF_DECL_IDS)
5843 return SourceLocation();
5844
5845 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5846
5847 if (Index > DeclsLoaded.size()) {
5848 Error("declaration ID out-of-range for AST file");
5849 return SourceLocation();
5850 }
5851
5852 if (Decl *D = DeclsLoaded[Index])
5853 return D->getLocation();
5854
5855 unsigned RawLocation = 0;
5856 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5857 return ReadSourceLocation(*Rec.F, RawLocation);
5858}
5859
5860Decl *ASTReader::GetDecl(DeclID ID) {
5861 if (ID < NUM_PREDEF_DECL_IDS) {
5862 switch ((PredefinedDeclIDs)ID) {
5863 case PREDEF_DECL_NULL_ID:
5864 return 0;
5865
5866 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5867 return Context.getTranslationUnitDecl();
5868
5869 case PREDEF_DECL_OBJC_ID_ID:
5870 return Context.getObjCIdDecl();
5871
5872 case PREDEF_DECL_OBJC_SEL_ID:
5873 return Context.getObjCSelDecl();
5874
5875 case PREDEF_DECL_OBJC_CLASS_ID:
5876 return Context.getObjCClassDecl();
5877
5878 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5879 return Context.getObjCProtocolDecl();
5880
5881 case PREDEF_DECL_INT_128_ID:
5882 return Context.getInt128Decl();
5883
5884 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5885 return Context.getUInt128Decl();
5886
5887 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5888 return Context.getObjCInstanceTypeDecl();
5889
5890 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5891 return Context.getBuiltinVaListDecl();
5892 }
5893 }
5894
5895 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5896
5897 if (Index >= DeclsLoaded.size()) {
5898 assert(0 && "declaration ID out-of-range for AST file");
5899 Error("declaration ID out-of-range for AST file");
5900 return 0;
5901 }
5902
5903 if (!DeclsLoaded[Index]) {
5904 ReadDeclRecord(ID);
5905 if (DeserializationListener)
5906 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5907 }
5908
5909 return DeclsLoaded[Index];
5910}
5911
5912DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5913 DeclID GlobalID) {
5914 if (GlobalID < NUM_PREDEF_DECL_IDS)
5915 return GlobalID;
5916
5917 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5918 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5919 ModuleFile *Owner = I->second;
5920
5921 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5922 = M.GlobalToLocalDeclIDs.find(Owner);
5923 if (Pos == M.GlobalToLocalDeclIDs.end())
5924 return 0;
5925
5926 return GlobalID - Owner->BaseDeclID + Pos->second;
5927}
5928
5929serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5930 const RecordData &Record,
5931 unsigned &Idx) {
5932 if (Idx >= Record.size()) {
5933 Error("Corrupted AST file");
5934 return 0;
5935 }
5936
5937 return getGlobalDeclID(F, Record[Idx++]);
5938}
5939
5940/// \brief Resolve the offset of a statement into a statement.
5941///
5942/// This operation will read a new statement from the external
5943/// source each time it is called, and is meant to be used via a
5944/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5945Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5946 // Switch case IDs are per Decl.
5947 ClearSwitchCaseIDs();
5948
5949 // Offset here is a global offset across the entire chain.
5950 RecordLocation Loc = getLocalBitOffset(Offset);
5951 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5952 return ReadStmtFromStream(*Loc.F);
5953}
5954
5955namespace {
5956 class FindExternalLexicalDeclsVisitor {
5957 ASTReader &Reader;
5958 const DeclContext *DC;
5959 bool (*isKindWeWant)(Decl::Kind);
5960
5961 SmallVectorImpl<Decl*> &Decls;
5962 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5963
5964 public:
5965 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5966 bool (*isKindWeWant)(Decl::Kind),
5967 SmallVectorImpl<Decl*> &Decls)
5968 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5969 {
5970 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5971 PredefsVisited[I] = false;
5972 }
5973
5974 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5975 if (Preorder)
5976 return false;
5977
5978 FindExternalLexicalDeclsVisitor *This
5979 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5980
5981 ModuleFile::DeclContextInfosMap::iterator Info
5982 = M.DeclContextInfos.find(This->DC);
5983 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5984 return false;
5985
5986 // Load all of the declaration IDs
5987 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5988 *IDE = ID + Info->second.NumLexicalDecls;
5989 ID != IDE; ++ID) {
5990 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5991 continue;
5992
5993 // Don't add predefined declarations to the lexical context more
5994 // than once.
5995 if (ID->second < NUM_PREDEF_DECL_IDS) {
5996 if (This->PredefsVisited[ID->second])
5997 continue;
5998
5999 This->PredefsVisited[ID->second] = true;
6000 }
6001
6002 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6003 if (!This->DC->isDeclInLexicalTraversal(D))
6004 This->Decls.push_back(D);
6005 }
6006 }
6007
6008 return false;
6009 }
6010 };
6011}
6012
6013ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6014 bool (*isKindWeWant)(Decl::Kind),
6015 SmallVectorImpl<Decl*> &Decls) {
6016 // There might be lexical decls in multiple modules, for the TU at
6017 // least. Walk all of the modules in the order they were loaded.
6018 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6019 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6020 ++NumLexicalDeclContextsRead;
6021 return ELR_Success;
6022}
6023
6024namespace {
6025
6026class DeclIDComp {
6027 ASTReader &Reader;
6028 ModuleFile &Mod;
6029
6030public:
6031 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6032
6033 bool operator()(LocalDeclID L, LocalDeclID R) const {
6034 SourceLocation LHS = getLocation(L);
6035 SourceLocation RHS = getLocation(R);
6036 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6037 }
6038
6039 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6040 SourceLocation RHS = getLocation(R);
6041 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6042 }
6043
6044 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6045 SourceLocation LHS = getLocation(L);
6046 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6047 }
6048
6049 SourceLocation getLocation(LocalDeclID ID) const {
6050 return Reader.getSourceManager().getFileLoc(
6051 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6052 }
6053};
6054
6055}
6056
6057void ASTReader::FindFileRegionDecls(FileID File,
6058 unsigned Offset, unsigned Length,
6059 SmallVectorImpl<Decl *> &Decls) {
6060 SourceManager &SM = getSourceManager();
6061
6062 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6063 if (I == FileDeclIDs.end())
6064 return;
6065
6066 FileDeclsInfo &DInfo = I->second;
6067 if (DInfo.Decls.empty())
6068 return;
6069
6070 SourceLocation
6071 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6072 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6073
6074 DeclIDComp DIDComp(*this, *DInfo.Mod);
6075 ArrayRef<serialization::LocalDeclID>::iterator
6076 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6077 BeginLoc, DIDComp);
6078 if (BeginIt != DInfo.Decls.begin())
6079 --BeginIt;
6080
6081 // If we are pointing at a top-level decl inside an objc container, we need
6082 // to backtrack until we find it otherwise we will fail to report that the
6083 // region overlaps with an objc container.
6084 while (BeginIt != DInfo.Decls.begin() &&
6085 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6086 ->isTopLevelDeclInObjCContainer())
6087 --BeginIt;
6088
6089 ArrayRef<serialization::LocalDeclID>::iterator
6090 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6091 EndLoc, DIDComp);
6092 if (EndIt != DInfo.Decls.end())
6093 ++EndIt;
6094
6095 for (ArrayRef<serialization::LocalDeclID>::iterator
6096 DIt = BeginIt; DIt != EndIt; ++DIt)
6097 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6098}
6099
6100namespace {
6101 /// \brief ModuleFile visitor used to perform name lookup into a
6102 /// declaration context.
6103 class DeclContextNameLookupVisitor {
6104 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006105 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006106 DeclarationName Name;
6107 SmallVectorImpl<NamedDecl *> &Decls;
6108
6109 public:
6110 DeclContextNameLookupVisitor(ASTReader &Reader,
6111 SmallVectorImpl<const DeclContext *> &Contexts,
6112 DeclarationName Name,
6113 SmallVectorImpl<NamedDecl *> &Decls)
6114 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6115
6116 static bool visit(ModuleFile &M, void *UserData) {
6117 DeclContextNameLookupVisitor *This
6118 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6119
6120 // Check whether we have any visible declaration information for
6121 // this context in this module.
6122 ModuleFile::DeclContextInfosMap::iterator Info;
6123 bool FoundInfo = false;
6124 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6125 Info = M.DeclContextInfos.find(This->Contexts[I]);
6126 if (Info != M.DeclContextInfos.end() &&
6127 Info->second.NameLookupTableData) {
6128 FoundInfo = true;
6129 break;
6130 }
6131 }
6132
6133 if (!FoundInfo)
6134 return false;
6135
6136 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006137 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006138 Info->second.NameLookupTableData;
6139 ASTDeclContextNameLookupTable::iterator Pos
6140 = LookupTable->find(This->Name);
6141 if (Pos == LookupTable->end())
6142 return false;
6143
6144 bool FoundAnything = false;
6145 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6146 for (; Data.first != Data.second; ++Data.first) {
6147 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6148 if (!ND)
6149 continue;
6150
6151 if (ND->getDeclName() != This->Name) {
6152 // A name might be null because the decl's redeclarable part is
6153 // currently read before reading its name. The lookup is triggered by
6154 // building that decl (likely indirectly), and so it is later in the
6155 // sense of "already existing" and can be ignored here.
6156 continue;
6157 }
6158
6159 // Record this declaration.
6160 FoundAnything = true;
6161 This->Decls.push_back(ND);
6162 }
6163
6164 return FoundAnything;
6165 }
6166 };
6167}
6168
Douglas Gregor9f782892013-01-21 15:25:38 +00006169/// \brief Retrieve the "definitive" module file for the definition of the
6170/// given declaration context, if there is one.
6171///
6172/// The "definitive" module file is the only place where we need to look to
6173/// find information about the declarations within the given declaration
6174/// context. For example, C++ and Objective-C classes, C structs/unions, and
6175/// Objective-C protocols, categories, and extensions are all defined in a
6176/// single place in the source code, so they have definitive module files
6177/// associated with them. C++ namespaces, on the other hand, can have
6178/// definitions in multiple different module files.
6179///
6180/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6181/// NDEBUG checking.
6182static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6183 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006184 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6185 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006186
6187 return 0;
6188}
6189
Richard Smith9ce12e32013-02-07 03:30:24 +00006190bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006191ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6192 DeclarationName Name) {
6193 assert(DC->hasExternalVisibleStorage() &&
6194 "DeclContext has no visible decls in storage");
6195 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006196 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006197
6198 SmallVector<NamedDecl *, 64> Decls;
6199
6200 // Compute the declaration contexts we need to look into. Multiple such
6201 // declaration contexts occur when two declaration contexts from disjoint
6202 // modules get merged, e.g., when two namespaces with the same name are
6203 // independently defined in separate modules.
6204 SmallVector<const DeclContext *, 2> Contexts;
6205 Contexts.push_back(DC);
6206
6207 if (DC->isNamespace()) {
6208 MergedDeclsMap::iterator Merged
6209 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6210 if (Merged != MergedDecls.end()) {
6211 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6212 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6213 }
6214 }
6215
6216 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006217
6218 // If we can definitively determine which module file to look into,
6219 // only look there. Otherwise, look in all module files.
6220 ModuleFile *Definitive;
6221 if (Contexts.size() == 1 &&
6222 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6223 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6224 } else {
6225 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6226 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006227 ++NumVisibleDeclContextsRead;
6228 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006229 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006230}
6231
6232namespace {
6233 /// \brief ModuleFile visitor used to retrieve all visible names in a
6234 /// declaration context.
6235 class DeclContextAllNamesVisitor {
6236 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006237 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006238 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006239 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006240
6241 public:
6242 DeclContextAllNamesVisitor(ASTReader &Reader,
6243 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006244 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006245 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006246
6247 static bool visit(ModuleFile &M, void *UserData) {
6248 DeclContextAllNamesVisitor *This
6249 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6250
6251 // Check whether we have any visible declaration information for
6252 // this context in this module.
6253 ModuleFile::DeclContextInfosMap::iterator Info;
6254 bool FoundInfo = false;
6255 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6256 Info = M.DeclContextInfos.find(This->Contexts[I]);
6257 if (Info != M.DeclContextInfos.end() &&
6258 Info->second.NameLookupTableData) {
6259 FoundInfo = true;
6260 break;
6261 }
6262 }
6263
6264 if (!FoundInfo)
6265 return false;
6266
Richard Smith52e3fba2014-03-11 07:17:35 +00006267 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006268 Info->second.NameLookupTableData;
6269 bool FoundAnything = false;
6270 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006271 I = LookupTable->data_begin(), E = LookupTable->data_end();
6272 I != E;
6273 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006274 ASTDeclContextNameLookupTrait::data_type Data = *I;
6275 for (; Data.first != Data.second; ++Data.first) {
6276 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6277 *Data.first);
6278 if (!ND)
6279 continue;
6280
6281 // Record this declaration.
6282 FoundAnything = true;
6283 This->Decls[ND->getDeclName()].push_back(ND);
6284 }
6285 }
6286
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006287 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006288 }
6289 };
6290}
6291
6292void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6293 if (!DC->hasExternalVisibleStorage())
6294 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006295 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006296
6297 // Compute the declaration contexts we need to look into. Multiple such
6298 // declaration contexts occur when two declaration contexts from disjoint
6299 // modules get merged, e.g., when two namespaces with the same name are
6300 // independently defined in separate modules.
6301 SmallVector<const DeclContext *, 2> Contexts;
6302 Contexts.push_back(DC);
6303
6304 if (DC->isNamespace()) {
6305 MergedDeclsMap::iterator Merged
6306 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6307 if (Merged != MergedDecls.end()) {
6308 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6309 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6310 }
6311 }
6312
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006313 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6314 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006315 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6316 ++NumVisibleDeclContextsRead;
6317
Craig Topper79be4cd2013-07-05 04:33:53 +00006318 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006319 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6320 }
6321 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6322}
6323
6324/// \brief Under non-PCH compilation the consumer receives the objc methods
6325/// before receiving the implementation, and codegen depends on this.
6326/// We simulate this by deserializing and passing to consumer the methods of the
6327/// implementation before passing the deserialized implementation decl.
6328static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6329 ASTConsumer *Consumer) {
6330 assert(ImplD && Consumer);
6331
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006332 for (auto *I : ImplD->methods())
6333 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006334
6335 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6336}
6337
6338void ASTReader::PassInterestingDeclsToConsumer() {
6339 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006340
6341 if (PassingDeclsToConsumer)
6342 return;
6343
6344 // Guard variable to avoid recursively redoing the process of passing
6345 // decls to consumer.
6346 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6347 true);
6348
Guy Benyei11169dd2012-12-18 14:30:41 +00006349 while (!InterestingDecls.empty()) {
6350 Decl *D = InterestingDecls.front();
6351 InterestingDecls.pop_front();
6352
6353 PassInterestingDeclToConsumer(D);
6354 }
6355}
6356
6357void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6358 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6359 PassObjCImplDeclToConsumer(ImplD, Consumer);
6360 else
6361 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6362}
6363
6364void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6365 this->Consumer = Consumer;
6366
6367 if (!Consumer)
6368 return;
6369
Ben Langmuir332aafe2014-01-31 01:06:56 +00006370 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006371 // Force deserialization of this decl, which will cause it to be queued for
6372 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006373 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006374 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006375 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006376
6377 PassInterestingDeclsToConsumer();
6378}
6379
6380void ASTReader::PrintStats() {
6381 std::fprintf(stderr, "*** AST File Statistics:\n");
6382
6383 unsigned NumTypesLoaded
6384 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6385 QualType());
6386 unsigned NumDeclsLoaded
6387 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6388 (Decl *)0);
6389 unsigned NumIdentifiersLoaded
6390 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6391 IdentifiersLoaded.end(),
6392 (IdentifierInfo *)0);
6393 unsigned NumMacrosLoaded
6394 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6395 MacrosLoaded.end(),
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006396 (MacroInfo *)0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006397 unsigned NumSelectorsLoaded
6398 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6399 SelectorsLoaded.end(),
6400 Selector());
6401
6402 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6403 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6404 NumSLocEntriesRead, TotalNumSLocEntries,
6405 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6406 if (!TypesLoaded.empty())
6407 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6408 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6409 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6410 if (!DeclsLoaded.empty())
6411 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6412 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6413 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6414 if (!IdentifiersLoaded.empty())
6415 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6416 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6417 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6418 if (!MacrosLoaded.empty())
6419 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6420 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6421 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6422 if (!SelectorsLoaded.empty())
6423 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6424 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6425 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6426 if (TotalNumStatements)
6427 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6428 NumStatementsRead, TotalNumStatements,
6429 ((float)NumStatementsRead/TotalNumStatements * 100));
6430 if (TotalNumMacros)
6431 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6432 NumMacrosRead, TotalNumMacros,
6433 ((float)NumMacrosRead/TotalNumMacros * 100));
6434 if (TotalLexicalDeclContexts)
6435 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6436 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6437 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6438 * 100));
6439 if (TotalVisibleDeclContexts)
6440 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6441 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6442 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6443 * 100));
6444 if (TotalNumMethodPoolEntries) {
6445 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6446 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6447 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6448 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006449 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006450 if (NumMethodPoolLookups) {
6451 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6452 NumMethodPoolHits, NumMethodPoolLookups,
6453 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6454 }
6455 if (NumMethodPoolTableLookups) {
6456 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6457 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6458 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6459 * 100.0));
6460 }
6461
Douglas Gregor00a50f72013-01-25 00:38:33 +00006462 if (NumIdentifierLookupHits) {
6463 std::fprintf(stderr,
6464 " %u / %u identifier table lookups succeeded (%f%%)\n",
6465 NumIdentifierLookupHits, NumIdentifierLookups,
6466 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6467 }
6468
Douglas Gregore060e572013-01-25 01:03:03 +00006469 if (GlobalIndex) {
6470 std::fprintf(stderr, "\n");
6471 GlobalIndex->printStats();
6472 }
6473
Guy Benyei11169dd2012-12-18 14:30:41 +00006474 std::fprintf(stderr, "\n");
6475 dump();
6476 std::fprintf(stderr, "\n");
6477}
6478
6479template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6480static void
6481dumpModuleIDMap(StringRef Name,
6482 const ContinuousRangeMap<Key, ModuleFile *,
6483 InitialCapacity> &Map) {
6484 if (Map.begin() == Map.end())
6485 return;
6486
6487 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6488 llvm::errs() << Name << ":\n";
6489 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6490 I != IEnd; ++I) {
6491 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6492 << "\n";
6493 }
6494}
6495
6496void ASTReader::dump() {
6497 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6498 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6499 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6500 dumpModuleIDMap("Global type map", GlobalTypeMap);
6501 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6502 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6503 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6504 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6505 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6506 dumpModuleIDMap("Global preprocessed entity map",
6507 GlobalPreprocessedEntityMap);
6508
6509 llvm::errs() << "\n*** PCH/Modules Loaded:";
6510 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6511 MEnd = ModuleMgr.end();
6512 M != MEnd; ++M)
6513 (*M)->dump();
6514}
6515
6516/// Return the amount of memory used by memory buffers, breaking down
6517/// by heap-backed versus mmap'ed memory.
6518void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6519 for (ModuleConstIterator I = ModuleMgr.begin(),
6520 E = ModuleMgr.end(); I != E; ++I) {
6521 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6522 size_t bytes = buf->getBufferSize();
6523 switch (buf->getBufferKind()) {
6524 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6525 sizes.malloc_bytes += bytes;
6526 break;
6527 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6528 sizes.mmap_bytes += bytes;
6529 break;
6530 }
6531 }
6532 }
6533}
6534
6535void ASTReader::InitializeSema(Sema &S) {
6536 SemaObj = &S;
6537 S.addExternalSource(this);
6538
6539 // Makes sure any declarations that were deserialized "too early"
6540 // still get added to the identifier's declaration chains.
6541 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006542 pushExternalDeclIntoScope(PreloadedDecls[I],
6543 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006544 }
6545 PreloadedDecls.clear();
6546
Richard Smith3d8e97e2013-10-18 06:54:39 +00006547 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006548 if (!FPPragmaOptions.empty()) {
6549 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6550 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6551 }
6552
Richard Smith3d8e97e2013-10-18 06:54:39 +00006553 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006554 if (!OpenCLExtensions.empty()) {
6555 unsigned I = 0;
6556#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6557#include "clang/Basic/OpenCLExtensions.def"
6558
6559 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6560 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006561
6562 UpdateSema();
6563}
6564
6565void ASTReader::UpdateSema() {
6566 assert(SemaObj && "no Sema to update");
6567
6568 // Load the offsets of the declarations that Sema references.
6569 // They will be lazily deserialized when needed.
6570 if (!SemaDeclRefs.empty()) {
6571 assert(SemaDeclRefs.size() % 2 == 0);
6572 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6573 if (!SemaObj->StdNamespace)
6574 SemaObj->StdNamespace = SemaDeclRefs[I];
6575 if (!SemaObj->StdBadAlloc)
6576 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6577 }
6578 SemaDeclRefs.clear();
6579 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006580}
6581
6582IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6583 // Note that we are loading an identifier.
6584 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006585 StringRef Name(NameStart, NameEnd - NameStart);
6586
6587 // If there is a global index, look there first to determine which modules
6588 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006589 GlobalModuleIndex::HitSet Hits;
6590 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00006591 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006592 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6593 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006594 }
6595 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006596 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006597 NumIdentifierLookups,
6598 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006599 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006600 IdentifierInfo *II = Visitor.getIdentifierInfo();
6601 markIdentifierUpToDate(II);
6602 return II;
6603}
6604
6605namespace clang {
6606 /// \brief An identifier-lookup iterator that enumerates all of the
6607 /// identifiers stored within a set of AST files.
6608 class ASTIdentifierIterator : public IdentifierIterator {
6609 /// \brief The AST reader whose identifiers are being enumerated.
6610 const ASTReader &Reader;
6611
6612 /// \brief The current index into the chain of AST files stored in
6613 /// the AST reader.
6614 unsigned Index;
6615
6616 /// \brief The current position within the identifier lookup table
6617 /// of the current AST file.
6618 ASTIdentifierLookupTable::key_iterator Current;
6619
6620 /// \brief The end position within the identifier lookup table of
6621 /// the current AST file.
6622 ASTIdentifierLookupTable::key_iterator End;
6623
6624 public:
6625 explicit ASTIdentifierIterator(const ASTReader &Reader);
6626
Craig Topper3e89dfe2014-03-13 02:13:41 +00006627 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006628 };
6629}
6630
6631ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6632 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6633 ASTIdentifierLookupTable *IdTable
6634 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6635 Current = IdTable->key_begin();
6636 End = IdTable->key_end();
6637}
6638
6639StringRef ASTIdentifierIterator::Next() {
6640 while (Current == End) {
6641 // If we have exhausted all of our AST files, we're done.
6642 if (Index == 0)
6643 return StringRef();
6644
6645 --Index;
6646 ASTIdentifierLookupTable *IdTable
6647 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6648 IdentifierLookupTable;
6649 Current = IdTable->key_begin();
6650 End = IdTable->key_end();
6651 }
6652
6653 // We have any identifiers remaining in the current AST file; return
6654 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006655 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006656 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006657 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006658}
6659
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006660IdentifierIterator *ASTReader::getIdentifiers() {
6661 if (!loadGlobalIndex())
6662 return GlobalIndex->createIdentifierIterator();
6663
Guy Benyei11169dd2012-12-18 14:30:41 +00006664 return new ASTIdentifierIterator(*this);
6665}
6666
6667namespace clang { namespace serialization {
6668 class ReadMethodPoolVisitor {
6669 ASTReader &Reader;
6670 Selector Sel;
6671 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006672 unsigned InstanceBits;
6673 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006674 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6675 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006676
6677 public:
6678 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6679 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006680 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6681 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006682
6683 static bool visit(ModuleFile &M, void *UserData) {
6684 ReadMethodPoolVisitor *This
6685 = static_cast<ReadMethodPoolVisitor *>(UserData);
6686
6687 if (!M.SelectorLookupTable)
6688 return false;
6689
6690 // If we've already searched this module file, skip it now.
6691 if (M.Generation <= This->PriorGeneration)
6692 return true;
6693
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006694 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006695 ASTSelectorLookupTable *PoolTable
6696 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6697 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6698 if (Pos == PoolTable->end())
6699 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006700
6701 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006702 ++This->Reader.NumSelectorsRead;
6703 // FIXME: Not quite happy with the statistics here. We probably should
6704 // disable this tracking when called via LoadSelector.
6705 // Also, should entries without methods count as misses?
6706 ++This->Reader.NumMethodPoolEntriesRead;
6707 ASTSelectorLookupTrait::data_type Data = *Pos;
6708 if (This->Reader.DeserializationListener)
6709 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6710 This->Sel);
6711
6712 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6713 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006714 This->InstanceBits = Data.InstanceBits;
6715 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006716 return true;
6717 }
6718
6719 /// \brief Retrieve the instance methods found by this visitor.
6720 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6721 return InstanceMethods;
6722 }
6723
6724 /// \brief Retrieve the instance methods found by this visitor.
6725 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6726 return FactoryMethods;
6727 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006728
6729 unsigned getInstanceBits() const { return InstanceBits; }
6730 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006731 };
6732} } // end namespace clang::serialization
6733
6734/// \brief Add the given set of methods to the method list.
6735static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6736 ObjCMethodList &List) {
6737 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6738 S.addMethodToGlobalList(&List, Methods[I]);
6739 }
6740}
6741
6742void ASTReader::ReadMethodPool(Selector Sel) {
6743 // Get the selector generation and update it to the current generation.
6744 unsigned &Generation = SelectorGeneration[Sel];
6745 unsigned PriorGeneration = Generation;
6746 Generation = CurrentGeneration;
6747
6748 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006749 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006750 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6751 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6752
6753 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006754 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006755 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006756
6757 ++NumMethodPoolHits;
6758
Guy Benyei11169dd2012-12-18 14:30:41 +00006759 if (!getSema())
6760 return;
6761
6762 Sema &S = *getSema();
6763 Sema::GlobalMethodPool::iterator Pos
6764 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6765
6766 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6767 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006768 Pos->second.first.setBits(Visitor.getInstanceBits());
6769 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00006770}
6771
6772void ASTReader::ReadKnownNamespaces(
6773 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6774 Namespaces.clear();
6775
6776 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6777 if (NamespaceDecl *Namespace
6778 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6779 Namespaces.push_back(Namespace);
6780 }
6781}
6782
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006783void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00006784 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006785 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6786 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00006787 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006788 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00006789 Undefined.insert(std::make_pair(D, Loc));
6790 }
6791}
Nick Lewycky8334af82013-01-26 00:35:08 +00006792
Guy Benyei11169dd2012-12-18 14:30:41 +00006793void ASTReader::ReadTentativeDefinitions(
6794 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6795 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6796 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6797 if (Var)
6798 TentativeDefs.push_back(Var);
6799 }
6800 TentativeDefinitions.clear();
6801}
6802
6803void ASTReader::ReadUnusedFileScopedDecls(
6804 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6805 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6806 DeclaratorDecl *D
6807 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6808 if (D)
6809 Decls.push_back(D);
6810 }
6811 UnusedFileScopedDecls.clear();
6812}
6813
6814void ASTReader::ReadDelegatingConstructors(
6815 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6816 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6817 CXXConstructorDecl *D
6818 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6819 if (D)
6820 Decls.push_back(D);
6821 }
6822 DelegatingCtorDecls.clear();
6823}
6824
6825void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6826 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6827 TypedefNameDecl *D
6828 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6829 if (D)
6830 Decls.push_back(D);
6831 }
6832 ExtVectorDecls.clear();
6833}
6834
6835void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6836 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6837 CXXRecordDecl *D
6838 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6839 if (D)
6840 Decls.push_back(D);
6841 }
6842 DynamicClasses.clear();
6843}
6844
6845void
Richard Smith78165b52013-01-10 23:43:47 +00006846ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6847 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6848 NamedDecl *D
6849 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006850 if (D)
6851 Decls.push_back(D);
6852 }
Richard Smith78165b52013-01-10 23:43:47 +00006853 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006854}
6855
6856void ASTReader::ReadReferencedSelectors(
6857 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6858 if (ReferencedSelectorsData.empty())
6859 return;
6860
6861 // If there are @selector references added them to its pool. This is for
6862 // implementation of -Wselector.
6863 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6864 unsigned I = 0;
6865 while (I < DataSize) {
6866 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6867 SourceLocation SelLoc
6868 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6869 Sels.push_back(std::make_pair(Sel, SelLoc));
6870 }
6871 ReferencedSelectorsData.clear();
6872}
6873
6874void ASTReader::ReadWeakUndeclaredIdentifiers(
6875 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6876 if (WeakUndeclaredIdentifiers.empty())
6877 return;
6878
6879 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6880 IdentifierInfo *WeakId
6881 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6882 IdentifierInfo *AliasId
6883 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6884 SourceLocation Loc
6885 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6886 bool Used = WeakUndeclaredIdentifiers[I++];
6887 WeakInfo WI(AliasId, Loc);
6888 WI.setUsed(Used);
6889 WeakIDs.push_back(std::make_pair(WeakId, WI));
6890 }
6891 WeakUndeclaredIdentifiers.clear();
6892}
6893
6894void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6895 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6896 ExternalVTableUse VT;
6897 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6898 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6899 VT.DefinitionRequired = VTableUses[Idx++];
6900 VTables.push_back(VT);
6901 }
6902
6903 VTableUses.clear();
6904}
6905
6906void ASTReader::ReadPendingInstantiations(
6907 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6908 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6909 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6910 SourceLocation Loc
6911 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6912
6913 Pending.push_back(std::make_pair(D, Loc));
6914 }
6915 PendingInstantiations.clear();
6916}
6917
Richard Smithe40f2ba2013-08-07 21:41:30 +00006918void ASTReader::ReadLateParsedTemplates(
6919 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
6920 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
6921 /* In loop */) {
6922 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
6923
6924 LateParsedTemplate *LT = new LateParsedTemplate;
6925 LT->D = GetDecl(LateParsedTemplates[Idx++]);
6926
6927 ModuleFile *F = getOwningModuleFile(LT->D);
6928 assert(F && "No module");
6929
6930 unsigned TokN = LateParsedTemplates[Idx++];
6931 LT->Toks.reserve(TokN);
6932 for (unsigned T = 0; T < TokN; ++T)
6933 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
6934
6935 LPTMap[FD] = LT;
6936 }
6937
6938 LateParsedTemplates.clear();
6939}
6940
Guy Benyei11169dd2012-12-18 14:30:41 +00006941void ASTReader::LoadSelector(Selector Sel) {
6942 // It would be complicated to avoid reading the methods anyway. So don't.
6943 ReadMethodPool(Sel);
6944}
6945
6946void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6947 assert(ID && "Non-zero identifier ID required");
6948 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6949 IdentifiersLoaded[ID - 1] = II;
6950 if (DeserializationListener)
6951 DeserializationListener->IdentifierRead(ID, II);
6952}
6953
6954/// \brief Set the globally-visible declarations associated with the given
6955/// identifier.
6956///
6957/// If the AST reader is currently in a state where the given declaration IDs
6958/// cannot safely be resolved, they are queued until it is safe to resolve
6959/// them.
6960///
6961/// \param II an IdentifierInfo that refers to one or more globally-visible
6962/// declarations.
6963///
6964/// \param DeclIDs the set of declaration IDs with the name @p II that are
6965/// visible at global scope.
6966///
Douglas Gregor6168bd22013-02-18 15:53:43 +00006967/// \param Decls if non-null, this vector will be populated with the set of
6968/// deserialized declarations. These declarations will not be pushed into
6969/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00006970void
6971ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6972 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00006973 SmallVectorImpl<Decl *> *Decls) {
6974 if (NumCurrentElementsDeserializing && !Decls) {
6975 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00006976 return;
6977 }
6978
6979 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6980 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6981 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00006982 // If we're simply supposed to record the declarations, do so now.
6983 if (Decls) {
6984 Decls->push_back(D);
6985 continue;
6986 }
6987
Guy Benyei11169dd2012-12-18 14:30:41 +00006988 // Introduce this declaration into the translation-unit scope
6989 // and add it to the declaration chain for this identifier, so
6990 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006991 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00006992 } else {
6993 // Queue this declaration so that it will be added to the
6994 // translation unit scope and identifier's declaration chain
6995 // once a Sema object is known.
6996 PreloadedDecls.push_back(D);
6997 }
6998 }
6999}
7000
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007001IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007002 if (ID == 0)
7003 return 0;
7004
7005 if (IdentifiersLoaded.empty()) {
7006 Error("no identifier table in AST file");
7007 return 0;
7008 }
7009
7010 ID -= 1;
7011 if (!IdentifiersLoaded[ID]) {
7012 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7013 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7014 ModuleFile *M = I->second;
7015 unsigned Index = ID - M->BaseIdentifierID;
7016 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7017
7018 // All of the strings in the AST file are preceded by a 16-bit length.
7019 // Extract that 16-bit length to avoid having to execute strlen().
7020 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7021 // unsigned integers. This is important to avoid integer overflow when
7022 // we cast them to 'unsigned'.
7023 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7024 unsigned StrLen = (((unsigned) StrLenPtr[0])
7025 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007026 IdentifiersLoaded[ID]
7027 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007028 if (DeserializationListener)
7029 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7030 }
7031
7032 return IdentifiersLoaded[ID];
7033}
7034
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007035IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7036 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007037}
7038
7039IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7040 if (LocalID < NUM_PREDEF_IDENT_IDS)
7041 return LocalID;
7042
7043 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7044 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7045 assert(I != M.IdentifierRemap.end()
7046 && "Invalid index into identifier index remap");
7047
7048 return LocalID + I->second;
7049}
7050
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007051MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007052 if (ID == 0)
7053 return 0;
7054
7055 if (MacrosLoaded.empty()) {
7056 Error("no macro table in AST file");
7057 return 0;
7058 }
7059
7060 ID -= NUM_PREDEF_MACRO_IDS;
7061 if (!MacrosLoaded[ID]) {
7062 GlobalMacroMapType::iterator I
7063 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7064 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7065 ModuleFile *M = I->second;
7066 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007067 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7068
7069 if (DeserializationListener)
7070 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7071 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007072 }
7073
7074 return MacrosLoaded[ID];
7075}
7076
7077MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7078 if (LocalID < NUM_PREDEF_MACRO_IDS)
7079 return LocalID;
7080
7081 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7082 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7083 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7084
7085 return LocalID + I->second;
7086}
7087
7088serialization::SubmoduleID
7089ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7090 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7091 return LocalID;
7092
7093 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7094 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7095 assert(I != M.SubmoduleRemap.end()
7096 && "Invalid index into submodule index remap");
7097
7098 return LocalID + I->second;
7099}
7100
7101Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7102 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7103 assert(GlobalID == 0 && "Unhandled global submodule ID");
7104 return 0;
7105 }
7106
7107 if (GlobalID > SubmodulesLoaded.size()) {
7108 Error("submodule ID out of range in AST file");
7109 return 0;
7110 }
7111
7112 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7113}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007114
7115Module *ASTReader::getModule(unsigned ID) {
7116 return getSubmodule(ID);
7117}
7118
Guy Benyei11169dd2012-12-18 14:30:41 +00007119Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7120 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7121}
7122
7123Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7124 if (ID == 0)
7125 return Selector();
7126
7127 if (ID > SelectorsLoaded.size()) {
7128 Error("selector ID out of range in AST file");
7129 return Selector();
7130 }
7131
7132 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
7133 // Load this selector from the selector table.
7134 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7135 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7136 ModuleFile &M = *I->second;
7137 ASTSelectorLookupTrait Trait(*this, M);
7138 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7139 SelectorsLoaded[ID - 1] =
7140 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7141 if (DeserializationListener)
7142 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7143 }
7144
7145 return SelectorsLoaded[ID - 1];
7146}
7147
7148Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7149 return DecodeSelector(ID);
7150}
7151
7152uint32_t ASTReader::GetNumExternalSelectors() {
7153 // ID 0 (the null selector) is considered an external selector.
7154 return getTotalNumSelectors() + 1;
7155}
7156
7157serialization::SelectorID
7158ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7159 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7160 return LocalID;
7161
7162 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7163 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7164 assert(I != M.SelectorRemap.end()
7165 && "Invalid index into selector index remap");
7166
7167 return LocalID + I->second;
7168}
7169
7170DeclarationName
7171ASTReader::ReadDeclarationName(ModuleFile &F,
7172 const RecordData &Record, unsigned &Idx) {
7173 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7174 switch (Kind) {
7175 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007176 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007177
7178 case DeclarationName::ObjCZeroArgSelector:
7179 case DeclarationName::ObjCOneArgSelector:
7180 case DeclarationName::ObjCMultiArgSelector:
7181 return DeclarationName(ReadSelector(F, Record, Idx));
7182
7183 case DeclarationName::CXXConstructorName:
7184 return Context.DeclarationNames.getCXXConstructorName(
7185 Context.getCanonicalType(readType(F, Record, Idx)));
7186
7187 case DeclarationName::CXXDestructorName:
7188 return Context.DeclarationNames.getCXXDestructorName(
7189 Context.getCanonicalType(readType(F, Record, Idx)));
7190
7191 case DeclarationName::CXXConversionFunctionName:
7192 return Context.DeclarationNames.getCXXConversionFunctionName(
7193 Context.getCanonicalType(readType(F, Record, Idx)));
7194
7195 case DeclarationName::CXXOperatorName:
7196 return Context.DeclarationNames.getCXXOperatorName(
7197 (OverloadedOperatorKind)Record[Idx++]);
7198
7199 case DeclarationName::CXXLiteralOperatorName:
7200 return Context.DeclarationNames.getCXXLiteralOperatorName(
7201 GetIdentifierInfo(F, Record, Idx));
7202
7203 case DeclarationName::CXXUsingDirective:
7204 return DeclarationName::getUsingDirectiveName();
7205 }
7206
7207 llvm_unreachable("Invalid NameKind!");
7208}
7209
7210void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7211 DeclarationNameLoc &DNLoc,
7212 DeclarationName Name,
7213 const RecordData &Record, unsigned &Idx) {
7214 switch (Name.getNameKind()) {
7215 case DeclarationName::CXXConstructorName:
7216 case DeclarationName::CXXDestructorName:
7217 case DeclarationName::CXXConversionFunctionName:
7218 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7219 break;
7220
7221 case DeclarationName::CXXOperatorName:
7222 DNLoc.CXXOperatorName.BeginOpNameLoc
7223 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7224 DNLoc.CXXOperatorName.EndOpNameLoc
7225 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7226 break;
7227
7228 case DeclarationName::CXXLiteralOperatorName:
7229 DNLoc.CXXLiteralOperatorName.OpNameLoc
7230 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7231 break;
7232
7233 case DeclarationName::Identifier:
7234 case DeclarationName::ObjCZeroArgSelector:
7235 case DeclarationName::ObjCOneArgSelector:
7236 case DeclarationName::ObjCMultiArgSelector:
7237 case DeclarationName::CXXUsingDirective:
7238 break;
7239 }
7240}
7241
7242void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7243 DeclarationNameInfo &NameInfo,
7244 const RecordData &Record, unsigned &Idx) {
7245 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7246 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7247 DeclarationNameLoc DNLoc;
7248 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7249 NameInfo.setInfo(DNLoc);
7250}
7251
7252void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7253 const RecordData &Record, unsigned &Idx) {
7254 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7255 unsigned NumTPLists = Record[Idx++];
7256 Info.NumTemplParamLists = NumTPLists;
7257 if (NumTPLists) {
7258 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7259 for (unsigned i=0; i != NumTPLists; ++i)
7260 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7261 }
7262}
7263
7264TemplateName
7265ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7266 unsigned &Idx) {
7267 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7268 switch (Kind) {
7269 case TemplateName::Template:
7270 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7271
7272 case TemplateName::OverloadedTemplate: {
7273 unsigned size = Record[Idx++];
7274 UnresolvedSet<8> Decls;
7275 while (size--)
7276 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7277
7278 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7279 }
7280
7281 case TemplateName::QualifiedTemplate: {
7282 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7283 bool hasTemplKeyword = Record[Idx++];
7284 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7285 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7286 }
7287
7288 case TemplateName::DependentTemplate: {
7289 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7290 if (Record[Idx++]) // isIdentifier
7291 return Context.getDependentTemplateName(NNS,
7292 GetIdentifierInfo(F, Record,
7293 Idx));
7294 return Context.getDependentTemplateName(NNS,
7295 (OverloadedOperatorKind)Record[Idx++]);
7296 }
7297
7298 case TemplateName::SubstTemplateTemplateParm: {
7299 TemplateTemplateParmDecl *param
7300 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7301 if (!param) return TemplateName();
7302 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7303 return Context.getSubstTemplateTemplateParm(param, replacement);
7304 }
7305
7306 case TemplateName::SubstTemplateTemplateParmPack: {
7307 TemplateTemplateParmDecl *Param
7308 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7309 if (!Param)
7310 return TemplateName();
7311
7312 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7313 if (ArgPack.getKind() != TemplateArgument::Pack)
7314 return TemplateName();
7315
7316 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7317 }
7318 }
7319
7320 llvm_unreachable("Unhandled template name kind!");
7321}
7322
7323TemplateArgument
7324ASTReader::ReadTemplateArgument(ModuleFile &F,
7325 const RecordData &Record, unsigned &Idx) {
7326 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7327 switch (Kind) {
7328 case TemplateArgument::Null:
7329 return TemplateArgument();
7330 case TemplateArgument::Type:
7331 return TemplateArgument(readType(F, Record, Idx));
7332 case TemplateArgument::Declaration: {
7333 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7334 bool ForReferenceParam = Record[Idx++];
7335 return TemplateArgument(D, ForReferenceParam);
7336 }
7337 case TemplateArgument::NullPtr:
7338 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7339 case TemplateArgument::Integral: {
7340 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7341 QualType T = readType(F, Record, Idx);
7342 return TemplateArgument(Context, Value, T);
7343 }
7344 case TemplateArgument::Template:
7345 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7346 case TemplateArgument::TemplateExpansion: {
7347 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007348 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007349 if (unsigned NumExpansions = Record[Idx++])
7350 NumTemplateExpansions = NumExpansions - 1;
7351 return TemplateArgument(Name, NumTemplateExpansions);
7352 }
7353 case TemplateArgument::Expression:
7354 return TemplateArgument(ReadExpr(F));
7355 case TemplateArgument::Pack: {
7356 unsigned NumArgs = Record[Idx++];
7357 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7358 for (unsigned I = 0; I != NumArgs; ++I)
7359 Args[I] = ReadTemplateArgument(F, Record, Idx);
7360 return TemplateArgument(Args, NumArgs);
7361 }
7362 }
7363
7364 llvm_unreachable("Unhandled template argument kind!");
7365}
7366
7367TemplateParameterList *
7368ASTReader::ReadTemplateParameterList(ModuleFile &F,
7369 const RecordData &Record, unsigned &Idx) {
7370 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7371 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7372 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7373
7374 unsigned NumParams = Record[Idx++];
7375 SmallVector<NamedDecl *, 16> Params;
7376 Params.reserve(NumParams);
7377 while (NumParams--)
7378 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7379
7380 TemplateParameterList* TemplateParams =
7381 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7382 Params.data(), Params.size(), RAngleLoc);
7383 return TemplateParams;
7384}
7385
7386void
7387ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007388ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007389 ModuleFile &F, const RecordData &Record,
7390 unsigned &Idx) {
7391 unsigned NumTemplateArgs = Record[Idx++];
7392 TemplArgs.reserve(NumTemplateArgs);
7393 while (NumTemplateArgs--)
7394 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7395}
7396
7397/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007398void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007399 const RecordData &Record, unsigned &Idx) {
7400 unsigned NumDecls = Record[Idx++];
7401 Set.reserve(Context, NumDecls);
7402 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007403 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007404 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007405 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007406 }
7407}
7408
7409CXXBaseSpecifier
7410ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7411 const RecordData &Record, unsigned &Idx) {
7412 bool isVirtual = static_cast<bool>(Record[Idx++]);
7413 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7414 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7415 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7416 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7417 SourceRange Range = ReadSourceRange(F, Record, Idx);
7418 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7419 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7420 EllipsisLoc);
7421 Result.setInheritConstructors(inheritConstructors);
7422 return Result;
7423}
7424
7425std::pair<CXXCtorInitializer **, unsigned>
7426ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7427 unsigned &Idx) {
7428 CXXCtorInitializer **CtorInitializers = 0;
7429 unsigned NumInitializers = Record[Idx++];
7430 if (NumInitializers) {
7431 CtorInitializers
7432 = new (Context) CXXCtorInitializer*[NumInitializers];
7433 for (unsigned i=0; i != NumInitializers; ++i) {
7434 TypeSourceInfo *TInfo = 0;
7435 bool IsBaseVirtual = false;
7436 FieldDecl *Member = 0;
7437 IndirectFieldDecl *IndirectMember = 0;
7438
7439 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7440 switch (Type) {
7441 case CTOR_INITIALIZER_BASE:
7442 TInfo = GetTypeSourceInfo(F, Record, Idx);
7443 IsBaseVirtual = Record[Idx++];
7444 break;
7445
7446 case CTOR_INITIALIZER_DELEGATING:
7447 TInfo = GetTypeSourceInfo(F, Record, Idx);
7448 break;
7449
7450 case CTOR_INITIALIZER_MEMBER:
7451 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7452 break;
7453
7454 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7455 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7456 break;
7457 }
7458
7459 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7460 Expr *Init = ReadExpr(F);
7461 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7462 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7463 bool IsWritten = Record[Idx++];
7464 unsigned SourceOrderOrNumArrayIndices;
7465 SmallVector<VarDecl *, 8> Indices;
7466 if (IsWritten) {
7467 SourceOrderOrNumArrayIndices = Record[Idx++];
7468 } else {
7469 SourceOrderOrNumArrayIndices = Record[Idx++];
7470 Indices.reserve(SourceOrderOrNumArrayIndices);
7471 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7472 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7473 }
7474
7475 CXXCtorInitializer *BOMInit;
7476 if (Type == CTOR_INITIALIZER_BASE) {
7477 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7478 LParenLoc, Init, RParenLoc,
7479 MemberOrEllipsisLoc);
7480 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7481 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7482 Init, RParenLoc);
7483 } else if (IsWritten) {
7484 if (Member)
7485 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7486 LParenLoc, Init, RParenLoc);
7487 else
7488 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7489 MemberOrEllipsisLoc, LParenLoc,
7490 Init, RParenLoc);
7491 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007492 if (IndirectMember) {
7493 assert(Indices.empty() && "Indirect field improperly initialized");
7494 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7495 MemberOrEllipsisLoc, LParenLoc,
7496 Init, RParenLoc);
7497 } else {
7498 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7499 LParenLoc, Init, RParenLoc,
7500 Indices.data(), Indices.size());
7501 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007502 }
7503
7504 if (IsWritten)
7505 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7506 CtorInitializers[i] = BOMInit;
7507 }
7508 }
7509
7510 return std::make_pair(CtorInitializers, NumInitializers);
7511}
7512
7513NestedNameSpecifier *
7514ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7515 const RecordData &Record, unsigned &Idx) {
7516 unsigned N = Record[Idx++];
7517 NestedNameSpecifier *NNS = 0, *Prev = 0;
7518 for (unsigned I = 0; I != N; ++I) {
7519 NestedNameSpecifier::SpecifierKind Kind
7520 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7521 switch (Kind) {
7522 case NestedNameSpecifier::Identifier: {
7523 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7524 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7525 break;
7526 }
7527
7528 case NestedNameSpecifier::Namespace: {
7529 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7530 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7531 break;
7532 }
7533
7534 case NestedNameSpecifier::NamespaceAlias: {
7535 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7536 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7537 break;
7538 }
7539
7540 case NestedNameSpecifier::TypeSpec:
7541 case NestedNameSpecifier::TypeSpecWithTemplate: {
7542 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7543 if (!T)
7544 return 0;
7545
7546 bool Template = Record[Idx++];
7547 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7548 break;
7549 }
7550
7551 case NestedNameSpecifier::Global: {
7552 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7553 // No associated value, and there can't be a prefix.
7554 break;
7555 }
7556 }
7557 Prev = NNS;
7558 }
7559 return NNS;
7560}
7561
7562NestedNameSpecifierLoc
7563ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7564 unsigned &Idx) {
7565 unsigned N = Record[Idx++];
7566 NestedNameSpecifierLocBuilder Builder;
7567 for (unsigned I = 0; I != N; ++I) {
7568 NestedNameSpecifier::SpecifierKind Kind
7569 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7570 switch (Kind) {
7571 case NestedNameSpecifier::Identifier: {
7572 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7573 SourceRange Range = ReadSourceRange(F, Record, Idx);
7574 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7575 break;
7576 }
7577
7578 case NestedNameSpecifier::Namespace: {
7579 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7580 SourceRange Range = ReadSourceRange(F, Record, Idx);
7581 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7582 break;
7583 }
7584
7585 case NestedNameSpecifier::NamespaceAlias: {
7586 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7587 SourceRange Range = ReadSourceRange(F, Record, Idx);
7588 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7589 break;
7590 }
7591
7592 case NestedNameSpecifier::TypeSpec:
7593 case NestedNameSpecifier::TypeSpecWithTemplate: {
7594 bool Template = Record[Idx++];
7595 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7596 if (!T)
7597 return NestedNameSpecifierLoc();
7598 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7599
7600 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7601 Builder.Extend(Context,
7602 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7603 T->getTypeLoc(), ColonColonLoc);
7604 break;
7605 }
7606
7607 case NestedNameSpecifier::Global: {
7608 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7609 Builder.MakeGlobal(Context, ColonColonLoc);
7610 break;
7611 }
7612 }
7613 }
7614
7615 return Builder.getWithLocInContext(Context);
7616}
7617
7618SourceRange
7619ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7620 unsigned &Idx) {
7621 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7622 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7623 return SourceRange(beg, end);
7624}
7625
7626/// \brief Read an integral value
7627llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7628 unsigned BitWidth = Record[Idx++];
7629 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7630 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7631 Idx += NumWords;
7632 return Result;
7633}
7634
7635/// \brief Read a signed integral value
7636llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7637 bool isUnsigned = Record[Idx++];
7638 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7639}
7640
7641/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007642llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7643 const llvm::fltSemantics &Sem,
7644 unsigned &Idx) {
7645 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007646}
7647
7648// \brief Read a string
7649std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7650 unsigned Len = Record[Idx++];
7651 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7652 Idx += Len;
7653 return Result;
7654}
7655
7656VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7657 unsigned &Idx) {
7658 unsigned Major = Record[Idx++];
7659 unsigned Minor = Record[Idx++];
7660 unsigned Subminor = Record[Idx++];
7661 if (Minor == 0)
7662 return VersionTuple(Major);
7663 if (Subminor == 0)
7664 return VersionTuple(Major, Minor - 1);
7665 return VersionTuple(Major, Minor - 1, Subminor - 1);
7666}
7667
7668CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7669 const RecordData &Record,
7670 unsigned &Idx) {
7671 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7672 return CXXTemporary::Create(Context, Decl);
7673}
7674
7675DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007676 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007677}
7678
7679DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7680 return Diags.Report(Loc, DiagID);
7681}
7682
7683/// \brief Retrieve the identifier table associated with the
7684/// preprocessor.
7685IdentifierTable &ASTReader::getIdentifierTable() {
7686 return PP.getIdentifierTable();
7687}
7688
7689/// \brief Record that the given ID maps to the given switch-case
7690/// statement.
7691void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7692 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7693 "Already have a SwitchCase with this ID");
7694 (*CurrSwitchCaseStmts)[ID] = SC;
7695}
7696
7697/// \brief Retrieve the switch-case statement with the given ID.
7698SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7699 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7700 return (*CurrSwitchCaseStmts)[ID];
7701}
7702
7703void ASTReader::ClearSwitchCaseIDs() {
7704 CurrSwitchCaseStmts->clear();
7705}
7706
7707void ASTReader::ReadComments() {
7708 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007709 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007710 serialization::ModuleFile *> >::iterator
7711 I = CommentsCursors.begin(),
7712 E = CommentsCursors.end();
7713 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007714 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007715 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007716 serialization::ModuleFile &F = *I->second;
7717 SavedStreamPosition SavedPosition(Cursor);
7718
7719 RecordData Record;
7720 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007721 llvm::BitstreamEntry Entry =
7722 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007723
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007724 switch (Entry.Kind) {
7725 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7726 case llvm::BitstreamEntry::Error:
7727 Error("malformed block record in AST file");
7728 return;
7729 case llvm::BitstreamEntry::EndBlock:
7730 goto NextCursor;
7731 case llvm::BitstreamEntry::Record:
7732 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007733 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007734 }
7735
7736 // Read a record.
7737 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007738 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007739 case COMMENTS_RAW_COMMENT: {
7740 unsigned Idx = 0;
7741 SourceRange SR = ReadSourceRange(F, Record, Idx);
7742 RawComment::CommentKind Kind =
7743 (RawComment::CommentKind) Record[Idx++];
7744 bool IsTrailingComment = Record[Idx++];
7745 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00007746 Comments.push_back(new (Context) RawComment(
7747 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7748 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00007749 break;
7750 }
7751 }
7752 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007753 NextCursor:
7754 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00007755 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007756}
7757
7758void ASTReader::finishPendingActions() {
7759 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00007760 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
7761 !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007762 // If any identifiers with corresponding top-level declarations have
7763 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00007764 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
7765 TopLevelDeclsMap;
7766 TopLevelDeclsMap TopLevelDecls;
7767
Guy Benyei11169dd2012-12-18 14:30:41 +00007768 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007769 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00007770 SmallVector<uint32_t, 4> DeclIDs =
7771 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00007772 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00007773
7774 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007775 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00007776
Guy Benyei11169dd2012-12-18 14:30:41 +00007777 // Load pending declaration chains.
7778 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7779 loadPendingDeclChain(PendingDeclChains[I]);
7780 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
7781 }
7782 PendingDeclChains.clear();
7783
Douglas Gregor6168bd22013-02-18 15:53:43 +00007784 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00007785 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
7786 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007787 IdentifierInfo *II = TLD->first;
7788 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007789 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00007790 }
7791 }
7792
Guy Benyei11169dd2012-12-18 14:30:41 +00007793 // Load any pending macro definitions.
7794 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007795 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
7796 SmallVector<PendingMacroInfo, 2> GlobalIDs;
7797 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
7798 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00007799 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00007800 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007801 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7802 if (Info.M->Kind != MK_Module)
7803 resolvePendingMacro(II, Info);
7804 }
7805 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00007806 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007807 ++IDIdx) {
7808 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7809 if (Info.M->Kind == MK_Module)
7810 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00007811 }
7812 }
7813 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00007814
7815 // Wire up the DeclContexts for Decls that we delayed setting until
7816 // recursive loading is completed.
7817 while (!PendingDeclContextInfos.empty()) {
7818 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7819 PendingDeclContextInfos.pop_front();
7820 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7821 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7822 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7823 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00007824
7825 // For each declaration from a merged context, check that the canonical
7826 // definition of that context also contains a declaration of the same
7827 // entity.
7828 while (!PendingOdrMergeChecks.empty()) {
7829 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
7830
7831 // FIXME: Skip over implicit declarations for now. This matters for things
7832 // like implicitly-declared special member functions. This isn't entirely
7833 // correct; we can end up with multiple unmerged declarations of the same
7834 // implicit entity.
7835 if (D->isImplicit())
7836 continue;
7837
7838 DeclContext *CanonDef = D->getDeclContext();
7839 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
7840
7841 bool Found = false;
7842 const Decl *DCanon = D->getCanonicalDecl();
7843
7844 llvm::SmallVector<const NamedDecl*, 4> Candidates;
7845 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
7846 !Found && I != E; ++I) {
Aaron Ballman86c93902014-03-06 23:45:36 +00007847 for (auto RI : (*I)->redecls()) {
7848 if (RI->getLexicalDeclContext() == CanonDef) {
Richard Smith2b9e3e32013-10-18 06:05:18 +00007849 // This declaration is present in the canonical definition. If it's
7850 // in the same redecl chain, it's the one we're looking for.
Aaron Ballman86c93902014-03-06 23:45:36 +00007851 if (RI->getCanonicalDecl() == DCanon)
Richard Smith2b9e3e32013-10-18 06:05:18 +00007852 Found = true;
7853 else
Aaron Ballman86c93902014-03-06 23:45:36 +00007854 Candidates.push_back(cast<NamedDecl>(RI));
Richard Smith2b9e3e32013-10-18 06:05:18 +00007855 break;
7856 }
7857 }
7858 }
7859
7860 if (!Found) {
7861 D->setInvalidDecl();
7862
7863 Module *CanonDefModule = cast<Decl>(CanonDef)->getOwningModule();
7864 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
7865 << D << D->getOwningModule()->getFullModuleName()
7866 << CanonDef << !CanonDefModule
7867 << (CanonDefModule ? CanonDefModule->getFullModuleName() : "");
7868
7869 if (Candidates.empty())
7870 Diag(cast<Decl>(CanonDef)->getLocation(),
7871 diag::note_module_odr_violation_no_possible_decls) << D;
7872 else {
7873 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
7874 Diag(Candidates[I]->getLocation(),
7875 diag::note_module_odr_violation_possible_decl)
7876 << Candidates[I];
7877 }
7878 }
7879 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007880 }
7881
7882 // If we deserialized any C++ or Objective-C class definitions, any
7883 // Objective-C protocol definitions, or any redeclarable templates, make sure
7884 // that all redeclarations point to the definitions. Note that this can only
7885 // happen now, after the redeclaration chains have been fully wired.
7886 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7887 DEnd = PendingDefinitions.end();
7888 D != DEnd; ++D) {
7889 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7890 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7891 // Make sure that the TagType points at the definition.
7892 const_cast<TagType*>(TagT)->decl = TD;
7893 }
7894
Aaron Ballman86c93902014-03-06 23:45:36 +00007895 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
7896 for (auto R : RD->redecls())
7897 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei11169dd2012-12-18 14:30:41 +00007898
7899 }
7900
7901 continue;
7902 }
7903
Aaron Ballman86c93902014-03-06 23:45:36 +00007904 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007905 // Make sure that the ObjCInterfaceType points at the definition.
7906 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7907 ->Decl = ID;
7908
Aaron Ballman86c93902014-03-06 23:45:36 +00007909 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00007910 R->Data = ID->Data;
7911
7912 continue;
7913 }
7914
Aaron Ballman86c93902014-03-06 23:45:36 +00007915 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7916 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00007917 R->Data = PD->Data;
7918
7919 continue;
7920 }
7921
Aaron Ballman86c93902014-03-06 23:45:36 +00007922 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7923 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00007924 R->Common = RTD->Common;
7925 }
7926 PendingDefinitions.clear();
7927
7928 // Load the bodies of any functions or methods we've encountered. We do
7929 // this now (delayed) so that we can be sure that the declaration chains
7930 // have been fully wired up.
7931 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7932 PBEnd = PendingBodies.end();
7933 PB != PBEnd; ++PB) {
7934 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7935 // FIXME: Check for =delete/=default?
7936 // FIXME: Complain about ODR violations here?
7937 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7938 FD->setLazyBody(PB->second);
7939 continue;
7940 }
7941
7942 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7943 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7944 MD->setLazyBody(PB->second);
7945 }
7946 PendingBodies.clear();
7947}
7948
7949void ASTReader::FinishedDeserializing() {
7950 assert(NumCurrentElementsDeserializing &&
7951 "FinishedDeserializing not paired with StartedDeserializing");
7952 if (NumCurrentElementsDeserializing == 1) {
7953 // We decrease NumCurrentElementsDeserializing only after pending actions
7954 // are finished, to avoid recursively re-calling finishPendingActions().
7955 finishPendingActions();
7956 }
7957 --NumCurrentElementsDeserializing;
7958
Richard Smith04d05b52014-03-23 00:27:18 +00007959 if (NumCurrentElementsDeserializing == 0 && Consumer) {
7960 // We are not in recursive loading, so it's safe to pass the "interesting"
7961 // decls to the consumer.
7962 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00007963 }
7964}
7965
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007966void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00007967 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007968
7969 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
7970 SemaObj->TUScope->AddDecl(D);
7971 } else if (SemaObj->TUScope) {
7972 // Adding the decl to IdResolver may have failed because it was already in
7973 // (even though it was not added in scope). If it is already in, make sure
7974 // it gets in the scope as well.
7975 if (std::find(SemaObj->IdResolver.begin(Name),
7976 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
7977 SemaObj->TUScope->AddDecl(D);
7978 }
7979}
7980
Guy Benyei11169dd2012-12-18 14:30:41 +00007981ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7982 StringRef isysroot, bool DisableValidation,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007983 bool AllowASTWithCompilerErrors,
7984 bool AllowConfigurationMismatch,
Ben Langmuir3d4417c2014-02-07 17:31:11 +00007985 bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007986 bool UseGlobalIndex)
Guy Benyei11169dd2012-12-18 14:30:41 +00007987 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7988 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7989 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7990 Consumer(0), ModuleMgr(PP.getFileManager()),
7991 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregor00a50f72013-01-25 00:38:33 +00007992 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007993 AllowConfigurationMismatch(AllowConfigurationMismatch),
Ben Langmuir3d4417c2014-02-07 17:31:11 +00007994 ValidateSystemInputs(ValidateSystemInputs),
Douglas Gregorc1bbec82013-01-25 00:45:27 +00007995 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei11169dd2012-12-18 14:30:41 +00007996 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7997 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregor00a50f72013-01-25 00:38:33 +00007998 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7999 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
8000 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008001 NumMethodPoolLookups(0), NumMethodPoolHits(0),
8002 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
8003 TotalNumMethodPoolEntries(0),
Guy Benyei11169dd2012-12-18 14:30:41 +00008004 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8005 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8006 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8007 PassingDeclsToConsumer(false),
Richard Smith629ff362013-07-31 00:26:46 +00008008 NumCXXBaseSpecifiersLoaded(0), ReadingKind(Read_None)
Guy Benyei11169dd2012-12-18 14:30:41 +00008009{
8010 SourceMgr.setExternalSLocEntrySource(this);
8011}
8012
8013ASTReader::~ASTReader() {
8014 for (DeclContextVisibleUpdatesPending::iterator
8015 I = PendingVisibleUpdates.begin(),
8016 E = PendingVisibleUpdates.end();
8017 I != E; ++I) {
8018 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8019 F = I->second.end();
8020 J != F; ++J)
8021 delete J->first;
8022 }
8023}