blob: 1d1957d6bfe7d24aa0cc41d103e991ccab55bafe [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 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000854 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
855 (const unsigned char *)Blob.data() + Record[0],
856 (const unsigned char *)Blob.data() + sizeof(uint32_t),
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
Ben Langmuir2c9af442014-04-10 17:57:43 +00002325ASTReader::ASTReadResult
2326ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002327 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002328
2329 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2330 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002331 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002332 }
2333
2334 // Read all of the records and blocks for the AST file.
2335 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002336 while (1) {
2337 llvm::BitstreamEntry Entry = Stream.advance();
2338
2339 switch (Entry.Kind) {
2340 case llvm::BitstreamEntry::Error:
2341 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002342 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002343 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002344 // Outside of C++, we do not store a lookup map for the translation unit.
2345 // Instead, mark it as needing a lookup map to be built if this module
2346 // contains any declarations lexically within it (which it always does!).
2347 // This usually has no cost, since we very rarely need the lookup map for
2348 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002349 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002350 if (DC->hasExternalLexicalStorage() &&
2351 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002352 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002353
Ben Langmuir2c9af442014-04-10 17:57:43 +00002354 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002355 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002356 case llvm::BitstreamEntry::SubBlock:
2357 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002358 case DECLTYPES_BLOCK_ID:
2359 // We lazily load the decls block, but we want to set up the
2360 // DeclsCursor cursor to point into it. Clone our current bitcode
2361 // cursor to it, enter the block and read the abbrevs in that block.
2362 // With the main cursor, we just skip over it.
2363 F.DeclsCursor = Stream;
2364 if (Stream.SkipBlock() || // Skip with the main cursor.
2365 // Read the abbrevs.
2366 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2367 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002368 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002369 }
2370 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002371
Guy Benyei11169dd2012-12-18 14:30:41 +00002372 case PREPROCESSOR_BLOCK_ID:
2373 F.MacroCursor = Stream;
2374 if (!PP.getExternalSource())
2375 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002376
Guy Benyei11169dd2012-12-18 14:30:41 +00002377 if (Stream.SkipBlock() ||
2378 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2379 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002380 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002381 }
2382 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2383 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002384
Guy Benyei11169dd2012-12-18 14:30:41 +00002385 case PREPROCESSOR_DETAIL_BLOCK_ID:
2386 F.PreprocessorDetailCursor = Stream;
2387 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002388 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002390 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002391 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002392 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002393 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002394 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2395
Guy Benyei11169dd2012-12-18 14:30:41 +00002396 if (!PP.getPreprocessingRecord())
2397 PP.createPreprocessingRecord();
2398 if (!PP.getPreprocessingRecord()->getExternalSource())
2399 PP.getPreprocessingRecord()->SetExternalSource(*this);
2400 break;
2401
2402 case SOURCE_MANAGER_BLOCK_ID:
2403 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002404 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002406
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002408 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2409 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002411
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002413 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 if (Stream.SkipBlock() ||
2415 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2416 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002417 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002418 }
2419 CommentsCursors.push_back(std::make_pair(C, &F));
2420 break;
2421 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002422
Guy Benyei11169dd2012-12-18 14:30:41 +00002423 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002424 if (Stream.SkipBlock()) {
2425 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002426 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002427 }
2428 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 }
2430 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002431
2432 case llvm::BitstreamEntry::Record:
2433 // The interesting case.
2434 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002435 }
2436
2437 // Read and process a record.
2438 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002439 StringRef Blob;
2440 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 default: // Default behavior: ignore.
2442 break;
2443
2444 case TYPE_OFFSET: {
2445 if (F.LocalNumTypes != 0) {
2446 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002447 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002448 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002449 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002450 F.LocalNumTypes = Record[0];
2451 unsigned LocalBaseTypeIndex = Record[1];
2452 F.BaseTypeIndex = getTotalNumTypes();
2453
2454 if (F.LocalNumTypes > 0) {
2455 // Introduce the global -> local mapping for types within this module.
2456 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2457
2458 // Introduce the local -> global mapping for types within this module.
2459 F.TypeRemap.insertOrReplace(
2460 std::make_pair(LocalBaseTypeIndex,
2461 F.BaseTypeIndex - LocalBaseTypeIndex));
2462
2463 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2464 }
2465 break;
2466 }
2467
2468 case DECL_OFFSET: {
2469 if (F.LocalNumDecls != 0) {
2470 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002471 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002473 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002474 F.LocalNumDecls = Record[0];
2475 unsigned LocalBaseDeclID = Record[1];
2476 F.BaseDeclID = getTotalNumDecls();
2477
2478 if (F.LocalNumDecls > 0) {
2479 // Introduce the global -> local mapping for declarations within this
2480 // module.
2481 GlobalDeclMap.insert(
2482 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2483
2484 // Introduce the local -> global mapping for declarations within this
2485 // module.
2486 F.DeclRemap.insertOrReplace(
2487 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2488
2489 // Introduce the global -> local mapping for declarations within this
2490 // module.
2491 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2492
2493 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2494 }
2495 break;
2496 }
2497
2498 case TU_UPDATE_LEXICAL: {
2499 DeclContext *TU = Context.getTranslationUnitDecl();
2500 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002501 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002503 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002504 TU->setHasExternalLexicalStorage(true);
2505 break;
2506 }
2507
2508 case UPDATE_VISIBLE: {
2509 unsigned Idx = 0;
2510 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2511 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002512 ASTDeclContextNameLookupTable::Create(
2513 (const unsigned char *)Blob.data() + Record[Idx++],
2514 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2515 (const unsigned char *)Blob.data(),
2516 ASTDeclContextNameLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002517 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2518 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith52e3fba2014-03-11 07:17:35 +00002519 F.DeclContextInfos[TU].NameLookupTableData = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002520 TU->setHasExternalVisibleStorage(true);
Richard Smithd9174792014-03-11 03:10:46 +00002521 } else if (Decl *D = DeclsLoaded[ID - NUM_PREDEF_DECL_IDS]) {
2522 auto *DC = cast<DeclContext>(D);
2523 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002524 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2525 delete LookupTable;
2526 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002527 } else
2528 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2529 break;
2530 }
2531
2532 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002533 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002534 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002535 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2536 (const unsigned char *)F.IdentifierTableData + Record[0],
2537 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2538 (const unsigned char *)F.IdentifierTableData,
2539 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002540
2541 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2542 }
2543 break;
2544
2545 case IDENTIFIER_OFFSET: {
2546 if (F.LocalNumIdentifiers != 0) {
2547 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002548 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002549 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002550 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002551 F.LocalNumIdentifiers = Record[0];
2552 unsigned LocalBaseIdentifierID = Record[1];
2553 F.BaseIdentifierID = getTotalNumIdentifiers();
2554
2555 if (F.LocalNumIdentifiers > 0) {
2556 // Introduce the global -> local mapping for identifiers within this
2557 // module.
2558 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2559 &F));
2560
2561 // Introduce the local -> global mapping for identifiers within this
2562 // module.
2563 F.IdentifierRemap.insertOrReplace(
2564 std::make_pair(LocalBaseIdentifierID,
2565 F.BaseIdentifierID - LocalBaseIdentifierID));
2566
2567 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2568 + F.LocalNumIdentifiers);
2569 }
2570 break;
2571 }
2572
Ben Langmuir332aafe2014-01-31 01:06:56 +00002573 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002575 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 break;
2577
2578 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002579 if (SpecialTypes.empty()) {
2580 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2581 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2582 break;
2583 }
2584
2585 if (SpecialTypes.size() != Record.size()) {
2586 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002587 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002588 }
2589
2590 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2591 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2592 if (!SpecialTypes[I])
2593 SpecialTypes[I] = ID;
2594 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2595 // merge step?
2596 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 break;
2598
2599 case STATISTICS:
2600 TotalNumStatements += Record[0];
2601 TotalNumMacros += Record[1];
2602 TotalLexicalDeclContexts += Record[2];
2603 TotalVisibleDeclContexts += Record[3];
2604 break;
2605
2606 case UNUSED_FILESCOPED_DECLS:
2607 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2608 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2609 break;
2610
2611 case DELEGATING_CTORS:
2612 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2613 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2614 break;
2615
2616 case WEAK_UNDECLARED_IDENTIFIERS:
2617 if (Record.size() % 4 != 0) {
2618 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002619 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 }
2621
2622 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2623 // files. This isn't the way to do it :)
2624 WeakUndeclaredIdentifiers.clear();
2625
2626 // Translate the weak, undeclared identifiers into global IDs.
2627 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2628 WeakUndeclaredIdentifiers.push_back(
2629 getGlobalIdentifierID(F, Record[I++]));
2630 WeakUndeclaredIdentifiers.push_back(
2631 getGlobalIdentifierID(F, Record[I++]));
2632 WeakUndeclaredIdentifiers.push_back(
2633 ReadSourceLocation(F, Record, I).getRawEncoding());
2634 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2635 }
2636 break;
2637
Richard Smith78165b52013-01-10 23:43:47 +00002638 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002639 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002640 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002641 break;
2642
2643 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002644 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002645 F.LocalNumSelectors = Record[0];
2646 unsigned LocalBaseSelectorID = Record[1];
2647 F.BaseSelectorID = getTotalNumSelectors();
2648
2649 if (F.LocalNumSelectors > 0) {
2650 // Introduce the global -> local mapping for selectors within this
2651 // module.
2652 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2653
2654 // Introduce the local -> global mapping for selectors within this
2655 // module.
2656 F.SelectorRemap.insertOrReplace(
2657 std::make_pair(LocalBaseSelectorID,
2658 F.BaseSelectorID - LocalBaseSelectorID));
2659
2660 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2661 }
2662 break;
2663 }
2664
2665 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002666 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002667 if (Record[0])
2668 F.SelectorLookupTable
2669 = ASTSelectorLookupTable::Create(
2670 F.SelectorLookupTableData + Record[0],
2671 F.SelectorLookupTableData,
2672 ASTSelectorLookupTrait(*this, F));
2673 TotalNumMethodPoolEntries += Record[1];
2674 break;
2675
2676 case REFERENCED_SELECTOR_POOL:
2677 if (!Record.empty()) {
2678 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2679 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2680 Record[Idx++]));
2681 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2682 getRawEncoding());
2683 }
2684 }
2685 break;
2686
2687 case PP_COUNTER_VALUE:
2688 if (!Record.empty() && Listener)
2689 Listener->ReadCounter(F, Record[0]);
2690 break;
2691
2692 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002693 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 F.NumFileSortedDecls = Record[0];
2695 break;
2696
2697 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002698 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002699 F.LocalNumSLocEntries = Record[0];
2700 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002701 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2703 SLocSpaceSize);
2704 // Make our entry in the range map. BaseID is negative and growing, so
2705 // we invert it. Because we invert it, though, we need the other end of
2706 // the range.
2707 unsigned RangeStart =
2708 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2709 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2710 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2711
2712 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2713 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2714 GlobalSLocOffsetMap.insert(
2715 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2716 - SLocSpaceSize,&F));
2717
2718 // Initialize the remapping table.
2719 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002720 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002722 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2724
2725 TotalNumSLocEntries += F.LocalNumSLocEntries;
2726 break;
2727 }
2728
2729 case MODULE_OFFSET_MAP: {
2730 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002731 const unsigned char *Data = (const unsigned char*)Blob.data();
2732 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002733
2734 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2735 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2736 F.SLocRemap.insert(std::make_pair(0U, 0));
2737 F.SLocRemap.insert(std::make_pair(2U, 1));
2738 }
2739
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 // Continuous range maps we may be updating in our module.
2741 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2742 ContinuousRangeMap<uint32_t, int, 2>::Builder
2743 IdentifierRemap(F.IdentifierRemap);
2744 ContinuousRangeMap<uint32_t, int, 2>::Builder
2745 MacroRemap(F.MacroRemap);
2746 ContinuousRangeMap<uint32_t, int, 2>::Builder
2747 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2748 ContinuousRangeMap<uint32_t, int, 2>::Builder
2749 SubmoduleRemap(F.SubmoduleRemap);
2750 ContinuousRangeMap<uint32_t, int, 2>::Builder
2751 SelectorRemap(F.SelectorRemap);
2752 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2753 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2754
2755 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002756 using namespace llvm::support;
2757 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 StringRef Name = StringRef((const char*)Data, Len);
2759 Data += Len;
2760 ModuleFile *OM = ModuleMgr.lookup(Name);
2761 if (!OM) {
2762 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002763 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002764 }
2765
Justin Bogner57ba0b22014-03-28 22:03:24 +00002766 uint32_t SLocOffset =
2767 endian::readNext<uint32_t, little, unaligned>(Data);
2768 uint32_t IdentifierIDOffset =
2769 endian::readNext<uint32_t, little, unaligned>(Data);
2770 uint32_t MacroIDOffset =
2771 endian::readNext<uint32_t, little, unaligned>(Data);
2772 uint32_t PreprocessedEntityIDOffset =
2773 endian::readNext<uint32_t, little, unaligned>(Data);
2774 uint32_t SubmoduleIDOffset =
2775 endian::readNext<uint32_t, little, unaligned>(Data);
2776 uint32_t SelectorIDOffset =
2777 endian::readNext<uint32_t, little, unaligned>(Data);
2778 uint32_t DeclIDOffset =
2779 endian::readNext<uint32_t, little, unaligned>(Data);
2780 uint32_t TypeIndexOffset =
2781 endian::readNext<uint32_t, little, unaligned>(Data);
2782
Guy Benyei11169dd2012-12-18 14:30:41 +00002783 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2784 SLocRemap.insert(std::make_pair(SLocOffset,
2785 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2786 IdentifierRemap.insert(
2787 std::make_pair(IdentifierIDOffset,
2788 OM->BaseIdentifierID - IdentifierIDOffset));
2789 MacroRemap.insert(std::make_pair(MacroIDOffset,
2790 OM->BaseMacroID - MacroIDOffset));
2791 PreprocessedEntityRemap.insert(
2792 std::make_pair(PreprocessedEntityIDOffset,
2793 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2794 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2795 OM->BaseSubmoduleID - SubmoduleIDOffset));
2796 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2797 OM->BaseSelectorID - SelectorIDOffset));
2798 DeclRemap.insert(std::make_pair(DeclIDOffset,
2799 OM->BaseDeclID - DeclIDOffset));
2800
2801 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2802 OM->BaseTypeIndex - TypeIndexOffset));
2803
2804 // Global -> local mappings.
2805 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2806 }
2807 break;
2808 }
2809
2810 case SOURCE_MANAGER_LINE_TABLE:
2811 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002812 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002813 break;
2814
2815 case SOURCE_LOCATION_PRELOADS: {
2816 // Need to transform from the local view (1-based IDs) to the global view,
2817 // which is based off F.SLocEntryBaseID.
2818 if (!F.PreloadSLocEntries.empty()) {
2819 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002820 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002821 }
2822
2823 F.PreloadSLocEntries.swap(Record);
2824 break;
2825 }
2826
2827 case EXT_VECTOR_DECLS:
2828 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2829 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2830 break;
2831
2832 case VTABLE_USES:
2833 if (Record.size() % 3 != 0) {
2834 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002835 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002836 }
2837
2838 // Later tables overwrite earlier ones.
2839 // FIXME: Modules will have some trouble with this. This is clearly not
2840 // the right way to do this.
2841 VTableUses.clear();
2842
2843 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2844 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2845 VTableUses.push_back(
2846 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2847 VTableUses.push_back(Record[Idx++]);
2848 }
2849 break;
2850
2851 case DYNAMIC_CLASSES:
2852 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2853 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2854 break;
2855
2856 case PENDING_IMPLICIT_INSTANTIATIONS:
2857 if (PendingInstantiations.size() % 2 != 0) {
2858 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002859 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 }
2861
2862 if (Record.size() % 2 != 0) {
2863 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002864 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002865 }
2866
2867 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2868 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2869 PendingInstantiations.push_back(
2870 ReadSourceLocation(F, Record, I).getRawEncoding());
2871 }
2872 break;
2873
2874 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002875 if (Record.size() != 2) {
2876 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002877 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002878 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002879 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2880 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2881 break;
2882
2883 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002884 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2885 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2886 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002887
2888 unsigned LocalBasePreprocessedEntityID = Record[0];
2889
2890 unsigned StartingID;
2891 if (!PP.getPreprocessingRecord())
2892 PP.createPreprocessingRecord();
2893 if (!PP.getPreprocessingRecord()->getExternalSource())
2894 PP.getPreprocessingRecord()->SetExternalSource(*this);
2895 StartingID
2896 = PP.getPreprocessingRecord()
2897 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2898 F.BasePreprocessedEntityID = StartingID;
2899
2900 if (F.NumPreprocessedEntities > 0) {
2901 // Introduce the global -> local mapping for preprocessed entities in
2902 // this module.
2903 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2904
2905 // Introduce the local -> global mapping for preprocessed entities in
2906 // this module.
2907 F.PreprocessedEntityRemap.insertOrReplace(
2908 std::make_pair(LocalBasePreprocessedEntityID,
2909 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2910 }
2911
2912 break;
2913 }
2914
2915 case DECL_UPDATE_OFFSETS: {
2916 if (Record.size() % 2 != 0) {
2917 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002918 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002919 }
Richard Smith04d05b52014-03-23 00:27:18 +00002920 // FIXME: If we've already loaded the decl, perform the updates now.
Guy Benyei11169dd2012-12-18 14:30:41 +00002921 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2922 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2923 .push_back(std::make_pair(&F, Record[I+1]));
2924 break;
2925 }
2926
2927 case DECL_REPLACEMENTS: {
2928 if (Record.size() % 3 != 0) {
2929 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002930 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002931 }
2932 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2933 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2934 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2935 break;
2936 }
2937
2938 case OBJC_CATEGORIES_MAP: {
2939 if (F.LocalNumObjCCategoriesInMap != 0) {
2940 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002941 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002942 }
2943
2944 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002945 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002946 break;
2947 }
2948
2949 case OBJC_CATEGORIES:
2950 F.ObjCCategories.swap(Record);
2951 break;
2952
2953 case CXX_BASE_SPECIFIER_OFFSETS: {
2954 if (F.LocalNumCXXBaseSpecifiers != 0) {
2955 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002956 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002957 }
2958
2959 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002960 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002961 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2962 break;
2963 }
2964
2965 case DIAG_PRAGMA_MAPPINGS:
2966 if (F.PragmaDiagMappings.empty())
2967 F.PragmaDiagMappings.swap(Record);
2968 else
2969 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2970 Record.begin(), Record.end());
2971 break;
2972
2973 case CUDA_SPECIAL_DECL_REFS:
2974 // Later tables overwrite earlier ones.
2975 // FIXME: Modules will have trouble with this.
2976 CUDASpecialDeclRefs.clear();
2977 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2978 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2979 break;
2980
2981 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002982 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002983 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002984 if (Record[0]) {
2985 F.HeaderFileInfoTable
2986 = HeaderFileInfoLookupTable::Create(
2987 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2988 (const unsigned char *)F.HeaderFileInfoTableData,
2989 HeaderFileInfoTrait(*this, F,
2990 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002991 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002992
2993 PP.getHeaderSearchInfo().SetExternalSource(this);
2994 if (!PP.getHeaderSearchInfo().getExternalLookup())
2995 PP.getHeaderSearchInfo().SetExternalLookup(this);
2996 }
2997 break;
2998 }
2999
3000 case FP_PRAGMA_OPTIONS:
3001 // Later tables overwrite earlier ones.
3002 FPPragmaOptions.swap(Record);
3003 break;
3004
3005 case OPENCL_EXTENSIONS:
3006 // Later tables overwrite earlier ones.
3007 OpenCLExtensions.swap(Record);
3008 break;
3009
3010 case TENTATIVE_DEFINITIONS:
3011 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3012 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3013 break;
3014
3015 case KNOWN_NAMESPACES:
3016 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3017 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3018 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003019
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003020 case UNDEFINED_BUT_USED:
3021 if (UndefinedButUsed.size() % 2 != 0) {
3022 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003023 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003024 }
3025
3026 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003027 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003028 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003029 }
3030 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003031 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3032 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003033 ReadSourceLocation(F, Record, I).getRawEncoding());
3034 }
3035 break;
3036
Guy Benyei11169dd2012-12-18 14:30:41 +00003037 case IMPORTED_MODULES: {
3038 if (F.Kind != MK_Module) {
3039 // If we aren't loading a module (which has its own exports), make
3040 // all of the imported modules visible.
3041 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003042 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3043 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3044 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3045 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003046 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003047 }
3048 }
3049 break;
3050 }
3051
3052 case LOCAL_REDECLARATIONS: {
3053 F.RedeclarationChains.swap(Record);
3054 break;
3055 }
3056
3057 case LOCAL_REDECLARATIONS_MAP: {
3058 if (F.LocalNumRedeclarationsInMap != 0) {
3059 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003060 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003061 }
3062
3063 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003064 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003065 break;
3066 }
3067
3068 case MERGED_DECLARATIONS: {
3069 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3070 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3071 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3072 for (unsigned N = Record[Idx++]; N > 0; --N)
3073 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3074 }
3075 break;
3076 }
3077
3078 case MACRO_OFFSET: {
3079 if (F.LocalNumMacros != 0) {
3080 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003081 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003082 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003083 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003084 F.LocalNumMacros = Record[0];
3085 unsigned LocalBaseMacroID = Record[1];
3086 F.BaseMacroID = getTotalNumMacros();
3087
3088 if (F.LocalNumMacros > 0) {
3089 // Introduce the global -> local mapping for macros within this module.
3090 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3091
3092 // Introduce the local -> global mapping for macros within this module.
3093 F.MacroRemap.insertOrReplace(
3094 std::make_pair(LocalBaseMacroID,
3095 F.BaseMacroID - LocalBaseMacroID));
3096
3097 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3098 }
3099 break;
3100 }
3101
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003102 case MACRO_TABLE: {
3103 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003104 break;
3105 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003106
3107 case LATE_PARSED_TEMPLATE: {
3108 LateParsedTemplates.append(Record.begin(), Record.end());
3109 break;
3110 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 }
3112 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003113}
3114
Douglas Gregorc1489562013-02-12 23:36:21 +00003115/// \brief Move the given method to the back of the global list of methods.
3116static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3117 // Find the entry for this selector in the method pool.
3118 Sema::GlobalMethodPool::iterator Known
3119 = S.MethodPool.find(Method->getSelector());
3120 if (Known == S.MethodPool.end())
3121 return;
3122
3123 // Retrieve the appropriate method list.
3124 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3125 : Known->second.second;
3126 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003127 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003128 if (!Found) {
3129 if (List->Method == Method) {
3130 Found = true;
3131 } else {
3132 // Keep searching.
3133 continue;
3134 }
3135 }
3136
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003137 if (List->getNext())
3138 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003139 else
3140 List->Method = Method;
3141 }
3142}
3143
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003144void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00003145 for (unsigned I = 0, N = Names.HiddenDecls.size(); I != N; ++I) {
3146 Decl *D = Names.HiddenDecls[I];
3147 bool wasHidden = D->Hidden;
3148 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003149
Richard Smith49f906a2014-03-01 00:08:04 +00003150 if (wasHidden && SemaObj) {
3151 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3152 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003153 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003154 }
3155 }
Richard Smith49f906a2014-03-01 00:08:04 +00003156
3157 for (HiddenMacrosMap::const_iterator I = Names.HiddenMacros.begin(),
3158 E = Names.HiddenMacros.end();
3159 I != E; ++I)
3160 installImportedMacro(I->first, I->second, Owner);
Guy Benyei11169dd2012-12-18 14:30:41 +00003161}
3162
Richard Smith49f906a2014-03-01 00:08:04 +00003163void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003164 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003165 SourceLocation ImportLoc,
3166 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003168 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003169 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003170 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003171 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003172
3173 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003174 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003175 // there is nothing more to do.
3176 continue;
3177 }
Richard Smith49f906a2014-03-01 00:08:04 +00003178
Guy Benyei11169dd2012-12-18 14:30:41 +00003179 if (!Mod->isAvailable()) {
3180 // Modules that aren't available cannot be made visible.
3181 continue;
3182 }
3183
3184 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003185 if (NameVisibility >= Module::MacrosVisible &&
3186 Mod->NameVisibility < Module::MacrosVisible)
3187 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003188 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003189
Guy Benyei11169dd2012-12-18 14:30:41 +00003190 // If we've already deserialized any names from this module,
3191 // mark them as visible.
3192 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3193 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003194 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003195 HiddenNamesMap.erase(Hidden);
3196 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003197
Guy Benyei11169dd2012-12-18 14:30:41 +00003198 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003199 SmallVector<Module *, 16> Exports;
3200 Mod->getExportedModules(Exports);
3201 for (SmallVectorImpl<Module *>::iterator
3202 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3203 Module *Exported = *I;
3204 if (Visited.insert(Exported))
3205 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003206 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003207
3208 // Detect any conflicts.
3209 if (Complain) {
3210 assert(ImportLoc.isValid() && "Missing import location");
3211 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3212 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3213 Diag(ImportLoc, diag::warn_module_conflict)
3214 << Mod->getFullModuleName()
3215 << Mod->Conflicts[I].Other->getFullModuleName()
3216 << Mod->Conflicts[I].Message;
3217 // FIXME: Need note where the other module was imported.
3218 }
3219 }
3220 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003221 }
3222}
3223
Douglas Gregore060e572013-01-25 01:03:03 +00003224bool ASTReader::loadGlobalIndex() {
3225 if (GlobalIndex)
3226 return false;
3227
3228 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3229 !Context.getLangOpts().Modules)
3230 return true;
3231
3232 // Try to load the global index.
3233 TriedLoadingGlobalIndex = true;
3234 StringRef ModuleCachePath
3235 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3236 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003237 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003238 if (!Result.first)
3239 return true;
3240
3241 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003242 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003243 return false;
3244}
3245
3246bool ASTReader::isGlobalIndexUnavailable() const {
3247 return Context.getLangOpts().Modules && UseGlobalIndex &&
3248 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3249}
3250
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003251static void updateModuleTimestamp(ModuleFile &MF) {
3252 // Overwrite the timestamp file contents so that file's mtime changes.
3253 std::string TimestampFilename = MF.getTimestampFilename();
3254 std::string ErrorInfo;
Rafael Espindola04a13be2014-02-24 15:06:52 +00003255 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
Rafael Espindola4fbd3732014-02-24 18:20:21 +00003256 llvm::sys::fs::F_Text);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003257 if (!ErrorInfo.empty())
3258 return;
3259 OS << "Timestamp file\n";
3260}
3261
Guy Benyei11169dd2012-12-18 14:30:41 +00003262ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3263 ModuleKind Type,
3264 SourceLocation ImportLoc,
3265 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003266 llvm::SaveAndRestore<SourceLocation>
3267 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3268
Guy Benyei11169dd2012-12-18 14:30:41 +00003269 // Bump the generation number.
3270 unsigned PreviousGeneration = CurrentGeneration++;
3271
3272 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003273 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003274 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3275 /*ImportedBy=*/0, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003276 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003277 ClientLoadCapabilities)) {
3278 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003279 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003280 case OutOfDate:
3281 case VersionMismatch:
3282 case ConfigurationMismatch:
3283 case HadErrors:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003284 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3285 Context.getLangOpts().Modules
3286 ? &PP.getHeaderSearchInfo().getModuleMap()
3287 : 0);
Douglas Gregore060e572013-01-25 01:03:03 +00003288
3289 // If we find that any modules are unusable, the global index is going
3290 // to be out-of-date. Just remove it.
3291 GlobalIndex.reset();
Douglas Gregor7211ac12013-01-25 23:32:03 +00003292 ModuleMgr.setGlobalIndex(0);
Guy Benyei11169dd2012-12-18 14:30:41 +00003293 return ReadResult;
3294
3295 case Success:
3296 break;
3297 }
3298
3299 // Here comes stuff that we only do once the entire chain is loaded.
3300
3301 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003302 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3303 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003304 M != MEnd; ++M) {
3305 ModuleFile &F = *M->Mod;
3306
3307 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003308 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3309 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003310
3311 // Once read, set the ModuleFile bit base offset and update the size in
3312 // bits of all files we've seen.
3313 F.GlobalBitOffset = TotalModulesSizeInBits;
3314 TotalModulesSizeInBits += F.SizeInBits;
3315 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3316
3317 // Preload SLocEntries.
3318 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3319 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3320 // Load it through the SourceManager and don't call ReadSLocEntry()
3321 // directly because the entry may have already been loaded in which case
3322 // calling ReadSLocEntry() directly would trigger an assertion in
3323 // SourceManager.
3324 SourceMgr.getLoadedSLocEntryByID(Index);
3325 }
3326 }
3327
Douglas Gregor603cd862013-03-22 18:50:14 +00003328 // Setup the import locations and notify the module manager that we've
3329 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003330 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3331 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003332 M != MEnd; ++M) {
3333 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003334
3335 ModuleMgr.moduleFileAccepted(&F);
3336
3337 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003338 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003339 if (!M->ImportedBy)
3340 F.ImportLoc = M->ImportLoc;
3341 else
3342 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3343 M->ImportLoc.getRawEncoding());
3344 }
3345
3346 // Mark all of the identifiers in the identifier table as being out of date,
3347 // so that various accessors know to check the loaded modules when the
3348 // identifier is used.
3349 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3350 IdEnd = PP.getIdentifierTable().end();
3351 Id != IdEnd; ++Id)
3352 Id->second->setOutOfDate(true);
3353
3354 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003355 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3356 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003357 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3358 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003359
3360 switch (Unresolved.Kind) {
3361 case UnresolvedModuleRef::Conflict:
3362 if (ResolvedMod) {
3363 Module::Conflict Conflict;
3364 Conflict.Other = ResolvedMod;
3365 Conflict.Message = Unresolved.String.str();
3366 Unresolved.Mod->Conflicts.push_back(Conflict);
3367 }
3368 continue;
3369
3370 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003371 if (ResolvedMod)
3372 Unresolved.Mod->Imports.push_back(ResolvedMod);
3373 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003374
Douglas Gregorfb912652013-03-20 21:10:35 +00003375 case UnresolvedModuleRef::Export:
3376 if (ResolvedMod || Unresolved.IsWildcard)
3377 Unresolved.Mod->Exports.push_back(
3378 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3379 continue;
3380 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003381 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003382 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003383
3384 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3385 // Might be unnecessary as use declarations are only used to build the
3386 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003387
3388 InitializeContext();
3389
Richard Smith3d8e97e2013-10-18 06:54:39 +00003390 if (SemaObj)
3391 UpdateSema();
3392
Guy Benyei11169dd2012-12-18 14:30:41 +00003393 if (DeserializationListener)
3394 DeserializationListener->ReaderInitialized(this);
3395
3396 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3397 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3398 PrimaryModule.OriginalSourceFileID
3399 = FileID::get(PrimaryModule.SLocEntryBaseID
3400 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3401
3402 // If this AST file is a precompiled preamble, then set the
3403 // preamble file ID of the source manager to the file source file
3404 // from which the preamble was built.
3405 if (Type == MK_Preamble) {
3406 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3407 } else if (Type == MK_MainFile) {
3408 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3409 }
3410 }
3411
3412 // For any Objective-C class definitions we have already loaded, make sure
3413 // that we load any additional categories.
3414 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3415 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3416 ObjCClassesLoaded[I],
3417 PreviousGeneration);
3418 }
Douglas Gregore060e572013-01-25 01:03:03 +00003419
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003420 if (PP.getHeaderSearchInfo()
3421 .getHeaderSearchOpts()
3422 .ModulesValidateOncePerBuildSession) {
3423 // Now we are certain that the module and all modules it depends on are
3424 // up to date. Create or update timestamp files for modules that are
3425 // located in the module cache (not for PCH files that could be anywhere
3426 // in the filesystem).
3427 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3428 ImportedModule &M = Loaded[I];
3429 if (M.Mod->Kind == MK_Module) {
3430 updateModuleTimestamp(*M.Mod);
3431 }
3432 }
3433 }
3434
Guy Benyei11169dd2012-12-18 14:30:41 +00003435 return Success;
3436}
3437
3438ASTReader::ASTReadResult
3439ASTReader::ReadASTCore(StringRef FileName,
3440 ModuleKind Type,
3441 SourceLocation ImportLoc,
3442 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003443 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003444 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003445 unsigned ClientLoadCapabilities) {
3446 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003447 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003448 ModuleManager::AddModuleResult AddResult
3449 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3450 CurrentGeneration, ExpectedSize, ExpectedModTime,
3451 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003452
Douglas Gregor7029ce12013-03-19 00:28:20 +00003453 switch (AddResult) {
3454 case ModuleManager::AlreadyLoaded:
3455 return Success;
3456
3457 case ModuleManager::NewlyLoaded:
3458 // Load module file below.
3459 break;
3460
3461 case ModuleManager::Missing:
3462 // The module file was missing; if the client handle handle, that, return
3463 // it.
3464 if (ClientLoadCapabilities & ARR_Missing)
3465 return Missing;
3466
3467 // Otherwise, return an error.
3468 {
3469 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3470 + ErrorStr;
3471 Error(Msg);
3472 }
3473 return Failure;
3474
3475 case ModuleManager::OutOfDate:
3476 // We couldn't load the module file because it is out-of-date. If the
3477 // client can handle out-of-date, return it.
3478 if (ClientLoadCapabilities & ARR_OutOfDate)
3479 return OutOfDate;
3480
3481 // Otherwise, return an error.
3482 {
3483 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3484 + ErrorStr;
3485 Error(Msg);
3486 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003487 return Failure;
3488 }
3489
Douglas Gregor7029ce12013-03-19 00:28:20 +00003490 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003491
3492 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3493 // module?
3494 if (FileName != "-") {
3495 CurrentDir = llvm::sys::path::parent_path(FileName);
3496 if (CurrentDir.empty()) CurrentDir = ".";
3497 }
3498
3499 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003500 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003501 Stream.init(F.StreamFile);
3502 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3503
3504 // Sniff for the signature.
3505 if (Stream.Read(8) != 'C' ||
3506 Stream.Read(8) != 'P' ||
3507 Stream.Read(8) != 'C' ||
3508 Stream.Read(8) != 'H') {
3509 Diag(diag::err_not_a_pch_file) << FileName;
3510 return Failure;
3511 }
3512
3513 // This is used for compatibility with older PCH formats.
3514 bool HaveReadControlBlock = false;
3515
Chris Lattnerefa77172013-01-20 00:00:22 +00003516 while (1) {
3517 llvm::BitstreamEntry Entry = Stream.advance();
3518
3519 switch (Entry.Kind) {
3520 case llvm::BitstreamEntry::Error:
3521 case llvm::BitstreamEntry::EndBlock:
3522 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003523 Error("invalid record at top-level of AST file");
3524 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003525
3526 case llvm::BitstreamEntry::SubBlock:
3527 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003528 }
3529
Guy Benyei11169dd2012-12-18 14:30:41 +00003530 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003531 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003532 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3533 if (Stream.ReadBlockInfoBlock()) {
3534 Error("malformed BlockInfoBlock in AST file");
3535 return Failure;
3536 }
3537 break;
3538 case CONTROL_BLOCK_ID:
3539 HaveReadControlBlock = true;
3540 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
3541 case Success:
3542 break;
3543
3544 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003545 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003546 case OutOfDate: return OutOfDate;
3547 case VersionMismatch: return VersionMismatch;
3548 case ConfigurationMismatch: return ConfigurationMismatch;
3549 case HadErrors: return HadErrors;
3550 }
3551 break;
3552 case AST_BLOCK_ID:
3553 if (!HaveReadControlBlock) {
3554 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003555 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003556 return VersionMismatch;
3557 }
3558
3559 // Record that we've loaded this module.
3560 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3561 return Success;
3562
3563 default:
3564 if (Stream.SkipBlock()) {
3565 Error("malformed block record in AST file");
3566 return Failure;
3567 }
3568 break;
3569 }
3570 }
3571
3572 return Success;
3573}
3574
3575void ASTReader::InitializeContext() {
3576 // If there's a listener, notify them that we "read" the translation unit.
3577 if (DeserializationListener)
3578 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3579 Context.getTranslationUnitDecl());
3580
3581 // Make sure we load the declaration update records for the translation unit,
3582 // if there are any.
3583 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3584 Context.getTranslationUnitDecl());
3585
3586 // FIXME: Find a better way to deal with collisions between these
3587 // built-in types. Right now, we just ignore the problem.
3588
3589 // Load the special types.
3590 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3591 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3592 if (!Context.CFConstantStringTypeDecl)
3593 Context.setCFConstantStringType(GetType(String));
3594 }
3595
3596 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3597 QualType FileType = GetType(File);
3598 if (FileType.isNull()) {
3599 Error("FILE type is NULL");
3600 return;
3601 }
3602
3603 if (!Context.FILEDecl) {
3604 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3605 Context.setFILEDecl(Typedef->getDecl());
3606 else {
3607 const TagType *Tag = FileType->getAs<TagType>();
3608 if (!Tag) {
3609 Error("Invalid FILE type in AST file");
3610 return;
3611 }
3612 Context.setFILEDecl(Tag->getDecl());
3613 }
3614 }
3615 }
3616
3617 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3618 QualType Jmp_bufType = GetType(Jmp_buf);
3619 if (Jmp_bufType.isNull()) {
3620 Error("jmp_buf type is NULL");
3621 return;
3622 }
3623
3624 if (!Context.jmp_bufDecl) {
3625 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3626 Context.setjmp_bufDecl(Typedef->getDecl());
3627 else {
3628 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3629 if (!Tag) {
3630 Error("Invalid jmp_buf type in AST file");
3631 return;
3632 }
3633 Context.setjmp_bufDecl(Tag->getDecl());
3634 }
3635 }
3636 }
3637
3638 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3639 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3640 if (Sigjmp_bufType.isNull()) {
3641 Error("sigjmp_buf type is NULL");
3642 return;
3643 }
3644
3645 if (!Context.sigjmp_bufDecl) {
3646 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3647 Context.setsigjmp_bufDecl(Typedef->getDecl());
3648 else {
3649 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3650 assert(Tag && "Invalid sigjmp_buf type in AST file");
3651 Context.setsigjmp_bufDecl(Tag->getDecl());
3652 }
3653 }
3654 }
3655
3656 if (unsigned ObjCIdRedef
3657 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3658 if (Context.ObjCIdRedefinitionType.isNull())
3659 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3660 }
3661
3662 if (unsigned ObjCClassRedef
3663 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3664 if (Context.ObjCClassRedefinitionType.isNull())
3665 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3666 }
3667
3668 if (unsigned ObjCSelRedef
3669 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3670 if (Context.ObjCSelRedefinitionType.isNull())
3671 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3672 }
3673
3674 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3675 QualType Ucontext_tType = GetType(Ucontext_t);
3676 if (Ucontext_tType.isNull()) {
3677 Error("ucontext_t type is NULL");
3678 return;
3679 }
3680
3681 if (!Context.ucontext_tDecl) {
3682 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3683 Context.setucontext_tDecl(Typedef->getDecl());
3684 else {
3685 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3686 assert(Tag && "Invalid ucontext_t type in AST file");
3687 Context.setucontext_tDecl(Tag->getDecl());
3688 }
3689 }
3690 }
3691 }
3692
3693 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3694
3695 // If there were any CUDA special declarations, deserialize them.
3696 if (!CUDASpecialDeclRefs.empty()) {
3697 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3698 Context.setcudaConfigureCallDecl(
3699 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3700 }
Richard Smith56be7542014-03-21 00:33:59 +00003701
Guy Benyei11169dd2012-12-18 14:30:41 +00003702 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00003703 // FIXME: This does not make macro-only imports visible again. It also doesn't
3704 // make #includes mapped to module imports visible.
3705 for (auto &Import : ImportedModules) {
3706 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003707 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00003708 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00003709 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003710 }
3711 ImportedModules.clear();
3712}
3713
3714void ASTReader::finalizeForWriting() {
3715 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3716 HiddenEnd = HiddenNamesMap.end();
3717 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003718 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003719 }
3720 HiddenNamesMap.clear();
3721}
3722
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003723/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3724/// cursor into the start of the given block ID, returning false on success and
3725/// true on failure.
3726static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003727 while (1) {
3728 llvm::BitstreamEntry Entry = Cursor.advance();
3729 switch (Entry.Kind) {
3730 case llvm::BitstreamEntry::Error:
3731 case llvm::BitstreamEntry::EndBlock:
3732 return true;
3733
3734 case llvm::BitstreamEntry::Record:
3735 // Ignore top-level records.
3736 Cursor.skipRecord(Entry.ID);
3737 break;
3738
3739 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003740 if (Entry.ID == BlockID) {
3741 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003742 return true;
3743 // Found it!
3744 return false;
3745 }
3746
3747 if (Cursor.SkipBlock())
3748 return true;
3749 }
3750 }
3751}
3752
Guy Benyei11169dd2012-12-18 14:30:41 +00003753/// \brief Retrieve the name of the original source file name
3754/// directly from the AST file, without actually loading the AST
3755/// file.
3756std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3757 FileManager &FileMgr,
3758 DiagnosticsEngine &Diags) {
3759 // Open the AST file.
3760 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003761 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003762 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3763 if (!Buffer) {
3764 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3765 return std::string();
3766 }
3767
3768 // Initialize the stream
3769 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003770 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003771 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3772 (const unsigned char *)Buffer->getBufferEnd());
3773 Stream.init(StreamFile);
3774
3775 // Sniff for the signature.
3776 if (Stream.Read(8) != 'C' ||
3777 Stream.Read(8) != 'P' ||
3778 Stream.Read(8) != 'C' ||
3779 Stream.Read(8) != 'H') {
3780 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3781 return std::string();
3782 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003783
Chris Lattnere7b154b2013-01-19 21:39:22 +00003784 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003785 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003786 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3787 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003788 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003789
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003790 // Scan for ORIGINAL_FILE inside the control block.
3791 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003792 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003793 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003794 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3795 return std::string();
3796
3797 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3798 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3799 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003800 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003801
Guy Benyei11169dd2012-12-18 14:30:41 +00003802 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003803 StringRef Blob;
3804 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3805 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003806 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003807}
3808
3809namespace {
3810 class SimplePCHValidator : public ASTReaderListener {
3811 const LangOptions &ExistingLangOpts;
3812 const TargetOptions &ExistingTargetOpts;
3813 const PreprocessorOptions &ExistingPPOpts;
3814 FileManager &FileMgr;
3815
3816 public:
3817 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3818 const TargetOptions &ExistingTargetOpts,
3819 const PreprocessorOptions &ExistingPPOpts,
3820 FileManager &FileMgr)
3821 : ExistingLangOpts(ExistingLangOpts),
3822 ExistingTargetOpts(ExistingTargetOpts),
3823 ExistingPPOpts(ExistingPPOpts),
3824 FileMgr(FileMgr)
3825 {
3826 }
3827
Craig Topper3e89dfe2014-03-13 02:13:41 +00003828 bool ReadLanguageOptions(const LangOptions &LangOpts,
3829 bool Complain) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003830 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3831 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003832 bool ReadTargetOptions(const TargetOptions &TargetOpts,
3833 bool Complain) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003834 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3835 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003836 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3837 bool Complain,
3838 std::string &SuggestedPredefines) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003839 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003840 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003841 }
3842 };
3843}
3844
3845bool ASTReader::readASTFileControlBlock(StringRef Filename,
3846 FileManager &FileMgr,
3847 ASTReaderListener &Listener) {
3848 // Open the AST file.
3849 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003850 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003851 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3852 if (!Buffer) {
3853 return true;
3854 }
3855
3856 // Initialize the stream
3857 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003858 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003859 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3860 (const unsigned char *)Buffer->getBufferEnd());
3861 Stream.init(StreamFile);
3862
3863 // Sniff for the signature.
3864 if (Stream.Read(8) != 'C' ||
3865 Stream.Read(8) != 'P' ||
3866 Stream.Read(8) != 'C' ||
3867 Stream.Read(8) != 'H') {
3868 return true;
3869 }
3870
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003871 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003872 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003873 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003874
3875 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00003876 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003877 BitstreamCursor InputFilesCursor;
3878 if (NeedsInputFiles) {
3879 InputFilesCursor = Stream;
3880 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
3881 return true;
3882
3883 // Read the abbreviations
3884 while (true) {
3885 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
3886 unsigned Code = InputFilesCursor.ReadCode();
3887
3888 // We expect all abbrevs to be at the start of the block.
3889 if (Code != llvm::bitc::DEFINE_ABBREV) {
3890 InputFilesCursor.JumpToBit(Offset);
3891 break;
3892 }
3893 InputFilesCursor.ReadAbbrevRecord();
3894 }
3895 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003896
3897 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00003898 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003899 while (1) {
3900 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3901 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3902 return false;
3903
3904 if (Entry.Kind != llvm::BitstreamEntry::Record)
3905 return true;
3906
Guy Benyei11169dd2012-12-18 14:30:41 +00003907 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003908 StringRef Blob;
3909 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003910 switch ((ControlRecordTypes)RecCode) {
3911 case METADATA: {
3912 if (Record[0] != VERSION_MAJOR)
3913 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003914
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003915 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003916 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003917
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003918 break;
3919 }
3920 case LANGUAGE_OPTIONS:
3921 if (ParseLanguageOptions(Record, false, Listener))
3922 return true;
3923 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003924
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003925 case TARGET_OPTIONS:
3926 if (ParseTargetOptions(Record, false, Listener))
3927 return true;
3928 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003929
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003930 case DIAGNOSTIC_OPTIONS:
3931 if (ParseDiagnosticOptions(Record, false, Listener))
3932 return true;
3933 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003934
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003935 case FILE_SYSTEM_OPTIONS:
3936 if (ParseFileSystemOptions(Record, false, Listener))
3937 return true;
3938 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003939
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003940 case HEADER_SEARCH_OPTIONS:
3941 if (ParseHeaderSearchOptions(Record, false, Listener))
3942 return true;
3943 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003944
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003945 case PREPROCESSOR_OPTIONS: {
3946 std::string IgnoredSuggestedPredefines;
3947 if (ParsePreprocessorOptions(Record, false, Listener,
3948 IgnoredSuggestedPredefines))
3949 return true;
3950 break;
3951 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003952
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003953 case INPUT_FILE_OFFSETS: {
3954 if (!NeedsInputFiles)
3955 break;
3956
3957 unsigned NumInputFiles = Record[0];
3958 unsigned NumUserFiles = Record[1];
3959 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
3960 for (unsigned I = 0; I != NumInputFiles; ++I) {
3961 // Go find this input file.
3962 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00003963
3964 if (isSystemFile && !NeedsSystemInputFiles)
3965 break; // the rest are system input files
3966
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003967 BitstreamCursor &Cursor = InputFilesCursor;
3968 SavedStreamPosition SavedPosition(Cursor);
3969 Cursor.JumpToBit(InputFileOffs[I]);
3970
3971 unsigned Code = Cursor.ReadCode();
3972 RecordData Record;
3973 StringRef Blob;
3974 bool shouldContinue = false;
3975 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
3976 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00003977 bool Overridden = static_cast<bool>(Record[3]);
3978 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003979 break;
3980 }
3981 if (!shouldContinue)
3982 break;
3983 }
3984 break;
3985 }
3986
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003987 default:
3988 // No other validation to perform.
3989 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003990 }
3991 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003992}
3993
3994
3995bool ASTReader::isAcceptableASTFile(StringRef Filename,
3996 FileManager &FileMgr,
3997 const LangOptions &LangOpts,
3998 const TargetOptions &TargetOpts,
3999 const PreprocessorOptions &PPOpts) {
4000 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4001 return !readASTFileControlBlock(Filename, FileMgr, validator);
4002}
4003
Ben Langmuir2c9af442014-04-10 17:57:43 +00004004ASTReader::ASTReadResult
4005ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004006 // Enter the submodule block.
4007 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4008 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004009 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004010 }
4011
4012 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4013 bool First = true;
4014 Module *CurrentModule = 0;
4015 RecordData Record;
4016 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004017 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4018
4019 switch (Entry.Kind) {
4020 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4021 case llvm::BitstreamEntry::Error:
4022 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004023 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004024 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004025 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004026 case llvm::BitstreamEntry::Record:
4027 // The interesting case.
4028 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004029 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004030
Guy Benyei11169dd2012-12-18 14:30:41 +00004031 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004032 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004033 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004034 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004035 default: // Default behavior: ignore.
4036 break;
4037
4038 case SUBMODULE_DEFINITION: {
4039 if (First) {
4040 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004041 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004042 }
4043
Douglas Gregor8d932422013-03-20 03:59:18 +00004044 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004045 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004046 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004047 }
4048
Chris Lattner0e6c9402013-01-20 02:38:54 +00004049 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004050 unsigned Idx = 0;
4051 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4052 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4053 bool IsFramework = Record[Idx++];
4054 bool IsExplicit = Record[Idx++];
4055 bool IsSystem = Record[Idx++];
4056 bool IsExternC = Record[Idx++];
4057 bool InferSubmodules = Record[Idx++];
4058 bool InferExplicitSubmodules = Record[Idx++];
4059 bool InferExportWildcard = Record[Idx++];
4060 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004061
Guy Benyei11169dd2012-12-18 14:30:41 +00004062 Module *ParentModule = 0;
4063 if (Parent)
4064 ParentModule = getSubmodule(Parent);
4065
4066 // Retrieve this (sub)module from the module map, creating it if
4067 // necessary.
4068 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
4069 IsFramework,
4070 IsExplicit).first;
4071 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4072 if (GlobalIndex >= SubmodulesLoaded.size() ||
4073 SubmodulesLoaded[GlobalIndex]) {
4074 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004075 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004076 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004077
Douglas Gregor7029ce12013-03-19 00:28:20 +00004078 if (!ParentModule) {
4079 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4080 if (CurFile != F.File) {
4081 if (!Diags.isDiagnosticInFlight()) {
4082 Diag(diag::err_module_file_conflict)
4083 << CurrentModule->getTopLevelModuleName()
4084 << CurFile->getName()
4085 << F.File->getName();
4086 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004087 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004088 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004089 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004090
4091 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004092 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004093
Guy Benyei11169dd2012-12-18 14:30:41 +00004094 CurrentModule->IsFromModuleFile = true;
4095 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004096 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004097 CurrentModule->InferSubmodules = InferSubmodules;
4098 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4099 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004100 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004101 if (DeserializationListener)
4102 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4103
4104 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004105
Douglas Gregorfb912652013-03-20 21:10:35 +00004106 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004107 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004108 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004109 CurrentModule->UnresolvedConflicts.clear();
4110 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004111 break;
4112 }
4113
4114 case SUBMODULE_UMBRELLA_HEADER: {
4115 if (First) {
4116 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004117 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004118 }
4119
4120 if (!CurrentModule)
4121 break;
4122
Chris Lattner0e6c9402013-01-20 02:38:54 +00004123 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004124 if (!CurrentModule->getUmbrellaHeader())
4125 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4126 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004127 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4128 Error("mismatched umbrella headers in submodule");
4129 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004130 }
4131 }
4132 break;
4133 }
4134
4135 case SUBMODULE_HEADER: {
4136 if (First) {
4137 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004138 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004139 }
4140
4141 if (!CurrentModule)
4142 break;
4143
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004144 // We lazily associate headers with their modules via the HeaderInfoTable.
4145 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4146 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004147 break;
4148 }
4149
4150 case SUBMODULE_EXCLUDED_HEADER: {
4151 if (First) {
4152 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004153 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004154 }
4155
4156 if (!CurrentModule)
4157 break;
4158
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004159 // We lazily associate headers with their modules via the HeaderInfoTable.
4160 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4161 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004162 break;
4163 }
4164
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004165 case SUBMODULE_PRIVATE_HEADER: {
4166 if (First) {
4167 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004168 return Failure;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004169 }
4170
4171 if (!CurrentModule)
4172 break;
4173
4174 // We lazily associate headers with their modules via the HeaderInfoTable.
4175 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4176 // of complete filenames or remove it entirely.
4177 break;
4178 }
4179
Guy Benyei11169dd2012-12-18 14:30:41 +00004180 case SUBMODULE_TOPHEADER: {
4181 if (First) {
4182 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004183 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004184 }
4185
4186 if (!CurrentModule)
4187 break;
4188
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004189 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004190 break;
4191 }
4192
4193 case SUBMODULE_UMBRELLA_DIR: {
4194 if (First) {
4195 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004196 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004197 }
4198
4199 if (!CurrentModule)
4200 break;
4201
Guy Benyei11169dd2012-12-18 14:30:41 +00004202 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004203 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004204 if (!CurrentModule->getUmbrellaDir())
4205 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4206 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004207 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4208 Error("mismatched umbrella directories in submodule");
4209 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004210 }
4211 }
4212 break;
4213 }
4214
4215 case SUBMODULE_METADATA: {
4216 if (!First) {
4217 Error("submodule metadata record not at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004218 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004219 }
4220 First = false;
4221
4222 F.BaseSubmoduleID = getTotalNumSubmodules();
4223 F.LocalNumSubmodules = Record[0];
4224 unsigned LocalBaseSubmoduleID = Record[1];
4225 if (F.LocalNumSubmodules > 0) {
4226 // Introduce the global -> local mapping for submodules within this
4227 // module.
4228 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4229
4230 // Introduce the local -> global mapping for submodules within this
4231 // module.
4232 F.SubmoduleRemap.insertOrReplace(
4233 std::make_pair(LocalBaseSubmoduleID,
4234 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4235
4236 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4237 }
4238 break;
4239 }
4240
4241 case SUBMODULE_IMPORTS: {
4242 if (First) {
4243 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004244 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004245 }
4246
4247 if (!CurrentModule)
4248 break;
4249
4250 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004251 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004252 Unresolved.File = &F;
4253 Unresolved.Mod = CurrentModule;
4254 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004255 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004257 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004258 }
4259 break;
4260 }
4261
4262 case SUBMODULE_EXPORTS: {
4263 if (First) {
4264 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004265 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004266 }
4267
4268 if (!CurrentModule)
4269 break;
4270
4271 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004272 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004273 Unresolved.File = &F;
4274 Unresolved.Mod = CurrentModule;
4275 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004276 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004277 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004278 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 }
4280
4281 // Once we've loaded the set of exports, there's no reason to keep
4282 // the parsed, unresolved exports around.
4283 CurrentModule->UnresolvedExports.clear();
4284 break;
4285 }
4286 case SUBMODULE_REQUIRES: {
4287 if (First) {
4288 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004289 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 }
4291
4292 if (!CurrentModule)
4293 break;
4294
Richard Smitha3feee22013-10-28 22:18:19 +00004295 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 Context.getTargetInfo());
4297 break;
4298 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004299
4300 case SUBMODULE_LINK_LIBRARY:
4301 if (First) {
4302 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004303 return Failure;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004304 }
4305
4306 if (!CurrentModule)
4307 break;
4308
4309 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004310 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004311 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004312
4313 case SUBMODULE_CONFIG_MACRO:
4314 if (First) {
4315 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004316 return Failure;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004317 }
4318
4319 if (!CurrentModule)
4320 break;
4321
4322 CurrentModule->ConfigMacros.push_back(Blob.str());
4323 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004324
4325 case SUBMODULE_CONFLICT: {
4326 if (First) {
4327 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004328 return Failure;
Douglas Gregorfb912652013-03-20 21:10:35 +00004329 }
4330
4331 if (!CurrentModule)
4332 break;
4333
4334 UnresolvedModuleRef Unresolved;
4335 Unresolved.File = &F;
4336 Unresolved.Mod = CurrentModule;
4337 Unresolved.ID = Record[0];
4338 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4339 Unresolved.IsWildcard = false;
4340 Unresolved.String = Blob;
4341 UnresolvedModuleRefs.push_back(Unresolved);
4342 break;
4343 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004344 }
4345 }
4346}
4347
4348/// \brief Parse the record that corresponds to a LangOptions data
4349/// structure.
4350///
4351/// This routine parses the language options from the AST file and then gives
4352/// them to the AST listener if one is set.
4353///
4354/// \returns true if the listener deems the file unacceptable, false otherwise.
4355bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4356 bool Complain,
4357 ASTReaderListener &Listener) {
4358 LangOptions LangOpts;
4359 unsigned Idx = 0;
4360#define LANGOPT(Name, Bits, Default, Description) \
4361 LangOpts.Name = Record[Idx++];
4362#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4363 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4364#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004365#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4366#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004367
4368 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4369 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4370 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4371
4372 unsigned Length = Record[Idx++];
4373 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4374 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004375
4376 Idx += Length;
4377
4378 // Comment options.
4379 for (unsigned N = Record[Idx++]; N; --N) {
4380 LangOpts.CommentOpts.BlockCommandNames.push_back(
4381 ReadString(Record, Idx));
4382 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004383 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004384
Guy Benyei11169dd2012-12-18 14:30:41 +00004385 return Listener.ReadLanguageOptions(LangOpts, Complain);
4386}
4387
4388bool ASTReader::ParseTargetOptions(const RecordData &Record,
4389 bool Complain,
4390 ASTReaderListener &Listener) {
4391 unsigned Idx = 0;
4392 TargetOptions TargetOpts;
4393 TargetOpts.Triple = ReadString(Record, Idx);
4394 TargetOpts.CPU = ReadString(Record, Idx);
4395 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004396 TargetOpts.LinkerVersion = ReadString(Record, Idx);
4397 for (unsigned N = Record[Idx++]; N; --N) {
4398 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4399 }
4400 for (unsigned N = Record[Idx++]; N; --N) {
4401 TargetOpts.Features.push_back(ReadString(Record, Idx));
4402 }
4403
4404 return Listener.ReadTargetOptions(TargetOpts, Complain);
4405}
4406
4407bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4408 ASTReaderListener &Listener) {
4409 DiagnosticOptions DiagOpts;
4410 unsigned Idx = 0;
4411#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
4412#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4413 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
4414#include "clang/Basic/DiagnosticOptions.def"
4415
4416 for (unsigned N = Record[Idx++]; N; --N) {
4417 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
4418 }
4419
4420 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4421}
4422
4423bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4424 ASTReaderListener &Listener) {
4425 FileSystemOptions FSOpts;
4426 unsigned Idx = 0;
4427 FSOpts.WorkingDir = ReadString(Record, Idx);
4428 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4429}
4430
4431bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4432 bool Complain,
4433 ASTReaderListener &Listener) {
4434 HeaderSearchOptions HSOpts;
4435 unsigned Idx = 0;
4436 HSOpts.Sysroot = ReadString(Record, Idx);
4437
4438 // Include entries.
4439 for (unsigned N = Record[Idx++]; N; --N) {
4440 std::string Path = ReadString(Record, Idx);
4441 frontend::IncludeDirGroup Group
4442 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 bool IsFramework = Record[Idx++];
4444 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004446 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004447 }
4448
4449 // System header prefixes.
4450 for (unsigned N = Record[Idx++]; N; --N) {
4451 std::string Prefix = ReadString(Record, Idx);
4452 bool IsSystemHeader = Record[Idx++];
4453 HSOpts.SystemHeaderPrefixes.push_back(
4454 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4455 }
4456
4457 HSOpts.ResourceDir = ReadString(Record, Idx);
4458 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004459 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 HSOpts.DisableModuleHash = Record[Idx++];
4461 HSOpts.UseBuiltinIncludes = Record[Idx++];
4462 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4463 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4464 HSOpts.UseLibcxx = Record[Idx++];
4465
4466 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4467}
4468
4469bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4470 bool Complain,
4471 ASTReaderListener &Listener,
4472 std::string &SuggestedPredefines) {
4473 PreprocessorOptions PPOpts;
4474 unsigned Idx = 0;
4475
4476 // Macro definitions/undefs
4477 for (unsigned N = Record[Idx++]; N; --N) {
4478 std::string Macro = ReadString(Record, Idx);
4479 bool IsUndef = Record[Idx++];
4480 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4481 }
4482
4483 // Includes
4484 for (unsigned N = Record[Idx++]; N; --N) {
4485 PPOpts.Includes.push_back(ReadString(Record, Idx));
4486 }
4487
4488 // Macro Includes
4489 for (unsigned N = Record[Idx++]; N; --N) {
4490 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4491 }
4492
4493 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004494 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4496 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4497 PPOpts.ObjCXXARCStandardLibrary =
4498 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4499 SuggestedPredefines.clear();
4500 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4501 SuggestedPredefines);
4502}
4503
4504std::pair<ModuleFile *, unsigned>
4505ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4506 GlobalPreprocessedEntityMapType::iterator
4507 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4508 assert(I != GlobalPreprocessedEntityMap.end() &&
4509 "Corrupted global preprocessed entity map");
4510 ModuleFile *M = I->second;
4511 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4512 return std::make_pair(M, LocalIndex);
4513}
4514
4515std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4516ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4517 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4518 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4519 Mod.NumPreprocessedEntities);
4520
4521 return std::make_pair(PreprocessingRecord::iterator(),
4522 PreprocessingRecord::iterator());
4523}
4524
4525std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4526ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4527 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4528 ModuleDeclIterator(this, &Mod,
4529 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4530}
4531
4532PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4533 PreprocessedEntityID PPID = Index+1;
4534 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4535 ModuleFile &M = *PPInfo.first;
4536 unsigned LocalIndex = PPInfo.second;
4537 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4538
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 if (!PP.getPreprocessingRecord()) {
4540 Error("no preprocessing record");
4541 return 0;
4542 }
4543
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004544 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4545 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4546
4547 llvm::BitstreamEntry Entry =
4548 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4549 if (Entry.Kind != llvm::BitstreamEntry::Record)
4550 return 0;
4551
Guy Benyei11169dd2012-12-18 14:30:41 +00004552 // Read the record.
4553 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4554 ReadSourceLocation(M, PPOffs.End));
4555 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004556 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 RecordData Record;
4558 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004559 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4560 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004561 switch (RecType) {
4562 case PPD_MACRO_EXPANSION: {
4563 bool isBuiltin = Record[0];
4564 IdentifierInfo *Name = 0;
4565 MacroDefinition *Def = 0;
4566 if (isBuiltin)
4567 Name = getLocalIdentifier(M, Record[1]);
4568 else {
4569 PreprocessedEntityID
4570 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4571 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4572 }
4573
4574 MacroExpansion *ME;
4575 if (isBuiltin)
4576 ME = new (PPRec) MacroExpansion(Name, Range);
4577 else
4578 ME = new (PPRec) MacroExpansion(Def, Range);
4579
4580 return ME;
4581 }
4582
4583 case PPD_MACRO_DEFINITION: {
4584 // Decode the identifier info and then check again; if the macro is
4585 // still defined and associated with the identifier,
4586 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4587 MacroDefinition *MD
4588 = new (PPRec) MacroDefinition(II, Range);
4589
4590 if (DeserializationListener)
4591 DeserializationListener->MacroDefinitionRead(PPID, MD);
4592
4593 return MD;
4594 }
4595
4596 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004597 const char *FullFileNameStart = Blob.data() + Record[0];
4598 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004599 const FileEntry *File = 0;
4600 if (!FullFileName.empty())
4601 File = PP.getFileManager().getFile(FullFileName);
4602
4603 // FIXME: Stable encoding
4604 InclusionDirective::InclusionKind Kind
4605 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4606 InclusionDirective *ID
4607 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004608 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004609 Record[1], Record[3],
4610 File,
4611 Range);
4612 return ID;
4613 }
4614 }
4615
4616 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4617}
4618
4619/// \brief \arg SLocMapI points at a chunk of a module that contains no
4620/// preprocessed entities or the entities it contains are not the ones we are
4621/// looking for. Find the next module that contains entities and return the ID
4622/// of the first entry.
4623PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4624 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4625 ++SLocMapI;
4626 for (GlobalSLocOffsetMapType::const_iterator
4627 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4628 ModuleFile &M = *SLocMapI->second;
4629 if (M.NumPreprocessedEntities)
4630 return M.BasePreprocessedEntityID;
4631 }
4632
4633 return getTotalNumPreprocessedEntities();
4634}
4635
4636namespace {
4637
4638template <unsigned PPEntityOffset::*PPLoc>
4639struct PPEntityComp {
4640 const ASTReader &Reader;
4641 ModuleFile &M;
4642
4643 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4644
4645 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4646 SourceLocation LHS = getLoc(L);
4647 SourceLocation RHS = getLoc(R);
4648 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4649 }
4650
4651 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4652 SourceLocation LHS = getLoc(L);
4653 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4654 }
4655
4656 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4657 SourceLocation RHS = getLoc(R);
4658 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4659 }
4660
4661 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4662 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4663 }
4664};
4665
4666}
4667
4668/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4669PreprocessedEntityID
4670ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4671 if (SourceMgr.isLocalSourceLocation(BLoc))
4672 return getTotalNumPreprocessedEntities();
4673
4674 GlobalSLocOffsetMapType::const_iterator
4675 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004676 BLoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004677 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4678 "Corrupted global sloc offset map");
4679
4680 if (SLocMapI->second->NumPreprocessedEntities == 0)
4681 return findNextPreprocessedEntity(SLocMapI);
4682
4683 ModuleFile &M = *SLocMapI->second;
4684 typedef const PPEntityOffset *pp_iterator;
4685 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4686 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4687
4688 size_t Count = M.NumPreprocessedEntities;
4689 size_t Half;
4690 pp_iterator First = pp_begin;
4691 pp_iterator PPI;
4692
4693 // Do a binary search manually instead of using std::lower_bound because
4694 // The end locations of entities may be unordered (when a macro expansion
4695 // is inside another macro argument), but for this case it is not important
4696 // whether we get the first macro expansion or its containing macro.
4697 while (Count > 0) {
4698 Half = Count/2;
4699 PPI = First;
4700 std::advance(PPI, Half);
4701 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4702 BLoc)){
4703 First = PPI;
4704 ++First;
4705 Count = Count - Half - 1;
4706 } else
4707 Count = Half;
4708 }
4709
4710 if (PPI == pp_end)
4711 return findNextPreprocessedEntity(SLocMapI);
4712
4713 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4714}
4715
4716/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4717PreprocessedEntityID
4718ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4719 if (SourceMgr.isLocalSourceLocation(ELoc))
4720 return getTotalNumPreprocessedEntities();
4721
4722 GlobalSLocOffsetMapType::const_iterator
4723 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004724 ELoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004725 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4726 "Corrupted global sloc offset map");
4727
4728 if (SLocMapI->second->NumPreprocessedEntities == 0)
4729 return findNextPreprocessedEntity(SLocMapI);
4730
4731 ModuleFile &M = *SLocMapI->second;
4732 typedef const PPEntityOffset *pp_iterator;
4733 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4734 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4735 pp_iterator PPI =
4736 std::upper_bound(pp_begin, pp_end, ELoc,
4737 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4738
4739 if (PPI == pp_end)
4740 return findNextPreprocessedEntity(SLocMapI);
4741
4742 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4743}
4744
4745/// \brief Returns a pair of [Begin, End) indices of preallocated
4746/// preprocessed entities that \arg Range encompasses.
4747std::pair<unsigned, unsigned>
4748 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4749 if (Range.isInvalid())
4750 return std::make_pair(0,0);
4751 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4752
4753 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4754 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4755 return std::make_pair(BeginID, EndID);
4756}
4757
4758/// \brief Optionally returns true or false if the preallocated preprocessed
4759/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004760Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004761 FileID FID) {
4762 if (FID.isInvalid())
4763 return false;
4764
4765 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4766 ModuleFile &M = *PPInfo.first;
4767 unsigned LocalIndex = PPInfo.second;
4768 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4769
4770 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4771 if (Loc.isInvalid())
4772 return false;
4773
4774 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4775 return true;
4776 else
4777 return false;
4778}
4779
4780namespace {
4781 /// \brief Visitor used to search for information about a header file.
4782 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 const FileEntry *FE;
4784
David Blaikie05785d12013-02-20 22:23:23 +00004785 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004786
4787 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004788 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4789 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004790
4791 static bool visit(ModuleFile &M, void *UserData) {
4792 HeaderFileInfoVisitor *This
4793 = static_cast<HeaderFileInfoVisitor *>(UserData);
4794
Guy Benyei11169dd2012-12-18 14:30:41 +00004795 HeaderFileInfoLookupTable *Table
4796 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4797 if (!Table)
4798 return false;
4799
4800 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004801 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004802 if (Pos == Table->end())
4803 return false;
4804
4805 This->HFI = *Pos;
4806 return true;
4807 }
4808
David Blaikie05785d12013-02-20 22:23:23 +00004809 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004810 };
4811}
4812
4813HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004814 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004815 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004816 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004817 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004818
4819 return HeaderFileInfo();
4820}
4821
4822void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4823 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004824 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004825 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4826 ModuleFile &F = *(*I);
4827 unsigned Idx = 0;
4828 DiagStates.clear();
4829 assert(!Diag.DiagStates.empty());
4830 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4831 while (Idx < F.PragmaDiagMappings.size()) {
4832 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4833 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4834 if (DiagStateID != 0) {
4835 Diag.DiagStatePoints.push_back(
4836 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4837 FullSourceLoc(Loc, SourceMgr)));
4838 continue;
4839 }
4840
4841 assert(DiagStateID == 0);
4842 // A new DiagState was created here.
4843 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4844 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4845 DiagStates.push_back(NewState);
4846 Diag.DiagStatePoints.push_back(
4847 DiagnosticsEngine::DiagStatePoint(NewState,
4848 FullSourceLoc(Loc, SourceMgr)));
4849 while (1) {
4850 assert(Idx < F.PragmaDiagMappings.size() &&
4851 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4852 if (Idx >= F.PragmaDiagMappings.size()) {
4853 break; // Something is messed up but at least avoid infinite loop in
4854 // release build.
4855 }
4856 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4857 if (DiagID == (unsigned)-1) {
4858 break; // no more diag/map pairs for this location.
4859 }
4860 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4861 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4862 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4863 }
4864 }
4865 }
4866}
4867
4868/// \brief Get the correct cursor and offset for loading a type.
4869ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4870 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4871 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4872 ModuleFile *M = I->second;
4873 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4874}
4875
4876/// \brief Read and return the type with the given index..
4877///
4878/// The index is the type ID, shifted and minus the number of predefs. This
4879/// routine actually reads the record corresponding to the type at the given
4880/// location. It is a helper routine for GetType, which deals with reading type
4881/// IDs.
4882QualType ASTReader::readTypeRecord(unsigned Index) {
4883 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004884 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004885
4886 // Keep track of where we are in the stream, then jump back there
4887 // after reading this type.
4888 SavedStreamPosition SavedPosition(DeclsCursor);
4889
4890 ReadingKindTracker ReadingKind(Read_Type, *this);
4891
4892 // Note that we are loading a type record.
4893 Deserializing AType(this);
4894
4895 unsigned Idx = 0;
4896 DeclsCursor.JumpToBit(Loc.Offset);
4897 RecordData Record;
4898 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004899 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004900 case TYPE_EXT_QUAL: {
4901 if (Record.size() != 2) {
4902 Error("Incorrect encoding of extended qualifier type");
4903 return QualType();
4904 }
4905 QualType Base = readType(*Loc.F, Record, Idx);
4906 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4907 return Context.getQualifiedType(Base, Quals);
4908 }
4909
4910 case TYPE_COMPLEX: {
4911 if (Record.size() != 1) {
4912 Error("Incorrect encoding of complex type");
4913 return QualType();
4914 }
4915 QualType ElemType = readType(*Loc.F, Record, Idx);
4916 return Context.getComplexType(ElemType);
4917 }
4918
4919 case TYPE_POINTER: {
4920 if (Record.size() != 1) {
4921 Error("Incorrect encoding of pointer type");
4922 return QualType();
4923 }
4924 QualType PointeeType = readType(*Loc.F, Record, Idx);
4925 return Context.getPointerType(PointeeType);
4926 }
4927
Reid Kleckner8a365022013-06-24 17:51:48 +00004928 case TYPE_DECAYED: {
4929 if (Record.size() != 1) {
4930 Error("Incorrect encoding of decayed type");
4931 return QualType();
4932 }
4933 QualType OriginalType = readType(*Loc.F, Record, Idx);
4934 QualType DT = Context.getAdjustedParameterType(OriginalType);
4935 if (!isa<DecayedType>(DT))
4936 Error("Decayed type does not decay");
4937 return DT;
4938 }
4939
Reid Kleckner0503a872013-12-05 01:23:43 +00004940 case TYPE_ADJUSTED: {
4941 if (Record.size() != 2) {
4942 Error("Incorrect encoding of adjusted type");
4943 return QualType();
4944 }
4945 QualType OriginalTy = readType(*Loc.F, Record, Idx);
4946 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
4947 return Context.getAdjustedType(OriginalTy, AdjustedTy);
4948 }
4949
Guy Benyei11169dd2012-12-18 14:30:41 +00004950 case TYPE_BLOCK_POINTER: {
4951 if (Record.size() != 1) {
4952 Error("Incorrect encoding of block pointer type");
4953 return QualType();
4954 }
4955 QualType PointeeType = readType(*Loc.F, Record, Idx);
4956 return Context.getBlockPointerType(PointeeType);
4957 }
4958
4959 case TYPE_LVALUE_REFERENCE: {
4960 if (Record.size() != 2) {
4961 Error("Incorrect encoding of lvalue reference type");
4962 return QualType();
4963 }
4964 QualType PointeeType = readType(*Loc.F, Record, Idx);
4965 return Context.getLValueReferenceType(PointeeType, Record[1]);
4966 }
4967
4968 case TYPE_RVALUE_REFERENCE: {
4969 if (Record.size() != 1) {
4970 Error("Incorrect encoding of rvalue reference type");
4971 return QualType();
4972 }
4973 QualType PointeeType = readType(*Loc.F, Record, Idx);
4974 return Context.getRValueReferenceType(PointeeType);
4975 }
4976
4977 case TYPE_MEMBER_POINTER: {
4978 if (Record.size() != 2) {
4979 Error("Incorrect encoding of member pointer type");
4980 return QualType();
4981 }
4982 QualType PointeeType = readType(*Loc.F, Record, Idx);
4983 QualType ClassType = readType(*Loc.F, Record, Idx);
4984 if (PointeeType.isNull() || ClassType.isNull())
4985 return QualType();
4986
4987 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4988 }
4989
4990 case TYPE_CONSTANT_ARRAY: {
4991 QualType ElementType = readType(*Loc.F, Record, Idx);
4992 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4993 unsigned IndexTypeQuals = Record[2];
4994 unsigned Idx = 3;
4995 llvm::APInt Size = ReadAPInt(Record, Idx);
4996 return Context.getConstantArrayType(ElementType, Size,
4997 ASM, IndexTypeQuals);
4998 }
4999
5000 case TYPE_INCOMPLETE_ARRAY: {
5001 QualType ElementType = readType(*Loc.F, Record, Idx);
5002 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5003 unsigned IndexTypeQuals = Record[2];
5004 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5005 }
5006
5007 case TYPE_VARIABLE_ARRAY: {
5008 QualType ElementType = readType(*Loc.F, Record, Idx);
5009 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5010 unsigned IndexTypeQuals = Record[2];
5011 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5012 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5013 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5014 ASM, IndexTypeQuals,
5015 SourceRange(LBLoc, RBLoc));
5016 }
5017
5018 case TYPE_VECTOR: {
5019 if (Record.size() != 3) {
5020 Error("incorrect encoding of vector type in AST file");
5021 return QualType();
5022 }
5023
5024 QualType ElementType = readType(*Loc.F, Record, Idx);
5025 unsigned NumElements = Record[1];
5026 unsigned VecKind = Record[2];
5027 return Context.getVectorType(ElementType, NumElements,
5028 (VectorType::VectorKind)VecKind);
5029 }
5030
5031 case TYPE_EXT_VECTOR: {
5032 if (Record.size() != 3) {
5033 Error("incorrect encoding of extended vector type in AST file");
5034 return QualType();
5035 }
5036
5037 QualType ElementType = readType(*Loc.F, Record, Idx);
5038 unsigned NumElements = Record[1];
5039 return Context.getExtVectorType(ElementType, NumElements);
5040 }
5041
5042 case TYPE_FUNCTION_NO_PROTO: {
5043 if (Record.size() != 6) {
5044 Error("incorrect encoding of no-proto function type");
5045 return QualType();
5046 }
5047 QualType ResultType = readType(*Loc.F, Record, Idx);
5048 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5049 (CallingConv)Record[4], Record[5]);
5050 return Context.getFunctionNoProtoType(ResultType, Info);
5051 }
5052
5053 case TYPE_FUNCTION_PROTO: {
5054 QualType ResultType = readType(*Loc.F, Record, Idx);
5055
5056 FunctionProtoType::ExtProtoInfo EPI;
5057 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5058 /*hasregparm*/ Record[2],
5059 /*regparm*/ Record[3],
5060 static_cast<CallingConv>(Record[4]),
5061 /*produces*/ Record[5]);
5062
5063 unsigned Idx = 6;
5064 unsigned NumParams = Record[Idx++];
5065 SmallVector<QualType, 16> ParamTypes;
5066 for (unsigned I = 0; I != NumParams; ++I)
5067 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5068
5069 EPI.Variadic = Record[Idx++];
5070 EPI.HasTrailingReturn = Record[Idx++];
5071 EPI.TypeQuals = Record[Idx++];
5072 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005073 SmallVector<QualType, 8> ExceptionStorage;
5074 readExceptionSpec(*Loc.F, ExceptionStorage, EPI, Record, Idx);
Jordan Rose5c382722013-03-08 21:51:21 +00005075 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 }
5077
5078 case TYPE_UNRESOLVED_USING: {
5079 unsigned Idx = 0;
5080 return Context.getTypeDeclType(
5081 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5082 }
5083
5084 case TYPE_TYPEDEF: {
5085 if (Record.size() != 2) {
5086 Error("incorrect encoding of typedef type");
5087 return QualType();
5088 }
5089 unsigned Idx = 0;
5090 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5091 QualType Canonical = readType(*Loc.F, Record, Idx);
5092 if (!Canonical.isNull())
5093 Canonical = Context.getCanonicalType(Canonical);
5094 return Context.getTypedefType(Decl, Canonical);
5095 }
5096
5097 case TYPE_TYPEOF_EXPR:
5098 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5099
5100 case TYPE_TYPEOF: {
5101 if (Record.size() != 1) {
5102 Error("incorrect encoding of typeof(type) in AST file");
5103 return QualType();
5104 }
5105 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5106 return Context.getTypeOfType(UnderlyingType);
5107 }
5108
5109 case TYPE_DECLTYPE: {
5110 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5111 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5112 }
5113
5114 case TYPE_UNARY_TRANSFORM: {
5115 QualType BaseType = readType(*Loc.F, Record, Idx);
5116 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5117 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5118 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5119 }
5120
Richard Smith74aeef52013-04-26 16:15:35 +00005121 case TYPE_AUTO: {
5122 QualType Deduced = readType(*Loc.F, Record, Idx);
5123 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005124 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005125 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005126 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005127
5128 case TYPE_RECORD: {
5129 if (Record.size() != 2) {
5130 Error("incorrect encoding of record type");
5131 return QualType();
5132 }
5133 unsigned Idx = 0;
5134 bool IsDependent = Record[Idx++];
5135 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5136 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5137 QualType T = Context.getRecordType(RD);
5138 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5139 return T;
5140 }
5141
5142 case TYPE_ENUM: {
5143 if (Record.size() != 2) {
5144 Error("incorrect encoding of enum type");
5145 return QualType();
5146 }
5147 unsigned Idx = 0;
5148 bool IsDependent = Record[Idx++];
5149 QualType T
5150 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5151 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5152 return T;
5153 }
5154
5155 case TYPE_ATTRIBUTED: {
5156 if (Record.size() != 3) {
5157 Error("incorrect encoding of attributed type");
5158 return QualType();
5159 }
5160 QualType modifiedType = readType(*Loc.F, Record, Idx);
5161 QualType equivalentType = readType(*Loc.F, Record, Idx);
5162 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5163 return Context.getAttributedType(kind, modifiedType, equivalentType);
5164 }
5165
5166 case TYPE_PAREN: {
5167 if (Record.size() != 1) {
5168 Error("incorrect encoding of paren type");
5169 return QualType();
5170 }
5171 QualType InnerType = readType(*Loc.F, Record, Idx);
5172 return Context.getParenType(InnerType);
5173 }
5174
5175 case TYPE_PACK_EXPANSION: {
5176 if (Record.size() != 2) {
5177 Error("incorrect encoding of pack expansion type");
5178 return QualType();
5179 }
5180 QualType Pattern = readType(*Loc.F, Record, Idx);
5181 if (Pattern.isNull())
5182 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005183 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005184 if (Record[1])
5185 NumExpansions = Record[1] - 1;
5186 return Context.getPackExpansionType(Pattern, NumExpansions);
5187 }
5188
5189 case TYPE_ELABORATED: {
5190 unsigned Idx = 0;
5191 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5192 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5193 QualType NamedType = readType(*Loc.F, Record, Idx);
5194 return Context.getElaboratedType(Keyword, NNS, NamedType);
5195 }
5196
5197 case TYPE_OBJC_INTERFACE: {
5198 unsigned Idx = 0;
5199 ObjCInterfaceDecl *ItfD
5200 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5201 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5202 }
5203
5204 case TYPE_OBJC_OBJECT: {
5205 unsigned Idx = 0;
5206 QualType Base = readType(*Loc.F, Record, Idx);
5207 unsigned NumProtos = Record[Idx++];
5208 SmallVector<ObjCProtocolDecl*, 4> Protos;
5209 for (unsigned I = 0; I != NumProtos; ++I)
5210 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5211 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5212 }
5213
5214 case TYPE_OBJC_OBJECT_POINTER: {
5215 unsigned Idx = 0;
5216 QualType Pointee = readType(*Loc.F, Record, Idx);
5217 return Context.getObjCObjectPointerType(Pointee);
5218 }
5219
5220 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5221 unsigned Idx = 0;
5222 QualType Parm = readType(*Loc.F, Record, Idx);
5223 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005224 return Context.getSubstTemplateTypeParmType(
5225 cast<TemplateTypeParmType>(Parm),
5226 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 }
5228
5229 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5230 unsigned Idx = 0;
5231 QualType Parm = readType(*Loc.F, Record, Idx);
5232 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5233 return Context.getSubstTemplateTypeParmPackType(
5234 cast<TemplateTypeParmType>(Parm),
5235 ArgPack);
5236 }
5237
5238 case TYPE_INJECTED_CLASS_NAME: {
5239 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5240 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5241 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5242 // for AST reading, too much interdependencies.
5243 return
5244 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
5245 }
5246
5247 case TYPE_TEMPLATE_TYPE_PARM: {
5248 unsigned Idx = 0;
5249 unsigned Depth = Record[Idx++];
5250 unsigned Index = Record[Idx++];
5251 bool Pack = Record[Idx++];
5252 TemplateTypeParmDecl *D
5253 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5254 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5255 }
5256
5257 case TYPE_DEPENDENT_NAME: {
5258 unsigned Idx = 0;
5259 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5260 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5261 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5262 QualType Canon = readType(*Loc.F, Record, Idx);
5263 if (!Canon.isNull())
5264 Canon = Context.getCanonicalType(Canon);
5265 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5266 }
5267
5268 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5269 unsigned Idx = 0;
5270 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5271 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5272 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5273 unsigned NumArgs = Record[Idx++];
5274 SmallVector<TemplateArgument, 8> Args;
5275 Args.reserve(NumArgs);
5276 while (NumArgs--)
5277 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5278 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5279 Args.size(), Args.data());
5280 }
5281
5282 case TYPE_DEPENDENT_SIZED_ARRAY: {
5283 unsigned Idx = 0;
5284
5285 // ArrayType
5286 QualType ElementType = readType(*Loc.F, Record, Idx);
5287 ArrayType::ArraySizeModifier ASM
5288 = (ArrayType::ArraySizeModifier)Record[Idx++];
5289 unsigned IndexTypeQuals = Record[Idx++];
5290
5291 // DependentSizedArrayType
5292 Expr *NumElts = ReadExpr(*Loc.F);
5293 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5294
5295 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5296 IndexTypeQuals, Brackets);
5297 }
5298
5299 case TYPE_TEMPLATE_SPECIALIZATION: {
5300 unsigned Idx = 0;
5301 bool IsDependent = Record[Idx++];
5302 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5303 SmallVector<TemplateArgument, 8> Args;
5304 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5305 QualType Underlying = readType(*Loc.F, Record, Idx);
5306 QualType T;
5307 if (Underlying.isNull())
5308 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5309 Args.size());
5310 else
5311 T = Context.getTemplateSpecializationType(Name, Args.data(),
5312 Args.size(), Underlying);
5313 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5314 return T;
5315 }
5316
5317 case TYPE_ATOMIC: {
5318 if (Record.size() != 1) {
5319 Error("Incorrect encoding of atomic type");
5320 return QualType();
5321 }
5322 QualType ValueType = readType(*Loc.F, Record, Idx);
5323 return Context.getAtomicType(ValueType);
5324 }
5325 }
5326 llvm_unreachable("Invalid TypeCode!");
5327}
5328
Richard Smith564417a2014-03-20 21:47:22 +00005329void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5330 SmallVectorImpl<QualType> &Exceptions,
5331 FunctionProtoType::ExtProtoInfo &EPI,
5332 const RecordData &Record, unsigned &Idx) {
5333 ExceptionSpecificationType EST =
5334 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5335 EPI.ExceptionSpecType = EST;
5336 if (EST == EST_Dynamic) {
5337 EPI.NumExceptions = Record[Idx++];
5338 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5339 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5340 EPI.Exceptions = Exceptions.data();
5341 } else if (EST == EST_ComputedNoexcept) {
5342 EPI.NoexceptExpr = ReadExpr(ModuleFile);
5343 } else if (EST == EST_Uninstantiated) {
5344 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5345 EPI.ExceptionSpecTemplate =
5346 ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5347 } else if (EST == EST_Unevaluated) {
5348 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5349 }
5350}
5351
Guy Benyei11169dd2012-12-18 14:30:41 +00005352class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5353 ASTReader &Reader;
5354 ModuleFile &F;
5355 const ASTReader::RecordData &Record;
5356 unsigned &Idx;
5357
5358 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5359 unsigned &I) {
5360 return Reader.ReadSourceLocation(F, R, I);
5361 }
5362
5363 template<typename T>
5364 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5365 return Reader.ReadDeclAs<T>(F, Record, Idx);
5366 }
5367
5368public:
5369 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5370 const ASTReader::RecordData &Record, unsigned &Idx)
5371 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5372 { }
5373
5374 // We want compile-time assurance that we've enumerated all of
5375 // these, so unfortunately we have to declare them first, then
5376 // define them out-of-line.
5377#define ABSTRACT_TYPELOC(CLASS, PARENT)
5378#define TYPELOC(CLASS, PARENT) \
5379 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5380#include "clang/AST/TypeLocNodes.def"
5381
5382 void VisitFunctionTypeLoc(FunctionTypeLoc);
5383 void VisitArrayTypeLoc(ArrayTypeLoc);
5384};
5385
5386void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5387 // nothing to do
5388}
5389void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5390 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5391 if (TL.needsExtraLocalData()) {
5392 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5393 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5394 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5395 TL.setModeAttr(Record[Idx++]);
5396 }
5397}
5398void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5399 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5400}
5401void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5402 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5403}
Reid Kleckner8a365022013-06-24 17:51:48 +00005404void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5405 // nothing to do
5406}
Reid Kleckner0503a872013-12-05 01:23:43 +00005407void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5408 // nothing to do
5409}
Guy Benyei11169dd2012-12-18 14:30:41 +00005410void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5411 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5412}
5413void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5414 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5415}
5416void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5417 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5418}
5419void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5420 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5421 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5422}
5423void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5424 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5425 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5426 if (Record[Idx++])
5427 TL.setSizeExpr(Reader.ReadExpr(F));
5428 else
5429 TL.setSizeExpr(0);
5430}
5431void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5432 VisitArrayTypeLoc(TL);
5433}
5434void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5435 VisitArrayTypeLoc(TL);
5436}
5437void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5438 VisitArrayTypeLoc(TL);
5439}
5440void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5441 DependentSizedArrayTypeLoc TL) {
5442 VisitArrayTypeLoc(TL);
5443}
5444void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5445 DependentSizedExtVectorTypeLoc TL) {
5446 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5447}
5448void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5449 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5450}
5451void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5452 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5453}
5454void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5455 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5456 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5457 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5458 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005459 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5460 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005461 }
5462}
5463void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5464 VisitFunctionTypeLoc(TL);
5465}
5466void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5467 VisitFunctionTypeLoc(TL);
5468}
5469void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5470 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5471}
5472void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5473 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5474}
5475void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5476 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5477 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5478 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5479}
5480void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5481 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5482 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5483 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5484 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5485}
5486void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5487 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5488}
5489void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5490 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5491 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5492 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5493 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5494}
5495void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5496 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5497}
5498void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5499 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5500}
5501void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5502 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5503}
5504void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5505 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5506 if (TL.hasAttrOperand()) {
5507 SourceRange range;
5508 range.setBegin(ReadSourceLocation(Record, Idx));
5509 range.setEnd(ReadSourceLocation(Record, Idx));
5510 TL.setAttrOperandParensRange(range);
5511 }
5512 if (TL.hasAttrExprOperand()) {
5513 if (Record[Idx++])
5514 TL.setAttrExprOperand(Reader.ReadExpr(F));
5515 else
5516 TL.setAttrExprOperand(0);
5517 } else if (TL.hasAttrEnumOperand())
5518 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5519}
5520void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5521 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5522}
5523void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5524 SubstTemplateTypeParmTypeLoc TL) {
5525 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5526}
5527void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5528 SubstTemplateTypeParmPackTypeLoc TL) {
5529 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5530}
5531void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5532 TemplateSpecializationTypeLoc TL) {
5533 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5534 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5535 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5536 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5537 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5538 TL.setArgLocInfo(i,
5539 Reader.GetTemplateArgumentLocInfo(F,
5540 TL.getTypePtr()->getArg(i).getKind(),
5541 Record, Idx));
5542}
5543void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5544 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5545 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5546}
5547void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5548 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5549 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5550}
5551void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5552 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5553}
5554void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5555 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5556 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5557 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5558}
5559void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5560 DependentTemplateSpecializationTypeLoc TL) {
5561 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5562 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5563 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5564 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5565 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5566 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5567 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5568 TL.setArgLocInfo(I,
5569 Reader.GetTemplateArgumentLocInfo(F,
5570 TL.getTypePtr()->getArg(I).getKind(),
5571 Record, Idx));
5572}
5573void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5574 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5575}
5576void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5577 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5578}
5579void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5580 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5581 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5582 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5583 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5584 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5585}
5586void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5587 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5588}
5589void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5590 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5591 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5592 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5593}
5594
5595TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5596 const RecordData &Record,
5597 unsigned &Idx) {
5598 QualType InfoTy = readType(F, Record, Idx);
5599 if (InfoTy.isNull())
5600 return 0;
5601
5602 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5603 TypeLocReader TLR(*this, F, Record, Idx);
5604 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5605 TLR.Visit(TL);
5606 return TInfo;
5607}
5608
5609QualType ASTReader::GetType(TypeID ID) {
5610 unsigned FastQuals = ID & Qualifiers::FastMask;
5611 unsigned Index = ID >> Qualifiers::FastWidth;
5612
5613 if (Index < NUM_PREDEF_TYPE_IDS) {
5614 QualType T;
5615 switch ((PredefinedTypeIDs)Index) {
5616 case PREDEF_TYPE_NULL_ID: return QualType();
5617 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5618 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5619
5620 case PREDEF_TYPE_CHAR_U_ID:
5621 case PREDEF_TYPE_CHAR_S_ID:
5622 // FIXME: Check that the signedness of CharTy is correct!
5623 T = Context.CharTy;
5624 break;
5625
5626 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5627 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5628 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5629 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5630 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5631 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5632 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5633 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5634 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5635 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5636 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5637 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5638 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5639 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5640 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5641 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5642 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5643 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5644 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5645 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5646 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5647 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5648 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5649 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5650 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5651 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5652 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5653 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005654 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5655 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5656 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5657 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5658 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5659 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005660 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005661 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005662 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5663
5664 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5665 T = Context.getAutoRRefDeductType();
5666 break;
5667
5668 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5669 T = Context.ARCUnbridgedCastTy;
5670 break;
5671
5672 case PREDEF_TYPE_VA_LIST_TAG:
5673 T = Context.getVaListTagType();
5674 break;
5675
5676 case PREDEF_TYPE_BUILTIN_FN:
5677 T = Context.BuiltinFnTy;
5678 break;
5679 }
5680
5681 assert(!T.isNull() && "Unknown predefined type");
5682 return T.withFastQualifiers(FastQuals);
5683 }
5684
5685 Index -= NUM_PREDEF_TYPE_IDS;
5686 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5687 if (TypesLoaded[Index].isNull()) {
5688 TypesLoaded[Index] = readTypeRecord(Index);
5689 if (TypesLoaded[Index].isNull())
5690 return QualType();
5691
5692 TypesLoaded[Index]->setFromAST();
5693 if (DeserializationListener)
5694 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5695 TypesLoaded[Index]);
5696 }
5697
5698 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5699}
5700
5701QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5702 return GetType(getGlobalTypeID(F, LocalID));
5703}
5704
5705serialization::TypeID
5706ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5707 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5708 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5709
5710 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5711 return LocalID;
5712
5713 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5714 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5715 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5716
5717 unsigned GlobalIndex = LocalIndex + I->second;
5718 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5719}
5720
5721TemplateArgumentLocInfo
5722ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5723 TemplateArgument::ArgKind Kind,
5724 const RecordData &Record,
5725 unsigned &Index) {
5726 switch (Kind) {
5727 case TemplateArgument::Expression:
5728 return ReadExpr(F);
5729 case TemplateArgument::Type:
5730 return GetTypeSourceInfo(F, Record, Index);
5731 case TemplateArgument::Template: {
5732 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5733 Index);
5734 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5735 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5736 SourceLocation());
5737 }
5738 case TemplateArgument::TemplateExpansion: {
5739 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5740 Index);
5741 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5742 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5743 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5744 EllipsisLoc);
5745 }
5746 case TemplateArgument::Null:
5747 case TemplateArgument::Integral:
5748 case TemplateArgument::Declaration:
5749 case TemplateArgument::NullPtr:
5750 case TemplateArgument::Pack:
5751 // FIXME: Is this right?
5752 return TemplateArgumentLocInfo();
5753 }
5754 llvm_unreachable("unexpected template argument loc");
5755}
5756
5757TemplateArgumentLoc
5758ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5759 const RecordData &Record, unsigned &Index) {
5760 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5761
5762 if (Arg.getKind() == TemplateArgument::Expression) {
5763 if (Record[Index++]) // bool InfoHasSameExpr.
5764 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5765 }
5766 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5767 Record, Index));
5768}
5769
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005770const ASTTemplateArgumentListInfo*
5771ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5772 const RecordData &Record,
5773 unsigned &Index) {
5774 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5775 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5776 unsigned NumArgsAsWritten = Record[Index++];
5777 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5778 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5779 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5780 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5781}
5782
Guy Benyei11169dd2012-12-18 14:30:41 +00005783Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5784 return GetDecl(ID);
5785}
5786
5787uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5788 unsigned &Idx){
5789 if (Idx >= Record.size())
5790 return 0;
5791
5792 unsigned LocalID = Record[Idx++];
5793 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5794}
5795
5796CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5797 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005798 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005799 SavedStreamPosition SavedPosition(Cursor);
5800 Cursor.JumpToBit(Loc.Offset);
5801 ReadingKindTracker ReadingKind(Read_Decl, *this);
5802 RecordData Record;
5803 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005804 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005805 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5806 Error("Malformed AST file: missing C++ base specifiers");
5807 return 0;
5808 }
5809
5810 unsigned Idx = 0;
5811 unsigned NumBases = Record[Idx++];
5812 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5813 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5814 for (unsigned I = 0; I != NumBases; ++I)
5815 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5816 return Bases;
5817}
5818
5819serialization::DeclID
5820ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5821 if (LocalID < NUM_PREDEF_DECL_IDS)
5822 return LocalID;
5823
5824 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5825 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5826 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5827
5828 return LocalID + I->second;
5829}
5830
5831bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5832 ModuleFile &M) const {
5833 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5834 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5835 return &M == I->second;
5836}
5837
Douglas Gregor9f782892013-01-21 15:25:38 +00005838ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005839 if (!D->isFromASTFile())
5840 return 0;
5841 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5842 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5843 return I->second;
5844}
5845
5846SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5847 if (ID < NUM_PREDEF_DECL_IDS)
5848 return SourceLocation();
5849
5850 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5851
5852 if (Index > DeclsLoaded.size()) {
5853 Error("declaration ID out-of-range for AST file");
5854 return SourceLocation();
5855 }
5856
5857 if (Decl *D = DeclsLoaded[Index])
5858 return D->getLocation();
5859
5860 unsigned RawLocation = 0;
5861 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5862 return ReadSourceLocation(*Rec.F, RawLocation);
5863}
5864
5865Decl *ASTReader::GetDecl(DeclID ID) {
5866 if (ID < NUM_PREDEF_DECL_IDS) {
5867 switch ((PredefinedDeclIDs)ID) {
5868 case PREDEF_DECL_NULL_ID:
5869 return 0;
5870
5871 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5872 return Context.getTranslationUnitDecl();
5873
5874 case PREDEF_DECL_OBJC_ID_ID:
5875 return Context.getObjCIdDecl();
5876
5877 case PREDEF_DECL_OBJC_SEL_ID:
5878 return Context.getObjCSelDecl();
5879
5880 case PREDEF_DECL_OBJC_CLASS_ID:
5881 return Context.getObjCClassDecl();
5882
5883 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5884 return Context.getObjCProtocolDecl();
5885
5886 case PREDEF_DECL_INT_128_ID:
5887 return Context.getInt128Decl();
5888
5889 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5890 return Context.getUInt128Decl();
5891
5892 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5893 return Context.getObjCInstanceTypeDecl();
5894
5895 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5896 return Context.getBuiltinVaListDecl();
5897 }
5898 }
5899
5900 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5901
5902 if (Index >= DeclsLoaded.size()) {
5903 assert(0 && "declaration ID out-of-range for AST file");
5904 Error("declaration ID out-of-range for AST file");
5905 return 0;
5906 }
5907
5908 if (!DeclsLoaded[Index]) {
5909 ReadDeclRecord(ID);
5910 if (DeserializationListener)
5911 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5912 }
5913
5914 return DeclsLoaded[Index];
5915}
5916
5917DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5918 DeclID GlobalID) {
5919 if (GlobalID < NUM_PREDEF_DECL_IDS)
5920 return GlobalID;
5921
5922 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5923 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5924 ModuleFile *Owner = I->second;
5925
5926 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5927 = M.GlobalToLocalDeclIDs.find(Owner);
5928 if (Pos == M.GlobalToLocalDeclIDs.end())
5929 return 0;
5930
5931 return GlobalID - Owner->BaseDeclID + Pos->second;
5932}
5933
5934serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5935 const RecordData &Record,
5936 unsigned &Idx) {
5937 if (Idx >= Record.size()) {
5938 Error("Corrupted AST file");
5939 return 0;
5940 }
5941
5942 return getGlobalDeclID(F, Record[Idx++]);
5943}
5944
5945/// \brief Resolve the offset of a statement into a statement.
5946///
5947/// This operation will read a new statement from the external
5948/// source each time it is called, and is meant to be used via a
5949/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5950Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5951 // Switch case IDs are per Decl.
5952 ClearSwitchCaseIDs();
5953
5954 // Offset here is a global offset across the entire chain.
5955 RecordLocation Loc = getLocalBitOffset(Offset);
5956 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5957 return ReadStmtFromStream(*Loc.F);
5958}
5959
5960namespace {
5961 class FindExternalLexicalDeclsVisitor {
5962 ASTReader &Reader;
5963 const DeclContext *DC;
5964 bool (*isKindWeWant)(Decl::Kind);
5965
5966 SmallVectorImpl<Decl*> &Decls;
5967 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5968
5969 public:
5970 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5971 bool (*isKindWeWant)(Decl::Kind),
5972 SmallVectorImpl<Decl*> &Decls)
5973 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5974 {
5975 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5976 PredefsVisited[I] = false;
5977 }
5978
5979 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5980 if (Preorder)
5981 return false;
5982
5983 FindExternalLexicalDeclsVisitor *This
5984 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5985
5986 ModuleFile::DeclContextInfosMap::iterator Info
5987 = M.DeclContextInfos.find(This->DC);
5988 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5989 return false;
5990
5991 // Load all of the declaration IDs
5992 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5993 *IDE = ID + Info->second.NumLexicalDecls;
5994 ID != IDE; ++ID) {
5995 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5996 continue;
5997
5998 // Don't add predefined declarations to the lexical context more
5999 // than once.
6000 if (ID->second < NUM_PREDEF_DECL_IDS) {
6001 if (This->PredefsVisited[ID->second])
6002 continue;
6003
6004 This->PredefsVisited[ID->second] = true;
6005 }
6006
6007 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6008 if (!This->DC->isDeclInLexicalTraversal(D))
6009 This->Decls.push_back(D);
6010 }
6011 }
6012
6013 return false;
6014 }
6015 };
6016}
6017
6018ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6019 bool (*isKindWeWant)(Decl::Kind),
6020 SmallVectorImpl<Decl*> &Decls) {
6021 // There might be lexical decls in multiple modules, for the TU at
6022 // least. Walk all of the modules in the order they were loaded.
6023 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6024 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6025 ++NumLexicalDeclContextsRead;
6026 return ELR_Success;
6027}
6028
6029namespace {
6030
6031class DeclIDComp {
6032 ASTReader &Reader;
6033 ModuleFile &Mod;
6034
6035public:
6036 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6037
6038 bool operator()(LocalDeclID L, LocalDeclID R) const {
6039 SourceLocation LHS = getLocation(L);
6040 SourceLocation RHS = getLocation(R);
6041 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6042 }
6043
6044 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6045 SourceLocation RHS = getLocation(R);
6046 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6047 }
6048
6049 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6050 SourceLocation LHS = getLocation(L);
6051 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6052 }
6053
6054 SourceLocation getLocation(LocalDeclID ID) const {
6055 return Reader.getSourceManager().getFileLoc(
6056 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6057 }
6058};
6059
6060}
6061
6062void ASTReader::FindFileRegionDecls(FileID File,
6063 unsigned Offset, unsigned Length,
6064 SmallVectorImpl<Decl *> &Decls) {
6065 SourceManager &SM = getSourceManager();
6066
6067 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6068 if (I == FileDeclIDs.end())
6069 return;
6070
6071 FileDeclsInfo &DInfo = I->second;
6072 if (DInfo.Decls.empty())
6073 return;
6074
6075 SourceLocation
6076 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6077 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6078
6079 DeclIDComp DIDComp(*this, *DInfo.Mod);
6080 ArrayRef<serialization::LocalDeclID>::iterator
6081 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6082 BeginLoc, DIDComp);
6083 if (BeginIt != DInfo.Decls.begin())
6084 --BeginIt;
6085
6086 // If we are pointing at a top-level decl inside an objc container, we need
6087 // to backtrack until we find it otherwise we will fail to report that the
6088 // region overlaps with an objc container.
6089 while (BeginIt != DInfo.Decls.begin() &&
6090 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6091 ->isTopLevelDeclInObjCContainer())
6092 --BeginIt;
6093
6094 ArrayRef<serialization::LocalDeclID>::iterator
6095 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6096 EndLoc, DIDComp);
6097 if (EndIt != DInfo.Decls.end())
6098 ++EndIt;
6099
6100 for (ArrayRef<serialization::LocalDeclID>::iterator
6101 DIt = BeginIt; DIt != EndIt; ++DIt)
6102 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6103}
6104
6105namespace {
6106 /// \brief ModuleFile visitor used to perform name lookup into a
6107 /// declaration context.
6108 class DeclContextNameLookupVisitor {
6109 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006110 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006111 DeclarationName Name;
6112 SmallVectorImpl<NamedDecl *> &Decls;
6113
6114 public:
6115 DeclContextNameLookupVisitor(ASTReader &Reader,
6116 SmallVectorImpl<const DeclContext *> &Contexts,
6117 DeclarationName Name,
6118 SmallVectorImpl<NamedDecl *> &Decls)
6119 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6120
6121 static bool visit(ModuleFile &M, void *UserData) {
6122 DeclContextNameLookupVisitor *This
6123 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6124
6125 // Check whether we have any visible declaration information for
6126 // this context in this module.
6127 ModuleFile::DeclContextInfosMap::iterator Info;
6128 bool FoundInfo = false;
6129 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6130 Info = M.DeclContextInfos.find(This->Contexts[I]);
6131 if (Info != M.DeclContextInfos.end() &&
6132 Info->second.NameLookupTableData) {
6133 FoundInfo = true;
6134 break;
6135 }
6136 }
6137
6138 if (!FoundInfo)
6139 return false;
6140
6141 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006142 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006143 Info->second.NameLookupTableData;
6144 ASTDeclContextNameLookupTable::iterator Pos
6145 = LookupTable->find(This->Name);
6146 if (Pos == LookupTable->end())
6147 return false;
6148
6149 bool FoundAnything = false;
6150 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6151 for (; Data.first != Data.second; ++Data.first) {
6152 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6153 if (!ND)
6154 continue;
6155
6156 if (ND->getDeclName() != This->Name) {
6157 // A name might be null because the decl's redeclarable part is
6158 // currently read before reading its name. The lookup is triggered by
6159 // building that decl (likely indirectly), and so it is later in the
6160 // sense of "already existing" and can be ignored here.
6161 continue;
6162 }
6163
6164 // Record this declaration.
6165 FoundAnything = true;
6166 This->Decls.push_back(ND);
6167 }
6168
6169 return FoundAnything;
6170 }
6171 };
6172}
6173
Douglas Gregor9f782892013-01-21 15:25:38 +00006174/// \brief Retrieve the "definitive" module file for the definition of the
6175/// given declaration context, if there is one.
6176///
6177/// The "definitive" module file is the only place where we need to look to
6178/// find information about the declarations within the given declaration
6179/// context. For example, C++ and Objective-C classes, C structs/unions, and
6180/// Objective-C protocols, categories, and extensions are all defined in a
6181/// single place in the source code, so they have definitive module files
6182/// associated with them. C++ namespaces, on the other hand, can have
6183/// definitions in multiple different module files.
6184///
6185/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6186/// NDEBUG checking.
6187static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6188 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006189 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6190 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006191
6192 return 0;
6193}
6194
Richard Smith9ce12e32013-02-07 03:30:24 +00006195bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006196ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6197 DeclarationName Name) {
6198 assert(DC->hasExternalVisibleStorage() &&
6199 "DeclContext has no visible decls in storage");
6200 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006201 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006202
6203 SmallVector<NamedDecl *, 64> Decls;
6204
6205 // Compute the declaration contexts we need to look into. Multiple such
6206 // declaration contexts occur when two declaration contexts from disjoint
6207 // modules get merged, e.g., when two namespaces with the same name are
6208 // independently defined in separate modules.
6209 SmallVector<const DeclContext *, 2> Contexts;
6210 Contexts.push_back(DC);
6211
6212 if (DC->isNamespace()) {
6213 MergedDeclsMap::iterator Merged
6214 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6215 if (Merged != MergedDecls.end()) {
6216 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6217 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6218 }
6219 }
6220
6221 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006222
6223 // If we can definitively determine which module file to look into,
6224 // only look there. Otherwise, look in all module files.
6225 ModuleFile *Definitive;
6226 if (Contexts.size() == 1 &&
6227 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6228 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6229 } else {
6230 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6231 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006232 ++NumVisibleDeclContextsRead;
6233 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006234 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006235}
6236
6237namespace {
6238 /// \brief ModuleFile visitor used to retrieve all visible names in a
6239 /// declaration context.
6240 class DeclContextAllNamesVisitor {
6241 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006242 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006243 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006244 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006245
6246 public:
6247 DeclContextAllNamesVisitor(ASTReader &Reader,
6248 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006249 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006250 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006251
6252 static bool visit(ModuleFile &M, void *UserData) {
6253 DeclContextAllNamesVisitor *This
6254 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6255
6256 // Check whether we have any visible declaration information for
6257 // this context in this module.
6258 ModuleFile::DeclContextInfosMap::iterator Info;
6259 bool FoundInfo = false;
6260 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6261 Info = M.DeclContextInfos.find(This->Contexts[I]);
6262 if (Info != M.DeclContextInfos.end() &&
6263 Info->second.NameLookupTableData) {
6264 FoundInfo = true;
6265 break;
6266 }
6267 }
6268
6269 if (!FoundInfo)
6270 return false;
6271
Richard Smith52e3fba2014-03-11 07:17:35 +00006272 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006273 Info->second.NameLookupTableData;
6274 bool FoundAnything = false;
6275 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006276 I = LookupTable->data_begin(), E = LookupTable->data_end();
6277 I != E;
6278 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006279 ASTDeclContextNameLookupTrait::data_type Data = *I;
6280 for (; Data.first != Data.second; ++Data.first) {
6281 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6282 *Data.first);
6283 if (!ND)
6284 continue;
6285
6286 // Record this declaration.
6287 FoundAnything = true;
6288 This->Decls[ND->getDeclName()].push_back(ND);
6289 }
6290 }
6291
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006292 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006293 }
6294 };
6295}
6296
6297void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6298 if (!DC->hasExternalVisibleStorage())
6299 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006300 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006301
6302 // Compute the declaration contexts we need to look into. Multiple such
6303 // declaration contexts occur when two declaration contexts from disjoint
6304 // modules get merged, e.g., when two namespaces with the same name are
6305 // independently defined in separate modules.
6306 SmallVector<const DeclContext *, 2> Contexts;
6307 Contexts.push_back(DC);
6308
6309 if (DC->isNamespace()) {
6310 MergedDeclsMap::iterator Merged
6311 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6312 if (Merged != MergedDecls.end()) {
6313 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6314 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6315 }
6316 }
6317
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006318 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6319 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006320 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6321 ++NumVisibleDeclContextsRead;
6322
Craig Topper79be4cd2013-07-05 04:33:53 +00006323 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006324 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6325 }
6326 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6327}
6328
6329/// \brief Under non-PCH compilation the consumer receives the objc methods
6330/// before receiving the implementation, and codegen depends on this.
6331/// We simulate this by deserializing and passing to consumer the methods of the
6332/// implementation before passing the deserialized implementation decl.
6333static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6334 ASTConsumer *Consumer) {
6335 assert(ImplD && Consumer);
6336
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006337 for (auto *I : ImplD->methods())
6338 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006339
6340 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6341}
6342
6343void ASTReader::PassInterestingDeclsToConsumer() {
6344 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006345
6346 if (PassingDeclsToConsumer)
6347 return;
6348
6349 // Guard variable to avoid recursively redoing the process of passing
6350 // decls to consumer.
6351 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6352 true);
6353
Guy Benyei11169dd2012-12-18 14:30:41 +00006354 while (!InterestingDecls.empty()) {
6355 Decl *D = InterestingDecls.front();
6356 InterestingDecls.pop_front();
6357
6358 PassInterestingDeclToConsumer(D);
6359 }
6360}
6361
6362void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6363 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6364 PassObjCImplDeclToConsumer(ImplD, Consumer);
6365 else
6366 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6367}
6368
6369void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6370 this->Consumer = Consumer;
6371
6372 if (!Consumer)
6373 return;
6374
Ben Langmuir332aafe2014-01-31 01:06:56 +00006375 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006376 // Force deserialization of this decl, which will cause it to be queued for
6377 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006378 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006379 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006380 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006381
6382 PassInterestingDeclsToConsumer();
6383}
6384
6385void ASTReader::PrintStats() {
6386 std::fprintf(stderr, "*** AST File Statistics:\n");
6387
6388 unsigned NumTypesLoaded
6389 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6390 QualType());
6391 unsigned NumDeclsLoaded
6392 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6393 (Decl *)0);
6394 unsigned NumIdentifiersLoaded
6395 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6396 IdentifiersLoaded.end(),
6397 (IdentifierInfo *)0);
6398 unsigned NumMacrosLoaded
6399 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6400 MacrosLoaded.end(),
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006401 (MacroInfo *)0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006402 unsigned NumSelectorsLoaded
6403 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6404 SelectorsLoaded.end(),
6405 Selector());
6406
6407 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6408 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6409 NumSLocEntriesRead, TotalNumSLocEntries,
6410 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6411 if (!TypesLoaded.empty())
6412 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6413 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6414 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6415 if (!DeclsLoaded.empty())
6416 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6417 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6418 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6419 if (!IdentifiersLoaded.empty())
6420 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6421 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6422 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6423 if (!MacrosLoaded.empty())
6424 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6425 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6426 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6427 if (!SelectorsLoaded.empty())
6428 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6429 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6430 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6431 if (TotalNumStatements)
6432 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6433 NumStatementsRead, TotalNumStatements,
6434 ((float)NumStatementsRead/TotalNumStatements * 100));
6435 if (TotalNumMacros)
6436 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6437 NumMacrosRead, TotalNumMacros,
6438 ((float)NumMacrosRead/TotalNumMacros * 100));
6439 if (TotalLexicalDeclContexts)
6440 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6441 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6442 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6443 * 100));
6444 if (TotalVisibleDeclContexts)
6445 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6446 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6447 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6448 * 100));
6449 if (TotalNumMethodPoolEntries) {
6450 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6451 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6452 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6453 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006454 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006455 if (NumMethodPoolLookups) {
6456 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6457 NumMethodPoolHits, NumMethodPoolLookups,
6458 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6459 }
6460 if (NumMethodPoolTableLookups) {
6461 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6462 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6463 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6464 * 100.0));
6465 }
6466
Douglas Gregor00a50f72013-01-25 00:38:33 +00006467 if (NumIdentifierLookupHits) {
6468 std::fprintf(stderr,
6469 " %u / %u identifier table lookups succeeded (%f%%)\n",
6470 NumIdentifierLookupHits, NumIdentifierLookups,
6471 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6472 }
6473
Douglas Gregore060e572013-01-25 01:03:03 +00006474 if (GlobalIndex) {
6475 std::fprintf(stderr, "\n");
6476 GlobalIndex->printStats();
6477 }
6478
Guy Benyei11169dd2012-12-18 14:30:41 +00006479 std::fprintf(stderr, "\n");
6480 dump();
6481 std::fprintf(stderr, "\n");
6482}
6483
6484template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6485static void
6486dumpModuleIDMap(StringRef Name,
6487 const ContinuousRangeMap<Key, ModuleFile *,
6488 InitialCapacity> &Map) {
6489 if (Map.begin() == Map.end())
6490 return;
6491
6492 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6493 llvm::errs() << Name << ":\n";
6494 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6495 I != IEnd; ++I) {
6496 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6497 << "\n";
6498 }
6499}
6500
6501void ASTReader::dump() {
6502 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6503 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6504 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6505 dumpModuleIDMap("Global type map", GlobalTypeMap);
6506 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6507 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6508 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6509 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6510 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6511 dumpModuleIDMap("Global preprocessed entity map",
6512 GlobalPreprocessedEntityMap);
6513
6514 llvm::errs() << "\n*** PCH/Modules Loaded:";
6515 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6516 MEnd = ModuleMgr.end();
6517 M != MEnd; ++M)
6518 (*M)->dump();
6519}
6520
6521/// Return the amount of memory used by memory buffers, breaking down
6522/// by heap-backed versus mmap'ed memory.
6523void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6524 for (ModuleConstIterator I = ModuleMgr.begin(),
6525 E = ModuleMgr.end(); I != E; ++I) {
6526 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6527 size_t bytes = buf->getBufferSize();
6528 switch (buf->getBufferKind()) {
6529 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6530 sizes.malloc_bytes += bytes;
6531 break;
6532 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6533 sizes.mmap_bytes += bytes;
6534 break;
6535 }
6536 }
6537 }
6538}
6539
6540void ASTReader::InitializeSema(Sema &S) {
6541 SemaObj = &S;
6542 S.addExternalSource(this);
6543
6544 // Makes sure any declarations that were deserialized "too early"
6545 // still get added to the identifier's declaration chains.
6546 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006547 pushExternalDeclIntoScope(PreloadedDecls[I],
6548 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006549 }
6550 PreloadedDecls.clear();
6551
Richard Smith3d8e97e2013-10-18 06:54:39 +00006552 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006553 if (!FPPragmaOptions.empty()) {
6554 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6555 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6556 }
6557
Richard Smith3d8e97e2013-10-18 06:54:39 +00006558 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006559 if (!OpenCLExtensions.empty()) {
6560 unsigned I = 0;
6561#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6562#include "clang/Basic/OpenCLExtensions.def"
6563
6564 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6565 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006566
6567 UpdateSema();
6568}
6569
6570void ASTReader::UpdateSema() {
6571 assert(SemaObj && "no Sema to update");
6572
6573 // Load the offsets of the declarations that Sema references.
6574 // They will be lazily deserialized when needed.
6575 if (!SemaDeclRefs.empty()) {
6576 assert(SemaDeclRefs.size() % 2 == 0);
6577 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6578 if (!SemaObj->StdNamespace)
6579 SemaObj->StdNamespace = SemaDeclRefs[I];
6580 if (!SemaObj->StdBadAlloc)
6581 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6582 }
6583 SemaDeclRefs.clear();
6584 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006585}
6586
6587IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6588 // Note that we are loading an identifier.
6589 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006590 StringRef Name(NameStart, NameEnd - NameStart);
6591
6592 // If there is a global index, look there first to determine which modules
6593 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006594 GlobalModuleIndex::HitSet Hits;
6595 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00006596 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006597 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6598 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006599 }
6600 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006601 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006602 NumIdentifierLookups,
6603 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006604 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006605 IdentifierInfo *II = Visitor.getIdentifierInfo();
6606 markIdentifierUpToDate(II);
6607 return II;
6608}
6609
6610namespace clang {
6611 /// \brief An identifier-lookup iterator that enumerates all of the
6612 /// identifiers stored within a set of AST files.
6613 class ASTIdentifierIterator : public IdentifierIterator {
6614 /// \brief The AST reader whose identifiers are being enumerated.
6615 const ASTReader &Reader;
6616
6617 /// \brief The current index into the chain of AST files stored in
6618 /// the AST reader.
6619 unsigned Index;
6620
6621 /// \brief The current position within the identifier lookup table
6622 /// of the current AST file.
6623 ASTIdentifierLookupTable::key_iterator Current;
6624
6625 /// \brief The end position within the identifier lookup table of
6626 /// the current AST file.
6627 ASTIdentifierLookupTable::key_iterator End;
6628
6629 public:
6630 explicit ASTIdentifierIterator(const ASTReader &Reader);
6631
Craig Topper3e89dfe2014-03-13 02:13:41 +00006632 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006633 };
6634}
6635
6636ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6637 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6638 ASTIdentifierLookupTable *IdTable
6639 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6640 Current = IdTable->key_begin();
6641 End = IdTable->key_end();
6642}
6643
6644StringRef ASTIdentifierIterator::Next() {
6645 while (Current == End) {
6646 // If we have exhausted all of our AST files, we're done.
6647 if (Index == 0)
6648 return StringRef();
6649
6650 --Index;
6651 ASTIdentifierLookupTable *IdTable
6652 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6653 IdentifierLookupTable;
6654 Current = IdTable->key_begin();
6655 End = IdTable->key_end();
6656 }
6657
6658 // We have any identifiers remaining in the current AST file; return
6659 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006660 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006661 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006662 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006663}
6664
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006665IdentifierIterator *ASTReader::getIdentifiers() {
6666 if (!loadGlobalIndex())
6667 return GlobalIndex->createIdentifierIterator();
6668
Guy Benyei11169dd2012-12-18 14:30:41 +00006669 return new ASTIdentifierIterator(*this);
6670}
6671
6672namespace clang { namespace serialization {
6673 class ReadMethodPoolVisitor {
6674 ASTReader &Reader;
6675 Selector Sel;
6676 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006677 unsigned InstanceBits;
6678 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006679 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6680 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006681
6682 public:
6683 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6684 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006685 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6686 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006687
6688 static bool visit(ModuleFile &M, void *UserData) {
6689 ReadMethodPoolVisitor *This
6690 = static_cast<ReadMethodPoolVisitor *>(UserData);
6691
6692 if (!M.SelectorLookupTable)
6693 return false;
6694
6695 // If we've already searched this module file, skip it now.
6696 if (M.Generation <= This->PriorGeneration)
6697 return true;
6698
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006699 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006700 ASTSelectorLookupTable *PoolTable
6701 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6702 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6703 if (Pos == PoolTable->end())
6704 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006705
6706 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006707 ++This->Reader.NumSelectorsRead;
6708 // FIXME: Not quite happy with the statistics here. We probably should
6709 // disable this tracking when called via LoadSelector.
6710 // Also, should entries without methods count as misses?
6711 ++This->Reader.NumMethodPoolEntriesRead;
6712 ASTSelectorLookupTrait::data_type Data = *Pos;
6713 if (This->Reader.DeserializationListener)
6714 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6715 This->Sel);
6716
6717 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6718 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006719 This->InstanceBits = Data.InstanceBits;
6720 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006721 return true;
6722 }
6723
6724 /// \brief Retrieve the instance methods found by this visitor.
6725 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6726 return InstanceMethods;
6727 }
6728
6729 /// \brief Retrieve the instance methods found by this visitor.
6730 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6731 return FactoryMethods;
6732 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006733
6734 unsigned getInstanceBits() const { return InstanceBits; }
6735 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006736 };
6737} } // end namespace clang::serialization
6738
6739/// \brief Add the given set of methods to the method list.
6740static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6741 ObjCMethodList &List) {
6742 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6743 S.addMethodToGlobalList(&List, Methods[I]);
6744 }
6745}
6746
6747void ASTReader::ReadMethodPool(Selector Sel) {
6748 // Get the selector generation and update it to the current generation.
6749 unsigned &Generation = SelectorGeneration[Sel];
6750 unsigned PriorGeneration = Generation;
6751 Generation = CurrentGeneration;
6752
6753 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006754 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006755 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6756 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6757
6758 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006759 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006760 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006761
6762 ++NumMethodPoolHits;
6763
Guy Benyei11169dd2012-12-18 14:30:41 +00006764 if (!getSema())
6765 return;
6766
6767 Sema &S = *getSema();
6768 Sema::GlobalMethodPool::iterator Pos
6769 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6770
6771 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6772 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006773 Pos->second.first.setBits(Visitor.getInstanceBits());
6774 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00006775}
6776
6777void ASTReader::ReadKnownNamespaces(
6778 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6779 Namespaces.clear();
6780
6781 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6782 if (NamespaceDecl *Namespace
6783 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6784 Namespaces.push_back(Namespace);
6785 }
6786}
6787
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006788void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00006789 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006790 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6791 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00006792 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006793 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00006794 Undefined.insert(std::make_pair(D, Loc));
6795 }
6796}
Nick Lewycky8334af82013-01-26 00:35:08 +00006797
Guy Benyei11169dd2012-12-18 14:30:41 +00006798void ASTReader::ReadTentativeDefinitions(
6799 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6800 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6801 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6802 if (Var)
6803 TentativeDefs.push_back(Var);
6804 }
6805 TentativeDefinitions.clear();
6806}
6807
6808void ASTReader::ReadUnusedFileScopedDecls(
6809 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6810 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6811 DeclaratorDecl *D
6812 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6813 if (D)
6814 Decls.push_back(D);
6815 }
6816 UnusedFileScopedDecls.clear();
6817}
6818
6819void ASTReader::ReadDelegatingConstructors(
6820 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6821 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6822 CXXConstructorDecl *D
6823 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6824 if (D)
6825 Decls.push_back(D);
6826 }
6827 DelegatingCtorDecls.clear();
6828}
6829
6830void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6831 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6832 TypedefNameDecl *D
6833 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6834 if (D)
6835 Decls.push_back(D);
6836 }
6837 ExtVectorDecls.clear();
6838}
6839
6840void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6841 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6842 CXXRecordDecl *D
6843 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6844 if (D)
6845 Decls.push_back(D);
6846 }
6847 DynamicClasses.clear();
6848}
6849
6850void
Richard Smith78165b52013-01-10 23:43:47 +00006851ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6852 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6853 NamedDecl *D
6854 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006855 if (D)
6856 Decls.push_back(D);
6857 }
Richard Smith78165b52013-01-10 23:43:47 +00006858 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006859}
6860
6861void ASTReader::ReadReferencedSelectors(
6862 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6863 if (ReferencedSelectorsData.empty())
6864 return;
6865
6866 // If there are @selector references added them to its pool. This is for
6867 // implementation of -Wselector.
6868 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6869 unsigned I = 0;
6870 while (I < DataSize) {
6871 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6872 SourceLocation SelLoc
6873 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6874 Sels.push_back(std::make_pair(Sel, SelLoc));
6875 }
6876 ReferencedSelectorsData.clear();
6877}
6878
6879void ASTReader::ReadWeakUndeclaredIdentifiers(
6880 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6881 if (WeakUndeclaredIdentifiers.empty())
6882 return;
6883
6884 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6885 IdentifierInfo *WeakId
6886 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6887 IdentifierInfo *AliasId
6888 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6889 SourceLocation Loc
6890 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6891 bool Used = WeakUndeclaredIdentifiers[I++];
6892 WeakInfo WI(AliasId, Loc);
6893 WI.setUsed(Used);
6894 WeakIDs.push_back(std::make_pair(WeakId, WI));
6895 }
6896 WeakUndeclaredIdentifiers.clear();
6897}
6898
6899void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6900 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6901 ExternalVTableUse VT;
6902 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6903 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6904 VT.DefinitionRequired = VTableUses[Idx++];
6905 VTables.push_back(VT);
6906 }
6907
6908 VTableUses.clear();
6909}
6910
6911void ASTReader::ReadPendingInstantiations(
6912 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6913 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6914 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6915 SourceLocation Loc
6916 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6917
6918 Pending.push_back(std::make_pair(D, Loc));
6919 }
6920 PendingInstantiations.clear();
6921}
6922
Richard Smithe40f2ba2013-08-07 21:41:30 +00006923void ASTReader::ReadLateParsedTemplates(
6924 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
6925 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
6926 /* In loop */) {
6927 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
6928
6929 LateParsedTemplate *LT = new LateParsedTemplate;
6930 LT->D = GetDecl(LateParsedTemplates[Idx++]);
6931
6932 ModuleFile *F = getOwningModuleFile(LT->D);
6933 assert(F && "No module");
6934
6935 unsigned TokN = LateParsedTemplates[Idx++];
6936 LT->Toks.reserve(TokN);
6937 for (unsigned T = 0; T < TokN; ++T)
6938 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
6939
6940 LPTMap[FD] = LT;
6941 }
6942
6943 LateParsedTemplates.clear();
6944}
6945
Guy Benyei11169dd2012-12-18 14:30:41 +00006946void ASTReader::LoadSelector(Selector Sel) {
6947 // It would be complicated to avoid reading the methods anyway. So don't.
6948 ReadMethodPool(Sel);
6949}
6950
6951void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6952 assert(ID && "Non-zero identifier ID required");
6953 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6954 IdentifiersLoaded[ID - 1] = II;
6955 if (DeserializationListener)
6956 DeserializationListener->IdentifierRead(ID, II);
6957}
6958
6959/// \brief Set the globally-visible declarations associated with the given
6960/// identifier.
6961///
6962/// If the AST reader is currently in a state where the given declaration IDs
6963/// cannot safely be resolved, they are queued until it is safe to resolve
6964/// them.
6965///
6966/// \param II an IdentifierInfo that refers to one or more globally-visible
6967/// declarations.
6968///
6969/// \param DeclIDs the set of declaration IDs with the name @p II that are
6970/// visible at global scope.
6971///
Douglas Gregor6168bd22013-02-18 15:53:43 +00006972/// \param Decls if non-null, this vector will be populated with the set of
6973/// deserialized declarations. These declarations will not be pushed into
6974/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00006975void
6976ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6977 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00006978 SmallVectorImpl<Decl *> *Decls) {
6979 if (NumCurrentElementsDeserializing && !Decls) {
6980 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00006981 return;
6982 }
6983
6984 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6985 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6986 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00006987 // If we're simply supposed to record the declarations, do so now.
6988 if (Decls) {
6989 Decls->push_back(D);
6990 continue;
6991 }
6992
Guy Benyei11169dd2012-12-18 14:30:41 +00006993 // Introduce this declaration into the translation-unit scope
6994 // and add it to the declaration chain for this identifier, so
6995 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006996 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00006997 } else {
6998 // Queue this declaration so that it will be added to the
6999 // translation unit scope and identifier's declaration chain
7000 // once a Sema object is known.
7001 PreloadedDecls.push_back(D);
7002 }
7003 }
7004}
7005
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007006IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007007 if (ID == 0)
7008 return 0;
7009
7010 if (IdentifiersLoaded.empty()) {
7011 Error("no identifier table in AST file");
7012 return 0;
7013 }
7014
7015 ID -= 1;
7016 if (!IdentifiersLoaded[ID]) {
7017 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7018 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7019 ModuleFile *M = I->second;
7020 unsigned Index = ID - M->BaseIdentifierID;
7021 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7022
7023 // All of the strings in the AST file are preceded by a 16-bit length.
7024 // Extract that 16-bit length to avoid having to execute strlen().
7025 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7026 // unsigned integers. This is important to avoid integer overflow when
7027 // we cast them to 'unsigned'.
7028 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7029 unsigned StrLen = (((unsigned) StrLenPtr[0])
7030 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007031 IdentifiersLoaded[ID]
7032 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007033 if (DeserializationListener)
7034 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7035 }
7036
7037 return IdentifiersLoaded[ID];
7038}
7039
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007040IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7041 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007042}
7043
7044IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7045 if (LocalID < NUM_PREDEF_IDENT_IDS)
7046 return LocalID;
7047
7048 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7049 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7050 assert(I != M.IdentifierRemap.end()
7051 && "Invalid index into identifier index remap");
7052
7053 return LocalID + I->second;
7054}
7055
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007056MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007057 if (ID == 0)
7058 return 0;
7059
7060 if (MacrosLoaded.empty()) {
7061 Error("no macro table in AST file");
7062 return 0;
7063 }
7064
7065 ID -= NUM_PREDEF_MACRO_IDS;
7066 if (!MacrosLoaded[ID]) {
7067 GlobalMacroMapType::iterator I
7068 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7069 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7070 ModuleFile *M = I->second;
7071 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007072 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7073
7074 if (DeserializationListener)
7075 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7076 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007077 }
7078
7079 return MacrosLoaded[ID];
7080}
7081
7082MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7083 if (LocalID < NUM_PREDEF_MACRO_IDS)
7084 return LocalID;
7085
7086 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7087 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7088 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7089
7090 return LocalID + I->second;
7091}
7092
7093serialization::SubmoduleID
7094ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7095 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7096 return LocalID;
7097
7098 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7099 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7100 assert(I != M.SubmoduleRemap.end()
7101 && "Invalid index into submodule index remap");
7102
7103 return LocalID + I->second;
7104}
7105
7106Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7107 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7108 assert(GlobalID == 0 && "Unhandled global submodule ID");
7109 return 0;
7110 }
7111
7112 if (GlobalID > SubmodulesLoaded.size()) {
7113 Error("submodule ID out of range in AST file");
7114 return 0;
7115 }
7116
7117 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7118}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007119
7120Module *ASTReader::getModule(unsigned ID) {
7121 return getSubmodule(ID);
7122}
7123
Guy Benyei11169dd2012-12-18 14:30:41 +00007124Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7125 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7126}
7127
7128Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7129 if (ID == 0)
7130 return Selector();
7131
7132 if (ID > SelectorsLoaded.size()) {
7133 Error("selector ID out of range in AST file");
7134 return Selector();
7135 }
7136
7137 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
7138 // Load this selector from the selector table.
7139 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7140 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7141 ModuleFile &M = *I->second;
7142 ASTSelectorLookupTrait Trait(*this, M);
7143 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7144 SelectorsLoaded[ID - 1] =
7145 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7146 if (DeserializationListener)
7147 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7148 }
7149
7150 return SelectorsLoaded[ID - 1];
7151}
7152
7153Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7154 return DecodeSelector(ID);
7155}
7156
7157uint32_t ASTReader::GetNumExternalSelectors() {
7158 // ID 0 (the null selector) is considered an external selector.
7159 return getTotalNumSelectors() + 1;
7160}
7161
7162serialization::SelectorID
7163ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7164 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7165 return LocalID;
7166
7167 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7168 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7169 assert(I != M.SelectorRemap.end()
7170 && "Invalid index into selector index remap");
7171
7172 return LocalID + I->second;
7173}
7174
7175DeclarationName
7176ASTReader::ReadDeclarationName(ModuleFile &F,
7177 const RecordData &Record, unsigned &Idx) {
7178 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7179 switch (Kind) {
7180 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007181 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007182
7183 case DeclarationName::ObjCZeroArgSelector:
7184 case DeclarationName::ObjCOneArgSelector:
7185 case DeclarationName::ObjCMultiArgSelector:
7186 return DeclarationName(ReadSelector(F, Record, Idx));
7187
7188 case DeclarationName::CXXConstructorName:
7189 return Context.DeclarationNames.getCXXConstructorName(
7190 Context.getCanonicalType(readType(F, Record, Idx)));
7191
7192 case DeclarationName::CXXDestructorName:
7193 return Context.DeclarationNames.getCXXDestructorName(
7194 Context.getCanonicalType(readType(F, Record, Idx)));
7195
7196 case DeclarationName::CXXConversionFunctionName:
7197 return Context.DeclarationNames.getCXXConversionFunctionName(
7198 Context.getCanonicalType(readType(F, Record, Idx)));
7199
7200 case DeclarationName::CXXOperatorName:
7201 return Context.DeclarationNames.getCXXOperatorName(
7202 (OverloadedOperatorKind)Record[Idx++]);
7203
7204 case DeclarationName::CXXLiteralOperatorName:
7205 return Context.DeclarationNames.getCXXLiteralOperatorName(
7206 GetIdentifierInfo(F, Record, Idx));
7207
7208 case DeclarationName::CXXUsingDirective:
7209 return DeclarationName::getUsingDirectiveName();
7210 }
7211
7212 llvm_unreachable("Invalid NameKind!");
7213}
7214
7215void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7216 DeclarationNameLoc &DNLoc,
7217 DeclarationName Name,
7218 const RecordData &Record, unsigned &Idx) {
7219 switch (Name.getNameKind()) {
7220 case DeclarationName::CXXConstructorName:
7221 case DeclarationName::CXXDestructorName:
7222 case DeclarationName::CXXConversionFunctionName:
7223 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7224 break;
7225
7226 case DeclarationName::CXXOperatorName:
7227 DNLoc.CXXOperatorName.BeginOpNameLoc
7228 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7229 DNLoc.CXXOperatorName.EndOpNameLoc
7230 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7231 break;
7232
7233 case DeclarationName::CXXLiteralOperatorName:
7234 DNLoc.CXXLiteralOperatorName.OpNameLoc
7235 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7236 break;
7237
7238 case DeclarationName::Identifier:
7239 case DeclarationName::ObjCZeroArgSelector:
7240 case DeclarationName::ObjCOneArgSelector:
7241 case DeclarationName::ObjCMultiArgSelector:
7242 case DeclarationName::CXXUsingDirective:
7243 break;
7244 }
7245}
7246
7247void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7248 DeclarationNameInfo &NameInfo,
7249 const RecordData &Record, unsigned &Idx) {
7250 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7251 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7252 DeclarationNameLoc DNLoc;
7253 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7254 NameInfo.setInfo(DNLoc);
7255}
7256
7257void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7258 const RecordData &Record, unsigned &Idx) {
7259 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7260 unsigned NumTPLists = Record[Idx++];
7261 Info.NumTemplParamLists = NumTPLists;
7262 if (NumTPLists) {
7263 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7264 for (unsigned i=0; i != NumTPLists; ++i)
7265 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7266 }
7267}
7268
7269TemplateName
7270ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7271 unsigned &Idx) {
7272 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7273 switch (Kind) {
7274 case TemplateName::Template:
7275 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7276
7277 case TemplateName::OverloadedTemplate: {
7278 unsigned size = Record[Idx++];
7279 UnresolvedSet<8> Decls;
7280 while (size--)
7281 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7282
7283 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7284 }
7285
7286 case TemplateName::QualifiedTemplate: {
7287 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7288 bool hasTemplKeyword = Record[Idx++];
7289 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7290 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7291 }
7292
7293 case TemplateName::DependentTemplate: {
7294 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7295 if (Record[Idx++]) // isIdentifier
7296 return Context.getDependentTemplateName(NNS,
7297 GetIdentifierInfo(F, Record,
7298 Idx));
7299 return Context.getDependentTemplateName(NNS,
7300 (OverloadedOperatorKind)Record[Idx++]);
7301 }
7302
7303 case TemplateName::SubstTemplateTemplateParm: {
7304 TemplateTemplateParmDecl *param
7305 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7306 if (!param) return TemplateName();
7307 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7308 return Context.getSubstTemplateTemplateParm(param, replacement);
7309 }
7310
7311 case TemplateName::SubstTemplateTemplateParmPack: {
7312 TemplateTemplateParmDecl *Param
7313 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7314 if (!Param)
7315 return TemplateName();
7316
7317 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7318 if (ArgPack.getKind() != TemplateArgument::Pack)
7319 return TemplateName();
7320
7321 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7322 }
7323 }
7324
7325 llvm_unreachable("Unhandled template name kind!");
7326}
7327
7328TemplateArgument
7329ASTReader::ReadTemplateArgument(ModuleFile &F,
7330 const RecordData &Record, unsigned &Idx) {
7331 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7332 switch (Kind) {
7333 case TemplateArgument::Null:
7334 return TemplateArgument();
7335 case TemplateArgument::Type:
7336 return TemplateArgument(readType(F, Record, Idx));
7337 case TemplateArgument::Declaration: {
7338 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7339 bool ForReferenceParam = Record[Idx++];
7340 return TemplateArgument(D, ForReferenceParam);
7341 }
7342 case TemplateArgument::NullPtr:
7343 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7344 case TemplateArgument::Integral: {
7345 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7346 QualType T = readType(F, Record, Idx);
7347 return TemplateArgument(Context, Value, T);
7348 }
7349 case TemplateArgument::Template:
7350 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7351 case TemplateArgument::TemplateExpansion: {
7352 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007353 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007354 if (unsigned NumExpansions = Record[Idx++])
7355 NumTemplateExpansions = NumExpansions - 1;
7356 return TemplateArgument(Name, NumTemplateExpansions);
7357 }
7358 case TemplateArgument::Expression:
7359 return TemplateArgument(ReadExpr(F));
7360 case TemplateArgument::Pack: {
7361 unsigned NumArgs = Record[Idx++];
7362 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7363 for (unsigned I = 0; I != NumArgs; ++I)
7364 Args[I] = ReadTemplateArgument(F, Record, Idx);
7365 return TemplateArgument(Args, NumArgs);
7366 }
7367 }
7368
7369 llvm_unreachable("Unhandled template argument kind!");
7370}
7371
7372TemplateParameterList *
7373ASTReader::ReadTemplateParameterList(ModuleFile &F,
7374 const RecordData &Record, unsigned &Idx) {
7375 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7376 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7377 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7378
7379 unsigned NumParams = Record[Idx++];
7380 SmallVector<NamedDecl *, 16> Params;
7381 Params.reserve(NumParams);
7382 while (NumParams--)
7383 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7384
7385 TemplateParameterList* TemplateParams =
7386 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7387 Params.data(), Params.size(), RAngleLoc);
7388 return TemplateParams;
7389}
7390
7391void
7392ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007393ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007394 ModuleFile &F, const RecordData &Record,
7395 unsigned &Idx) {
7396 unsigned NumTemplateArgs = Record[Idx++];
7397 TemplArgs.reserve(NumTemplateArgs);
7398 while (NumTemplateArgs--)
7399 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7400}
7401
7402/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007403void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007404 const RecordData &Record, unsigned &Idx) {
7405 unsigned NumDecls = Record[Idx++];
7406 Set.reserve(Context, NumDecls);
7407 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007408 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007409 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007410 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007411 }
7412}
7413
7414CXXBaseSpecifier
7415ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7416 const RecordData &Record, unsigned &Idx) {
7417 bool isVirtual = static_cast<bool>(Record[Idx++]);
7418 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7419 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7420 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7421 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7422 SourceRange Range = ReadSourceRange(F, Record, Idx);
7423 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7424 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7425 EllipsisLoc);
7426 Result.setInheritConstructors(inheritConstructors);
7427 return Result;
7428}
7429
7430std::pair<CXXCtorInitializer **, unsigned>
7431ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7432 unsigned &Idx) {
7433 CXXCtorInitializer **CtorInitializers = 0;
7434 unsigned NumInitializers = Record[Idx++];
7435 if (NumInitializers) {
7436 CtorInitializers
7437 = new (Context) CXXCtorInitializer*[NumInitializers];
7438 for (unsigned i=0; i != NumInitializers; ++i) {
7439 TypeSourceInfo *TInfo = 0;
7440 bool IsBaseVirtual = false;
7441 FieldDecl *Member = 0;
7442 IndirectFieldDecl *IndirectMember = 0;
7443
7444 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7445 switch (Type) {
7446 case CTOR_INITIALIZER_BASE:
7447 TInfo = GetTypeSourceInfo(F, Record, Idx);
7448 IsBaseVirtual = Record[Idx++];
7449 break;
7450
7451 case CTOR_INITIALIZER_DELEGATING:
7452 TInfo = GetTypeSourceInfo(F, Record, Idx);
7453 break;
7454
7455 case CTOR_INITIALIZER_MEMBER:
7456 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7457 break;
7458
7459 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7460 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7461 break;
7462 }
7463
7464 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7465 Expr *Init = ReadExpr(F);
7466 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7467 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7468 bool IsWritten = Record[Idx++];
7469 unsigned SourceOrderOrNumArrayIndices;
7470 SmallVector<VarDecl *, 8> Indices;
7471 if (IsWritten) {
7472 SourceOrderOrNumArrayIndices = Record[Idx++];
7473 } else {
7474 SourceOrderOrNumArrayIndices = Record[Idx++];
7475 Indices.reserve(SourceOrderOrNumArrayIndices);
7476 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7477 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7478 }
7479
7480 CXXCtorInitializer *BOMInit;
7481 if (Type == CTOR_INITIALIZER_BASE) {
7482 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7483 LParenLoc, Init, RParenLoc,
7484 MemberOrEllipsisLoc);
7485 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7486 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7487 Init, RParenLoc);
7488 } else if (IsWritten) {
7489 if (Member)
7490 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7491 LParenLoc, Init, RParenLoc);
7492 else
7493 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7494 MemberOrEllipsisLoc, LParenLoc,
7495 Init, RParenLoc);
7496 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007497 if (IndirectMember) {
7498 assert(Indices.empty() && "Indirect field improperly initialized");
7499 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7500 MemberOrEllipsisLoc, LParenLoc,
7501 Init, RParenLoc);
7502 } else {
7503 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7504 LParenLoc, Init, RParenLoc,
7505 Indices.data(), Indices.size());
7506 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007507 }
7508
7509 if (IsWritten)
7510 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7511 CtorInitializers[i] = BOMInit;
7512 }
7513 }
7514
7515 return std::make_pair(CtorInitializers, NumInitializers);
7516}
7517
7518NestedNameSpecifier *
7519ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7520 const RecordData &Record, unsigned &Idx) {
7521 unsigned N = Record[Idx++];
7522 NestedNameSpecifier *NNS = 0, *Prev = 0;
7523 for (unsigned I = 0; I != N; ++I) {
7524 NestedNameSpecifier::SpecifierKind Kind
7525 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7526 switch (Kind) {
7527 case NestedNameSpecifier::Identifier: {
7528 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7529 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7530 break;
7531 }
7532
7533 case NestedNameSpecifier::Namespace: {
7534 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7535 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7536 break;
7537 }
7538
7539 case NestedNameSpecifier::NamespaceAlias: {
7540 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7541 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7542 break;
7543 }
7544
7545 case NestedNameSpecifier::TypeSpec:
7546 case NestedNameSpecifier::TypeSpecWithTemplate: {
7547 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7548 if (!T)
7549 return 0;
7550
7551 bool Template = Record[Idx++];
7552 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7553 break;
7554 }
7555
7556 case NestedNameSpecifier::Global: {
7557 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7558 // No associated value, and there can't be a prefix.
7559 break;
7560 }
7561 }
7562 Prev = NNS;
7563 }
7564 return NNS;
7565}
7566
7567NestedNameSpecifierLoc
7568ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7569 unsigned &Idx) {
7570 unsigned N = Record[Idx++];
7571 NestedNameSpecifierLocBuilder Builder;
7572 for (unsigned I = 0; I != N; ++I) {
7573 NestedNameSpecifier::SpecifierKind Kind
7574 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7575 switch (Kind) {
7576 case NestedNameSpecifier::Identifier: {
7577 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7578 SourceRange Range = ReadSourceRange(F, Record, Idx);
7579 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7580 break;
7581 }
7582
7583 case NestedNameSpecifier::Namespace: {
7584 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7585 SourceRange Range = ReadSourceRange(F, Record, Idx);
7586 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7587 break;
7588 }
7589
7590 case NestedNameSpecifier::NamespaceAlias: {
7591 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7592 SourceRange Range = ReadSourceRange(F, Record, Idx);
7593 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7594 break;
7595 }
7596
7597 case NestedNameSpecifier::TypeSpec:
7598 case NestedNameSpecifier::TypeSpecWithTemplate: {
7599 bool Template = Record[Idx++];
7600 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7601 if (!T)
7602 return NestedNameSpecifierLoc();
7603 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7604
7605 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7606 Builder.Extend(Context,
7607 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7608 T->getTypeLoc(), ColonColonLoc);
7609 break;
7610 }
7611
7612 case NestedNameSpecifier::Global: {
7613 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7614 Builder.MakeGlobal(Context, ColonColonLoc);
7615 break;
7616 }
7617 }
7618 }
7619
7620 return Builder.getWithLocInContext(Context);
7621}
7622
7623SourceRange
7624ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7625 unsigned &Idx) {
7626 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7627 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7628 return SourceRange(beg, end);
7629}
7630
7631/// \brief Read an integral value
7632llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7633 unsigned BitWidth = Record[Idx++];
7634 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7635 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7636 Idx += NumWords;
7637 return Result;
7638}
7639
7640/// \brief Read a signed integral value
7641llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7642 bool isUnsigned = Record[Idx++];
7643 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7644}
7645
7646/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007647llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7648 const llvm::fltSemantics &Sem,
7649 unsigned &Idx) {
7650 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007651}
7652
7653// \brief Read a string
7654std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7655 unsigned Len = Record[Idx++];
7656 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7657 Idx += Len;
7658 return Result;
7659}
7660
7661VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7662 unsigned &Idx) {
7663 unsigned Major = Record[Idx++];
7664 unsigned Minor = Record[Idx++];
7665 unsigned Subminor = Record[Idx++];
7666 if (Minor == 0)
7667 return VersionTuple(Major);
7668 if (Subminor == 0)
7669 return VersionTuple(Major, Minor - 1);
7670 return VersionTuple(Major, Minor - 1, Subminor - 1);
7671}
7672
7673CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7674 const RecordData &Record,
7675 unsigned &Idx) {
7676 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7677 return CXXTemporary::Create(Context, Decl);
7678}
7679
7680DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007681 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007682}
7683
7684DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7685 return Diags.Report(Loc, DiagID);
7686}
7687
7688/// \brief Retrieve the identifier table associated with the
7689/// preprocessor.
7690IdentifierTable &ASTReader::getIdentifierTable() {
7691 return PP.getIdentifierTable();
7692}
7693
7694/// \brief Record that the given ID maps to the given switch-case
7695/// statement.
7696void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7697 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7698 "Already have a SwitchCase with this ID");
7699 (*CurrSwitchCaseStmts)[ID] = SC;
7700}
7701
7702/// \brief Retrieve the switch-case statement with the given ID.
7703SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7704 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7705 return (*CurrSwitchCaseStmts)[ID];
7706}
7707
7708void ASTReader::ClearSwitchCaseIDs() {
7709 CurrSwitchCaseStmts->clear();
7710}
7711
7712void ASTReader::ReadComments() {
7713 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007714 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007715 serialization::ModuleFile *> >::iterator
7716 I = CommentsCursors.begin(),
7717 E = CommentsCursors.end();
7718 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007719 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007720 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007721 serialization::ModuleFile &F = *I->second;
7722 SavedStreamPosition SavedPosition(Cursor);
7723
7724 RecordData Record;
7725 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007726 llvm::BitstreamEntry Entry =
7727 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007728
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007729 switch (Entry.Kind) {
7730 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7731 case llvm::BitstreamEntry::Error:
7732 Error("malformed block record in AST file");
7733 return;
7734 case llvm::BitstreamEntry::EndBlock:
7735 goto NextCursor;
7736 case llvm::BitstreamEntry::Record:
7737 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007738 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007739 }
7740
7741 // Read a record.
7742 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007743 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007744 case COMMENTS_RAW_COMMENT: {
7745 unsigned Idx = 0;
7746 SourceRange SR = ReadSourceRange(F, Record, Idx);
7747 RawComment::CommentKind Kind =
7748 (RawComment::CommentKind) Record[Idx++];
7749 bool IsTrailingComment = Record[Idx++];
7750 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00007751 Comments.push_back(new (Context) RawComment(
7752 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7753 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00007754 break;
7755 }
7756 }
7757 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007758 NextCursor:
7759 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00007760 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007761}
7762
7763void ASTReader::finishPendingActions() {
7764 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00007765 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
7766 !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007767 // If any identifiers with corresponding top-level declarations have
7768 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00007769 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
7770 TopLevelDeclsMap;
7771 TopLevelDeclsMap TopLevelDecls;
7772
Guy Benyei11169dd2012-12-18 14:30:41 +00007773 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007774 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00007775 SmallVector<uint32_t, 4> DeclIDs =
7776 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00007777 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00007778
7779 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007780 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00007781
Guy Benyei11169dd2012-12-18 14:30:41 +00007782 // Load pending declaration chains.
7783 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7784 loadPendingDeclChain(PendingDeclChains[I]);
7785 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
7786 }
7787 PendingDeclChains.clear();
7788
Douglas Gregor6168bd22013-02-18 15:53:43 +00007789 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00007790 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
7791 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007792 IdentifierInfo *II = TLD->first;
7793 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007794 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00007795 }
7796 }
7797
Guy Benyei11169dd2012-12-18 14:30:41 +00007798 // Load any pending macro definitions.
7799 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007800 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
7801 SmallVector<PendingMacroInfo, 2> GlobalIDs;
7802 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
7803 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00007804 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00007805 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007806 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7807 if (Info.M->Kind != MK_Module)
7808 resolvePendingMacro(II, Info);
7809 }
7810 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00007811 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007812 ++IDIdx) {
7813 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7814 if (Info.M->Kind == MK_Module)
7815 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00007816 }
7817 }
7818 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00007819
7820 // Wire up the DeclContexts for Decls that we delayed setting until
7821 // recursive loading is completed.
7822 while (!PendingDeclContextInfos.empty()) {
7823 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7824 PendingDeclContextInfos.pop_front();
7825 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7826 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7827 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7828 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00007829
7830 // For each declaration from a merged context, check that the canonical
7831 // definition of that context also contains a declaration of the same
7832 // entity.
7833 while (!PendingOdrMergeChecks.empty()) {
7834 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
7835
7836 // FIXME: Skip over implicit declarations for now. This matters for things
7837 // like implicitly-declared special member functions. This isn't entirely
7838 // correct; we can end up with multiple unmerged declarations of the same
7839 // implicit entity.
7840 if (D->isImplicit())
7841 continue;
7842
7843 DeclContext *CanonDef = D->getDeclContext();
7844 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
7845
7846 bool Found = false;
7847 const Decl *DCanon = D->getCanonicalDecl();
7848
7849 llvm::SmallVector<const NamedDecl*, 4> Candidates;
7850 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
7851 !Found && I != E; ++I) {
Aaron Ballman86c93902014-03-06 23:45:36 +00007852 for (auto RI : (*I)->redecls()) {
7853 if (RI->getLexicalDeclContext() == CanonDef) {
Richard Smith2b9e3e32013-10-18 06:05:18 +00007854 // This declaration is present in the canonical definition. If it's
7855 // in the same redecl chain, it's the one we're looking for.
Aaron Ballman86c93902014-03-06 23:45:36 +00007856 if (RI->getCanonicalDecl() == DCanon)
Richard Smith2b9e3e32013-10-18 06:05:18 +00007857 Found = true;
7858 else
Aaron Ballman86c93902014-03-06 23:45:36 +00007859 Candidates.push_back(cast<NamedDecl>(RI));
Richard Smith2b9e3e32013-10-18 06:05:18 +00007860 break;
7861 }
7862 }
7863 }
7864
7865 if (!Found) {
7866 D->setInvalidDecl();
7867
7868 Module *CanonDefModule = cast<Decl>(CanonDef)->getOwningModule();
7869 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
7870 << D << D->getOwningModule()->getFullModuleName()
7871 << CanonDef << !CanonDefModule
7872 << (CanonDefModule ? CanonDefModule->getFullModuleName() : "");
7873
7874 if (Candidates.empty())
7875 Diag(cast<Decl>(CanonDef)->getLocation(),
7876 diag::note_module_odr_violation_no_possible_decls) << D;
7877 else {
7878 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
7879 Diag(Candidates[I]->getLocation(),
7880 diag::note_module_odr_violation_possible_decl)
7881 << Candidates[I];
7882 }
7883 }
7884 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007885 }
7886
7887 // If we deserialized any C++ or Objective-C class definitions, any
7888 // Objective-C protocol definitions, or any redeclarable templates, make sure
7889 // that all redeclarations point to the definitions. Note that this can only
7890 // happen now, after the redeclaration chains have been fully wired.
7891 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7892 DEnd = PendingDefinitions.end();
7893 D != DEnd; ++D) {
7894 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7895 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7896 // Make sure that the TagType points at the definition.
7897 const_cast<TagType*>(TagT)->decl = TD;
7898 }
7899
Aaron Ballman86c93902014-03-06 23:45:36 +00007900 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
7901 for (auto R : RD->redecls())
7902 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei11169dd2012-12-18 14:30:41 +00007903
7904 }
7905
7906 continue;
7907 }
7908
Aaron Ballman86c93902014-03-06 23:45:36 +00007909 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007910 // Make sure that the ObjCInterfaceType points at the definition.
7911 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7912 ->Decl = ID;
7913
Aaron Ballman86c93902014-03-06 23:45:36 +00007914 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00007915 R->Data = ID->Data;
7916
7917 continue;
7918 }
7919
Aaron Ballman86c93902014-03-06 23:45:36 +00007920 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7921 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00007922 R->Data = PD->Data;
7923
7924 continue;
7925 }
7926
Aaron Ballman86c93902014-03-06 23:45:36 +00007927 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7928 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00007929 R->Common = RTD->Common;
7930 }
7931 PendingDefinitions.clear();
7932
7933 // Load the bodies of any functions or methods we've encountered. We do
7934 // this now (delayed) so that we can be sure that the declaration chains
7935 // have been fully wired up.
7936 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7937 PBEnd = PendingBodies.end();
7938 PB != PBEnd; ++PB) {
7939 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7940 // FIXME: Check for =delete/=default?
7941 // FIXME: Complain about ODR violations here?
7942 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7943 FD->setLazyBody(PB->second);
7944 continue;
7945 }
7946
7947 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7948 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7949 MD->setLazyBody(PB->second);
7950 }
7951 PendingBodies.clear();
7952}
7953
7954void ASTReader::FinishedDeserializing() {
7955 assert(NumCurrentElementsDeserializing &&
7956 "FinishedDeserializing not paired with StartedDeserializing");
7957 if (NumCurrentElementsDeserializing == 1) {
7958 // We decrease NumCurrentElementsDeserializing only after pending actions
7959 // are finished, to avoid recursively re-calling finishPendingActions().
7960 finishPendingActions();
7961 }
7962 --NumCurrentElementsDeserializing;
7963
Richard Smith04d05b52014-03-23 00:27:18 +00007964 if (NumCurrentElementsDeserializing == 0 && Consumer) {
7965 // We are not in recursive loading, so it's safe to pass the "interesting"
7966 // decls to the consumer.
7967 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00007968 }
7969}
7970
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007971void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00007972 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007973
7974 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
7975 SemaObj->TUScope->AddDecl(D);
7976 } else if (SemaObj->TUScope) {
7977 // Adding the decl to IdResolver may have failed because it was already in
7978 // (even though it was not added in scope). If it is already in, make sure
7979 // it gets in the scope as well.
7980 if (std::find(SemaObj->IdResolver.begin(Name),
7981 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
7982 SemaObj->TUScope->AddDecl(D);
7983 }
7984}
7985
Guy Benyei11169dd2012-12-18 14:30:41 +00007986ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7987 StringRef isysroot, bool DisableValidation,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007988 bool AllowASTWithCompilerErrors,
7989 bool AllowConfigurationMismatch,
Ben Langmuir3d4417c2014-02-07 17:31:11 +00007990 bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007991 bool UseGlobalIndex)
Guy Benyei11169dd2012-12-18 14:30:41 +00007992 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7993 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7994 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7995 Consumer(0), ModuleMgr(PP.getFileManager()),
7996 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregor00a50f72013-01-25 00:38:33 +00007997 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007998 AllowConfigurationMismatch(AllowConfigurationMismatch),
Ben Langmuir3d4417c2014-02-07 17:31:11 +00007999 ValidateSystemInputs(ValidateSystemInputs),
Douglas Gregorc1bbec82013-01-25 00:45:27 +00008000 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei11169dd2012-12-18 14:30:41 +00008001 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
8002 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregor00a50f72013-01-25 00:38:33 +00008003 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
8004 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
8005 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008006 NumMethodPoolLookups(0), NumMethodPoolHits(0),
8007 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
8008 TotalNumMethodPoolEntries(0),
Guy Benyei11169dd2012-12-18 14:30:41 +00008009 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8010 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8011 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8012 PassingDeclsToConsumer(false),
Richard Smith629ff362013-07-31 00:26:46 +00008013 NumCXXBaseSpecifiersLoaded(0), ReadingKind(Read_None)
Guy Benyei11169dd2012-12-18 14:30:41 +00008014{
8015 SourceMgr.setExternalSLocEntrySource(this);
8016}
8017
8018ASTReader::~ASTReader() {
8019 for (DeclContextVisibleUpdatesPending::iterator
8020 I = PendingVisibleUpdates.begin(),
8021 E = PendingVisibleUpdates.end();
8022 I != E; ++I) {
8023 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8024 F = I->second.end();
8025 J != F; ++J)
8026 delete J->first;
8027 }
8028}