blob: fd4f90e3ef7bbdbbecb830ddf44b16f002eeeca7 [file] [log] [blame]
Nick Lewycky995e26b2013-01-31 03:23:57 +00001//===--- ASTReader.cpp - AST File Reader ----------------------------------===//
Guy Benyei7f92f2d2012-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 Benyei7f92f2d2012-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 Gregor1a49d972013-01-25 01:03:03 +000041#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000042#include "clang/Serialization/ModuleManager.h"
43#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +000044#include "llvm/ADT/Hashing.h"
Guy Benyei7f92f2d2012-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"
52#include "llvm/Support/system_error.h"
53#include <algorithm>
Chris Lattnere4e4a882013-01-20 00:57:52 +000054#include <cstdio>
Guy Benyei7f92f2d2012-12-18 14:30:41 +000055#include <iterator>
56
57using namespace clang;
58using namespace clang::serialization;
59using namespace clang::serialization::reader;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +000060using llvm::BitstreamCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +000061
62//===----------------------------------------------------------------------===//
63// PCH validator implementation
64//===----------------------------------------------------------------------===//
65
66ASTReaderListener::~ASTReaderListener() {}
67
68/// \brief Compare the given set of language options against an existing set of
69/// language options.
70///
71/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
72///
73/// \returns true if the languagae options mis-match, false otherwise.
74static bool checkLanguageOptions(const LangOptions &LangOpts,
75 const LangOptions &ExistingLangOpts,
76 DiagnosticsEngine *Diags) {
77#define LANGOPT(Name, Bits, Default, Description) \
78 if (ExistingLangOpts.Name != LangOpts.Name) { \
79 if (Diags) \
80 Diags->Report(diag::err_pch_langopt_mismatch) \
81 << Description << LangOpts.Name << ExistingLangOpts.Name; \
82 return true; \
83 }
84
85#define VALUE_LANGOPT(Name, Bits, Default, Description) \
86 if (ExistingLangOpts.Name != LangOpts.Name) { \
87 if (Diags) \
88 Diags->Report(diag::err_pch_langopt_value_mismatch) \
89 << Description; \
90 return true; \
91 }
92
93#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
94 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
95 if (Diags) \
96 Diags->Report(diag::err_pch_langopt_value_mismatch) \
97 << Description; \
98 return true; \
99 }
100
101#define BENIGN_LANGOPT(Name, Bits, Default, Description)
102#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
103#include "clang/Basic/LangOptions.def"
104
105 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
106 if (Diags)
107 Diags->Report(diag::err_pch_langopt_value_mismatch)
108 << "target Objective-C runtime";
109 return true;
110 }
111
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000112 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
113 LangOpts.CommentOpts.BlockCommandNames) {
114 if (Diags)
115 Diags->Report(diag::err_pch_langopt_value_mismatch)
116 << "block command names";
117 return true;
118 }
119
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000120 return false;
121}
122
123/// \brief Compare the given set of target options against an existing set of
124/// target options.
125///
126/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
127///
128/// \returns true if the target options mis-match, false otherwise.
129static bool checkTargetOptions(const TargetOptions &TargetOpts,
130 const TargetOptions &ExistingTargetOpts,
131 DiagnosticsEngine *Diags) {
132#define CHECK_TARGET_OPT(Field, Name) \
133 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
134 if (Diags) \
135 Diags->Report(diag::err_pch_targetopt_mismatch) \
136 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
137 return true; \
138 }
139
140 CHECK_TARGET_OPT(Triple, "target");
141 CHECK_TARGET_OPT(CPU, "target CPU");
142 CHECK_TARGET_OPT(ABI, "target ABI");
143 CHECK_TARGET_OPT(CXXABI, "target C++ ABI");
144 CHECK_TARGET_OPT(LinkerVersion, "target linker version");
145#undef CHECK_TARGET_OPT
146
147 // Compare feature sets.
148 SmallVector<StringRef, 4> ExistingFeatures(
149 ExistingTargetOpts.FeaturesAsWritten.begin(),
150 ExistingTargetOpts.FeaturesAsWritten.end());
151 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
152 TargetOpts.FeaturesAsWritten.end());
153 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
154 std::sort(ReadFeatures.begin(), ReadFeatures.end());
155
156 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
157 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
158 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
159 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
160 ++ExistingIdx;
161 ++ReadIdx;
162 continue;
163 }
164
165 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
166 if (Diags)
167 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
168 << false << ReadFeatures[ReadIdx];
169 return true;
170 }
171
172 if (Diags)
173 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
174 << true << ExistingFeatures[ExistingIdx];
175 return true;
176 }
177
178 if (ExistingIdx < ExistingN) {
179 if (Diags)
180 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
181 << true << ExistingFeatures[ExistingIdx];
182 return true;
183 }
184
185 if (ReadIdx < ReadN) {
186 if (Diags)
187 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
188 << false << ReadFeatures[ReadIdx];
189 return true;
190 }
191
192 return false;
193}
194
195bool
196PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
197 bool Complain) {
198 const LangOptions &ExistingLangOpts = PP.getLangOpts();
199 return checkLanguageOptions(LangOpts, ExistingLangOpts,
200 Complain? &Reader.Diags : 0);
201}
202
203bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
204 bool Complain) {
205 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
206 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
207 Complain? &Reader.Diags : 0);
208}
209
210namespace {
211 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
212 MacroDefinitionsMap;
213}
214
215/// \brief Collect the macro definitions provided by the given preprocessor
216/// options.
217static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
218 MacroDefinitionsMap &Macros,
219 SmallVectorImpl<StringRef> *MacroNames = 0){
220 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
221 StringRef Macro = PPOpts.Macros[I].first;
222 bool IsUndef = PPOpts.Macros[I].second;
223
224 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
225 StringRef MacroName = MacroPair.first;
226 StringRef MacroBody = MacroPair.second;
227
228 // For an #undef'd macro, we only care about the name.
229 if (IsUndef) {
230 if (MacroNames && !Macros.count(MacroName))
231 MacroNames->push_back(MacroName);
232
233 Macros[MacroName] = std::make_pair("", true);
234 continue;
235 }
236
237 // For a #define'd macro, figure out the actual definition.
238 if (MacroName.size() == Macro.size())
239 MacroBody = "1";
240 else {
241 // Note: GCC drops anything following an end-of-line character.
242 StringRef::size_type End = MacroBody.find_first_of("\n\r");
243 MacroBody = MacroBody.substr(0, End);
244 }
245
246 if (MacroNames && !Macros.count(MacroName))
247 MacroNames->push_back(MacroName);
248 Macros[MacroName] = std::make_pair(MacroBody, false);
249 }
250}
251
252/// \brief Check the preprocessor options deserialized from the control block
253/// against the preprocessor options in an existing preprocessor.
254///
255/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
256static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
257 const PreprocessorOptions &ExistingPPOpts,
258 DiagnosticsEngine *Diags,
259 FileManager &FileMgr,
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +0000260 std::string &SuggestedPredefines,
261 const LangOptions &LangOpts) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000262 // Check macro definitions.
263 MacroDefinitionsMap ASTFileMacros;
264 collectMacroDefinitions(PPOpts, ASTFileMacros);
265 MacroDefinitionsMap ExistingMacros;
266 SmallVector<StringRef, 4> ExistingMacroNames;
267 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
268
269 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
270 // Dig out the macro definition in the existing preprocessor options.
271 StringRef MacroName = ExistingMacroNames[I];
272 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
273
274 // Check whether we know anything about this macro name or not.
275 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
276 = ASTFileMacros.find(MacroName);
277 if (Known == ASTFileMacros.end()) {
278 // FIXME: Check whether this identifier was referenced anywhere in the
279 // AST file. If so, we should reject the AST file. Unfortunately, this
280 // information isn't in the control block. What shall we do about it?
281
282 if (Existing.second) {
283 SuggestedPredefines += "#undef ";
284 SuggestedPredefines += MacroName.str();
285 SuggestedPredefines += '\n';
286 } else {
287 SuggestedPredefines += "#define ";
288 SuggestedPredefines += MacroName.str();
289 SuggestedPredefines += ' ';
290 SuggestedPredefines += Existing.first.str();
291 SuggestedPredefines += '\n';
292 }
293 continue;
294 }
295
296 // If the macro was defined in one but undef'd in the other, we have a
297 // conflict.
298 if (Existing.second != Known->second.second) {
299 if (Diags) {
300 Diags->Report(diag::err_pch_macro_def_undef)
301 << MacroName << Known->second.second;
302 }
303 return true;
304 }
305
306 // If the macro was #undef'd in both, or if the macro bodies are identical,
307 // it's fine.
308 if (Existing.second || Existing.first == Known->second.first)
309 continue;
310
311 // The macro bodies differ; complain.
312 if (Diags) {
313 Diags->Report(diag::err_pch_macro_def_conflict)
314 << MacroName << Known->second.first << Existing.first;
315 }
316 return true;
317 }
318
319 // Check whether we're using predefines.
320 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
321 if (Diags) {
322 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
323 }
324 return true;
325 }
326
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +0000327 // Detailed record is important since it is used for the module cache hash.
328 if (LangOpts.Modules &&
329 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
330 if (Diags) {
331 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
332 }
333 return true;
334 }
335
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000336 // Compute the #include and #include_macros lines we need.
337 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
338 StringRef File = ExistingPPOpts.Includes[I];
339 if (File == ExistingPPOpts.ImplicitPCHInclude)
340 continue;
341
342 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
343 != PPOpts.Includes.end())
344 continue;
345
346 SuggestedPredefines += "#include \"";
347 SuggestedPredefines +=
348 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
349 SuggestedPredefines += "\"\n";
350 }
351
352 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
353 StringRef File = ExistingPPOpts.MacroIncludes[I];
354 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
355 File)
356 != PPOpts.MacroIncludes.end())
357 continue;
358
359 SuggestedPredefines += "#__include_macros \"";
360 SuggestedPredefines +=
361 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
362 SuggestedPredefines += "\"\n##\n";
363 }
364
365 return false;
366}
367
368bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
369 bool Complain,
370 std::string &SuggestedPredefines) {
371 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
372
373 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
374 Complain? &Reader.Diags : 0,
375 PP.getFileManager(),
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +0000376 SuggestedPredefines,
377 PP.getLangOpts());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000378}
379
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000380void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
381 PP.setCounterValue(Value);
382}
383
384//===----------------------------------------------------------------------===//
385// AST reader implementation
386//===----------------------------------------------------------------------===//
387
388void
389ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
390 DeserializationListener = Listener;
391}
392
393
394
395unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
396 return serialization::ComputeHash(Sel);
397}
398
399
400std::pair<unsigned, unsigned>
401ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
402 using namespace clang::io;
403 unsigned KeyLen = ReadUnalignedLE16(d);
404 unsigned DataLen = ReadUnalignedLE16(d);
405 return std::make_pair(KeyLen, DataLen);
406}
407
408ASTSelectorLookupTrait::internal_key_type
409ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
410 using namespace clang::io;
411 SelectorTable &SelTable = Reader.getContext().Selectors;
412 unsigned N = ReadUnalignedLE16(d);
413 IdentifierInfo *FirstII
Douglas Gregor8222b892013-01-21 16:52:34 +0000414 = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000415 if (N == 0)
416 return SelTable.getNullarySelector(FirstII);
417 else if (N == 1)
418 return SelTable.getUnarySelector(FirstII);
419
420 SmallVector<IdentifierInfo *, 16> Args;
421 Args.push_back(FirstII);
422 for (unsigned I = 1; I != N; ++I)
Douglas Gregor8222b892013-01-21 16:52:34 +0000423 Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000424
425 return SelTable.getSelector(N, Args.data());
426}
427
428ASTSelectorLookupTrait::data_type
429ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
430 unsigned DataLen) {
431 using namespace clang::io;
432
433 data_type Result;
434
435 Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +0000436 unsigned NumInstanceMethodsAndBits = ReadUnalignedLE16(d);
437 unsigned NumFactoryMethodsAndBits = ReadUnalignedLE16(d);
438 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
439 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
440 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
441 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000442
443 // Load instance methods
444 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
445 if (ObjCMethodDecl *Method
446 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
447 Result.Instance.push_back(Method);
448 }
449
450 // Load factory methods
451 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
452 if (ObjCMethodDecl *Method
453 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
454 Result.Factory.push_back(Method);
455 }
456
457 return Result;
458}
459
Douglas Gregor479633c2013-01-23 18:53:14 +0000460unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
461 return llvm::HashString(a);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000462}
463
464std::pair<unsigned, unsigned>
Douglas Gregor479633c2013-01-23 18:53:14 +0000465ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000466 using namespace clang::io;
467 unsigned DataLen = ReadUnalignedLE16(d);
468 unsigned KeyLen = ReadUnalignedLE16(d);
469 return std::make_pair(KeyLen, DataLen);
470}
471
Douglas Gregor479633c2013-01-23 18:53:14 +0000472ASTIdentifierLookupTraitBase::internal_key_type
473ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000474 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregor479633c2013-01-23 18:53:14 +0000475 return StringRef((const char*) d, n-1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000476}
477
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000478/// \brief Whether the given identifier is "interesting".
479static bool isInterestingIdentifier(IdentifierInfo &II) {
480 return II.isPoisoned() ||
481 II.isExtensionToken() ||
482 II.getObjCOrBuiltinID() ||
483 II.hasRevertedTokenIDToIdentifier() ||
484 II.hadMacroDefinition() ||
485 II.getFETokenInfo<void>();
486}
487
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000488IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
489 const unsigned char* d,
490 unsigned DataLen) {
491 using namespace clang::io;
492 unsigned RawID = ReadUnalignedLE32(d);
493 bool IsInteresting = RawID & 0x01;
494
495 // Wipe out the "is interesting" bit.
496 RawID = RawID >> 1;
497
498 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
499 if (!IsInteresting) {
500 // For uninteresting identifiers, just build the IdentifierInfo
501 // and associate it with the persistent ID.
502 IdentifierInfo *II = KnownII;
503 if (!II) {
Douglas Gregor479633c2013-01-23 18:53:14 +0000504 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000505 KnownII = II;
506 }
507 Reader.SetIdentifierInfo(ID, II);
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000508 if (!II->isFromAST()) {
509 bool WasInteresting = isInterestingIdentifier(*II);
510 II->setIsFromAST();
511 if (WasInteresting)
512 II->setChangedSinceDeserialization();
513 }
514 Reader.markIdentifierUpToDate(II);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000515 return II;
516 }
517
518 unsigned ObjCOrBuiltinID = ReadUnalignedLE16(d);
519 unsigned Bits = ReadUnalignedLE16(d);
520 bool CPlusPlusOperatorKeyword = Bits & 0x01;
521 Bits >>= 1;
522 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
523 Bits >>= 1;
524 bool Poisoned = Bits & 0x01;
525 Bits >>= 1;
526 bool ExtensionToken = Bits & 0x01;
527 Bits >>= 1;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000528 bool hasSubmoduleMacros = Bits & 0x01;
529 Bits >>= 1;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000530 bool hadMacroDefinition = Bits & 0x01;
531 Bits >>= 1;
532
533 assert(Bits == 0 && "Extra bits in the identifier?");
534 DataLen -= 8;
535
536 // Build the IdentifierInfo itself and link the identifier ID with
537 // the new IdentifierInfo.
538 IdentifierInfo *II = KnownII;
539 if (!II) {
Douglas Gregor479633c2013-01-23 18:53:14 +0000540 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000541 KnownII = II;
542 }
543 Reader.markIdentifierUpToDate(II);
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000544 if (!II->isFromAST()) {
545 bool WasInteresting = isInterestingIdentifier(*II);
546 II->setIsFromAST();
547 if (WasInteresting)
548 II->setChangedSinceDeserialization();
549 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000550
551 // Set or check the various bits in the IdentifierInfo structure.
552 // Token IDs are read-only.
Argyrios Kyrtzidis1ebefc72013-02-27 01:13:51 +0000553 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000554 II->RevertTokenIDToIdentifier();
555 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
556 assert(II->isExtensionToken() == ExtensionToken &&
557 "Incorrect extension token flag");
558 (void)ExtensionToken;
559 if (Poisoned)
560 II->setIsPoisoned(true);
561 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
562 "Incorrect C++ operator keyword flag");
563 (void)CPlusPlusOperatorKeyword;
564
565 // If this identifier is a macro, deserialize the macro
566 // definition.
567 if (hadMacroDefinition) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000568 uint32_t MacroDirectivesOffset = ReadUnalignedLE32(d);
569 DataLen -= 4;
570 SmallVector<uint32_t, 8> LocalMacroIDs;
571 if (hasSubmoduleMacros) {
572 while (uint32_t LocalMacroID = ReadUnalignedLE32(d)) {
573 DataLen -= 4;
574 LocalMacroIDs.push_back(LocalMacroID);
575 }
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +0000576 DataLen -= 4;
577 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000578
579 if (F.Kind == MK_Module) {
580 for (SmallVectorImpl<uint32_t>::iterator
581 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; ++I) {
582 MacroID MacID = Reader.getGlobalMacroID(F, *I);
583 Reader.addPendingMacroFromModule(II, &F, MacID, F.DirectImportLoc);
584 }
585 } else {
586 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
587 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000588 }
589
590 Reader.SetIdentifierInfo(ID, II);
591
592 // Read all of the declarations visible at global scope with this
593 // name.
594 if (DataLen > 0) {
595 SmallVector<uint32_t, 4> DeclIDs;
596 for (; DataLen > 0; DataLen -= 4)
597 DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
598 Reader.SetGloballyVisibleDecls(II, DeclIDs);
599 }
600
601 return II;
602}
603
604unsigned
605ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
606 llvm::FoldingSetNodeID ID;
607 ID.AddInteger(Key.Kind);
608
609 switch (Key.Kind) {
610 case DeclarationName::Identifier:
611 case DeclarationName::CXXLiteralOperatorName:
612 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
613 break;
614 case DeclarationName::ObjCZeroArgSelector:
615 case DeclarationName::ObjCOneArgSelector:
616 case DeclarationName::ObjCMultiArgSelector:
617 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
618 break;
619 case DeclarationName::CXXOperatorName:
620 ID.AddInteger((OverloadedOperatorKind)Key.Data);
621 break;
622 case DeclarationName::CXXConstructorName:
623 case DeclarationName::CXXDestructorName:
624 case DeclarationName::CXXConversionFunctionName:
625 case DeclarationName::CXXUsingDirective:
626 break;
627 }
628
629 return ID.ComputeHash();
630}
631
632ASTDeclContextNameLookupTrait::internal_key_type
633ASTDeclContextNameLookupTrait::GetInternalKey(
634 const external_key_type& Name) const {
635 DeclNameKey Key;
636 Key.Kind = Name.getNameKind();
637 switch (Name.getNameKind()) {
638 case DeclarationName::Identifier:
639 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
640 break;
641 case DeclarationName::ObjCZeroArgSelector:
642 case DeclarationName::ObjCOneArgSelector:
643 case DeclarationName::ObjCMultiArgSelector:
644 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
645 break;
646 case DeclarationName::CXXOperatorName:
647 Key.Data = Name.getCXXOverloadedOperator();
648 break;
649 case DeclarationName::CXXLiteralOperatorName:
650 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
651 break;
652 case DeclarationName::CXXConstructorName:
653 case DeclarationName::CXXDestructorName:
654 case DeclarationName::CXXConversionFunctionName:
655 case DeclarationName::CXXUsingDirective:
656 Key.Data = 0;
657 break;
658 }
659
660 return Key;
661}
662
663std::pair<unsigned, unsigned>
664ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
665 using namespace clang::io;
666 unsigned KeyLen = ReadUnalignedLE16(d);
667 unsigned DataLen = ReadUnalignedLE16(d);
668 return std::make_pair(KeyLen, DataLen);
669}
670
671ASTDeclContextNameLookupTrait::internal_key_type
672ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
673 using namespace clang::io;
674
675 DeclNameKey Key;
676 Key.Kind = (DeclarationName::NameKind)*d++;
677 switch (Key.Kind) {
678 case DeclarationName::Identifier:
679 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
680 break;
681 case DeclarationName::ObjCZeroArgSelector:
682 case DeclarationName::ObjCOneArgSelector:
683 case DeclarationName::ObjCMultiArgSelector:
684 Key.Data =
685 (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
686 .getAsOpaquePtr();
687 break;
688 case DeclarationName::CXXOperatorName:
689 Key.Data = *d++; // OverloadedOperatorKind
690 break;
691 case DeclarationName::CXXLiteralOperatorName:
692 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
693 break;
694 case DeclarationName::CXXConstructorName:
695 case DeclarationName::CXXDestructorName:
696 case DeclarationName::CXXConversionFunctionName:
697 case DeclarationName::CXXUsingDirective:
698 Key.Data = 0;
699 break;
700 }
701
702 return Key;
703}
704
705ASTDeclContextNameLookupTrait::data_type
706ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
707 const unsigned char* d,
708 unsigned DataLen) {
709 using namespace clang::io;
710 unsigned NumDecls = ReadUnalignedLE16(d);
Argyrios Kyrtzidise8b61cf2013-01-11 22:29:49 +0000711 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
712 const_cast<unsigned char *>(d));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000713 return std::make_pair(Start, Start + NumDecls);
714}
715
716bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000717 BitstreamCursor &Cursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000718 const std::pair<uint64_t, uint64_t> &Offsets,
719 DeclContextInfo &Info) {
720 SavedStreamPosition SavedPosition(Cursor);
721 // First the lexical decls.
722 if (Offsets.first != 0) {
723 Cursor.JumpToBit(Offsets.first);
724
725 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000726 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000727 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000728 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000729 if (RecCode != DECL_CONTEXT_LEXICAL) {
730 Error("Expected lexical block");
731 return true;
732 }
733
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000734 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
735 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000736 }
737
738 // Now the lookup table.
739 if (Offsets.second != 0) {
740 Cursor.JumpToBit(Offsets.second);
741
742 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000743 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000744 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000745 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000746 if (RecCode != DECL_CONTEXT_VISIBLE) {
747 Error("Expected visible lookup table block");
748 return true;
749 }
750 Info.NameLookupTableData
751 = ASTDeclContextNameLookupTable::Create(
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000752 (const unsigned char *)Blob.data() + Record[0],
753 (const unsigned char *)Blob.data(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000754 ASTDeclContextNameLookupTrait(*this, M));
755 }
756
757 return false;
758}
759
760void ASTReader::Error(StringRef Msg) {
761 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregorc1478612013-05-10 22:15:13 +0000762 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
763 Diag(diag::note_module_cache_path)
764 << PP.getHeaderSearchInfo().getModuleCachePath();
765 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000766}
767
768void ASTReader::Error(unsigned DiagID,
769 StringRef Arg1, StringRef Arg2) {
770 if (Diags.isDiagnosticInFlight())
771 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
772 else
773 Diag(DiagID) << Arg1 << Arg2;
774}
775
776//===----------------------------------------------------------------------===//
777// Source Manager Deserialization
778//===----------------------------------------------------------------------===//
779
780/// \brief Read the line table in the source manager block.
781/// \returns true if there was an error.
782bool ASTReader::ParseLineTable(ModuleFile &F,
783 SmallVectorImpl<uint64_t> &Record) {
784 unsigned Idx = 0;
785 LineTableInfo &LineTable = SourceMgr.getLineTable();
786
787 // Parse the file names
788 std::map<int, int> FileIDs;
789 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
790 // Extract the file name
791 unsigned FilenameLen = Record[Idx++];
792 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
793 Idx += FilenameLen;
794 MaybeAddSystemRootToFilename(F, Filename);
795 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
796 }
797
798 // Parse the line entries
799 std::vector<LineEntry> Entries;
800 while (Idx < Record.size()) {
801 int FID = Record[Idx++];
802 assert(FID >= 0 && "Serialized line entries for non-local file.");
803 // Remap FileID from 1-based old view.
804 FID += F.SLocEntryBaseID - 1;
805
806 // Extract the line entries
807 unsigned NumEntries = Record[Idx++];
808 assert(NumEntries && "Numentries is 00000");
809 Entries.clear();
810 Entries.reserve(NumEntries);
811 for (unsigned I = 0; I != NumEntries; ++I) {
812 unsigned FileOffset = Record[Idx++];
813 unsigned LineNo = Record[Idx++];
814 int FilenameID = FileIDs[Record[Idx++]];
815 SrcMgr::CharacteristicKind FileKind
816 = (SrcMgr::CharacteristicKind)Record[Idx++];
817 unsigned IncludeOffset = Record[Idx++];
818 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
819 FileKind, IncludeOffset));
820 }
821 LineTable.AddEntry(FileID::get(FID), Entries);
822 }
823
824 return false;
825}
826
827/// \brief Read a source manager block
828bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
829 using namespace SrcMgr;
830
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000831 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000832
833 // Set the source-location entry cursor to the current position in
834 // the stream. This cursor will be used to read the contents of the
835 // source manager block initially, and then lazily read
836 // source-location entries as needed.
837 SLocEntryCursor = F.Stream;
838
839 // The stream itself is going to skip over the source manager block.
840 if (F.Stream.SkipBlock()) {
841 Error("malformed block record in AST file");
842 return true;
843 }
844
845 // Enter the source manager block.
846 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
847 Error("malformed source manager block record in AST file");
848 return true;
849 }
850
851 RecordData Record;
852 while (true) {
Chris Lattner88bde502013-01-19 21:39:22 +0000853 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
854
855 switch (E.Kind) {
856 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
857 case llvm::BitstreamEntry::Error:
858 Error("malformed block record in AST file");
859 return true;
860 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000861 return false;
Chris Lattner88bde502013-01-19 21:39:22 +0000862 case llvm::BitstreamEntry::Record:
863 // The interesting case.
864 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000865 }
Chris Lattner88bde502013-01-19 21:39:22 +0000866
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000867 // Read a record.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000868 Record.clear();
Chris Lattner125eb3e2013-01-21 18:28:26 +0000869 StringRef Blob;
870 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000871 default: // Default behavior: ignore.
872 break;
873
874 case SM_SLOC_FILE_ENTRY:
875 case SM_SLOC_BUFFER_ENTRY:
876 case SM_SLOC_EXPANSION_ENTRY:
877 // Once we hit one of the source location entries, we're done.
878 return false;
879 }
880 }
881}
882
883/// \brief If a header file is not found at the path that we expect it to be
884/// and the PCH file was moved from its original location, try to resolve the
885/// file by assuming that header+PCH were moved together and the header is in
886/// the same place relative to the PCH.
887static std::string
888resolveFileRelativeToOriginalDir(const std::string &Filename,
889 const std::string &OriginalDir,
890 const std::string &CurrDir) {
891 assert(OriginalDir != CurrDir &&
892 "No point trying to resolve the file if the PCH dir didn't change");
893 using namespace llvm::sys;
894 SmallString<128> filePath(Filename);
895 fs::make_absolute(filePath);
896 assert(path::is_absolute(OriginalDir));
897 SmallString<128> currPCHPath(CurrDir);
898
899 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
900 fileDirE = path::end(path::parent_path(filePath));
901 path::const_iterator origDirI = path::begin(OriginalDir),
902 origDirE = path::end(OriginalDir);
903 // Skip the common path components from filePath and OriginalDir.
904 while (fileDirI != fileDirE && origDirI != origDirE &&
905 *fileDirI == *origDirI) {
906 ++fileDirI;
907 ++origDirI;
908 }
909 for (; origDirI != origDirE; ++origDirI)
910 path::append(currPCHPath, "..");
911 path::append(currPCHPath, fileDirI, fileDirE);
912 path::append(currPCHPath, path::filename(Filename));
913 return currPCHPath.str();
914}
915
916bool ASTReader::ReadSLocEntry(int ID) {
917 if (ID == 0)
918 return false;
919
920 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
921 Error("source location entry ID out-of-range for AST file");
922 return true;
923 }
924
925 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
926 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000927 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000928 unsigned BaseOffset = F->SLocEntryBaseOffset;
929
930 ++NumSLocEntriesRead;
Chris Lattner88bde502013-01-19 21:39:22 +0000931 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
932 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000933 Error("incorrectly-formatted source location entry in AST file");
934 return true;
935 }
Chris Lattner88bde502013-01-19 21:39:22 +0000936
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000937 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000938 StringRef Blob;
939 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000940 default:
941 Error("incorrectly-formatted source location entry in AST file");
942 return true;
943
944 case SM_SLOC_FILE_ENTRY: {
945 // We will detect whether a file changed and return 'Failure' for it, but
946 // we will also try to fail gracefully by setting up the SLocEntry.
947 unsigned InputID = Record[4];
948 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +0000949 const FileEntry *File = IF.getFile();
950 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000951
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +0000952 // Note that we only check if a File was returned. If it was out-of-date
953 // we have complained but we will continue creating a FileID to recover
954 // gracefully.
955 if (!File)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000956 return true;
957
958 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
959 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
960 // This is the module's main file.
961 IncludeLoc = getImportLocation(F);
962 }
963 SrcMgr::CharacteristicKind
964 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
965 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
966 ID, BaseOffset + Record[0]);
967 SrcMgr::FileInfo &FileInfo =
968 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
969 FileInfo.NumCreatedFIDs = Record[5];
970 if (Record[3])
971 FileInfo.setHasLineDirectives();
972
973 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
974 unsigned NumFileDecls = Record[7];
975 if (NumFileDecls) {
976 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
977 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
978 NumFileDecls));
979 }
980
981 const SrcMgr::ContentCache *ContentCache
982 = SourceMgr.getOrCreateContentCache(File,
983 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
984 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
985 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
986 unsigned Code = SLocEntryCursor.ReadCode();
987 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000988 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000989
990 if (RecCode != SM_SLOC_BUFFER_BLOB) {
991 Error("AST record has invalid code");
992 return true;
993 }
994
995 llvm::MemoryBuffer *Buffer
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000996 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000997 SourceMgr.overrideFileContents(File, Buffer);
998 }
999
1000 break;
1001 }
1002
1003 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001004 const char *Name = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001005 unsigned Offset = Record[0];
1006 SrcMgr::CharacteristicKind
1007 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1008 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1009 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1010 IncludeLoc = getImportLocation(F);
1011 }
1012 unsigned Code = SLocEntryCursor.ReadCode();
1013 Record.clear();
1014 unsigned RecCode
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001015 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001016
1017 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1018 Error("AST record has invalid code");
1019 return true;
1020 }
1021
1022 llvm::MemoryBuffer *Buffer
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001023 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001024 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
1025 BaseOffset + Offset, IncludeLoc);
1026 break;
1027 }
1028
1029 case SM_SLOC_EXPANSION_ENTRY: {
1030 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1031 SourceMgr.createExpansionLoc(SpellingLoc,
1032 ReadSourceLocation(*F, Record[2]),
1033 ReadSourceLocation(*F, Record[3]),
1034 Record[4],
1035 ID,
1036 BaseOffset + Record[0]);
1037 break;
1038 }
1039 }
1040
1041 return false;
1042}
1043
1044std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1045 if (ID == 0)
1046 return std::make_pair(SourceLocation(), "");
1047
1048 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1049 Error("source location entry ID out-of-range for AST file");
1050 return std::make_pair(SourceLocation(), "");
1051 }
1052
1053 // Find which module file this entry lands in.
1054 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1055 if (M->Kind != MK_Module)
1056 return std::make_pair(SourceLocation(), "");
1057
1058 // FIXME: Can we map this down to a particular submodule? That would be
1059 // ideal.
1060 return std::make_pair(M->ImportLoc, llvm::sys::path::stem(M->FileName));
1061}
1062
1063/// \brief Find the location where the module F is imported.
1064SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1065 if (F->ImportLoc.isValid())
1066 return F->ImportLoc;
1067
1068 // Otherwise we have a PCH. It's considered to be "imported" at the first
1069 // location of its includer.
1070 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1071 // Main file is the importer. We assume that it is the first entry in the
1072 // entry table. We can't ask the manager, because at the time of PCH loading
1073 // the main file entry doesn't exist yet.
1074 // The very first entry is the invalid instantiation loc, which takes up
1075 // offsets 0 and 1.
1076 return SourceLocation::getFromRawEncoding(2U);
1077 }
1078 //return F->Loaders[0]->FirstLoc;
1079 return F->ImportedBy[0]->FirstLoc;
1080}
1081
1082/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1083/// specified cursor. Read the abbreviations that are at the top of the block
1084/// and then leave the cursor pointing into the block.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001085bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001086 if (Cursor.EnterSubBlock(BlockID)) {
1087 Error("malformed block record in AST file");
1088 return Failure;
1089 }
1090
1091 while (true) {
1092 uint64_t Offset = Cursor.GetCurrentBitNo();
1093 unsigned Code = Cursor.ReadCode();
1094
1095 // We expect all abbrevs to be at the start of the block.
1096 if (Code != llvm::bitc::DEFINE_ABBREV) {
1097 Cursor.JumpToBit(Offset);
1098 return false;
1099 }
1100 Cursor.ReadAbbrevRecord();
1101 }
1102}
1103
John McCallaeeacf72013-05-03 00:10:13 +00001104Token ASTReader::ReadToken(ModuleFile &F, const RecordData &Record,
1105 unsigned &Idx) {
1106 Token Tok;
1107 Tok.startToken();
1108 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1109 Tok.setLength(Record[Idx++]);
1110 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1111 Tok.setIdentifierInfo(II);
1112 Tok.setKind((tok::TokenKind)Record[Idx++]);
1113 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1114 return Tok;
1115}
1116
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001117MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001118 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001119
1120 // Keep track of where we are in the stream, then jump back there
1121 // after reading this macro.
1122 SavedStreamPosition SavedPosition(Stream);
1123
1124 Stream.JumpToBit(Offset);
1125 RecordData Record;
1126 SmallVector<IdentifierInfo*, 16> MacroArgs;
1127 MacroInfo *Macro = 0;
1128
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001129 while (true) {
Chris Lattner99a5af02013-01-20 00:00:22 +00001130 // Advance to the next record, but if we get to the end of the block, don't
1131 // pop it (removing all the abbreviations from the cursor) since we want to
1132 // be able to reseek within the block and read entries.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001133 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattner99a5af02013-01-20 00:00:22 +00001134 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1135
1136 switch (Entry.Kind) {
1137 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1138 case llvm::BitstreamEntry::Error:
1139 Error("malformed block record in AST file");
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001140 return Macro;
Chris Lattner99a5af02013-01-20 00:00:22 +00001141 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001142 return Macro;
Chris Lattner99a5af02013-01-20 00:00:22 +00001143 case llvm::BitstreamEntry::Record:
1144 // The interesting case.
1145 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001146 }
1147
1148 // Read a record.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001149 Record.clear();
1150 PreprocessorRecordTypes RecType =
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001151 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001152 switch (RecType) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001153 case PP_MACRO_DIRECTIVE_HISTORY:
1154 return Macro;
1155
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001156 case PP_MACRO_OBJECT_LIKE:
1157 case PP_MACRO_FUNCTION_LIKE: {
1158 // If we already have a macro, that means that we've hit the end
1159 // of the definition of the macro we were looking for. We're
1160 // done.
1161 if (Macro)
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001162 return Macro;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001163
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001164 unsigned NextIndex = 1; // Skip identifier ID.
1165 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001166 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001167 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis8169b672013-01-07 19:16:23 +00001168 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001169 MI->setIsUsed(Record[NextIndex++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001170
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001171 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1172 // Decode function-like macro info.
1173 bool isC99VarArgs = Record[NextIndex++];
1174 bool isGNUVarArgs = Record[NextIndex++];
1175 bool hasCommaPasting = Record[NextIndex++];
1176 MacroArgs.clear();
1177 unsigned NumArgs = Record[NextIndex++];
1178 for (unsigned i = 0; i != NumArgs; ++i)
1179 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1180
1181 // Install function-like macro info.
1182 MI->setIsFunctionLike();
1183 if (isC99VarArgs) MI->setIsC99Varargs();
1184 if (isGNUVarArgs) MI->setIsGNUVarargs();
1185 if (hasCommaPasting) MI->setHasCommaPasting();
1186 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1187 PP.getPreprocessorAllocator());
1188 }
1189
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001190 // Remember that we saw this macro last so that we add the tokens that
1191 // form its body to it.
1192 Macro = MI;
1193
1194 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1195 Record[NextIndex]) {
1196 // We have a macro definition. Register the association
1197 PreprocessedEntityID
1198 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1199 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis0b849d32013-02-22 18:35:59 +00001200 PreprocessingRecord::PPEntityID
1201 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1202 MacroDefinition *PPDef =
1203 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1204 if (PPDef)
1205 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001206 }
1207
1208 ++NumMacrosRead;
1209 break;
1210 }
1211
1212 case PP_TOKEN: {
1213 // If we see a TOKEN before a PP_MACRO_*, then the file is
1214 // erroneous, just pretend we didn't see this.
1215 if (Macro == 0) break;
1216
John McCallaeeacf72013-05-03 00:10:13 +00001217 unsigned Idx = 0;
1218 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001219 Macro->AddTokenToBody(Tok);
1220 break;
1221 }
1222 }
1223 }
1224}
1225
1226PreprocessedEntityID
1227ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1228 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1229 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1230 assert(I != M.PreprocessedEntityRemap.end()
1231 && "Invalid index into preprocessed entity index remap");
1232
1233 return LocalID + I->second;
1234}
1235
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001236unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1237 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001238}
1239
1240HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001241HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1242 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1243 FE->getName() };
1244 return ikey;
1245}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001246
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001247bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1248 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001249 return false;
1250
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001251 if (strcmp(a.Filename, b.Filename) == 0)
1252 return true;
1253
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001254 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis1c1508b2013-03-04 20:33:40 +00001255 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001256 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1257 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis1c1508b2013-03-04 20:33:40 +00001258 return (FEA && FEA == FEB);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001259}
1260
1261std::pair<unsigned, unsigned>
1262HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1263 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1264 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001265 return std::make_pair(KeyLen, DataLen);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001266}
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001267
1268HeaderFileInfoTrait::internal_key_type
1269HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1270 internal_key_type ikey;
1271 ikey.Size = off_t(clang::io::ReadUnalignedLE64(d));
1272 ikey.ModTime = time_t(clang::io::ReadUnalignedLE64(d));
1273 ikey.Filename = (const char *)d;
1274 return ikey;
1275}
1276
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001277HeaderFileInfoTrait::data_type
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001278HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001279 unsigned DataLen) {
1280 const unsigned char *End = d + DataLen;
1281 using namespace clang::io;
1282 HeaderFileInfo HFI;
1283 unsigned Flags = *d++;
1284 HFI.isImport = (Flags >> 5) & 0x01;
1285 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1286 HFI.DirInfo = (Flags >> 2) & 0x03;
1287 HFI.Resolved = (Flags >> 1) & 0x01;
1288 HFI.IndexHeaderMapHeader = Flags & 0x01;
1289 HFI.NumIncludes = ReadUnalignedLE16(d);
1290 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1291 ReadUnalignedLE32(d));
1292 if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1293 // The framework offset is 1 greater than the actual offset,
1294 // since 0 is used as an indicator for "no framework name".
1295 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1296 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1297 }
1298
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001299 if (d != End) {
1300 uint32_t LocalSMID = ReadUnalignedLE32(d);
1301 if (LocalSMID) {
1302 // This header is part of a module. Associate it with the module to enable
1303 // implicit module import.
1304 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1305 Module *Mod = Reader.getSubmodule(GlobalSMID);
1306 HFI.isModuleHeader = true;
1307 FileManager &FileMgr = Reader.getFileManager();
1308 ModuleMap &ModMap =
1309 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1310 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), /*Excluded=*/false);
1311 }
1312 }
1313
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001314 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1315 (void)End;
1316
1317 // This HeaderFileInfo was externally loaded.
1318 HFI.External = true;
1319 return HFI;
1320}
1321
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001322void ASTReader::addPendingMacroFromModule(IdentifierInfo *II,
1323 ModuleFile *M,
1324 GlobalMacroID GMacID,
1325 SourceLocation ImportLoc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001326 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001327 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, ImportLoc));
1328}
1329
1330void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1331 ModuleFile *M,
1332 uint64_t MacroDirectivesOffset) {
1333 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1334 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001335}
1336
1337void ASTReader::ReadDefinedMacros() {
1338 // Note that we are loading defined macros.
1339 Deserializing Macros(this);
1340
1341 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1342 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001343 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001344
1345 // If there was no preprocessor block, skip this file.
1346 if (!MacroCursor.getBitStreamReader())
1347 continue;
1348
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001349 BitstreamCursor Cursor = MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001350 Cursor.JumpToBit((*I)->MacroStartOffset);
1351
1352 RecordData Record;
1353 while (true) {
Chris Lattner88bde502013-01-19 21:39:22 +00001354 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1355
1356 switch (E.Kind) {
1357 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1358 case llvm::BitstreamEntry::Error:
1359 Error("malformed block record in AST file");
1360 return;
1361 case llvm::BitstreamEntry::EndBlock:
1362 goto NextCursor;
1363
1364 case llvm::BitstreamEntry::Record:
Chris Lattner88bde502013-01-19 21:39:22 +00001365 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001366 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattner88bde502013-01-19 21:39:22 +00001367 default: // Default behavior: ignore.
1368 break;
1369
1370 case PP_MACRO_OBJECT_LIKE:
1371 case PP_MACRO_FUNCTION_LIKE:
1372 getLocalIdentifier(**I, Record[0]);
1373 break;
1374
1375 case PP_TOKEN:
1376 // Ignore tokens.
1377 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001378 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001379 break;
1380 }
1381 }
Chris Lattner88bde502013-01-19 21:39:22 +00001382 NextCursor: ;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001383 }
1384}
1385
1386namespace {
1387 /// \brief Visitor class used to look up identifirs in an AST file.
1388 class IdentifierLookupVisitor {
1389 StringRef Name;
1390 unsigned PriorGeneration;
Douglas Gregore1698072013-01-25 00:38:33 +00001391 unsigned &NumIdentifierLookups;
1392 unsigned &NumIdentifierLookupHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001393 IdentifierInfo *Found;
Douglas Gregore1698072013-01-25 00:38:33 +00001394
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001395 public:
Douglas Gregore1698072013-01-25 00:38:33 +00001396 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1397 unsigned &NumIdentifierLookups,
1398 unsigned &NumIdentifierLookupHits)
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001399 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregore1698072013-01-25 00:38:33 +00001400 NumIdentifierLookups(NumIdentifierLookups),
1401 NumIdentifierLookupHits(NumIdentifierLookupHits),
1402 Found()
1403 {
1404 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001405
1406 static bool visit(ModuleFile &M, void *UserData) {
1407 IdentifierLookupVisitor *This
1408 = static_cast<IdentifierLookupVisitor *>(UserData);
1409
1410 // If we've already searched this module file, skip it now.
1411 if (M.Generation <= This->PriorGeneration)
1412 return true;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001413
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001414 ASTIdentifierLookupTable *IdTable
1415 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1416 if (!IdTable)
1417 return false;
1418
1419 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1420 M, This->Found);
Douglas Gregore1698072013-01-25 00:38:33 +00001421 ++This->NumIdentifierLookups;
1422 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001423 if (Pos == IdTable->end())
1424 return false;
1425
1426 // Dereferencing the iterator has the effect of building the
1427 // IdentifierInfo node and populating it with the various
1428 // declarations it needs.
Douglas Gregore1698072013-01-25 00:38:33 +00001429 ++This->NumIdentifierLookupHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001430 This->Found = *Pos;
1431 return true;
1432 }
1433
1434 // \brief Retrieve the identifier info found within the module
1435 // files.
1436 IdentifierInfo *getIdentifierInfo() const { return Found; }
1437 };
1438}
1439
1440void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1441 // Note that we are loading an identifier.
1442 Deserializing AnIdentifier(this);
1443
1444 unsigned PriorGeneration = 0;
1445 if (getContext().getLangOpts().Modules)
1446 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregor1a49d972013-01-25 01:03:03 +00001447
1448 // If there is a global index, look there first to determine which modules
1449 // provably do not have any results for this identifier.
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001450 GlobalModuleIndex::HitSet Hits;
1451 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001452 if (!loadGlobalIndex()) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001453 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1454 HitsPtr = &Hits;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001455 }
1456 }
1457
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001458 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregore1698072013-01-25 00:38:33 +00001459 NumIdentifierLookups,
1460 NumIdentifierLookupHits);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001461 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001462 markIdentifierUpToDate(&II);
1463}
1464
1465void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1466 if (!II)
1467 return;
1468
1469 II->setOutOfDate(false);
1470
1471 // Update the generation for this identifier.
1472 if (getContext().getLangOpts().Modules)
1473 IdentifierGeneration[II] = CurrentGeneration;
1474}
1475
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001476void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1477 const PendingMacroInfo &PMInfo) {
1478 assert(II);
1479
1480 if (PMInfo.M->Kind != MK_Module) {
1481 installPCHMacroDirectives(II, *PMInfo.M,
1482 PMInfo.PCHMacroData.MacroDirectivesOffset);
1483 return;
1484 }
1485
1486 // Module Macro.
1487
1488 GlobalMacroID GMacID = PMInfo.ModuleMacroData.GMacID;
1489 SourceLocation ImportLoc =
1490 SourceLocation::getFromRawEncoding(PMInfo.ModuleMacroData.ImportLoc);
1491
1492 assert(GMacID);
1493 // If this macro has already been loaded, don't do so again.
1494 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1495 return;
1496
1497 MacroInfo *MI = getMacro(GMacID);
1498 SubmoduleID SubModID = MI->getOwningModuleID();
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001499 MacroDirective *MD = PP.AllocateDefMacroDirective(MI, ImportLoc,
1500 /*isImported=*/true);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001501
1502 // Determine whether this macro definition is visible.
1503 bool Hidden = false;
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001504 Module *Owner = 0;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001505 if (SubModID) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001506 if ((Owner = getSubmodule(SubModID))) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001507 if (Owner->NameVisibility == Module::Hidden) {
1508 // The owning module is not visible, and this macro definition
1509 // should not be, either.
1510 Hidden = true;
1511
1512 // Note that this macro definition was hidden because its owning
1513 // module is not yet visible.
1514 HiddenNamesMap[Owner].push_back(HiddenName(II, MD));
1515 }
1516 }
1517 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001518
1519 if (!Hidden)
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001520 installImportedMacro(II, MD, Owner);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001521}
1522
1523void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1524 ModuleFile &M, uint64_t Offset) {
1525 assert(M.Kind != MK_Module);
1526
1527 BitstreamCursor &Cursor = M.MacroCursor;
1528 SavedStreamPosition SavedPosition(Cursor);
1529 Cursor.JumpToBit(Offset);
1530
1531 llvm::BitstreamEntry Entry =
1532 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1533 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1534 Error("malformed block record in AST file");
1535 return;
1536 }
1537
1538 RecordData Record;
1539 PreprocessorRecordTypes RecType =
1540 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1541 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1542 Error("malformed block record in AST file");
1543 return;
1544 }
1545
1546 // Deserialize the macro directives history in reverse source-order.
1547 MacroDirective *Latest = 0, *Earliest = 0;
1548 unsigned Idx = 0, N = Record.size();
1549 while (Idx < N) {
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001550 MacroDirective *MD = 0;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001551 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001552 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1553 switch (K) {
1554 case MacroDirective::MD_Define: {
1555 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1556 MacroInfo *MI = getMacro(GMacID);
1557 bool isImported = Record[Idx++];
1558 bool isAmbiguous = Record[Idx++];
1559 DefMacroDirective *DefMD =
1560 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1561 DefMD->setAmbiguous(isAmbiguous);
1562 MD = DefMD;
1563 break;
1564 }
1565 case MacroDirective::MD_Undefine:
1566 MD = PP.AllocateUndefMacroDirective(Loc);
1567 break;
1568 case MacroDirective::MD_Visibility: {
1569 bool isPublic = Record[Idx++];
1570 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1571 break;
1572 }
1573 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001574
1575 if (!Latest)
1576 Latest = MD;
1577 if (Earliest)
1578 Earliest->setPrevious(MD);
1579 Earliest = MD;
1580 }
1581
1582 PP.setLoadedMacroDirective(II, Latest);
1583}
1584
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001585/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor7332ae42013-04-12 21:00:54 +00001586/// modules.
1587static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregorf9dbae72013-06-07 22:56:11 +00001588 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001589 assert(PrevMI && NewMI);
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001590 Module *PrevOwner = 0;
1591 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1592 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregorf9dbae72013-06-07 22:56:11 +00001593 SourceManager &SrcMgr = Reader.getSourceManager();
1594 bool PrevInSystem
1595 = PrevOwner? PrevOwner->IsSystem
1596 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1597 bool NewInSystem
1598 = NewOwner? NewOwner->IsSystem
1599 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1600 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001601 return false;
Douglas Gregorf9dbae72013-06-07 22:56:11 +00001602 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001603}
1604
1605void ASTReader::installImportedMacro(IdentifierInfo *II, MacroDirective *MD,
1606 Module *Owner) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001607 assert(II && MD);
1608
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001609 DefMacroDirective *DefMD = cast<DefMacroDirective>(MD);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001610 MacroDirective *Prev = PP.getMacroDirective(II);
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001611 if (Prev) {
1612 MacroDirective::DefInfo PrevDef = Prev->getDefinition();
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001613 MacroInfo *PrevMI = PrevDef.getMacroInfo();
1614 MacroInfo *NewMI = DefMD->getInfo();
Argyrios Kyrtzidisbd25ff82013-04-03 17:39:30 +00001615 if (NewMI != PrevMI && !PrevMI->isIdenticalTo(*NewMI, PP,
1616 /*Syntactically=*/true)) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001617 // Before marking the macros as ambiguous, check if this is a case where
Douglas Gregor7332ae42013-04-12 21:00:54 +00001618 // both macros are in system headers. If so, we trust that the system
1619 // did not get it wrong. This also handles cases where Clang's own
1620 // headers have a different spelling of certain system macros:
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001621 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1622 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
Douglas Gregor7332ae42013-04-12 21:00:54 +00001623 if (!areDefinedInSystemModules(PrevMI, NewMI, Owner, *this)) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001624 PrevDef.getDirective()->setAmbiguous(true);
1625 DefMD->setAmbiguous(true);
1626 }
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001627 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001628 }
1629
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001630 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001631}
1632
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001633InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001634 // If this ID is bogus, just return an empty input file.
1635 if (ID == 0 || ID > F.InputFilesLoaded.size())
1636 return InputFile();
1637
1638 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001639 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001640 return F.InputFilesLoaded[ID-1];
1641
1642 // Go find this input file.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001643 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001644 SavedStreamPosition SavedPosition(Cursor);
1645 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1646
1647 unsigned Code = Cursor.ReadCode();
1648 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001649 StringRef Blob;
1650 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001651 case INPUT_FILE: {
1652 unsigned StoredID = Record[0];
1653 assert(ID == StoredID && "Bogus stored ID or offset");
1654 (void)StoredID;
1655 off_t StoredSize = (off_t)Record[1];
1656 time_t StoredTime = (time_t)Record[2];
1657 bool Overridden = (bool)Record[3];
1658
1659 // Get the file entry for this input file.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001660 StringRef OrigFilename = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001661 std::string Filename = OrigFilename;
1662 MaybeAddSystemRootToFilename(F, Filename);
1663 const FileEntry *File
1664 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1665 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1666
1667 // If we didn't find the file, resolve it relative to the
1668 // original directory from which this AST file was created.
1669 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1670 F.OriginalDir != CurrentDir) {
1671 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1672 F.OriginalDir,
1673 CurrentDir);
1674 if (!Resolved.empty())
1675 File = FileMgr.getFile(Resolved);
1676 }
1677
1678 // For an overridden file, create a virtual file with the stored
1679 // size/timestamp.
1680 if (Overridden && File == 0) {
1681 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1682 }
1683
1684 if (File == 0) {
1685 if (Complain) {
1686 std::string ErrorStr = "could not find file '";
1687 ErrorStr += Filename;
1688 ErrorStr += "' referenced by AST file";
1689 Error(ErrorStr.c_str());
1690 }
1691 return InputFile();
1692 }
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001693
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001694 // Check if there was a request to override the contents of the file
1695 // that was part of the precompiled header. Overridding such a file
1696 // can lead to problems when lexing using the source locations from the
1697 // PCH.
1698 SourceManager &SM = getSourceManager();
1699 if (!Overridden && SM.isFileOverridden(File)) {
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001700 if (Complain)
1701 Error(diag::err_fe_pch_file_overridden, Filename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001702 // After emitting the diagnostic, recover by disabling the override so
1703 // that the original file will be used.
1704 SM.disableFileContentsOverride(File);
1705 // The FileEntry is a virtual file entry with the size of the contents
1706 // that would override the original contents. Set it to the original's
1707 // size/time.
1708 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1709 StoredSize, StoredTime);
1710 }
1711
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001712 bool IsOutOfDate = false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001713
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001714 // For an overridden file, there is nothing to validate.
1715 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001716#if !defined(LLVM_ON_WIN32)
1717 // In our regression testing, the Windows file system seems to
1718 // have inconsistent modification times that sometimes
1719 // erroneously trigger this error-handling path.
1720 || StoredTime != File->getModificationTime()
1721#endif
1722 )) {
Douglas Gregor677e15f2013-03-19 00:28:20 +00001723 if (Complain) {
Argyrios Kyrtzidisf8f373f2013-03-08 20:42:38 +00001724 Error(diag::err_fe_pch_file_modified, Filename, F.FileName);
Douglas Gregorc1478612013-05-10 22:15:13 +00001725 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1726 Diag(diag::note_module_cache_path)
1727 << PP.getHeaderSearchInfo().getModuleCachePath();
1728 }
Douglas Gregor677e15f2013-03-19 00:28:20 +00001729 }
1730
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001731 IsOutOfDate = true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001732 }
1733
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001734 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
1735
1736 // Note that we've loaded this input file.
1737 F.InputFilesLoaded[ID-1] = IF;
1738 return IF;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001739 }
1740 }
1741
1742 return InputFile();
1743}
1744
1745const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
1746 ModuleFile &M = ModuleMgr.getPrimaryModule();
1747 std::string Filename = filenameStrRef;
1748 MaybeAddSystemRootToFilename(M, Filename);
1749 const FileEntry *File = FileMgr.getFile(Filename);
1750 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
1751 M.OriginalDir != CurrentDir) {
1752 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1753 M.OriginalDir,
1754 CurrentDir);
1755 if (!resolved.empty())
1756 File = FileMgr.getFile(resolved);
1757 }
1758
1759 return File;
1760}
1761
1762/// \brief If we are loading a relocatable PCH file, and the filename is
1763/// not an absolute path, add the system root to the beginning of the file
1764/// name.
1765void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
1766 std::string &Filename) {
1767 // If this is not a relocatable PCH file, there's nothing to do.
1768 if (!M.RelocatablePCH)
1769 return;
1770
1771 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
1772 return;
1773
1774 if (isysroot.empty()) {
1775 // If no system root was given, default to '/'
1776 Filename.insert(Filename.begin(), '/');
1777 return;
1778 }
1779
1780 unsigned Length = isysroot.size();
1781 if (isysroot[Length - 1] != '/')
1782 Filename.insert(Filename.begin(), '/');
1783
1784 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
1785}
1786
1787ASTReader::ASTReadResult
1788ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001789 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001790 unsigned ClientLoadCapabilities) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001791 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001792
1793 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
1794 Error("malformed block record in AST file");
1795 return Failure;
1796 }
1797
1798 // Read all of the records and blocks in the control block.
1799 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00001800 while (1) {
1801 llvm::BitstreamEntry Entry = Stream.advance();
1802
1803 switch (Entry.Kind) {
1804 case llvm::BitstreamEntry::Error:
1805 Error("malformed block record in AST file");
1806 return Failure;
1807 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001808 // Validate all of the non-system input files.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001809 if (!DisableValidation) {
1810 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001811 // All user input files reside at the index range [0, Record[1]).
1812 // Record is the one from INPUT_FILE_OFFSETS.
1813 for (unsigned I = 0, N = Record[1]; I < N; ++I) {
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001814 InputFile IF = getInputFile(F, I+1, Complain);
1815 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001816 return OutOfDate;
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001817 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001818 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001819 return Success;
Chris Lattner88bde502013-01-19 21:39:22 +00001820
1821 case llvm::BitstreamEntry::SubBlock:
1822 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001823 case INPUT_FILES_BLOCK_ID:
1824 F.InputFilesCursor = Stream;
1825 if (Stream.SkipBlock() || // Skip with the main cursor
1826 // Read the abbreviations
1827 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
1828 Error("malformed block record in AST file");
1829 return Failure;
1830 }
1831 continue;
Chris Lattner88bde502013-01-19 21:39:22 +00001832
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001833 default:
Chris Lattner88bde502013-01-19 21:39:22 +00001834 if (Stream.SkipBlock()) {
1835 Error("malformed block record in AST file");
1836 return Failure;
1837 }
1838 continue;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001839 }
Chris Lattner88bde502013-01-19 21:39:22 +00001840
1841 case llvm::BitstreamEntry::Record:
1842 // The interesting case.
1843 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001844 }
1845
1846 // Read and process a record.
1847 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001848 StringRef Blob;
1849 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001850 case METADATA: {
1851 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1852 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
1853 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1854 : diag::warn_pch_version_too_new);
1855 return VersionMismatch;
1856 }
1857
1858 bool hasErrors = Record[5];
1859 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
1860 Diag(diag::err_pch_with_compiler_errors);
1861 return HadErrors;
1862 }
1863
1864 F.RelocatablePCH = Record[4];
1865
1866 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001867 StringRef ASTBranch = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001868 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
1869 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
1870 Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
1871 return VersionMismatch;
1872 }
1873 break;
1874 }
1875
1876 case IMPORTS: {
1877 // Load each of the imported PCH files.
1878 unsigned Idx = 0, N = Record.size();
1879 while (Idx < N) {
1880 // Read information about the AST file.
1881 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
1882 // The import location will be the local one for now; we will adjust
1883 // all import locations of module imports after the global source
1884 // location info are setup.
1885 SourceLocation ImportLoc =
1886 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor677e15f2013-03-19 00:28:20 +00001887 off_t StoredSize = (off_t)Record[Idx++];
1888 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001889 unsigned Length = Record[Idx++];
1890 SmallString<128> ImportedFile(Record.begin() + Idx,
1891 Record.begin() + Idx + Length);
1892 Idx += Length;
1893
1894 // Load the AST file.
1895 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor677e15f2013-03-19 00:28:20 +00001896 StoredSize, StoredModTime,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001897 ClientLoadCapabilities)) {
1898 case Failure: return Failure;
1899 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregorac39f132013-03-19 00:38:50 +00001900 case Missing:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001901 case OutOfDate: return OutOfDate;
1902 case VersionMismatch: return VersionMismatch;
1903 case ConfigurationMismatch: return ConfigurationMismatch;
1904 case HadErrors: return HadErrors;
1905 case Success: break;
1906 }
1907 }
1908 break;
1909 }
1910
1911 case LANGUAGE_OPTIONS: {
1912 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
1913 if (Listener && &F == *ModuleMgr.begin() &&
1914 ParseLanguageOptions(Record, Complain, *Listener) &&
1915 !DisableValidation)
1916 return ConfigurationMismatch;
1917 break;
1918 }
1919
1920 case TARGET_OPTIONS: {
1921 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1922 if (Listener && &F == *ModuleMgr.begin() &&
1923 ParseTargetOptions(Record, Complain, *Listener) &&
1924 !DisableValidation)
1925 return ConfigurationMismatch;
1926 break;
1927 }
1928
1929 case DIAGNOSTIC_OPTIONS: {
1930 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1931 if (Listener && &F == *ModuleMgr.begin() &&
1932 ParseDiagnosticOptions(Record, Complain, *Listener) &&
1933 !DisableValidation)
1934 return ConfigurationMismatch;
1935 break;
1936 }
1937
1938 case FILE_SYSTEM_OPTIONS: {
1939 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1940 if (Listener && &F == *ModuleMgr.begin() &&
1941 ParseFileSystemOptions(Record, Complain, *Listener) &&
1942 !DisableValidation)
1943 return ConfigurationMismatch;
1944 break;
1945 }
1946
1947 case HEADER_SEARCH_OPTIONS: {
1948 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1949 if (Listener && &F == *ModuleMgr.begin() &&
1950 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
1951 !DisableValidation)
1952 return ConfigurationMismatch;
1953 break;
1954 }
1955
1956 case PREPROCESSOR_OPTIONS: {
1957 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1958 if (Listener && &F == *ModuleMgr.begin() &&
1959 ParsePreprocessorOptions(Record, Complain, *Listener,
1960 SuggestedPredefines) &&
1961 !DisableValidation)
1962 return ConfigurationMismatch;
1963 break;
1964 }
1965
1966 case ORIGINAL_FILE:
1967 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001968 F.ActualOriginalSourceFileName = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001969 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
1970 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
1971 break;
1972
1973 case ORIGINAL_FILE_ID:
1974 F.OriginalSourceFileID = FileID::get(Record[0]);
1975 break;
1976
1977 case ORIGINAL_PCH_DIR:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001978 F.OriginalDir = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001979 break;
1980
1981 case INPUT_FILE_OFFSETS:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001982 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001983 F.InputFilesLoaded.resize(Record[0]);
1984 break;
1985 }
1986 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001987}
1988
1989bool ASTReader::ReadASTBlock(ModuleFile &F) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001990 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001991
1992 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
1993 Error("malformed block record in AST file");
1994 return true;
1995 }
1996
1997 // Read all of the records and blocks for the AST file.
1998 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00001999 while (1) {
2000 llvm::BitstreamEntry Entry = Stream.advance();
2001
2002 switch (Entry.Kind) {
2003 case llvm::BitstreamEntry::Error:
2004 Error("error at end of module block in AST file");
2005 return true;
2006 case llvm::BitstreamEntry::EndBlock: {
Richard Smith43828672013-04-03 22:49:41 +00002007 // Outside of C++, we do not store a lookup map for the translation unit.
2008 // Instead, mark it as needing a lookup map to be built if this module
2009 // contains any declarations lexically within it (which it always does!).
2010 // This usually has no cost, since we very rarely need the lookup map for
2011 // the translation unit outside C++.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002012 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smith43828672013-04-03 22:49:41 +00002013 if (DC->hasExternalLexicalStorage() &&
2014 !getContext().getLangOpts().CPlusPlus)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002015 DC->setMustBuildLookupTable();
Chris Lattner88bde502013-01-19 21:39:22 +00002016
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002017 return false;
2018 }
Chris Lattner88bde502013-01-19 21:39:22 +00002019 case llvm::BitstreamEntry::SubBlock:
2020 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002021 case DECLTYPES_BLOCK_ID:
2022 // We lazily load the decls block, but we want to set up the
2023 // DeclsCursor cursor to point into it. Clone our current bitcode
2024 // cursor to it, enter the block and read the abbrevs in that block.
2025 // With the main cursor, we just skip over it.
2026 F.DeclsCursor = Stream;
2027 if (Stream.SkipBlock() || // Skip with the main cursor.
2028 // Read the abbrevs.
2029 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2030 Error("malformed block record in AST file");
2031 return true;
2032 }
2033 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002034
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002035 case DECL_UPDATES_BLOCK_ID:
2036 if (Stream.SkipBlock()) {
2037 Error("malformed block record in AST file");
2038 return true;
2039 }
2040 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002041
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002042 case PREPROCESSOR_BLOCK_ID:
2043 F.MacroCursor = Stream;
2044 if (!PP.getExternalSource())
2045 PP.setExternalSource(this);
Chris Lattner88bde502013-01-19 21:39:22 +00002046
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002047 if (Stream.SkipBlock() ||
2048 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2049 Error("malformed block record in AST file");
2050 return true;
2051 }
2052 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2053 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002054
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002055 case PREPROCESSOR_DETAIL_BLOCK_ID:
2056 F.PreprocessorDetailCursor = Stream;
2057 if (Stream.SkipBlock() ||
Chris Lattner88bde502013-01-19 21:39:22 +00002058 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002059 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattner88bde502013-01-19 21:39:22 +00002060 Error("malformed preprocessor detail record in AST file");
2061 return true;
2062 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002063 F.PreprocessorDetailStartOffset
Chris Lattner88bde502013-01-19 21:39:22 +00002064 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2065
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002066 if (!PP.getPreprocessingRecord())
2067 PP.createPreprocessingRecord();
2068 if (!PP.getPreprocessingRecord()->getExternalSource())
2069 PP.getPreprocessingRecord()->SetExternalSource(*this);
2070 break;
2071
2072 case SOURCE_MANAGER_BLOCK_ID:
2073 if (ReadSourceManagerBlock(F))
2074 return true;
2075 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002076
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002077 case SUBMODULE_BLOCK_ID:
2078 if (ReadSubmoduleBlock(F))
2079 return true;
2080 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002081
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002082 case COMMENTS_BLOCK_ID: {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00002083 BitstreamCursor C = Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002084 if (Stream.SkipBlock() ||
2085 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2086 Error("malformed comments block in AST file");
2087 return true;
2088 }
2089 CommentsCursors.push_back(std::make_pair(C, &F));
2090 break;
2091 }
Chris Lattner88bde502013-01-19 21:39:22 +00002092
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002093 default:
Chris Lattner88bde502013-01-19 21:39:22 +00002094 if (Stream.SkipBlock()) {
2095 Error("malformed block record in AST file");
2096 return true;
2097 }
2098 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002099 }
2100 continue;
Chris Lattner88bde502013-01-19 21:39:22 +00002101
2102 case llvm::BitstreamEntry::Record:
2103 // The interesting case.
2104 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002105 }
2106
2107 // Read and process a record.
2108 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002109 StringRef Blob;
2110 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002111 default: // Default behavior: ignore.
2112 break;
2113
2114 case TYPE_OFFSET: {
2115 if (F.LocalNumTypes != 0) {
2116 Error("duplicate TYPE_OFFSET record in AST file");
2117 return true;
2118 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002119 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002120 F.LocalNumTypes = Record[0];
2121 unsigned LocalBaseTypeIndex = Record[1];
2122 F.BaseTypeIndex = getTotalNumTypes();
2123
2124 if (F.LocalNumTypes > 0) {
2125 // Introduce the global -> local mapping for types within this module.
2126 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2127
2128 // Introduce the local -> global mapping for types within this module.
2129 F.TypeRemap.insertOrReplace(
2130 std::make_pair(LocalBaseTypeIndex,
2131 F.BaseTypeIndex - LocalBaseTypeIndex));
2132
2133 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2134 }
2135 break;
2136 }
2137
2138 case DECL_OFFSET: {
2139 if (F.LocalNumDecls != 0) {
2140 Error("duplicate DECL_OFFSET record in AST file");
2141 return true;
2142 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002143 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002144 F.LocalNumDecls = Record[0];
2145 unsigned LocalBaseDeclID = Record[1];
2146 F.BaseDeclID = getTotalNumDecls();
2147
2148 if (F.LocalNumDecls > 0) {
2149 // Introduce the global -> local mapping for declarations within this
2150 // module.
2151 GlobalDeclMap.insert(
2152 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2153
2154 // Introduce the local -> global mapping for declarations within this
2155 // module.
2156 F.DeclRemap.insertOrReplace(
2157 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2158
2159 // Introduce the global -> local mapping for declarations within this
2160 // module.
2161 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2162
2163 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2164 }
2165 break;
2166 }
2167
2168 case TU_UPDATE_LEXICAL: {
2169 DeclContext *TU = Context.getTranslationUnitDecl();
2170 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002171 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002172 Info.NumLexicalDecls
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002173 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002174 TU->setHasExternalLexicalStorage(true);
2175 break;
2176 }
2177
2178 case UPDATE_VISIBLE: {
2179 unsigned Idx = 0;
2180 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2181 ASTDeclContextNameLookupTable *Table =
2182 ASTDeclContextNameLookupTable::Create(
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002183 (const unsigned char *)Blob.data() + Record[Idx++],
2184 (const unsigned char *)Blob.data(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002185 ASTDeclContextNameLookupTrait(*this, F));
2186 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2187 DeclContext *TU = Context.getTranslationUnitDecl();
2188 F.DeclContextInfos[TU].NameLookupTableData = Table;
2189 TU->setHasExternalVisibleStorage(true);
2190 } else
2191 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2192 break;
2193 }
2194
2195 case IDENTIFIER_TABLE:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002196 F.IdentifierTableData = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002197 if (Record[0]) {
2198 F.IdentifierLookupTable
2199 = ASTIdentifierLookupTable::Create(
2200 (const unsigned char *)F.IdentifierTableData + Record[0],
2201 (const unsigned char *)F.IdentifierTableData,
2202 ASTIdentifierLookupTrait(*this, F));
2203
2204 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2205 }
2206 break;
2207
2208 case IDENTIFIER_OFFSET: {
2209 if (F.LocalNumIdentifiers != 0) {
2210 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2211 return true;
2212 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002213 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002214 F.LocalNumIdentifiers = Record[0];
2215 unsigned LocalBaseIdentifierID = Record[1];
2216 F.BaseIdentifierID = getTotalNumIdentifiers();
2217
2218 if (F.LocalNumIdentifiers > 0) {
2219 // Introduce the global -> local mapping for identifiers within this
2220 // module.
2221 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2222 &F));
2223
2224 // Introduce the local -> global mapping for identifiers within this
2225 // module.
2226 F.IdentifierRemap.insertOrReplace(
2227 std::make_pair(LocalBaseIdentifierID,
2228 F.BaseIdentifierID - LocalBaseIdentifierID));
2229
2230 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2231 + F.LocalNumIdentifiers);
2232 }
2233 break;
2234 }
2235
2236 case EXTERNAL_DEFINITIONS:
2237 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2238 ExternalDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2239 break;
2240
2241 case SPECIAL_TYPES:
Douglas Gregorf5cfc892013-02-01 23:45:03 +00002242 if (SpecialTypes.empty()) {
2243 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2244 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2245 break;
2246 }
2247
2248 if (SpecialTypes.size() != Record.size()) {
2249 Error("invalid special-types record");
2250 return true;
2251 }
2252
2253 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2254 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2255 if (!SpecialTypes[I])
2256 SpecialTypes[I] = ID;
2257 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2258 // merge step?
2259 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002260 break;
2261
2262 case STATISTICS:
2263 TotalNumStatements += Record[0];
2264 TotalNumMacros += Record[1];
2265 TotalLexicalDeclContexts += Record[2];
2266 TotalVisibleDeclContexts += Record[3];
2267 break;
2268
2269 case UNUSED_FILESCOPED_DECLS:
2270 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2271 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2272 break;
2273
2274 case DELEGATING_CTORS:
2275 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2276 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2277 break;
2278
2279 case WEAK_UNDECLARED_IDENTIFIERS:
2280 if (Record.size() % 4 != 0) {
2281 Error("invalid weak identifiers record");
2282 return true;
2283 }
2284
2285 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2286 // files. This isn't the way to do it :)
2287 WeakUndeclaredIdentifiers.clear();
2288
2289 // Translate the weak, undeclared identifiers into global IDs.
2290 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2291 WeakUndeclaredIdentifiers.push_back(
2292 getGlobalIdentifierID(F, Record[I++]));
2293 WeakUndeclaredIdentifiers.push_back(
2294 getGlobalIdentifierID(F, Record[I++]));
2295 WeakUndeclaredIdentifiers.push_back(
2296 ReadSourceLocation(F, Record, I).getRawEncoding());
2297 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2298 }
2299 break;
2300
Richard Smith5ea6ef42013-01-10 23:43:47 +00002301 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002302 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith5ea6ef42013-01-10 23:43:47 +00002303 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002304 break;
2305
2306 case SELECTOR_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002307 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002308 F.LocalNumSelectors = Record[0];
2309 unsigned LocalBaseSelectorID = Record[1];
2310 F.BaseSelectorID = getTotalNumSelectors();
2311
2312 if (F.LocalNumSelectors > 0) {
2313 // Introduce the global -> local mapping for selectors within this
2314 // module.
2315 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2316
2317 // Introduce the local -> global mapping for selectors within this
2318 // module.
2319 F.SelectorRemap.insertOrReplace(
2320 std::make_pair(LocalBaseSelectorID,
2321 F.BaseSelectorID - LocalBaseSelectorID));
2322
2323 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2324 }
2325 break;
2326 }
2327
2328 case METHOD_POOL:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002329 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002330 if (Record[0])
2331 F.SelectorLookupTable
2332 = ASTSelectorLookupTable::Create(
2333 F.SelectorLookupTableData + Record[0],
2334 F.SelectorLookupTableData,
2335 ASTSelectorLookupTrait(*this, F));
2336 TotalNumMethodPoolEntries += Record[1];
2337 break;
2338
2339 case REFERENCED_SELECTOR_POOL:
2340 if (!Record.empty()) {
2341 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2342 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2343 Record[Idx++]));
2344 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2345 getRawEncoding());
2346 }
2347 }
2348 break;
2349
2350 case PP_COUNTER_VALUE:
2351 if (!Record.empty() && Listener)
2352 Listener->ReadCounter(F, Record[0]);
2353 break;
2354
2355 case FILE_SORTED_DECLS:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002356 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002357 F.NumFileSortedDecls = Record[0];
2358 break;
2359
2360 case SOURCE_LOCATION_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002361 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002362 F.LocalNumSLocEntries = Record[0];
2363 unsigned SLocSpaceSize = Record[1];
2364 llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2365 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2366 SLocSpaceSize);
2367 // Make our entry in the range map. BaseID is negative and growing, so
2368 // we invert it. Because we invert it, though, we need the other end of
2369 // the range.
2370 unsigned RangeStart =
2371 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2372 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2373 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2374
2375 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2376 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2377 GlobalSLocOffsetMap.insert(
2378 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2379 - SLocSpaceSize,&F));
2380
2381 // Initialize the remapping table.
2382 // Invalid stays invalid.
2383 F.SLocRemap.insert(std::make_pair(0U, 0));
2384 // This module. Base was 2 when being compiled.
2385 F.SLocRemap.insert(std::make_pair(2U,
2386 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2387
2388 TotalNumSLocEntries += F.LocalNumSLocEntries;
2389 break;
2390 }
2391
2392 case MODULE_OFFSET_MAP: {
2393 // Additional remapping information.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002394 const unsigned char *Data = (const unsigned char*)Blob.data();
2395 const unsigned char *DataEnd = Data + Blob.size();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002396
2397 // Continuous range maps we may be updating in our module.
2398 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2399 ContinuousRangeMap<uint32_t, int, 2>::Builder
2400 IdentifierRemap(F.IdentifierRemap);
2401 ContinuousRangeMap<uint32_t, int, 2>::Builder
2402 MacroRemap(F.MacroRemap);
2403 ContinuousRangeMap<uint32_t, int, 2>::Builder
2404 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2405 ContinuousRangeMap<uint32_t, int, 2>::Builder
2406 SubmoduleRemap(F.SubmoduleRemap);
2407 ContinuousRangeMap<uint32_t, int, 2>::Builder
2408 SelectorRemap(F.SelectorRemap);
2409 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2410 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2411
2412 while(Data < DataEnd) {
2413 uint16_t Len = io::ReadUnalignedLE16(Data);
2414 StringRef Name = StringRef((const char*)Data, Len);
2415 Data += Len;
2416 ModuleFile *OM = ModuleMgr.lookup(Name);
2417 if (!OM) {
2418 Error("SourceLocation remap refers to unknown module");
2419 return true;
2420 }
2421
2422 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2423 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2424 uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
2425 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2426 uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
2427 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2428 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2429 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2430
2431 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2432 SLocRemap.insert(std::make_pair(SLocOffset,
2433 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2434 IdentifierRemap.insert(
2435 std::make_pair(IdentifierIDOffset,
2436 OM->BaseIdentifierID - IdentifierIDOffset));
2437 MacroRemap.insert(std::make_pair(MacroIDOffset,
2438 OM->BaseMacroID - MacroIDOffset));
2439 PreprocessedEntityRemap.insert(
2440 std::make_pair(PreprocessedEntityIDOffset,
2441 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2442 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2443 OM->BaseSubmoduleID - SubmoduleIDOffset));
2444 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2445 OM->BaseSelectorID - SelectorIDOffset));
2446 DeclRemap.insert(std::make_pair(DeclIDOffset,
2447 OM->BaseDeclID - DeclIDOffset));
2448
2449 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2450 OM->BaseTypeIndex - TypeIndexOffset));
2451
2452 // Global -> local mappings.
2453 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2454 }
2455 break;
2456 }
2457
2458 case SOURCE_MANAGER_LINE_TABLE:
2459 if (ParseLineTable(F, Record))
2460 return true;
2461 break;
2462
2463 case SOURCE_LOCATION_PRELOADS: {
2464 // Need to transform from the local view (1-based IDs) to the global view,
2465 // which is based off F.SLocEntryBaseID.
2466 if (!F.PreloadSLocEntries.empty()) {
2467 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2468 return true;
2469 }
2470
2471 F.PreloadSLocEntries.swap(Record);
2472 break;
2473 }
2474
2475 case EXT_VECTOR_DECLS:
2476 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2477 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2478 break;
2479
2480 case VTABLE_USES:
2481 if (Record.size() % 3 != 0) {
2482 Error("Invalid VTABLE_USES record");
2483 return true;
2484 }
2485
2486 // Later tables overwrite earlier ones.
2487 // FIXME: Modules will have some trouble with this. This is clearly not
2488 // the right way to do this.
2489 VTableUses.clear();
2490
2491 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2492 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2493 VTableUses.push_back(
2494 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2495 VTableUses.push_back(Record[Idx++]);
2496 }
2497 break;
2498
2499 case DYNAMIC_CLASSES:
2500 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2501 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2502 break;
2503
2504 case PENDING_IMPLICIT_INSTANTIATIONS:
2505 if (PendingInstantiations.size() % 2 != 0) {
2506 Error("Invalid existing PendingInstantiations");
2507 return true;
2508 }
2509
2510 if (Record.size() % 2 != 0) {
2511 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2512 return true;
2513 }
2514
2515 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2516 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2517 PendingInstantiations.push_back(
2518 ReadSourceLocation(F, Record, I).getRawEncoding());
2519 }
2520 break;
2521
2522 case SEMA_DECL_REFS:
2523 // Later tables overwrite earlier ones.
2524 // FIXME: Modules will have some trouble with this.
2525 SemaDeclRefs.clear();
2526 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2527 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2528 break;
2529
2530 case PPD_ENTITIES_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002531 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2532 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2533 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002534
2535 unsigned LocalBasePreprocessedEntityID = Record[0];
2536
2537 unsigned StartingID;
2538 if (!PP.getPreprocessingRecord())
2539 PP.createPreprocessingRecord();
2540 if (!PP.getPreprocessingRecord()->getExternalSource())
2541 PP.getPreprocessingRecord()->SetExternalSource(*this);
2542 StartingID
2543 = PP.getPreprocessingRecord()
2544 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2545 F.BasePreprocessedEntityID = StartingID;
2546
2547 if (F.NumPreprocessedEntities > 0) {
2548 // Introduce the global -> local mapping for preprocessed entities in
2549 // this module.
2550 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2551
2552 // Introduce the local -> global mapping for preprocessed entities in
2553 // this module.
2554 F.PreprocessedEntityRemap.insertOrReplace(
2555 std::make_pair(LocalBasePreprocessedEntityID,
2556 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2557 }
2558
2559 break;
2560 }
2561
2562 case DECL_UPDATE_OFFSETS: {
2563 if (Record.size() % 2 != 0) {
2564 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2565 return true;
2566 }
2567 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2568 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2569 .push_back(std::make_pair(&F, Record[I+1]));
2570 break;
2571 }
2572
2573 case DECL_REPLACEMENTS: {
2574 if (Record.size() % 3 != 0) {
2575 Error("invalid DECL_REPLACEMENTS block in AST file");
2576 return true;
2577 }
2578 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2579 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2580 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2581 break;
2582 }
2583
2584 case OBJC_CATEGORIES_MAP: {
2585 if (F.LocalNumObjCCategoriesInMap != 0) {
2586 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2587 return true;
2588 }
2589
2590 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002591 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002592 break;
2593 }
2594
2595 case OBJC_CATEGORIES:
2596 F.ObjCCategories.swap(Record);
2597 break;
2598
2599 case CXX_BASE_SPECIFIER_OFFSETS: {
2600 if (F.LocalNumCXXBaseSpecifiers != 0) {
2601 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2602 return true;
2603 }
2604
2605 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002606 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002607 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2608 break;
2609 }
2610
2611 case DIAG_PRAGMA_MAPPINGS:
2612 if (F.PragmaDiagMappings.empty())
2613 F.PragmaDiagMappings.swap(Record);
2614 else
2615 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2616 Record.begin(), Record.end());
2617 break;
2618
2619 case CUDA_SPECIAL_DECL_REFS:
2620 // Later tables overwrite earlier ones.
2621 // FIXME: Modules will have trouble with this.
2622 CUDASpecialDeclRefs.clear();
2623 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2624 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2625 break;
2626
2627 case HEADER_SEARCH_TABLE: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002628 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002629 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002630 if (Record[0]) {
2631 F.HeaderFileInfoTable
2632 = HeaderFileInfoLookupTable::Create(
2633 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2634 (const unsigned char *)F.HeaderFileInfoTableData,
2635 HeaderFileInfoTrait(*this, F,
2636 &PP.getHeaderSearchInfo(),
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002637 Blob.data() + Record[2]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002638
2639 PP.getHeaderSearchInfo().SetExternalSource(this);
2640 if (!PP.getHeaderSearchInfo().getExternalLookup())
2641 PP.getHeaderSearchInfo().SetExternalLookup(this);
2642 }
2643 break;
2644 }
2645
2646 case FP_PRAGMA_OPTIONS:
2647 // Later tables overwrite earlier ones.
2648 FPPragmaOptions.swap(Record);
2649 break;
2650
2651 case OPENCL_EXTENSIONS:
2652 // Later tables overwrite earlier ones.
2653 OpenCLExtensions.swap(Record);
2654 break;
2655
2656 case TENTATIVE_DEFINITIONS:
2657 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2658 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2659 break;
2660
2661 case KNOWN_NAMESPACES:
2662 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2663 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2664 break;
Nick Lewycky01a41142013-01-26 00:35:08 +00002665
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002666 case UNDEFINED_BUT_USED:
2667 if (UndefinedButUsed.size() % 2 != 0) {
2668 Error("Invalid existing UndefinedButUsed");
Nick Lewycky01a41142013-01-26 00:35:08 +00002669 return true;
2670 }
2671
2672 if (Record.size() % 2 != 0) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002673 Error("invalid undefined-but-used record");
Nick Lewycky01a41142013-01-26 00:35:08 +00002674 return true;
2675 }
2676 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002677 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
2678 UndefinedButUsed.push_back(
Nick Lewycky01a41142013-01-26 00:35:08 +00002679 ReadSourceLocation(F, Record, I).getRawEncoding());
2680 }
2681 break;
2682
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002683 case IMPORTED_MODULES: {
2684 if (F.Kind != MK_Module) {
2685 // If we aren't loading a module (which has its own exports), make
2686 // all of the imported modules visible.
2687 // FIXME: Deal with macros-only imports.
2688 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2689 if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
2690 ImportedModules.push_back(GlobalID);
2691 }
2692 }
2693 break;
2694 }
2695
2696 case LOCAL_REDECLARATIONS: {
2697 F.RedeclarationChains.swap(Record);
2698 break;
2699 }
2700
2701 case LOCAL_REDECLARATIONS_MAP: {
2702 if (F.LocalNumRedeclarationsInMap != 0) {
2703 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
2704 return true;
2705 }
2706
2707 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002708 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002709 break;
2710 }
2711
2712 case MERGED_DECLARATIONS: {
2713 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
2714 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
2715 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
2716 for (unsigned N = Record[Idx++]; N > 0; --N)
2717 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
2718 }
2719 break;
2720 }
2721
2722 case MACRO_OFFSET: {
2723 if (F.LocalNumMacros != 0) {
2724 Error("duplicate MACRO_OFFSET record in AST file");
2725 return true;
2726 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002727 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002728 F.LocalNumMacros = Record[0];
2729 unsigned LocalBaseMacroID = Record[1];
2730 F.BaseMacroID = getTotalNumMacros();
2731
2732 if (F.LocalNumMacros > 0) {
2733 // Introduce the global -> local mapping for macros within this module.
2734 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
2735
2736 // Introduce the local -> global mapping for macros within this module.
2737 F.MacroRemap.insertOrReplace(
2738 std::make_pair(LocalBaseMacroID,
2739 F.BaseMacroID - LocalBaseMacroID));
2740
2741 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
2742 }
2743 break;
2744 }
2745
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00002746 case MACRO_TABLE: {
2747 // FIXME: Not used yet.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002748 break;
2749 }
2750 }
2751 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002752}
2753
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002754/// \brief Move the given method to the back of the global list of methods.
2755static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
2756 // Find the entry for this selector in the method pool.
2757 Sema::GlobalMethodPool::iterator Known
2758 = S.MethodPool.find(Method->getSelector());
2759 if (Known == S.MethodPool.end())
2760 return;
2761
2762 // Retrieve the appropriate method list.
2763 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
2764 : Known->second.second;
2765 bool Found = false;
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002766 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002767 if (!Found) {
2768 if (List->Method == Method) {
2769 Found = true;
2770 } else {
2771 // Keep searching.
2772 continue;
2773 }
2774 }
2775
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002776 if (List->getNext())
2777 List->Method = List->getNext()->Method;
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002778 else
2779 List->Method = Method;
2780 }
2781}
2782
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00002783void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002784 for (unsigned I = 0, N = Names.size(); I != N; ++I) {
2785 switch (Names[I].getKind()) {
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002786 case HiddenName::Declaration: {
2787 Decl *D = Names[I].getDecl();
2788 bool wasHidden = D->Hidden;
2789 D->Hidden = false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002790
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002791 if (wasHidden && SemaObj) {
2792 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
2793 moveMethodToBackOfGlobalList(*SemaObj, Method);
2794 }
2795 }
2796 break;
2797 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002798 case HiddenName::MacroVisibility: {
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00002799 std::pair<IdentifierInfo *, MacroDirective *> Macro = Names[I].getMacro();
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00002800 installImportedMacro(Macro.first, Macro.second, Owner);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002801 break;
2802 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002803 }
2804 }
2805}
2806
2807void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis5ebcb202013-02-01 16:36:12 +00002808 Module::NameVisibilityKind NameVisibility,
Douglas Gregor906d66a2013-03-20 21:10:35 +00002809 SourceLocation ImportLoc,
2810 bool Complain) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002811 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002812 SmallVector<Module *, 4> Stack;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002813 Stack.push_back(Mod);
2814 while (!Stack.empty()) {
2815 Mod = Stack.back();
2816 Stack.pop_back();
2817
2818 if (NameVisibility <= Mod->NameVisibility) {
2819 // This module already has this level of visibility (or greater), so
2820 // there is nothing more to do.
2821 continue;
2822 }
2823
2824 if (!Mod->isAvailable()) {
2825 // Modules that aren't available cannot be made visible.
2826 continue;
2827 }
2828
2829 // Update the module's name visibility.
2830 Mod->NameVisibility = NameVisibility;
2831
2832 // If we've already deserialized any names from this module,
2833 // mark them as visible.
2834 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
2835 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00002836 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002837 HiddenNamesMap.erase(Hidden);
2838 }
2839
2840 // Push any non-explicit submodules onto the stack to be marked as
2841 // visible.
2842 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2843 SubEnd = Mod->submodule_end();
2844 Sub != SubEnd; ++Sub) {
2845 if (!(*Sub)->IsExplicit && Visited.insert(*Sub))
2846 Stack.push_back(*Sub);
2847 }
2848
2849 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis21a00042013-02-19 19:34:40 +00002850 SmallVector<Module *, 16> Exports;
2851 Mod->getExportedModules(Exports);
2852 for (SmallVectorImpl<Module *>::iterator
2853 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
2854 Module *Exported = *I;
2855 if (Visited.insert(Exported))
2856 Stack.push_back(Exported);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002857 }
Douglas Gregor906d66a2013-03-20 21:10:35 +00002858
2859 // Detect any conflicts.
2860 if (Complain) {
2861 assert(ImportLoc.isValid() && "Missing import location");
2862 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
2863 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
2864 Diag(ImportLoc, diag::warn_module_conflict)
2865 << Mod->getFullModuleName()
2866 << Mod->Conflicts[I].Other->getFullModuleName()
2867 << Mod->Conflicts[I].Message;
2868 // FIXME: Need note where the other module was imported.
2869 }
2870 }
2871 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002872 }
2873}
2874
Douglas Gregor1a49d972013-01-25 01:03:03 +00002875bool ASTReader::loadGlobalIndex() {
2876 if (GlobalIndex)
2877 return false;
2878
2879 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
2880 !Context.getLangOpts().Modules)
2881 return true;
2882
2883 // Try to load the global index.
2884 TriedLoadingGlobalIndex = true;
2885 StringRef ModuleCachePath
2886 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
2887 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor677e15f2013-03-19 00:28:20 +00002888 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregor1a49d972013-01-25 01:03:03 +00002889 if (!Result.first)
2890 return true;
2891
2892 GlobalIndex.reset(Result.first);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00002893 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregor1a49d972013-01-25 01:03:03 +00002894 return false;
2895}
2896
2897bool ASTReader::isGlobalIndexUnavailable() const {
2898 return Context.getLangOpts().Modules && UseGlobalIndex &&
2899 !hasGlobalIndex() && TriedLoadingGlobalIndex;
2900}
2901
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002902ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
2903 ModuleKind Type,
2904 SourceLocation ImportLoc,
2905 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +00002906 llvm::SaveAndRestore<SourceLocation>
2907 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
2908
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002909 // Bump the generation number.
2910 unsigned PreviousGeneration = CurrentGeneration++;
2911
2912 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002913 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002914 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
2915 /*ImportedBy=*/0, Loaded,
Douglas Gregor677e15f2013-03-19 00:28:20 +00002916 0, 0,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002917 ClientLoadCapabilities)) {
2918 case Failure:
Douglas Gregor677e15f2013-03-19 00:28:20 +00002919 case Missing:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002920 case OutOfDate:
2921 case VersionMismatch:
2922 case ConfigurationMismatch:
2923 case HadErrors:
Douglas Gregor677e15f2013-03-19 00:28:20 +00002924 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
2925 Context.getLangOpts().Modules
2926 ? &PP.getHeaderSearchInfo().getModuleMap()
2927 : 0);
Douglas Gregor1a49d972013-01-25 01:03:03 +00002928
2929 // If we find that any modules are unusable, the global index is going
2930 // to be out-of-date. Just remove it.
2931 GlobalIndex.reset();
Douglas Gregor188bdcd2013-01-25 23:32:03 +00002932 ModuleMgr.setGlobalIndex(0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002933 return ReadResult;
2934
2935 case Success:
2936 break;
2937 }
2938
2939 // Here comes stuff that we only do once the entire chain is loaded.
2940
2941 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002942 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
2943 MEnd = Loaded.end();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002944 M != MEnd; ++M) {
2945 ModuleFile &F = *M->Mod;
2946
2947 // Read the AST block.
2948 if (ReadASTBlock(F))
2949 return Failure;
2950
2951 // Once read, set the ModuleFile bit base offset and update the size in
2952 // bits of all files we've seen.
2953 F.GlobalBitOffset = TotalModulesSizeInBits;
2954 TotalModulesSizeInBits += F.SizeInBits;
2955 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
2956
2957 // Preload SLocEntries.
2958 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
2959 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
2960 // Load it through the SourceManager and don't call ReadSLocEntry()
2961 // directly because the entry may have already been loaded in which case
2962 // calling ReadSLocEntry() directly would trigger an assertion in
2963 // SourceManager.
2964 SourceMgr.getLoadedSLocEntryByID(Index);
2965 }
2966 }
2967
Douglas Gregorfa69fc12013-03-22 18:50:14 +00002968 // Setup the import locations and notify the module manager that we've
2969 // committed to these module files.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002970 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
2971 MEnd = Loaded.end();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002972 M != MEnd; ++M) {
2973 ModuleFile &F = *M->Mod;
Douglas Gregorfa69fc12013-03-22 18:50:14 +00002974
2975 ModuleMgr.moduleFileAccepted(&F);
2976
2977 // Set the import location.
Argyrios Kyrtzidis8b136d82013-02-01 16:36:14 +00002978 F.DirectImportLoc = ImportLoc;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002979 if (!M->ImportedBy)
2980 F.ImportLoc = M->ImportLoc;
2981 else
2982 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
2983 M->ImportLoc.getRawEncoding());
2984 }
2985
2986 // Mark all of the identifiers in the identifier table as being out of date,
2987 // so that various accessors know to check the loaded modules when the
2988 // identifier is used.
2989 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
2990 IdEnd = PP.getIdentifierTable().end();
2991 Id != IdEnd; ++Id)
2992 Id->second->setOutOfDate(true);
2993
2994 // Resolve any unresolved module exports.
Douglas Gregor906d66a2013-03-20 21:10:35 +00002995 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
2996 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002997 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
2998 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregor906d66a2013-03-20 21:10:35 +00002999
3000 switch (Unresolved.Kind) {
3001 case UnresolvedModuleRef::Conflict:
3002 if (ResolvedMod) {
3003 Module::Conflict Conflict;
3004 Conflict.Other = ResolvedMod;
3005 Conflict.Message = Unresolved.String.str();
3006 Unresolved.Mod->Conflicts.push_back(Conflict);
3007 }
3008 continue;
3009
3010 case UnresolvedModuleRef::Import:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003011 if (ResolvedMod)
3012 Unresolved.Mod->Imports.push_back(ResolvedMod);
3013 continue;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003014
Douglas Gregor906d66a2013-03-20 21:10:35 +00003015 case UnresolvedModuleRef::Export:
3016 if (ResolvedMod || Unresolved.IsWildcard)
3017 Unresolved.Mod->Exports.push_back(
3018 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3019 continue;
3020 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003021 }
Douglas Gregor906d66a2013-03-20 21:10:35 +00003022 UnresolvedModuleRefs.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003023
3024 InitializeContext();
3025
3026 if (DeserializationListener)
3027 DeserializationListener->ReaderInitialized(this);
3028
3029 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3030 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3031 PrimaryModule.OriginalSourceFileID
3032 = FileID::get(PrimaryModule.SLocEntryBaseID
3033 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3034
3035 // If this AST file is a precompiled preamble, then set the
3036 // preamble file ID of the source manager to the file source file
3037 // from which the preamble was built.
3038 if (Type == MK_Preamble) {
3039 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3040 } else if (Type == MK_MainFile) {
3041 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3042 }
3043 }
3044
3045 // For any Objective-C class definitions we have already loaded, make sure
3046 // that we load any additional categories.
3047 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3048 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3049 ObjCClassesLoaded[I],
3050 PreviousGeneration);
3051 }
Douglas Gregor1a49d972013-01-25 01:03:03 +00003052
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003053 return Success;
3054}
3055
3056ASTReader::ASTReadResult
3057ASTReader::ReadASTCore(StringRef FileName,
3058 ModuleKind Type,
3059 SourceLocation ImportLoc,
3060 ModuleFile *ImportedBy,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003061 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor677e15f2013-03-19 00:28:20 +00003062 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003063 unsigned ClientLoadCapabilities) {
3064 ModuleFile *M;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003065 std::string ErrorStr;
Douglas Gregor677e15f2013-03-19 00:28:20 +00003066 ModuleManager::AddModuleResult AddResult
3067 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3068 CurrentGeneration, ExpectedSize, ExpectedModTime,
3069 M, ErrorStr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003070
Douglas Gregor677e15f2013-03-19 00:28:20 +00003071 switch (AddResult) {
3072 case ModuleManager::AlreadyLoaded:
3073 return Success;
3074
3075 case ModuleManager::NewlyLoaded:
3076 // Load module file below.
3077 break;
3078
3079 case ModuleManager::Missing:
3080 // The module file was missing; if the client handle handle, that, return
3081 // it.
3082 if (ClientLoadCapabilities & ARR_Missing)
3083 return Missing;
3084
3085 // Otherwise, return an error.
3086 {
3087 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3088 + ErrorStr;
3089 Error(Msg);
3090 }
3091 return Failure;
3092
3093 case ModuleManager::OutOfDate:
3094 // We couldn't load the module file because it is out-of-date. If the
3095 // client can handle out-of-date, return it.
3096 if (ClientLoadCapabilities & ARR_OutOfDate)
3097 return OutOfDate;
3098
3099 // Otherwise, return an error.
3100 {
3101 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3102 + ErrorStr;
3103 Error(Msg);
3104 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003105 return Failure;
3106 }
3107
Douglas Gregor677e15f2013-03-19 00:28:20 +00003108 assert(M && "Missing module file");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003109
3110 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3111 // module?
3112 if (FileName != "-") {
3113 CurrentDir = llvm::sys::path::parent_path(FileName);
3114 if (CurrentDir.empty()) CurrentDir = ".";
3115 }
3116
3117 ModuleFile &F = *M;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003118 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003119 Stream.init(F.StreamFile);
3120 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3121
3122 // Sniff for the signature.
3123 if (Stream.Read(8) != 'C' ||
3124 Stream.Read(8) != 'P' ||
3125 Stream.Read(8) != 'C' ||
3126 Stream.Read(8) != 'H') {
3127 Diag(diag::err_not_a_pch_file) << FileName;
3128 return Failure;
3129 }
3130
3131 // This is used for compatibility with older PCH formats.
3132 bool HaveReadControlBlock = false;
3133
Chris Lattner99a5af02013-01-20 00:00:22 +00003134 while (1) {
3135 llvm::BitstreamEntry Entry = Stream.advance();
3136
3137 switch (Entry.Kind) {
3138 case llvm::BitstreamEntry::Error:
3139 case llvm::BitstreamEntry::EndBlock:
3140 case llvm::BitstreamEntry::Record:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003141 Error("invalid record at top-level of AST file");
3142 return Failure;
Chris Lattner99a5af02013-01-20 00:00:22 +00003143
3144 case llvm::BitstreamEntry::SubBlock:
3145 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003146 }
3147
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003148 // We only know the control subblock ID.
Chris Lattner99a5af02013-01-20 00:00:22 +00003149 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003150 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3151 if (Stream.ReadBlockInfoBlock()) {
3152 Error("malformed BlockInfoBlock in AST file");
3153 return Failure;
3154 }
3155 break;
3156 case CONTROL_BLOCK_ID:
3157 HaveReadControlBlock = true;
3158 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
3159 case Success:
3160 break;
3161
3162 case Failure: return Failure;
Douglas Gregor677e15f2013-03-19 00:28:20 +00003163 case Missing: return Missing;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003164 case OutOfDate: return OutOfDate;
3165 case VersionMismatch: return VersionMismatch;
3166 case ConfigurationMismatch: return ConfigurationMismatch;
3167 case HadErrors: return HadErrors;
3168 }
3169 break;
3170 case AST_BLOCK_ID:
3171 if (!HaveReadControlBlock) {
3172 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3173 Diag(diag::warn_pch_version_too_old);
3174 return VersionMismatch;
3175 }
3176
3177 // Record that we've loaded this module.
3178 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3179 return Success;
3180
3181 default:
3182 if (Stream.SkipBlock()) {
3183 Error("malformed block record in AST file");
3184 return Failure;
3185 }
3186 break;
3187 }
3188 }
3189
3190 return Success;
3191}
3192
3193void ASTReader::InitializeContext() {
3194 // If there's a listener, notify them that we "read" the translation unit.
3195 if (DeserializationListener)
3196 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3197 Context.getTranslationUnitDecl());
3198
3199 // Make sure we load the declaration update records for the translation unit,
3200 // if there are any.
3201 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3202 Context.getTranslationUnitDecl());
3203
3204 // FIXME: Find a better way to deal with collisions between these
3205 // built-in types. Right now, we just ignore the problem.
3206
3207 // Load the special types.
3208 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3209 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3210 if (!Context.CFConstantStringTypeDecl)
3211 Context.setCFConstantStringType(GetType(String));
3212 }
3213
3214 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3215 QualType FileType = GetType(File);
3216 if (FileType.isNull()) {
3217 Error("FILE type is NULL");
3218 return;
3219 }
3220
3221 if (!Context.FILEDecl) {
3222 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3223 Context.setFILEDecl(Typedef->getDecl());
3224 else {
3225 const TagType *Tag = FileType->getAs<TagType>();
3226 if (!Tag) {
3227 Error("Invalid FILE type in AST file");
3228 return;
3229 }
3230 Context.setFILEDecl(Tag->getDecl());
3231 }
3232 }
3233 }
3234
3235 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3236 QualType Jmp_bufType = GetType(Jmp_buf);
3237 if (Jmp_bufType.isNull()) {
3238 Error("jmp_buf type is NULL");
3239 return;
3240 }
3241
3242 if (!Context.jmp_bufDecl) {
3243 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3244 Context.setjmp_bufDecl(Typedef->getDecl());
3245 else {
3246 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3247 if (!Tag) {
3248 Error("Invalid jmp_buf type in AST file");
3249 return;
3250 }
3251 Context.setjmp_bufDecl(Tag->getDecl());
3252 }
3253 }
3254 }
3255
3256 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3257 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3258 if (Sigjmp_bufType.isNull()) {
3259 Error("sigjmp_buf type is NULL");
3260 return;
3261 }
3262
3263 if (!Context.sigjmp_bufDecl) {
3264 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3265 Context.setsigjmp_bufDecl(Typedef->getDecl());
3266 else {
3267 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3268 assert(Tag && "Invalid sigjmp_buf type in AST file");
3269 Context.setsigjmp_bufDecl(Tag->getDecl());
3270 }
3271 }
3272 }
3273
3274 if (unsigned ObjCIdRedef
3275 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3276 if (Context.ObjCIdRedefinitionType.isNull())
3277 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3278 }
3279
3280 if (unsigned ObjCClassRedef
3281 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3282 if (Context.ObjCClassRedefinitionType.isNull())
3283 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3284 }
3285
3286 if (unsigned ObjCSelRedef
3287 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3288 if (Context.ObjCSelRedefinitionType.isNull())
3289 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3290 }
3291
3292 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3293 QualType Ucontext_tType = GetType(Ucontext_t);
3294 if (Ucontext_tType.isNull()) {
3295 Error("ucontext_t type is NULL");
3296 return;
3297 }
3298
3299 if (!Context.ucontext_tDecl) {
3300 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3301 Context.setucontext_tDecl(Typedef->getDecl());
3302 else {
3303 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3304 assert(Tag && "Invalid ucontext_t type in AST file");
3305 Context.setucontext_tDecl(Tag->getDecl());
3306 }
3307 }
3308 }
3309 }
3310
3311 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3312
3313 // If there were any CUDA special declarations, deserialize them.
3314 if (!CUDASpecialDeclRefs.empty()) {
3315 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3316 Context.setcudaConfigureCallDecl(
3317 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3318 }
3319
3320 // Re-export any modules that were imported by a non-module AST file.
3321 for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3322 if (Module *Imported = getSubmodule(ImportedModules[I]))
Argyrios Kyrtzidis5ebcb202013-02-01 16:36:12 +00003323 makeModuleVisible(Imported, Module::AllVisible,
Douglas Gregor906d66a2013-03-20 21:10:35 +00003324 /*ImportLoc=*/SourceLocation(),
3325 /*Complain=*/false);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003326 }
3327 ImportedModules.clear();
3328}
3329
3330void ASTReader::finalizeForWriting() {
3331 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3332 HiddenEnd = HiddenNamesMap.end();
3333 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00003334 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003335 }
3336 HiddenNamesMap.clear();
3337}
3338
Argyrios Kyrtzidisbdfdb1d2013-05-06 19:23:40 +00003339/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3340/// cursor into the start of the given block ID, returning false on success and
3341/// true on failure.
3342static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003343 while (1) {
3344 llvm::BitstreamEntry Entry = Cursor.advance();
3345 switch (Entry.Kind) {
3346 case llvm::BitstreamEntry::Error:
3347 case llvm::BitstreamEntry::EndBlock:
3348 return true;
3349
3350 case llvm::BitstreamEntry::Record:
3351 // Ignore top-level records.
3352 Cursor.skipRecord(Entry.ID);
3353 break;
3354
3355 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisbdfdb1d2013-05-06 19:23:40 +00003356 if (Entry.ID == BlockID) {
3357 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003358 return true;
3359 // Found it!
3360 return false;
3361 }
3362
3363 if (Cursor.SkipBlock())
3364 return true;
3365 }
3366 }
3367}
3368
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003369/// \brief Retrieve the name of the original source file name
3370/// directly from the AST file, without actually loading the AST
3371/// file.
3372std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3373 FileManager &FileMgr,
3374 DiagnosticsEngine &Diags) {
3375 // Open the AST file.
3376 std::string ErrStr;
3377 OwningPtr<llvm::MemoryBuffer> Buffer;
3378 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3379 if (!Buffer) {
3380 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3381 return std::string();
3382 }
3383
3384 // Initialize the stream
3385 llvm::BitstreamReader StreamFile;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003386 BitstreamCursor Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003387 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3388 (const unsigned char *)Buffer->getBufferEnd());
3389 Stream.init(StreamFile);
3390
3391 // Sniff for the signature.
3392 if (Stream.Read(8) != 'C' ||
3393 Stream.Read(8) != 'P' ||
3394 Stream.Read(8) != 'C' ||
3395 Stream.Read(8) != 'H') {
3396 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3397 return std::string();
3398 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003399
Chris Lattner88bde502013-01-19 21:39:22 +00003400 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisbdfdb1d2013-05-06 19:23:40 +00003401 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003402 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3403 return std::string();
Chris Lattner88bde502013-01-19 21:39:22 +00003404 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003405
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003406 // Scan for ORIGINAL_FILE inside the control block.
3407 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00003408 while (1) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003409 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattner88bde502013-01-19 21:39:22 +00003410 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3411 return std::string();
3412
3413 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3414 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3415 return std::string();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003416 }
Chris Lattner88bde502013-01-19 21:39:22 +00003417
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003418 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003419 StringRef Blob;
3420 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3421 return Blob.str();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003422 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003423}
3424
3425namespace {
3426 class SimplePCHValidator : public ASTReaderListener {
3427 const LangOptions &ExistingLangOpts;
3428 const TargetOptions &ExistingTargetOpts;
3429 const PreprocessorOptions &ExistingPPOpts;
3430 FileManager &FileMgr;
3431
3432 public:
3433 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3434 const TargetOptions &ExistingTargetOpts,
3435 const PreprocessorOptions &ExistingPPOpts,
3436 FileManager &FileMgr)
3437 : ExistingLangOpts(ExistingLangOpts),
3438 ExistingTargetOpts(ExistingTargetOpts),
3439 ExistingPPOpts(ExistingPPOpts),
3440 FileMgr(FileMgr)
3441 {
3442 }
3443
3444 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
3445 bool Complain) {
3446 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3447 }
3448 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
3449 bool Complain) {
3450 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3451 }
3452 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3453 bool Complain,
3454 std::string &SuggestedPredefines) {
3455 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +00003456 SuggestedPredefines, ExistingLangOpts);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003457 }
3458 };
3459}
3460
3461bool ASTReader::readASTFileControlBlock(StringRef Filename,
3462 FileManager &FileMgr,
3463 ASTReaderListener &Listener) {
3464 // Open the AST file.
3465 std::string ErrStr;
3466 OwningPtr<llvm::MemoryBuffer> Buffer;
3467 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3468 if (!Buffer) {
3469 return true;
3470 }
3471
3472 // Initialize the stream
3473 llvm::BitstreamReader StreamFile;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003474 BitstreamCursor Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003475 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3476 (const unsigned char *)Buffer->getBufferEnd());
3477 Stream.init(StreamFile);
3478
3479 // Sniff for the signature.
3480 if (Stream.Read(8) != 'C' ||
3481 Stream.Read(8) != 'P' ||
3482 Stream.Read(8) != 'C' ||
3483 Stream.Read(8) != 'H') {
3484 return true;
3485 }
3486
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003487 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisbdfdb1d2013-05-06 19:23:40 +00003488 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003489 return true;
Argyrios Kyrtzidisbdfdb1d2013-05-06 19:23:40 +00003490
3491 bool NeedsInputFiles = Listener.needsInputFileVisitation();
3492 BitstreamCursor InputFilesCursor;
3493 if (NeedsInputFiles) {
3494 InputFilesCursor = Stream;
3495 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
3496 return true;
3497
3498 // Read the abbreviations
3499 while (true) {
3500 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
3501 unsigned Code = InputFilesCursor.ReadCode();
3502
3503 // We expect all abbrevs to be at the start of the block.
3504 if (Code != llvm::bitc::DEFINE_ABBREV) {
3505 InputFilesCursor.JumpToBit(Offset);
3506 break;
3507 }
3508 InputFilesCursor.ReadAbbrevRecord();
3509 }
3510 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003511
3512 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003513 RecordData Record;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003514 while (1) {
3515 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3516 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3517 return false;
3518
3519 if (Entry.Kind != llvm::BitstreamEntry::Record)
3520 return true;
3521
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003522 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003523 StringRef Blob;
3524 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003525 switch ((ControlRecordTypes)RecCode) {
3526 case METADATA: {
3527 if (Record[0] != VERSION_MAJOR)
3528 return true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003529
Douglas Gregorc544ba02013-03-27 16:47:18 +00003530 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003531 return true;
Douglas Gregorc544ba02013-03-27 16:47:18 +00003532
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003533 break;
3534 }
3535 case LANGUAGE_OPTIONS:
3536 if (ParseLanguageOptions(Record, false, Listener))
3537 return true;
3538 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003539
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003540 case TARGET_OPTIONS:
3541 if (ParseTargetOptions(Record, false, Listener))
3542 return true;
3543 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003544
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003545 case DIAGNOSTIC_OPTIONS:
3546 if (ParseDiagnosticOptions(Record, false, Listener))
3547 return true;
3548 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003549
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003550 case FILE_SYSTEM_OPTIONS:
3551 if (ParseFileSystemOptions(Record, false, Listener))
3552 return true;
3553 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003554
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003555 case HEADER_SEARCH_OPTIONS:
3556 if (ParseHeaderSearchOptions(Record, false, Listener))
3557 return true;
3558 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003559
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003560 case PREPROCESSOR_OPTIONS: {
3561 std::string IgnoredSuggestedPredefines;
3562 if (ParsePreprocessorOptions(Record, false, Listener,
3563 IgnoredSuggestedPredefines))
3564 return true;
3565 break;
3566 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003567
Argyrios Kyrtzidisbdfdb1d2013-05-06 19:23:40 +00003568 case INPUT_FILE_OFFSETS: {
3569 if (!NeedsInputFiles)
3570 break;
3571
3572 unsigned NumInputFiles = Record[0];
3573 unsigned NumUserFiles = Record[1];
3574 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
3575 for (unsigned I = 0; I != NumInputFiles; ++I) {
3576 // Go find this input file.
3577 bool isSystemFile = I >= NumUserFiles;
3578 BitstreamCursor &Cursor = InputFilesCursor;
3579 SavedStreamPosition SavedPosition(Cursor);
3580 Cursor.JumpToBit(InputFileOffs[I]);
3581
3582 unsigned Code = Cursor.ReadCode();
3583 RecordData Record;
3584 StringRef Blob;
3585 bool shouldContinue = false;
3586 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
3587 case INPUT_FILE:
3588 shouldContinue = Listener.visitInputFile(Blob, isSystemFile);
3589 break;
3590 }
3591 if (!shouldContinue)
3592 break;
3593 }
3594 break;
3595 }
3596
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003597 default:
3598 // No other validation to perform.
3599 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003600 }
3601 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003602}
3603
3604
3605bool ASTReader::isAcceptableASTFile(StringRef Filename,
3606 FileManager &FileMgr,
3607 const LangOptions &LangOpts,
3608 const TargetOptions &TargetOpts,
3609 const PreprocessorOptions &PPOpts) {
3610 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3611 return !readASTFileControlBlock(Filename, FileMgr, validator);
3612}
3613
3614bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
3615 // Enter the submodule block.
3616 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3617 Error("malformed submodule block record in AST file");
3618 return true;
3619 }
3620
3621 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
3622 bool First = true;
3623 Module *CurrentModule = 0;
3624 RecordData Record;
3625 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003626 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
3627
3628 switch (Entry.Kind) {
3629 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
3630 case llvm::BitstreamEntry::Error:
3631 Error("malformed block record in AST file");
3632 return true;
3633 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003634 return false;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003635 case llvm::BitstreamEntry::Record:
3636 // The interesting case.
3637 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003638 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003639
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003640 // Read a record.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003641 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003642 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003643 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003644 default: // Default behavior: ignore.
3645 break;
3646
3647 case SUBMODULE_DEFINITION: {
3648 if (First) {
3649 Error("missing submodule metadata record at beginning of block");
3650 return true;
3651 }
3652
Douglas Gregor970e4412013-03-20 03:59:18 +00003653 if (Record.size() < 8) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003654 Error("malformed module definition");
3655 return true;
3656 }
3657
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003658 StringRef Name = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003659 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
3660 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[1]);
3661 bool IsFramework = Record[2];
3662 bool IsExplicit = Record[3];
3663 bool IsSystem = Record[4];
3664 bool InferSubmodules = Record[5];
3665 bool InferExplicitSubmodules = Record[6];
3666 bool InferExportWildcard = Record[7];
Douglas Gregor970e4412013-03-20 03:59:18 +00003667 bool ConfigMacrosExhaustive = Record[8];
3668
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003669 Module *ParentModule = 0;
3670 if (Parent)
3671 ParentModule = getSubmodule(Parent);
3672
3673 // Retrieve this (sub)module from the module map, creating it if
3674 // necessary.
3675 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
3676 IsFramework,
3677 IsExplicit).first;
3678 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
3679 if (GlobalIndex >= SubmodulesLoaded.size() ||
3680 SubmodulesLoaded[GlobalIndex]) {
3681 Error("too many submodules");
3682 return true;
3683 }
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003684
Douglas Gregor677e15f2013-03-19 00:28:20 +00003685 if (!ParentModule) {
3686 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
3687 if (CurFile != F.File) {
3688 if (!Diags.isDiagnosticInFlight()) {
3689 Diag(diag::err_module_file_conflict)
3690 << CurrentModule->getTopLevelModuleName()
3691 << CurFile->getName()
3692 << F.File->getName();
3693 }
3694 return true;
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003695 }
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003696 }
Douglas Gregor677e15f2013-03-19 00:28:20 +00003697
3698 CurrentModule->setASTFile(F.File);
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003699 }
Douglas Gregor677e15f2013-03-19 00:28:20 +00003700
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003701 CurrentModule->IsFromModuleFile = true;
3702 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
3703 CurrentModule->InferSubmodules = InferSubmodules;
3704 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
3705 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor970e4412013-03-20 03:59:18 +00003706 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003707 if (DeserializationListener)
3708 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
3709
3710 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003711
Douglas Gregor906d66a2013-03-20 21:10:35 +00003712 // Clear out data that will be replaced by what is the module file.
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003713 CurrentModule->LinkLibraries.clear();
Douglas Gregor970e4412013-03-20 03:59:18 +00003714 CurrentModule->ConfigMacros.clear();
Douglas Gregor906d66a2013-03-20 21:10:35 +00003715 CurrentModule->UnresolvedConflicts.clear();
3716 CurrentModule->Conflicts.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003717 break;
3718 }
3719
3720 case SUBMODULE_UMBRELLA_HEADER: {
3721 if (First) {
3722 Error("missing submodule metadata record at beginning of block");
3723 return true;
3724 }
3725
3726 if (!CurrentModule)
3727 break;
3728
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003729 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003730 if (!CurrentModule->getUmbrellaHeader())
3731 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
3732 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
3733 Error("mismatched umbrella headers in submodule");
3734 return true;
3735 }
3736 }
3737 break;
3738 }
3739
3740 case SUBMODULE_HEADER: {
3741 if (First) {
3742 Error("missing submodule metadata record at beginning of block");
3743 return true;
3744 }
3745
3746 if (!CurrentModule)
3747 break;
3748
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00003749 // We lazily associate headers with their modules via the HeaderInfoTable.
3750 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
3751 // of complete filenames or remove it entirely.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003752 break;
3753 }
3754
3755 case SUBMODULE_EXCLUDED_HEADER: {
3756 if (First) {
3757 Error("missing submodule metadata record at beginning of block");
3758 return true;
3759 }
3760
3761 if (!CurrentModule)
3762 break;
3763
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00003764 // We lazily associate headers with their modules via the HeaderInfoTable.
3765 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
3766 // of complete filenames or remove it entirely.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003767 break;
3768 }
3769
3770 case SUBMODULE_TOPHEADER: {
3771 if (First) {
3772 Error("missing submodule metadata record at beginning of block");
3773 return true;
3774 }
3775
3776 if (!CurrentModule)
3777 break;
3778
Argyrios Kyrtzidisc1d22392013-03-13 21:13:43 +00003779 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003780 break;
3781 }
3782
3783 case SUBMODULE_UMBRELLA_DIR: {
3784 if (First) {
3785 Error("missing submodule metadata record at beginning of block");
3786 return true;
3787 }
3788
3789 if (!CurrentModule)
3790 break;
3791
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003792 if (const DirectoryEntry *Umbrella
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003793 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003794 if (!CurrentModule->getUmbrellaDir())
3795 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
3796 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
3797 Error("mismatched umbrella directories in submodule");
3798 return true;
3799 }
3800 }
3801 break;
3802 }
3803
3804 case SUBMODULE_METADATA: {
3805 if (!First) {
3806 Error("submodule metadata record not at beginning of block");
3807 return true;
3808 }
3809 First = false;
3810
3811 F.BaseSubmoduleID = getTotalNumSubmodules();
3812 F.LocalNumSubmodules = Record[0];
3813 unsigned LocalBaseSubmoduleID = Record[1];
3814 if (F.LocalNumSubmodules > 0) {
3815 // Introduce the global -> local mapping for submodules within this
3816 // module.
3817 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
3818
3819 // Introduce the local -> global mapping for submodules within this
3820 // module.
3821 F.SubmoduleRemap.insertOrReplace(
3822 std::make_pair(LocalBaseSubmoduleID,
3823 F.BaseSubmoduleID - LocalBaseSubmoduleID));
3824
3825 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
3826 }
3827 break;
3828 }
3829
3830 case SUBMODULE_IMPORTS: {
3831 if (First) {
3832 Error("missing submodule metadata record at beginning of block");
3833 return true;
3834 }
3835
3836 if (!CurrentModule)
3837 break;
3838
3839 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregor906d66a2013-03-20 21:10:35 +00003840 UnresolvedModuleRef Unresolved;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003841 Unresolved.File = &F;
3842 Unresolved.Mod = CurrentModule;
3843 Unresolved.ID = Record[Idx];
Douglas Gregor906d66a2013-03-20 21:10:35 +00003844 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003845 Unresolved.IsWildcard = false;
Douglas Gregor906d66a2013-03-20 21:10:35 +00003846 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003847 }
3848 break;
3849 }
3850
3851 case SUBMODULE_EXPORTS: {
3852 if (First) {
3853 Error("missing submodule metadata record at beginning of block");
3854 return true;
3855 }
3856
3857 if (!CurrentModule)
3858 break;
3859
3860 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregor906d66a2013-03-20 21:10:35 +00003861 UnresolvedModuleRef Unresolved;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003862 Unresolved.File = &F;
3863 Unresolved.Mod = CurrentModule;
3864 Unresolved.ID = Record[Idx];
Douglas Gregor906d66a2013-03-20 21:10:35 +00003865 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003866 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregor906d66a2013-03-20 21:10:35 +00003867 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003868 }
3869
3870 // Once we've loaded the set of exports, there's no reason to keep
3871 // the parsed, unresolved exports around.
3872 CurrentModule->UnresolvedExports.clear();
3873 break;
3874 }
3875 case SUBMODULE_REQUIRES: {
3876 if (First) {
3877 Error("missing submodule metadata record at beginning of block");
3878 return true;
3879 }
3880
3881 if (!CurrentModule)
3882 break;
3883
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003884 CurrentModule->addRequirement(Blob, Context.getLangOpts(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003885 Context.getTargetInfo());
3886 break;
3887 }
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003888
3889 case SUBMODULE_LINK_LIBRARY:
3890 if (First) {
3891 Error("missing submodule metadata record at beginning of block");
3892 return true;
3893 }
3894
3895 if (!CurrentModule)
3896 break;
3897
3898 CurrentModule->LinkLibraries.push_back(
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003899 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003900 break;
Douglas Gregor63a72682013-03-20 00:22:05 +00003901
3902 case SUBMODULE_CONFIG_MACRO:
3903 if (First) {
3904 Error("missing submodule metadata record at beginning of block");
3905 return true;
3906 }
3907
3908 if (!CurrentModule)
3909 break;
3910
3911 CurrentModule->ConfigMacros.push_back(Blob.str());
3912 break;
Douglas Gregor906d66a2013-03-20 21:10:35 +00003913
3914 case SUBMODULE_CONFLICT: {
3915 if (First) {
3916 Error("missing submodule metadata record at beginning of block");
3917 return true;
3918 }
3919
3920 if (!CurrentModule)
3921 break;
3922
3923 UnresolvedModuleRef Unresolved;
3924 Unresolved.File = &F;
3925 Unresolved.Mod = CurrentModule;
3926 Unresolved.ID = Record[0];
3927 Unresolved.Kind = UnresolvedModuleRef::Conflict;
3928 Unresolved.IsWildcard = false;
3929 Unresolved.String = Blob;
3930 UnresolvedModuleRefs.push_back(Unresolved);
3931 break;
3932 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003933 }
3934 }
3935}
3936
3937/// \brief Parse the record that corresponds to a LangOptions data
3938/// structure.
3939///
3940/// This routine parses the language options from the AST file and then gives
3941/// them to the AST listener if one is set.
3942///
3943/// \returns true if the listener deems the file unacceptable, false otherwise.
3944bool ASTReader::ParseLanguageOptions(const RecordData &Record,
3945 bool Complain,
3946 ASTReaderListener &Listener) {
3947 LangOptions LangOpts;
3948 unsigned Idx = 0;
3949#define LANGOPT(Name, Bits, Default, Description) \
3950 LangOpts.Name = Record[Idx++];
3951#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
3952 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
3953#include "clang/Basic/LangOptions.def"
Will Dietz4f45bc02013-01-18 11:30:38 +00003954#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
3955#include "clang/Basic/Sanitizers.def"
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003956
3957 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
3958 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
3959 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
3960
3961 unsigned Length = Record[Idx++];
3962 LangOpts.CurrentModule.assign(Record.begin() + Idx,
3963 Record.begin() + Idx + Length);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +00003964
3965 Idx += Length;
3966
3967 // Comment options.
3968 for (unsigned N = Record[Idx++]; N; --N) {
3969 LangOpts.CommentOpts.BlockCommandNames.push_back(
3970 ReadString(Record, Idx));
3971 }
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +00003972 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +00003973
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003974 return Listener.ReadLanguageOptions(LangOpts, Complain);
3975}
3976
3977bool ASTReader::ParseTargetOptions(const RecordData &Record,
3978 bool Complain,
3979 ASTReaderListener &Listener) {
3980 unsigned Idx = 0;
3981 TargetOptions TargetOpts;
3982 TargetOpts.Triple = ReadString(Record, Idx);
3983 TargetOpts.CPU = ReadString(Record, Idx);
3984 TargetOpts.ABI = ReadString(Record, Idx);
3985 TargetOpts.CXXABI = ReadString(Record, Idx);
3986 TargetOpts.LinkerVersion = ReadString(Record, Idx);
3987 for (unsigned N = Record[Idx++]; N; --N) {
3988 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
3989 }
3990 for (unsigned N = Record[Idx++]; N; --N) {
3991 TargetOpts.Features.push_back(ReadString(Record, Idx));
3992 }
3993
3994 return Listener.ReadTargetOptions(TargetOpts, Complain);
3995}
3996
3997bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
3998 ASTReaderListener &Listener) {
3999 DiagnosticOptions DiagOpts;
4000 unsigned Idx = 0;
4001#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
4002#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4003 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
4004#include "clang/Basic/DiagnosticOptions.def"
4005
4006 for (unsigned N = Record[Idx++]; N; --N) {
4007 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
4008 }
4009
4010 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4011}
4012
4013bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4014 ASTReaderListener &Listener) {
4015 FileSystemOptions FSOpts;
4016 unsigned Idx = 0;
4017 FSOpts.WorkingDir = ReadString(Record, Idx);
4018 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4019}
4020
4021bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4022 bool Complain,
4023 ASTReaderListener &Listener) {
4024 HeaderSearchOptions HSOpts;
4025 unsigned Idx = 0;
4026 HSOpts.Sysroot = ReadString(Record, Idx);
4027
4028 // Include entries.
4029 for (unsigned N = Record[Idx++]; N; --N) {
4030 std::string Path = ReadString(Record, Idx);
4031 frontend::IncludeDirGroup Group
4032 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004033 bool IsFramework = Record[Idx++];
4034 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004035 HSOpts.UserEntries.push_back(
Daniel Dunbar59fd6352013-01-30 00:34:26 +00004036 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004037 }
4038
4039 // System header prefixes.
4040 for (unsigned N = Record[Idx++]; N; --N) {
4041 std::string Prefix = ReadString(Record, Idx);
4042 bool IsSystemHeader = Record[Idx++];
4043 HSOpts.SystemHeaderPrefixes.push_back(
4044 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4045 }
4046
4047 HSOpts.ResourceDir = ReadString(Record, Idx);
4048 HSOpts.ModuleCachePath = ReadString(Record, Idx);
4049 HSOpts.DisableModuleHash = Record[Idx++];
4050 HSOpts.UseBuiltinIncludes = Record[Idx++];
4051 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4052 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4053 HSOpts.UseLibcxx = Record[Idx++];
4054
4055 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4056}
4057
4058bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4059 bool Complain,
4060 ASTReaderListener &Listener,
4061 std::string &SuggestedPredefines) {
4062 PreprocessorOptions PPOpts;
4063 unsigned Idx = 0;
4064
4065 // Macro definitions/undefs
4066 for (unsigned N = Record[Idx++]; N; --N) {
4067 std::string Macro = ReadString(Record, Idx);
4068 bool IsUndef = Record[Idx++];
4069 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4070 }
4071
4072 // Includes
4073 for (unsigned N = Record[Idx++]; N; --N) {
4074 PPOpts.Includes.push_back(ReadString(Record, Idx));
4075 }
4076
4077 // Macro Includes
4078 for (unsigned N = Record[Idx++]; N; --N) {
4079 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4080 }
4081
4082 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +00004083 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004084 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4085 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4086 PPOpts.ObjCXXARCStandardLibrary =
4087 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4088 SuggestedPredefines.clear();
4089 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4090 SuggestedPredefines);
4091}
4092
4093std::pair<ModuleFile *, unsigned>
4094ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4095 GlobalPreprocessedEntityMapType::iterator
4096 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4097 assert(I != GlobalPreprocessedEntityMap.end() &&
4098 "Corrupted global preprocessed entity map");
4099 ModuleFile *M = I->second;
4100 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4101 return std::make_pair(M, LocalIndex);
4102}
4103
4104std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4105ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4106 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4107 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4108 Mod.NumPreprocessedEntities);
4109
4110 return std::make_pair(PreprocessingRecord::iterator(),
4111 PreprocessingRecord::iterator());
4112}
4113
4114std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4115ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4116 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4117 ModuleDeclIterator(this, &Mod,
4118 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4119}
4120
4121PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4122 PreprocessedEntityID PPID = Index+1;
4123 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4124 ModuleFile &M = *PPInfo.first;
4125 unsigned LocalIndex = PPInfo.second;
4126 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4127
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004128 if (!PP.getPreprocessingRecord()) {
4129 Error("no preprocessing record");
4130 return 0;
4131 }
4132
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004133 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4134 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4135
4136 llvm::BitstreamEntry Entry =
4137 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4138 if (Entry.Kind != llvm::BitstreamEntry::Record)
4139 return 0;
4140
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004141 // Read the record.
4142 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4143 ReadSourceLocation(M, PPOffs.End));
4144 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004145 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004146 RecordData Record;
4147 PreprocessorDetailRecordTypes RecType =
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004148 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4149 Entry.ID, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004150 switch (RecType) {
4151 case PPD_MACRO_EXPANSION: {
4152 bool isBuiltin = Record[0];
4153 IdentifierInfo *Name = 0;
4154 MacroDefinition *Def = 0;
4155 if (isBuiltin)
4156 Name = getLocalIdentifier(M, Record[1]);
4157 else {
4158 PreprocessedEntityID
4159 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4160 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4161 }
4162
4163 MacroExpansion *ME;
4164 if (isBuiltin)
4165 ME = new (PPRec) MacroExpansion(Name, Range);
4166 else
4167 ME = new (PPRec) MacroExpansion(Def, Range);
4168
4169 return ME;
4170 }
4171
4172 case PPD_MACRO_DEFINITION: {
4173 // Decode the identifier info and then check again; if the macro is
4174 // still defined and associated with the identifier,
4175 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4176 MacroDefinition *MD
4177 = new (PPRec) MacroDefinition(II, Range);
4178
4179 if (DeserializationListener)
4180 DeserializationListener->MacroDefinitionRead(PPID, MD);
4181
4182 return MD;
4183 }
4184
4185 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004186 const char *FullFileNameStart = Blob.data() + Record[0];
4187 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004188 const FileEntry *File = 0;
4189 if (!FullFileName.empty())
4190 File = PP.getFileManager().getFile(FullFileName);
4191
4192 // FIXME: Stable encoding
4193 InclusionDirective::InclusionKind Kind
4194 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4195 InclusionDirective *ID
4196 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004197 StringRef(Blob.data(), Record[0]),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004198 Record[1], Record[3],
4199 File,
4200 Range);
4201 return ID;
4202 }
4203 }
4204
4205 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4206}
4207
4208/// \brief \arg SLocMapI points at a chunk of a module that contains no
4209/// preprocessed entities or the entities it contains are not the ones we are
4210/// looking for. Find the next module that contains entities and return the ID
4211/// of the first entry.
4212PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4213 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4214 ++SLocMapI;
4215 for (GlobalSLocOffsetMapType::const_iterator
4216 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4217 ModuleFile &M = *SLocMapI->second;
4218 if (M.NumPreprocessedEntities)
4219 return M.BasePreprocessedEntityID;
4220 }
4221
4222 return getTotalNumPreprocessedEntities();
4223}
4224
4225namespace {
4226
4227template <unsigned PPEntityOffset::*PPLoc>
4228struct PPEntityComp {
4229 const ASTReader &Reader;
4230 ModuleFile &M;
4231
4232 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4233
4234 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4235 SourceLocation LHS = getLoc(L);
4236 SourceLocation RHS = getLoc(R);
4237 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4238 }
4239
4240 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4241 SourceLocation LHS = getLoc(L);
4242 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4243 }
4244
4245 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4246 SourceLocation RHS = getLoc(R);
4247 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4248 }
4249
4250 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4251 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4252 }
4253};
4254
4255}
4256
4257/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4258PreprocessedEntityID
4259ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4260 if (SourceMgr.isLocalSourceLocation(BLoc))
4261 return getTotalNumPreprocessedEntities();
4262
4263 GlobalSLocOffsetMapType::const_iterator
4264 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00004265 BLoc.getOffset() - 1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004266 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4267 "Corrupted global sloc offset map");
4268
4269 if (SLocMapI->second->NumPreprocessedEntities == 0)
4270 return findNextPreprocessedEntity(SLocMapI);
4271
4272 ModuleFile &M = *SLocMapI->second;
4273 typedef const PPEntityOffset *pp_iterator;
4274 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4275 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4276
4277 size_t Count = M.NumPreprocessedEntities;
4278 size_t Half;
4279 pp_iterator First = pp_begin;
4280 pp_iterator PPI;
4281
4282 // Do a binary search manually instead of using std::lower_bound because
4283 // The end locations of entities may be unordered (when a macro expansion
4284 // is inside another macro argument), but for this case it is not important
4285 // whether we get the first macro expansion or its containing macro.
4286 while (Count > 0) {
4287 Half = Count/2;
4288 PPI = First;
4289 std::advance(PPI, Half);
4290 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4291 BLoc)){
4292 First = PPI;
4293 ++First;
4294 Count = Count - Half - 1;
4295 } else
4296 Count = Half;
4297 }
4298
4299 if (PPI == pp_end)
4300 return findNextPreprocessedEntity(SLocMapI);
4301
4302 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4303}
4304
4305/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4306PreprocessedEntityID
4307ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4308 if (SourceMgr.isLocalSourceLocation(ELoc))
4309 return getTotalNumPreprocessedEntities();
4310
4311 GlobalSLocOffsetMapType::const_iterator
4312 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00004313 ELoc.getOffset() - 1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004314 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4315 "Corrupted global sloc offset map");
4316
4317 if (SLocMapI->second->NumPreprocessedEntities == 0)
4318 return findNextPreprocessedEntity(SLocMapI);
4319
4320 ModuleFile &M = *SLocMapI->second;
4321 typedef const PPEntityOffset *pp_iterator;
4322 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4323 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4324 pp_iterator PPI =
4325 std::upper_bound(pp_begin, pp_end, ELoc,
4326 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4327
4328 if (PPI == pp_end)
4329 return findNextPreprocessedEntity(SLocMapI);
4330
4331 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4332}
4333
4334/// \brief Returns a pair of [Begin, End) indices of preallocated
4335/// preprocessed entities that \arg Range encompasses.
4336std::pair<unsigned, unsigned>
4337 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4338 if (Range.isInvalid())
4339 return std::make_pair(0,0);
4340 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4341
4342 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4343 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4344 return std::make_pair(BeginID, EndID);
4345}
4346
4347/// \brief Optionally returns true or false if the preallocated preprocessed
4348/// entity with index \arg Index came from file \arg FID.
David Blaikiedc84cd52013-02-20 22:23:23 +00004349Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004350 FileID FID) {
4351 if (FID.isInvalid())
4352 return false;
4353
4354 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4355 ModuleFile &M = *PPInfo.first;
4356 unsigned LocalIndex = PPInfo.second;
4357 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4358
4359 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4360 if (Loc.isInvalid())
4361 return false;
4362
4363 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4364 return true;
4365 else
4366 return false;
4367}
4368
4369namespace {
4370 /// \brief Visitor used to search for information about a header file.
4371 class HeaderFileInfoVisitor {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004372 const FileEntry *FE;
4373
David Blaikiedc84cd52013-02-20 22:23:23 +00004374 Optional<HeaderFileInfo> HFI;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004375
4376 public:
Argyrios Kyrtzidis36592b12013-03-06 18:12:44 +00004377 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4378 : FE(FE) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004379
4380 static bool visit(ModuleFile &M, void *UserData) {
4381 HeaderFileInfoVisitor *This
4382 = static_cast<HeaderFileInfoVisitor *>(UserData);
4383
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004384 HeaderFileInfoLookupTable *Table
4385 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4386 if (!Table)
4387 return false;
4388
4389 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00004390 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004391 if (Pos == Table->end())
4392 return false;
4393
4394 This->HFI = *Pos;
4395 return true;
4396 }
4397
David Blaikiedc84cd52013-02-20 22:23:23 +00004398 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004399 };
4400}
4401
4402HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis36592b12013-03-06 18:12:44 +00004403 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004404 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +00004405 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004406 return *HFI;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004407
4408 return HeaderFileInfo();
4409}
4410
4411void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4412 // FIXME: Make it work properly with modules.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004413 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004414 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4415 ModuleFile &F = *(*I);
4416 unsigned Idx = 0;
4417 DiagStates.clear();
4418 assert(!Diag.DiagStates.empty());
4419 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4420 while (Idx < F.PragmaDiagMappings.size()) {
4421 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4422 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4423 if (DiagStateID != 0) {
4424 Diag.DiagStatePoints.push_back(
4425 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4426 FullSourceLoc(Loc, SourceMgr)));
4427 continue;
4428 }
4429
4430 assert(DiagStateID == 0);
4431 // A new DiagState was created here.
4432 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4433 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4434 DiagStates.push_back(NewState);
4435 Diag.DiagStatePoints.push_back(
4436 DiagnosticsEngine::DiagStatePoint(NewState,
4437 FullSourceLoc(Loc, SourceMgr)));
4438 while (1) {
4439 assert(Idx < F.PragmaDiagMappings.size() &&
4440 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4441 if (Idx >= F.PragmaDiagMappings.size()) {
4442 break; // Something is messed up but at least avoid infinite loop in
4443 // release build.
4444 }
4445 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4446 if (DiagID == (unsigned)-1) {
4447 break; // no more diag/map pairs for this location.
4448 }
4449 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4450 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4451 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4452 }
4453 }
4454 }
4455}
4456
4457/// \brief Get the correct cursor and offset for loading a type.
4458ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4459 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4460 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4461 ModuleFile *M = I->second;
4462 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4463}
4464
4465/// \brief Read and return the type with the given index..
4466///
4467/// The index is the type ID, shifted and minus the number of predefs. This
4468/// routine actually reads the record corresponding to the type at the given
4469/// location. It is a helper routine for GetType, which deals with reading type
4470/// IDs.
4471QualType ASTReader::readTypeRecord(unsigned Index) {
4472 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004473 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004474
4475 // Keep track of where we are in the stream, then jump back there
4476 // after reading this type.
4477 SavedStreamPosition SavedPosition(DeclsCursor);
4478
4479 ReadingKindTracker ReadingKind(Read_Type, *this);
4480
4481 // Note that we are loading a type record.
4482 Deserializing AType(this);
4483
4484 unsigned Idx = 0;
4485 DeclsCursor.JumpToBit(Loc.Offset);
4486 RecordData Record;
4487 unsigned Code = DeclsCursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004488 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004489 case TYPE_EXT_QUAL: {
4490 if (Record.size() != 2) {
4491 Error("Incorrect encoding of extended qualifier type");
4492 return QualType();
4493 }
4494 QualType Base = readType(*Loc.F, Record, Idx);
4495 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4496 return Context.getQualifiedType(Base, Quals);
4497 }
4498
4499 case TYPE_COMPLEX: {
4500 if (Record.size() != 1) {
4501 Error("Incorrect encoding of complex type");
4502 return QualType();
4503 }
4504 QualType ElemType = readType(*Loc.F, Record, Idx);
4505 return Context.getComplexType(ElemType);
4506 }
4507
4508 case TYPE_POINTER: {
4509 if (Record.size() != 1) {
4510 Error("Incorrect encoding of pointer type");
4511 return QualType();
4512 }
4513 QualType PointeeType = readType(*Loc.F, Record, Idx);
4514 return Context.getPointerType(PointeeType);
4515 }
4516
4517 case TYPE_BLOCK_POINTER: {
4518 if (Record.size() != 1) {
4519 Error("Incorrect encoding of block pointer type");
4520 return QualType();
4521 }
4522 QualType PointeeType = readType(*Loc.F, Record, Idx);
4523 return Context.getBlockPointerType(PointeeType);
4524 }
4525
4526 case TYPE_LVALUE_REFERENCE: {
4527 if (Record.size() != 2) {
4528 Error("Incorrect encoding of lvalue reference type");
4529 return QualType();
4530 }
4531 QualType PointeeType = readType(*Loc.F, Record, Idx);
4532 return Context.getLValueReferenceType(PointeeType, Record[1]);
4533 }
4534
4535 case TYPE_RVALUE_REFERENCE: {
4536 if (Record.size() != 1) {
4537 Error("Incorrect encoding of rvalue reference type");
4538 return QualType();
4539 }
4540 QualType PointeeType = readType(*Loc.F, Record, Idx);
4541 return Context.getRValueReferenceType(PointeeType);
4542 }
4543
4544 case TYPE_MEMBER_POINTER: {
4545 if (Record.size() != 2) {
4546 Error("Incorrect encoding of member pointer type");
4547 return QualType();
4548 }
4549 QualType PointeeType = readType(*Loc.F, Record, Idx);
4550 QualType ClassType = readType(*Loc.F, Record, Idx);
4551 if (PointeeType.isNull() || ClassType.isNull())
4552 return QualType();
4553
4554 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4555 }
4556
4557 case TYPE_CONSTANT_ARRAY: {
4558 QualType ElementType = readType(*Loc.F, Record, Idx);
4559 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4560 unsigned IndexTypeQuals = Record[2];
4561 unsigned Idx = 3;
4562 llvm::APInt Size = ReadAPInt(Record, Idx);
4563 return Context.getConstantArrayType(ElementType, Size,
4564 ASM, IndexTypeQuals);
4565 }
4566
4567 case TYPE_INCOMPLETE_ARRAY: {
4568 QualType ElementType = readType(*Loc.F, Record, Idx);
4569 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4570 unsigned IndexTypeQuals = Record[2];
4571 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4572 }
4573
4574 case TYPE_VARIABLE_ARRAY: {
4575 QualType ElementType = readType(*Loc.F, Record, Idx);
4576 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4577 unsigned IndexTypeQuals = Record[2];
4578 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4579 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
4580 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
4581 ASM, IndexTypeQuals,
4582 SourceRange(LBLoc, RBLoc));
4583 }
4584
4585 case TYPE_VECTOR: {
4586 if (Record.size() != 3) {
4587 Error("incorrect encoding of vector type in AST file");
4588 return QualType();
4589 }
4590
4591 QualType ElementType = readType(*Loc.F, Record, Idx);
4592 unsigned NumElements = Record[1];
4593 unsigned VecKind = Record[2];
4594 return Context.getVectorType(ElementType, NumElements,
4595 (VectorType::VectorKind)VecKind);
4596 }
4597
4598 case TYPE_EXT_VECTOR: {
4599 if (Record.size() != 3) {
4600 Error("incorrect encoding of extended vector type in AST file");
4601 return QualType();
4602 }
4603
4604 QualType ElementType = readType(*Loc.F, Record, Idx);
4605 unsigned NumElements = Record[1];
4606 return Context.getExtVectorType(ElementType, NumElements);
4607 }
4608
4609 case TYPE_FUNCTION_NO_PROTO: {
4610 if (Record.size() != 6) {
4611 Error("incorrect encoding of no-proto function type");
4612 return QualType();
4613 }
4614 QualType ResultType = readType(*Loc.F, Record, Idx);
4615 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
4616 (CallingConv)Record[4], Record[5]);
4617 return Context.getFunctionNoProtoType(ResultType, Info);
4618 }
4619
4620 case TYPE_FUNCTION_PROTO: {
4621 QualType ResultType = readType(*Loc.F, Record, Idx);
4622
4623 FunctionProtoType::ExtProtoInfo EPI;
4624 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
4625 /*hasregparm*/ Record[2],
4626 /*regparm*/ Record[3],
4627 static_cast<CallingConv>(Record[4]),
4628 /*produces*/ Record[5]);
4629
4630 unsigned Idx = 6;
4631 unsigned NumParams = Record[Idx++];
4632 SmallVector<QualType, 16> ParamTypes;
4633 for (unsigned I = 0; I != NumParams; ++I)
4634 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
4635
4636 EPI.Variadic = Record[Idx++];
4637 EPI.HasTrailingReturn = Record[Idx++];
4638 EPI.TypeQuals = Record[Idx++];
4639 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
4640 ExceptionSpecificationType EST =
4641 static_cast<ExceptionSpecificationType>(Record[Idx++]);
4642 EPI.ExceptionSpecType = EST;
4643 SmallVector<QualType, 2> Exceptions;
4644 if (EST == EST_Dynamic) {
4645 EPI.NumExceptions = Record[Idx++];
4646 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
4647 Exceptions.push_back(readType(*Loc.F, Record, Idx));
4648 EPI.Exceptions = Exceptions.data();
4649 } else if (EST == EST_ComputedNoexcept) {
4650 EPI.NoexceptExpr = ReadExpr(*Loc.F);
4651 } else if (EST == EST_Uninstantiated) {
4652 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4653 EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4654 } else if (EST == EST_Unevaluated) {
4655 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4656 }
Jordan Rosebea522f2013-03-08 21:51:21 +00004657 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004658 }
4659
4660 case TYPE_UNRESOLVED_USING: {
4661 unsigned Idx = 0;
4662 return Context.getTypeDeclType(
4663 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
4664 }
4665
4666 case TYPE_TYPEDEF: {
4667 if (Record.size() != 2) {
4668 Error("incorrect encoding of typedef type");
4669 return QualType();
4670 }
4671 unsigned Idx = 0;
4672 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
4673 QualType Canonical = readType(*Loc.F, Record, Idx);
4674 if (!Canonical.isNull())
4675 Canonical = Context.getCanonicalType(Canonical);
4676 return Context.getTypedefType(Decl, Canonical);
4677 }
4678
4679 case TYPE_TYPEOF_EXPR:
4680 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
4681
4682 case TYPE_TYPEOF: {
4683 if (Record.size() != 1) {
4684 Error("incorrect encoding of typeof(type) in AST file");
4685 return QualType();
4686 }
4687 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4688 return Context.getTypeOfType(UnderlyingType);
4689 }
4690
4691 case TYPE_DECLTYPE: {
4692 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4693 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
4694 }
4695
4696 case TYPE_UNARY_TRANSFORM: {
4697 QualType BaseType = readType(*Loc.F, Record, Idx);
4698 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4699 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
4700 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
4701 }
4702
Richard Smitha2c36462013-04-26 16:15:35 +00004703 case TYPE_AUTO: {
4704 QualType Deduced = readType(*Loc.F, Record, Idx);
4705 bool IsDecltypeAuto = Record[Idx++];
Richard Smithdc7a4f52013-04-30 13:56:41 +00004706 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
4707 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smitha2c36462013-04-26 16:15:35 +00004708 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004709
4710 case TYPE_RECORD: {
4711 if (Record.size() != 2) {
4712 Error("incorrect encoding of record type");
4713 return QualType();
4714 }
4715 unsigned Idx = 0;
4716 bool IsDependent = Record[Idx++];
4717 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
4718 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
4719 QualType T = Context.getRecordType(RD);
4720 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4721 return T;
4722 }
4723
4724 case TYPE_ENUM: {
4725 if (Record.size() != 2) {
4726 Error("incorrect encoding of enum type");
4727 return QualType();
4728 }
4729 unsigned Idx = 0;
4730 bool IsDependent = Record[Idx++];
4731 QualType T
4732 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
4733 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4734 return T;
4735 }
4736
4737 case TYPE_ATTRIBUTED: {
4738 if (Record.size() != 3) {
4739 Error("incorrect encoding of attributed type");
4740 return QualType();
4741 }
4742 QualType modifiedType = readType(*Loc.F, Record, Idx);
4743 QualType equivalentType = readType(*Loc.F, Record, Idx);
4744 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
4745 return Context.getAttributedType(kind, modifiedType, equivalentType);
4746 }
4747
4748 case TYPE_PAREN: {
4749 if (Record.size() != 1) {
4750 Error("incorrect encoding of paren type");
4751 return QualType();
4752 }
4753 QualType InnerType = readType(*Loc.F, Record, Idx);
4754 return Context.getParenType(InnerType);
4755 }
4756
4757 case TYPE_PACK_EXPANSION: {
4758 if (Record.size() != 2) {
4759 Error("incorrect encoding of pack expansion type");
4760 return QualType();
4761 }
4762 QualType Pattern = readType(*Loc.F, Record, Idx);
4763 if (Pattern.isNull())
4764 return QualType();
David Blaikiedc84cd52013-02-20 22:23:23 +00004765 Optional<unsigned> NumExpansions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004766 if (Record[1])
4767 NumExpansions = Record[1] - 1;
4768 return Context.getPackExpansionType(Pattern, NumExpansions);
4769 }
4770
4771 case TYPE_ELABORATED: {
4772 unsigned Idx = 0;
4773 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4774 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4775 QualType NamedType = readType(*Loc.F, Record, Idx);
4776 return Context.getElaboratedType(Keyword, NNS, NamedType);
4777 }
4778
4779 case TYPE_OBJC_INTERFACE: {
4780 unsigned Idx = 0;
4781 ObjCInterfaceDecl *ItfD
4782 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
4783 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
4784 }
4785
4786 case TYPE_OBJC_OBJECT: {
4787 unsigned Idx = 0;
4788 QualType Base = readType(*Loc.F, Record, Idx);
4789 unsigned NumProtos = Record[Idx++];
4790 SmallVector<ObjCProtocolDecl*, 4> Protos;
4791 for (unsigned I = 0; I != NumProtos; ++I)
4792 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
4793 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
4794 }
4795
4796 case TYPE_OBJC_OBJECT_POINTER: {
4797 unsigned Idx = 0;
4798 QualType Pointee = readType(*Loc.F, Record, Idx);
4799 return Context.getObjCObjectPointerType(Pointee);
4800 }
4801
4802 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
4803 unsigned Idx = 0;
4804 QualType Parm = readType(*Loc.F, Record, Idx);
4805 QualType Replacement = readType(*Loc.F, Record, Idx);
4806 return
4807 Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
4808 Replacement);
4809 }
4810
4811 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
4812 unsigned Idx = 0;
4813 QualType Parm = readType(*Loc.F, Record, Idx);
4814 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
4815 return Context.getSubstTemplateTypeParmPackType(
4816 cast<TemplateTypeParmType>(Parm),
4817 ArgPack);
4818 }
4819
4820 case TYPE_INJECTED_CLASS_NAME: {
4821 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
4822 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
4823 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
4824 // for AST reading, too much interdependencies.
4825 return
4826 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
4827 }
4828
4829 case TYPE_TEMPLATE_TYPE_PARM: {
4830 unsigned Idx = 0;
4831 unsigned Depth = Record[Idx++];
4832 unsigned Index = Record[Idx++];
4833 bool Pack = Record[Idx++];
4834 TemplateTypeParmDecl *D
4835 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
4836 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
4837 }
4838
4839 case TYPE_DEPENDENT_NAME: {
4840 unsigned Idx = 0;
4841 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4842 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4843 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4844 QualType Canon = readType(*Loc.F, Record, Idx);
4845 if (!Canon.isNull())
4846 Canon = Context.getCanonicalType(Canon);
4847 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
4848 }
4849
4850 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
4851 unsigned Idx = 0;
4852 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4853 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4854 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4855 unsigned NumArgs = Record[Idx++];
4856 SmallVector<TemplateArgument, 8> Args;
4857 Args.reserve(NumArgs);
4858 while (NumArgs--)
4859 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
4860 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
4861 Args.size(), Args.data());
4862 }
4863
4864 case TYPE_DEPENDENT_SIZED_ARRAY: {
4865 unsigned Idx = 0;
4866
4867 // ArrayType
4868 QualType ElementType = readType(*Loc.F, Record, Idx);
4869 ArrayType::ArraySizeModifier ASM
4870 = (ArrayType::ArraySizeModifier)Record[Idx++];
4871 unsigned IndexTypeQuals = Record[Idx++];
4872
4873 // DependentSizedArrayType
4874 Expr *NumElts = ReadExpr(*Loc.F);
4875 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
4876
4877 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
4878 IndexTypeQuals, Brackets);
4879 }
4880
4881 case TYPE_TEMPLATE_SPECIALIZATION: {
4882 unsigned Idx = 0;
4883 bool IsDependent = Record[Idx++];
4884 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
4885 SmallVector<TemplateArgument, 8> Args;
4886 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
4887 QualType Underlying = readType(*Loc.F, Record, Idx);
4888 QualType T;
4889 if (Underlying.isNull())
4890 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
4891 Args.size());
4892 else
4893 T = Context.getTemplateSpecializationType(Name, Args.data(),
4894 Args.size(), Underlying);
4895 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4896 return T;
4897 }
4898
4899 case TYPE_ATOMIC: {
4900 if (Record.size() != 1) {
4901 Error("Incorrect encoding of atomic type");
4902 return QualType();
4903 }
4904 QualType ValueType = readType(*Loc.F, Record, Idx);
4905 return Context.getAtomicType(ValueType);
4906 }
4907 }
4908 llvm_unreachable("Invalid TypeCode!");
4909}
4910
4911class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
4912 ASTReader &Reader;
4913 ModuleFile &F;
4914 const ASTReader::RecordData &Record;
4915 unsigned &Idx;
4916
4917 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
4918 unsigned &I) {
4919 return Reader.ReadSourceLocation(F, R, I);
4920 }
4921
4922 template<typename T>
4923 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
4924 return Reader.ReadDeclAs<T>(F, Record, Idx);
4925 }
4926
4927public:
4928 TypeLocReader(ASTReader &Reader, ModuleFile &F,
4929 const ASTReader::RecordData &Record, unsigned &Idx)
4930 : Reader(Reader), F(F), Record(Record), Idx(Idx)
4931 { }
4932
4933 // We want compile-time assurance that we've enumerated all of
4934 // these, so unfortunately we have to declare them first, then
4935 // define them out-of-line.
4936#define ABSTRACT_TYPELOC(CLASS, PARENT)
4937#define TYPELOC(CLASS, PARENT) \
4938 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
4939#include "clang/AST/TypeLocNodes.def"
4940
4941 void VisitFunctionTypeLoc(FunctionTypeLoc);
4942 void VisitArrayTypeLoc(ArrayTypeLoc);
4943};
4944
4945void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4946 // nothing to do
4947}
4948void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4949 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
4950 if (TL.needsExtraLocalData()) {
4951 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
4952 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
4953 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
4954 TL.setModeAttr(Record[Idx++]);
4955 }
4956}
4957void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
4958 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4959}
4960void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
4961 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4962}
4963void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
4964 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
4965}
4966void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
4967 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
4968}
4969void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
4970 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
4971}
4972void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
4973 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4974 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4975}
4976void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
4977 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
4978 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
4979 if (Record[Idx++])
4980 TL.setSizeExpr(Reader.ReadExpr(F));
4981 else
4982 TL.setSizeExpr(0);
4983}
4984void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
4985 VisitArrayTypeLoc(TL);
4986}
4987void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
4988 VisitArrayTypeLoc(TL);
4989}
4990void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
4991 VisitArrayTypeLoc(TL);
4992}
4993void TypeLocReader::VisitDependentSizedArrayTypeLoc(
4994 DependentSizedArrayTypeLoc TL) {
4995 VisitArrayTypeLoc(TL);
4996}
4997void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
4998 DependentSizedExtVectorTypeLoc TL) {
4999 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5000}
5001void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5002 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5003}
5004void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5005 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5006}
5007void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5008 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5009 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5010 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5011 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
5012 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
5013 TL.setArg(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
5014 }
5015}
5016void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5017 VisitFunctionTypeLoc(TL);
5018}
5019void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5020 VisitFunctionTypeLoc(TL);
5021}
5022void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5023 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5024}
5025void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5026 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5027}
5028void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5029 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5030 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5031 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5032}
5033void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5034 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5035 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5036 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5037 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5038}
5039void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5040 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5041}
5042void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5043 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5044 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5045 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5046 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5047}
5048void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5049 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5050}
5051void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5052 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5053}
5054void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5055 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5056}
5057void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5058 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5059 if (TL.hasAttrOperand()) {
5060 SourceRange range;
5061 range.setBegin(ReadSourceLocation(Record, Idx));
5062 range.setEnd(ReadSourceLocation(Record, Idx));
5063 TL.setAttrOperandParensRange(range);
5064 }
5065 if (TL.hasAttrExprOperand()) {
5066 if (Record[Idx++])
5067 TL.setAttrExprOperand(Reader.ReadExpr(F));
5068 else
5069 TL.setAttrExprOperand(0);
5070 } else if (TL.hasAttrEnumOperand())
5071 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5072}
5073void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5074 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5075}
5076void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5077 SubstTemplateTypeParmTypeLoc TL) {
5078 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5079}
5080void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5081 SubstTemplateTypeParmPackTypeLoc TL) {
5082 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5083}
5084void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5085 TemplateSpecializationTypeLoc TL) {
5086 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5087 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5088 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5089 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5090 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5091 TL.setArgLocInfo(i,
5092 Reader.GetTemplateArgumentLocInfo(F,
5093 TL.getTypePtr()->getArg(i).getKind(),
5094 Record, Idx));
5095}
5096void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5097 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5098 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5099}
5100void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5101 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5102 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5103}
5104void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5105 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5106}
5107void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5108 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5109 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5110 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5111}
5112void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5113 DependentTemplateSpecializationTypeLoc TL) {
5114 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5115 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5116 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5117 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5118 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5119 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5120 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5121 TL.setArgLocInfo(I,
5122 Reader.GetTemplateArgumentLocInfo(F,
5123 TL.getTypePtr()->getArg(I).getKind(),
5124 Record, Idx));
5125}
5126void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5127 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5128}
5129void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5130 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5131}
5132void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5133 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5134 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5135 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5136 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5137 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5138}
5139void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5140 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5141}
5142void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5143 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5144 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5145 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5146}
5147
5148TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5149 const RecordData &Record,
5150 unsigned &Idx) {
5151 QualType InfoTy = readType(F, Record, Idx);
5152 if (InfoTy.isNull())
5153 return 0;
5154
5155 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5156 TypeLocReader TLR(*this, F, Record, Idx);
5157 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5158 TLR.Visit(TL);
5159 return TInfo;
5160}
5161
5162QualType ASTReader::GetType(TypeID ID) {
5163 unsigned FastQuals = ID & Qualifiers::FastMask;
5164 unsigned Index = ID >> Qualifiers::FastWidth;
5165
5166 if (Index < NUM_PREDEF_TYPE_IDS) {
5167 QualType T;
5168 switch ((PredefinedTypeIDs)Index) {
5169 case PREDEF_TYPE_NULL_ID: return QualType();
5170 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5171 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5172
5173 case PREDEF_TYPE_CHAR_U_ID:
5174 case PREDEF_TYPE_CHAR_S_ID:
5175 // FIXME: Check that the signedness of CharTy is correct!
5176 T = Context.CharTy;
5177 break;
5178
5179 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5180 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5181 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5182 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5183 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5184 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5185 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5186 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5187 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5188 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5189 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5190 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5191 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5192 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5193 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5194 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5195 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5196 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5197 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5198 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5199 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5200 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5201 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5202 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5203 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5204 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5205 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5206 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeib13621d2012-12-18 14:38:23 +00005207 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5208 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5209 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5210 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5211 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5212 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei21f18c42013-02-07 10:55:47 +00005213 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00005214 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005215 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5216
5217 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5218 T = Context.getAutoRRefDeductType();
5219 break;
5220
5221 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5222 T = Context.ARCUnbridgedCastTy;
5223 break;
5224
5225 case PREDEF_TYPE_VA_LIST_TAG:
5226 T = Context.getVaListTagType();
5227 break;
5228
5229 case PREDEF_TYPE_BUILTIN_FN:
5230 T = Context.BuiltinFnTy;
5231 break;
5232 }
5233
5234 assert(!T.isNull() && "Unknown predefined type");
5235 return T.withFastQualifiers(FastQuals);
5236 }
5237
5238 Index -= NUM_PREDEF_TYPE_IDS;
5239 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5240 if (TypesLoaded[Index].isNull()) {
5241 TypesLoaded[Index] = readTypeRecord(Index);
5242 if (TypesLoaded[Index].isNull())
5243 return QualType();
5244
5245 TypesLoaded[Index]->setFromAST();
5246 if (DeserializationListener)
5247 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5248 TypesLoaded[Index]);
5249 }
5250
5251 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5252}
5253
5254QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5255 return GetType(getGlobalTypeID(F, LocalID));
5256}
5257
5258serialization::TypeID
5259ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5260 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5261 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5262
5263 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5264 return LocalID;
5265
5266 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5267 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5268 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5269
5270 unsigned GlobalIndex = LocalIndex + I->second;
5271 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5272}
5273
5274TemplateArgumentLocInfo
5275ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5276 TemplateArgument::ArgKind Kind,
5277 const RecordData &Record,
5278 unsigned &Index) {
5279 switch (Kind) {
5280 case TemplateArgument::Expression:
5281 return ReadExpr(F);
5282 case TemplateArgument::Type:
5283 return GetTypeSourceInfo(F, Record, Index);
5284 case TemplateArgument::Template: {
5285 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5286 Index);
5287 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5288 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5289 SourceLocation());
5290 }
5291 case TemplateArgument::TemplateExpansion: {
5292 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5293 Index);
5294 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5295 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5296 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5297 EllipsisLoc);
5298 }
5299 case TemplateArgument::Null:
5300 case TemplateArgument::Integral:
5301 case TemplateArgument::Declaration:
5302 case TemplateArgument::NullPtr:
5303 case TemplateArgument::Pack:
5304 // FIXME: Is this right?
5305 return TemplateArgumentLocInfo();
5306 }
5307 llvm_unreachable("unexpected template argument loc");
5308}
5309
5310TemplateArgumentLoc
5311ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5312 const RecordData &Record, unsigned &Index) {
5313 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5314
5315 if (Arg.getKind() == TemplateArgument::Expression) {
5316 if (Record[Index++]) // bool InfoHasSameExpr.
5317 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5318 }
5319 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5320 Record, Index));
5321}
5322
5323Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5324 return GetDecl(ID);
5325}
5326
5327uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5328 unsigned &Idx){
5329 if (Idx >= Record.size())
5330 return 0;
5331
5332 unsigned LocalID = Record[Idx++];
5333 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5334}
5335
5336CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5337 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00005338 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005339 SavedStreamPosition SavedPosition(Cursor);
5340 Cursor.JumpToBit(Loc.Offset);
5341 ReadingKindTracker ReadingKind(Read_Decl, *this);
5342 RecordData Record;
5343 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00005344 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005345 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5346 Error("Malformed AST file: missing C++ base specifiers");
5347 return 0;
5348 }
5349
5350 unsigned Idx = 0;
5351 unsigned NumBases = Record[Idx++];
5352 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5353 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5354 for (unsigned I = 0; I != NumBases; ++I)
5355 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5356 return Bases;
5357}
5358
5359serialization::DeclID
5360ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5361 if (LocalID < NUM_PREDEF_DECL_IDS)
5362 return LocalID;
5363
5364 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5365 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5366 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5367
5368 return LocalID + I->second;
5369}
5370
5371bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5372 ModuleFile &M) const {
5373 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5374 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5375 return &M == I->second;
5376}
5377
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005378ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005379 if (!D->isFromASTFile())
5380 return 0;
5381 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5382 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5383 return I->second;
5384}
5385
5386SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5387 if (ID < NUM_PREDEF_DECL_IDS)
5388 return SourceLocation();
5389
5390 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5391
5392 if (Index > DeclsLoaded.size()) {
5393 Error("declaration ID out-of-range for AST file");
5394 return SourceLocation();
5395 }
5396
5397 if (Decl *D = DeclsLoaded[Index])
5398 return D->getLocation();
5399
5400 unsigned RawLocation = 0;
5401 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5402 return ReadSourceLocation(*Rec.F, RawLocation);
5403}
5404
5405Decl *ASTReader::GetDecl(DeclID ID) {
5406 if (ID < NUM_PREDEF_DECL_IDS) {
5407 switch ((PredefinedDeclIDs)ID) {
5408 case PREDEF_DECL_NULL_ID:
5409 return 0;
5410
5411 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5412 return Context.getTranslationUnitDecl();
5413
5414 case PREDEF_DECL_OBJC_ID_ID:
5415 return Context.getObjCIdDecl();
5416
5417 case PREDEF_DECL_OBJC_SEL_ID:
5418 return Context.getObjCSelDecl();
5419
5420 case PREDEF_DECL_OBJC_CLASS_ID:
5421 return Context.getObjCClassDecl();
5422
5423 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5424 return Context.getObjCProtocolDecl();
5425
5426 case PREDEF_DECL_INT_128_ID:
5427 return Context.getInt128Decl();
5428
5429 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5430 return Context.getUInt128Decl();
5431
5432 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5433 return Context.getObjCInstanceTypeDecl();
5434
5435 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5436 return Context.getBuiltinVaListDecl();
5437 }
5438 }
5439
5440 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5441
5442 if (Index >= DeclsLoaded.size()) {
5443 assert(0 && "declaration ID out-of-range for AST file");
5444 Error("declaration ID out-of-range for AST file");
5445 return 0;
5446 }
5447
5448 if (!DeclsLoaded[Index]) {
5449 ReadDeclRecord(ID);
5450 if (DeserializationListener)
5451 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5452 }
5453
5454 return DeclsLoaded[Index];
5455}
5456
5457DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5458 DeclID GlobalID) {
5459 if (GlobalID < NUM_PREDEF_DECL_IDS)
5460 return GlobalID;
5461
5462 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5463 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5464 ModuleFile *Owner = I->second;
5465
5466 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5467 = M.GlobalToLocalDeclIDs.find(Owner);
5468 if (Pos == M.GlobalToLocalDeclIDs.end())
5469 return 0;
5470
5471 return GlobalID - Owner->BaseDeclID + Pos->second;
5472}
5473
5474serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5475 const RecordData &Record,
5476 unsigned &Idx) {
5477 if (Idx >= Record.size()) {
5478 Error("Corrupted AST file");
5479 return 0;
5480 }
5481
5482 return getGlobalDeclID(F, Record[Idx++]);
5483}
5484
5485/// \brief Resolve the offset of a statement into a statement.
5486///
5487/// This operation will read a new statement from the external
5488/// source each time it is called, and is meant to be used via a
5489/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5490Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5491 // Switch case IDs are per Decl.
5492 ClearSwitchCaseIDs();
5493
5494 // Offset here is a global offset across the entire chain.
5495 RecordLocation Loc = getLocalBitOffset(Offset);
5496 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5497 return ReadStmtFromStream(*Loc.F);
5498}
5499
5500namespace {
5501 class FindExternalLexicalDeclsVisitor {
5502 ASTReader &Reader;
5503 const DeclContext *DC;
5504 bool (*isKindWeWant)(Decl::Kind);
5505
5506 SmallVectorImpl<Decl*> &Decls;
5507 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5508
5509 public:
5510 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5511 bool (*isKindWeWant)(Decl::Kind),
5512 SmallVectorImpl<Decl*> &Decls)
5513 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5514 {
5515 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5516 PredefsVisited[I] = false;
5517 }
5518
5519 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5520 if (Preorder)
5521 return false;
5522
5523 FindExternalLexicalDeclsVisitor *This
5524 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5525
5526 ModuleFile::DeclContextInfosMap::iterator Info
5527 = M.DeclContextInfos.find(This->DC);
5528 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5529 return false;
5530
5531 // Load all of the declaration IDs
5532 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5533 *IDE = ID + Info->second.NumLexicalDecls;
5534 ID != IDE; ++ID) {
5535 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5536 continue;
5537
5538 // Don't add predefined declarations to the lexical context more
5539 // than once.
5540 if (ID->second < NUM_PREDEF_DECL_IDS) {
5541 if (This->PredefsVisited[ID->second])
5542 continue;
5543
5544 This->PredefsVisited[ID->second] = true;
5545 }
5546
5547 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5548 if (!This->DC->isDeclInLexicalTraversal(D))
5549 This->Decls.push_back(D);
5550 }
5551 }
5552
5553 return false;
5554 }
5555 };
5556}
5557
5558ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
5559 bool (*isKindWeWant)(Decl::Kind),
5560 SmallVectorImpl<Decl*> &Decls) {
5561 // There might be lexical decls in multiple modules, for the TU at
5562 // least. Walk all of the modules in the order they were loaded.
5563 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5564 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
5565 ++NumLexicalDeclContextsRead;
5566 return ELR_Success;
5567}
5568
5569namespace {
5570
5571class DeclIDComp {
5572 ASTReader &Reader;
5573 ModuleFile &Mod;
5574
5575public:
5576 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
5577
5578 bool operator()(LocalDeclID L, LocalDeclID R) const {
5579 SourceLocation LHS = getLocation(L);
5580 SourceLocation RHS = getLocation(R);
5581 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5582 }
5583
5584 bool operator()(SourceLocation LHS, LocalDeclID R) const {
5585 SourceLocation RHS = getLocation(R);
5586 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5587 }
5588
5589 bool operator()(LocalDeclID L, SourceLocation RHS) const {
5590 SourceLocation LHS = getLocation(L);
5591 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5592 }
5593
5594 SourceLocation getLocation(LocalDeclID ID) const {
5595 return Reader.getSourceManager().getFileLoc(
5596 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
5597 }
5598};
5599
5600}
5601
5602void ASTReader::FindFileRegionDecls(FileID File,
5603 unsigned Offset, unsigned Length,
5604 SmallVectorImpl<Decl *> &Decls) {
5605 SourceManager &SM = getSourceManager();
5606
5607 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
5608 if (I == FileDeclIDs.end())
5609 return;
5610
5611 FileDeclsInfo &DInfo = I->second;
5612 if (DInfo.Decls.empty())
5613 return;
5614
5615 SourceLocation
5616 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
5617 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
5618
5619 DeclIDComp DIDComp(*this, *DInfo.Mod);
5620 ArrayRef<serialization::LocalDeclID>::iterator
5621 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5622 BeginLoc, DIDComp);
5623 if (BeginIt != DInfo.Decls.begin())
5624 --BeginIt;
5625
5626 // If we are pointing at a top-level decl inside an objc container, we need
5627 // to backtrack until we find it otherwise we will fail to report that the
5628 // region overlaps with an objc container.
5629 while (BeginIt != DInfo.Decls.begin() &&
5630 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
5631 ->isTopLevelDeclInObjCContainer())
5632 --BeginIt;
5633
5634 ArrayRef<serialization::LocalDeclID>::iterator
5635 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5636 EndLoc, DIDComp);
5637 if (EndIt != DInfo.Decls.end())
5638 ++EndIt;
5639
5640 for (ArrayRef<serialization::LocalDeclID>::iterator
5641 DIt = BeginIt; DIt != EndIt; ++DIt)
5642 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
5643}
5644
5645namespace {
5646 /// \brief ModuleFile visitor used to perform name lookup into a
5647 /// declaration context.
5648 class DeclContextNameLookupVisitor {
5649 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005650 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005651 DeclarationName Name;
5652 SmallVectorImpl<NamedDecl *> &Decls;
5653
5654 public:
5655 DeclContextNameLookupVisitor(ASTReader &Reader,
5656 SmallVectorImpl<const DeclContext *> &Contexts,
5657 DeclarationName Name,
5658 SmallVectorImpl<NamedDecl *> &Decls)
5659 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
5660
5661 static bool visit(ModuleFile &M, void *UserData) {
5662 DeclContextNameLookupVisitor *This
5663 = static_cast<DeclContextNameLookupVisitor *>(UserData);
5664
5665 // Check whether we have any visible declaration information for
5666 // this context in this module.
5667 ModuleFile::DeclContextInfosMap::iterator Info;
5668 bool FoundInfo = false;
5669 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5670 Info = M.DeclContextInfos.find(This->Contexts[I]);
5671 if (Info != M.DeclContextInfos.end() &&
5672 Info->second.NameLookupTableData) {
5673 FoundInfo = true;
5674 break;
5675 }
5676 }
5677
5678 if (!FoundInfo)
5679 return false;
5680
5681 // Look for this name within this module.
5682 ASTDeclContextNameLookupTable *LookupTable =
5683 Info->second.NameLookupTableData;
5684 ASTDeclContextNameLookupTable::iterator Pos
5685 = LookupTable->find(This->Name);
5686 if (Pos == LookupTable->end())
5687 return false;
5688
5689 bool FoundAnything = false;
5690 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
5691 for (; Data.first != Data.second; ++Data.first) {
5692 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
5693 if (!ND)
5694 continue;
5695
5696 if (ND->getDeclName() != This->Name) {
5697 // A name might be null because the decl's redeclarable part is
5698 // currently read before reading its name. The lookup is triggered by
5699 // building that decl (likely indirectly), and so it is later in the
5700 // sense of "already existing" and can be ignored here.
5701 continue;
5702 }
5703
5704 // Record this declaration.
5705 FoundAnything = true;
5706 This->Decls.push_back(ND);
5707 }
5708
5709 return FoundAnything;
5710 }
5711 };
5712}
5713
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005714/// \brief Retrieve the "definitive" module file for the definition of the
5715/// given declaration context, if there is one.
5716///
5717/// The "definitive" module file is the only place where we need to look to
5718/// find information about the declarations within the given declaration
5719/// context. For example, C++ and Objective-C classes, C structs/unions, and
5720/// Objective-C protocols, categories, and extensions are all defined in a
5721/// single place in the source code, so they have definitive module files
5722/// associated with them. C++ namespaces, on the other hand, can have
5723/// definitions in multiple different module files.
5724///
5725/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
5726/// NDEBUG checking.
5727static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
5728 ASTReader &Reader) {
Douglas Gregore0d20662013-01-22 17:08:30 +00005729 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
5730 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005731
5732 return 0;
5733}
5734
Richard Smith3646c682013-02-07 03:30:24 +00005735bool
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005736ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
5737 DeclarationName Name) {
5738 assert(DC->hasExternalVisibleStorage() &&
5739 "DeclContext has no visible decls in storage");
5740 if (!Name)
Richard Smith3646c682013-02-07 03:30:24 +00005741 return false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005742
5743 SmallVector<NamedDecl *, 64> Decls;
5744
5745 // Compute the declaration contexts we need to look into. Multiple such
5746 // declaration contexts occur when two declaration contexts from disjoint
5747 // modules get merged, e.g., when two namespaces with the same name are
5748 // independently defined in separate modules.
5749 SmallVector<const DeclContext *, 2> Contexts;
5750 Contexts.push_back(DC);
5751
5752 if (DC->isNamespace()) {
5753 MergedDeclsMap::iterator Merged
5754 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5755 if (Merged != MergedDecls.end()) {
5756 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5757 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5758 }
5759 }
5760
5761 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005762
5763 // If we can definitively determine which module file to look into,
5764 // only look there. Otherwise, look in all module files.
5765 ModuleFile *Definitive;
5766 if (Contexts.size() == 1 &&
5767 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
5768 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
5769 } else {
5770 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
5771 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005772 ++NumVisibleDeclContextsRead;
5773 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith3646c682013-02-07 03:30:24 +00005774 return !Decls.empty();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005775}
5776
5777namespace {
5778 /// \brief ModuleFile visitor used to retrieve all visible names in a
5779 /// declaration context.
5780 class DeclContextAllNamesVisitor {
5781 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005782 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005783 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > &Decls;
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005784 bool VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005785
5786 public:
5787 DeclContextAllNamesVisitor(ASTReader &Reader,
5788 SmallVectorImpl<const DeclContext *> &Contexts,
5789 llvm::DenseMap<DeclarationName,
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005790 SmallVector<NamedDecl *, 8> > &Decls,
5791 bool VisitAll)
5792 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005793
5794 static bool visit(ModuleFile &M, void *UserData) {
5795 DeclContextAllNamesVisitor *This
5796 = static_cast<DeclContextAllNamesVisitor *>(UserData);
5797
5798 // Check whether we have any visible declaration information for
5799 // this context in this module.
5800 ModuleFile::DeclContextInfosMap::iterator Info;
5801 bool FoundInfo = false;
5802 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5803 Info = M.DeclContextInfos.find(This->Contexts[I]);
5804 if (Info != M.DeclContextInfos.end() &&
5805 Info->second.NameLookupTableData) {
5806 FoundInfo = true;
5807 break;
5808 }
5809 }
5810
5811 if (!FoundInfo)
5812 return false;
5813
5814 ASTDeclContextNameLookupTable *LookupTable =
5815 Info->second.NameLookupTableData;
5816 bool FoundAnything = false;
5817 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregora6b00fc2013-01-23 22:38:11 +00005818 I = LookupTable->data_begin(), E = LookupTable->data_end();
5819 I != E;
5820 ++I) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005821 ASTDeclContextNameLookupTrait::data_type Data = *I;
5822 for (; Data.first != Data.second; ++Data.first) {
5823 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
5824 *Data.first);
5825 if (!ND)
5826 continue;
5827
5828 // Record this declaration.
5829 FoundAnything = true;
5830 This->Decls[ND->getDeclName()].push_back(ND);
5831 }
5832 }
5833
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005834 return FoundAnything && !This->VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005835 }
5836 };
5837}
5838
5839void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
5840 if (!DC->hasExternalVisibleStorage())
5841 return;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005842 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > Decls;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005843
5844 // Compute the declaration contexts we need to look into. Multiple such
5845 // declaration contexts occur when two declaration contexts from disjoint
5846 // modules get merged, e.g., when two namespaces with the same name are
5847 // independently defined in separate modules.
5848 SmallVector<const DeclContext *, 2> Contexts;
5849 Contexts.push_back(DC);
5850
5851 if (DC->isNamespace()) {
5852 MergedDeclsMap::iterator Merged
5853 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5854 if (Merged != MergedDecls.end()) {
5855 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5856 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5857 }
5858 }
5859
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005860 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
5861 /*VisitAll=*/DC->isFileContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005862 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
5863 ++NumVisibleDeclContextsRead;
5864
5865 for (llvm::DenseMap<DeclarationName,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005866 SmallVector<NamedDecl *, 8> >::iterator
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005867 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
5868 SetExternalVisibleDeclsForName(DC, I->first, I->second);
5869 }
5870 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
5871}
5872
5873/// \brief Under non-PCH compilation the consumer receives the objc methods
5874/// before receiving the implementation, and codegen depends on this.
5875/// We simulate this by deserializing and passing to consumer the methods of the
5876/// implementation before passing the deserialized implementation decl.
5877static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
5878 ASTConsumer *Consumer) {
5879 assert(ImplD && Consumer);
5880
5881 for (ObjCImplDecl::method_iterator
5882 I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
5883 Consumer->HandleInterestingDecl(DeclGroupRef(*I));
5884
5885 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
5886}
5887
5888void ASTReader::PassInterestingDeclsToConsumer() {
5889 assert(Consumer);
5890 while (!InterestingDecls.empty()) {
5891 Decl *D = InterestingDecls.front();
5892 InterestingDecls.pop_front();
5893
5894 PassInterestingDeclToConsumer(D);
5895 }
5896}
5897
5898void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
5899 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5900 PassObjCImplDeclToConsumer(ImplD, Consumer);
5901 else
5902 Consumer->HandleInterestingDecl(DeclGroupRef(D));
5903}
5904
5905void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
5906 this->Consumer = Consumer;
5907
5908 if (!Consumer)
5909 return;
5910
5911 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
5912 // Force deserialization of this decl, which will cause it to be queued for
5913 // passing to the consumer.
5914 GetDecl(ExternalDefinitions[I]);
5915 }
5916 ExternalDefinitions.clear();
5917
5918 PassInterestingDeclsToConsumer();
5919}
5920
5921void ASTReader::PrintStats() {
5922 std::fprintf(stderr, "*** AST File Statistics:\n");
5923
5924 unsigned NumTypesLoaded
5925 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
5926 QualType());
5927 unsigned NumDeclsLoaded
5928 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
5929 (Decl *)0);
5930 unsigned NumIdentifiersLoaded
5931 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
5932 IdentifiersLoaded.end(),
5933 (IdentifierInfo *)0);
5934 unsigned NumMacrosLoaded
5935 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
5936 MacrosLoaded.end(),
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00005937 (MacroInfo *)0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005938 unsigned NumSelectorsLoaded
5939 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
5940 SelectorsLoaded.end(),
5941 Selector());
5942
5943 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
5944 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
5945 NumSLocEntriesRead, TotalNumSLocEntries,
5946 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
5947 if (!TypesLoaded.empty())
5948 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
5949 NumTypesLoaded, (unsigned)TypesLoaded.size(),
5950 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
5951 if (!DeclsLoaded.empty())
5952 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
5953 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
5954 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
5955 if (!IdentifiersLoaded.empty())
5956 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
5957 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
5958 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
5959 if (!MacrosLoaded.empty())
5960 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5961 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
5962 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
5963 if (!SelectorsLoaded.empty())
5964 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
5965 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
5966 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
5967 if (TotalNumStatements)
5968 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
5969 NumStatementsRead, TotalNumStatements,
5970 ((float)NumStatementsRead/TotalNumStatements * 100));
5971 if (TotalNumMacros)
5972 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5973 NumMacrosRead, TotalNumMacros,
5974 ((float)NumMacrosRead/TotalNumMacros * 100));
5975 if (TotalLexicalDeclContexts)
5976 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
5977 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
5978 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
5979 * 100));
5980 if (TotalVisibleDeclContexts)
5981 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
5982 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
5983 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
5984 * 100));
5985 if (TotalNumMethodPoolEntries) {
5986 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
5987 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
5988 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
5989 * 100));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005990 }
Douglas Gregor95fb36e2013-01-28 17:54:36 +00005991 if (NumMethodPoolLookups) {
5992 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
5993 NumMethodPoolHits, NumMethodPoolLookups,
5994 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
5995 }
5996 if (NumMethodPoolTableLookups) {
5997 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
5998 NumMethodPoolTableHits, NumMethodPoolTableLookups,
5999 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6000 * 100.0));
6001 }
6002
Douglas Gregore1698072013-01-25 00:38:33 +00006003 if (NumIdentifierLookupHits) {
6004 std::fprintf(stderr,
6005 " %u / %u identifier table lookups succeeded (%f%%)\n",
6006 NumIdentifierLookupHits, NumIdentifierLookups,
6007 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6008 }
6009
Douglas Gregor1a49d972013-01-25 01:03:03 +00006010 if (GlobalIndex) {
6011 std::fprintf(stderr, "\n");
6012 GlobalIndex->printStats();
6013 }
6014
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006015 std::fprintf(stderr, "\n");
6016 dump();
6017 std::fprintf(stderr, "\n");
6018}
6019
6020template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6021static void
6022dumpModuleIDMap(StringRef Name,
6023 const ContinuousRangeMap<Key, ModuleFile *,
6024 InitialCapacity> &Map) {
6025 if (Map.begin() == Map.end())
6026 return;
6027
6028 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6029 llvm::errs() << Name << ":\n";
6030 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6031 I != IEnd; ++I) {
6032 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6033 << "\n";
6034 }
6035}
6036
6037void ASTReader::dump() {
6038 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6039 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6040 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6041 dumpModuleIDMap("Global type map", GlobalTypeMap);
6042 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6043 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6044 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6045 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6046 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6047 dumpModuleIDMap("Global preprocessed entity map",
6048 GlobalPreprocessedEntityMap);
6049
6050 llvm::errs() << "\n*** PCH/Modules Loaded:";
6051 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6052 MEnd = ModuleMgr.end();
6053 M != MEnd; ++M)
6054 (*M)->dump();
6055}
6056
6057/// Return the amount of memory used by memory buffers, breaking down
6058/// by heap-backed versus mmap'ed memory.
6059void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6060 for (ModuleConstIterator I = ModuleMgr.begin(),
6061 E = ModuleMgr.end(); I != E; ++I) {
6062 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6063 size_t bytes = buf->getBufferSize();
6064 switch (buf->getBufferKind()) {
6065 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6066 sizes.malloc_bytes += bytes;
6067 break;
6068 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6069 sizes.mmap_bytes += bytes;
6070 break;
6071 }
6072 }
6073 }
6074}
6075
6076void ASTReader::InitializeSema(Sema &S) {
6077 SemaObj = &S;
6078 S.addExternalSource(this);
6079
6080 // Makes sure any declarations that were deserialized "too early"
6081 // still get added to the identifier's declaration chains.
6082 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidis0532df02013-04-26 21:33:35 +00006083 pushExternalDeclIntoScope(PreloadedDecls[I],
6084 PreloadedDecls[I]->getDeclName());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006085 }
6086 PreloadedDecls.clear();
6087
6088 // Load the offsets of the declarations that Sema references.
6089 // They will be lazily deserialized when needed.
6090 if (!SemaDeclRefs.empty()) {
6091 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
6092 if (!SemaObj->StdNamespace)
6093 SemaObj->StdNamespace = SemaDeclRefs[0];
6094 if (!SemaObj->StdBadAlloc)
6095 SemaObj->StdBadAlloc = SemaDeclRefs[1];
6096 }
6097
6098 if (!FPPragmaOptions.empty()) {
6099 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6100 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6101 }
6102
6103 if (!OpenCLExtensions.empty()) {
6104 unsigned I = 0;
6105#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6106#include "clang/Basic/OpenCLExtensions.def"
6107
6108 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6109 }
6110}
6111
6112IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6113 // Note that we are loading an identifier.
6114 Deserializing AnIdentifier(this);
Douglas Gregor1a49d972013-01-25 01:03:03 +00006115 StringRef Name(NameStart, NameEnd - NameStart);
6116
6117 // If there is a global index, look there first to determine which modules
6118 // provably do not have any results for this identifier.
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006119 GlobalModuleIndex::HitSet Hits;
6120 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregor1a49d972013-01-25 01:03:03 +00006121 if (!loadGlobalIndex()) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006122 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6123 HitsPtr = &Hits;
Douglas Gregor1a49d972013-01-25 01:03:03 +00006124 }
6125 }
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006126 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregore1698072013-01-25 00:38:33 +00006127 NumIdentifierLookups,
6128 NumIdentifierLookupHits);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006129 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006130 IdentifierInfo *II = Visitor.getIdentifierInfo();
6131 markIdentifierUpToDate(II);
6132 return II;
6133}
6134
6135namespace clang {
6136 /// \brief An identifier-lookup iterator that enumerates all of the
6137 /// identifiers stored within a set of AST files.
6138 class ASTIdentifierIterator : public IdentifierIterator {
6139 /// \brief The AST reader whose identifiers are being enumerated.
6140 const ASTReader &Reader;
6141
6142 /// \brief The current index into the chain of AST files stored in
6143 /// the AST reader.
6144 unsigned Index;
6145
6146 /// \brief The current position within the identifier lookup table
6147 /// of the current AST file.
6148 ASTIdentifierLookupTable::key_iterator Current;
6149
6150 /// \brief The end position within the identifier lookup table of
6151 /// the current AST file.
6152 ASTIdentifierLookupTable::key_iterator End;
6153
6154 public:
6155 explicit ASTIdentifierIterator(const ASTReader &Reader);
6156
6157 virtual StringRef Next();
6158 };
6159}
6160
6161ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6162 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6163 ASTIdentifierLookupTable *IdTable
6164 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6165 Current = IdTable->key_begin();
6166 End = IdTable->key_end();
6167}
6168
6169StringRef ASTIdentifierIterator::Next() {
6170 while (Current == End) {
6171 // If we have exhausted all of our AST files, we're done.
6172 if (Index == 0)
6173 return StringRef();
6174
6175 --Index;
6176 ASTIdentifierLookupTable *IdTable
6177 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6178 IdentifierLookupTable;
6179 Current = IdTable->key_begin();
6180 End = IdTable->key_end();
6181 }
6182
6183 // We have any identifiers remaining in the current AST file; return
6184 // the next one.
Douglas Gregor479633c2013-01-23 18:53:14 +00006185 StringRef Result = *Current;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006186 ++Current;
Douglas Gregor479633c2013-01-23 18:53:14 +00006187 return Result;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006188}
6189
Argyrios Kyrtzidis87f9d812013-04-17 22:10:55 +00006190IdentifierIterator *ASTReader::getIdentifiers() {
6191 if (!loadGlobalIndex())
6192 return GlobalIndex->createIdentifierIterator();
6193
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006194 return new ASTIdentifierIterator(*this);
6195}
6196
6197namespace clang { namespace serialization {
6198 class ReadMethodPoolVisitor {
6199 ASTReader &Reader;
6200 Selector Sel;
6201 unsigned PriorGeneration;
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006202 unsigned InstanceBits;
6203 unsigned FactoryBits;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006204 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6205 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006206
6207 public:
6208 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6209 unsigned PriorGeneration)
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006210 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6211 InstanceBits(0), FactoryBits(0) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006212
6213 static bool visit(ModuleFile &M, void *UserData) {
6214 ReadMethodPoolVisitor *This
6215 = static_cast<ReadMethodPoolVisitor *>(UserData);
6216
6217 if (!M.SelectorLookupTable)
6218 return false;
6219
6220 // If we've already searched this module file, skip it now.
6221 if (M.Generation <= This->PriorGeneration)
6222 return true;
6223
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006224 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006225 ASTSelectorLookupTable *PoolTable
6226 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6227 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6228 if (Pos == PoolTable->end())
6229 return false;
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006230
6231 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006232 ++This->Reader.NumSelectorsRead;
6233 // FIXME: Not quite happy with the statistics here. We probably should
6234 // disable this tracking when called via LoadSelector.
6235 // Also, should entries without methods count as misses?
6236 ++This->Reader.NumMethodPoolEntriesRead;
6237 ASTSelectorLookupTrait::data_type Data = *Pos;
6238 if (This->Reader.DeserializationListener)
6239 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6240 This->Sel);
6241
6242 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6243 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006244 This->InstanceBits = Data.InstanceBits;
6245 This->FactoryBits = Data.FactoryBits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006246 return true;
6247 }
6248
6249 /// \brief Retrieve the instance methods found by this visitor.
6250 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6251 return InstanceMethods;
6252 }
6253
6254 /// \brief Retrieve the instance methods found by this visitor.
6255 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6256 return FactoryMethods;
6257 }
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006258
6259 unsigned getInstanceBits() const { return InstanceBits; }
6260 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006261 };
6262} } // end namespace clang::serialization
6263
6264/// \brief Add the given set of methods to the method list.
6265static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6266 ObjCMethodList &List) {
6267 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6268 S.addMethodToGlobalList(&List, Methods[I]);
6269 }
6270}
6271
6272void ASTReader::ReadMethodPool(Selector Sel) {
6273 // Get the selector generation and update it to the current generation.
6274 unsigned &Generation = SelectorGeneration[Sel];
6275 unsigned PriorGeneration = Generation;
6276 Generation = CurrentGeneration;
6277
6278 // Search for methods defined with this selector.
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006279 ++NumMethodPoolLookups;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006280 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6281 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6282
6283 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006284 Visitor.getFactoryMethods().empty())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006285 return;
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006286
6287 ++NumMethodPoolHits;
6288
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006289 if (!getSema())
6290 return;
6291
6292 Sema &S = *getSema();
6293 Sema::GlobalMethodPool::iterator Pos
6294 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6295
6296 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6297 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006298 Pos->second.first.setBits(Visitor.getInstanceBits());
6299 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006300}
6301
6302void ASTReader::ReadKnownNamespaces(
6303 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6304 Namespaces.clear();
6305
6306 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6307 if (NamespaceDecl *Namespace
6308 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6309 Namespaces.push_back(Namespace);
6310 }
6311}
6312
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006313void ASTReader::ReadUndefinedButUsed(
Nick Lewycky995e26b2013-01-31 03:23:57 +00006314 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006315 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6316 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky01a41142013-01-26 00:35:08 +00006317 SourceLocation Loc =
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006318 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky01a41142013-01-26 00:35:08 +00006319 Undefined.insert(std::make_pair(D, Loc));
6320 }
6321}
Nick Lewycky01a41142013-01-26 00:35:08 +00006322
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006323void ASTReader::ReadTentativeDefinitions(
6324 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6325 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6326 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6327 if (Var)
6328 TentativeDefs.push_back(Var);
6329 }
6330 TentativeDefinitions.clear();
6331}
6332
6333void ASTReader::ReadUnusedFileScopedDecls(
6334 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6335 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6336 DeclaratorDecl *D
6337 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6338 if (D)
6339 Decls.push_back(D);
6340 }
6341 UnusedFileScopedDecls.clear();
6342}
6343
6344void ASTReader::ReadDelegatingConstructors(
6345 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6346 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6347 CXXConstructorDecl *D
6348 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6349 if (D)
6350 Decls.push_back(D);
6351 }
6352 DelegatingCtorDecls.clear();
6353}
6354
6355void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6356 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6357 TypedefNameDecl *D
6358 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6359 if (D)
6360 Decls.push_back(D);
6361 }
6362 ExtVectorDecls.clear();
6363}
6364
6365void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6366 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6367 CXXRecordDecl *D
6368 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6369 if (D)
6370 Decls.push_back(D);
6371 }
6372 DynamicClasses.clear();
6373}
6374
6375void
Richard Smith5ea6ef42013-01-10 23:43:47 +00006376ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6377 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6378 NamedDecl *D
6379 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006380 if (D)
6381 Decls.push_back(D);
6382 }
Richard Smith5ea6ef42013-01-10 23:43:47 +00006383 LocallyScopedExternCDecls.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006384}
6385
6386void ASTReader::ReadReferencedSelectors(
6387 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6388 if (ReferencedSelectorsData.empty())
6389 return;
6390
6391 // If there are @selector references added them to its pool. This is for
6392 // implementation of -Wselector.
6393 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6394 unsigned I = 0;
6395 while (I < DataSize) {
6396 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6397 SourceLocation SelLoc
6398 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6399 Sels.push_back(std::make_pair(Sel, SelLoc));
6400 }
6401 ReferencedSelectorsData.clear();
6402}
6403
6404void ASTReader::ReadWeakUndeclaredIdentifiers(
6405 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6406 if (WeakUndeclaredIdentifiers.empty())
6407 return;
6408
6409 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6410 IdentifierInfo *WeakId
6411 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6412 IdentifierInfo *AliasId
6413 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6414 SourceLocation Loc
6415 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6416 bool Used = WeakUndeclaredIdentifiers[I++];
6417 WeakInfo WI(AliasId, Loc);
6418 WI.setUsed(Used);
6419 WeakIDs.push_back(std::make_pair(WeakId, WI));
6420 }
6421 WeakUndeclaredIdentifiers.clear();
6422}
6423
6424void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6425 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6426 ExternalVTableUse VT;
6427 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6428 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6429 VT.DefinitionRequired = VTableUses[Idx++];
6430 VTables.push_back(VT);
6431 }
6432
6433 VTableUses.clear();
6434}
6435
6436void ASTReader::ReadPendingInstantiations(
6437 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6438 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6439 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6440 SourceLocation Loc
6441 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6442
6443 Pending.push_back(std::make_pair(D, Loc));
6444 }
6445 PendingInstantiations.clear();
6446}
6447
6448void ASTReader::LoadSelector(Selector Sel) {
6449 // It would be complicated to avoid reading the methods anyway. So don't.
6450 ReadMethodPool(Sel);
6451}
6452
6453void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6454 assert(ID && "Non-zero identifier ID required");
6455 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6456 IdentifiersLoaded[ID - 1] = II;
6457 if (DeserializationListener)
6458 DeserializationListener->IdentifierRead(ID, II);
6459}
6460
6461/// \brief Set the globally-visible declarations associated with the given
6462/// identifier.
6463///
6464/// If the AST reader is currently in a state where the given declaration IDs
6465/// cannot safely be resolved, they are queued until it is safe to resolve
6466/// them.
6467///
6468/// \param II an IdentifierInfo that refers to one or more globally-visible
6469/// declarations.
6470///
6471/// \param DeclIDs the set of declaration IDs with the name @p II that are
6472/// visible at global scope.
6473///
Douglas Gregoraa945902013-02-18 15:53:43 +00006474/// \param Decls if non-null, this vector will be populated with the set of
6475/// deserialized declarations. These declarations will not be pushed into
6476/// scope.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006477void
6478ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6479 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregoraa945902013-02-18 15:53:43 +00006480 SmallVectorImpl<Decl *> *Decls) {
6481 if (NumCurrentElementsDeserializing && !Decls) {
6482 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006483 return;
6484 }
6485
6486 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6487 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6488 if (SemaObj) {
Douglas Gregoraa945902013-02-18 15:53:43 +00006489 // If we're simply supposed to record the declarations, do so now.
6490 if (Decls) {
6491 Decls->push_back(D);
6492 continue;
6493 }
6494
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006495 // Introduce this declaration into the translation-unit scope
6496 // and add it to the declaration chain for this identifier, so
6497 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidis0532df02013-04-26 21:33:35 +00006498 pushExternalDeclIntoScope(D, II);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006499 } else {
6500 // Queue this declaration so that it will be added to the
6501 // translation unit scope and identifier's declaration chain
6502 // once a Sema object is known.
6503 PreloadedDecls.push_back(D);
6504 }
6505 }
6506}
6507
Douglas Gregor8222b892013-01-21 16:52:34 +00006508IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006509 if (ID == 0)
6510 return 0;
6511
6512 if (IdentifiersLoaded.empty()) {
6513 Error("no identifier table in AST file");
6514 return 0;
6515 }
6516
6517 ID -= 1;
6518 if (!IdentifiersLoaded[ID]) {
6519 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6520 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
6521 ModuleFile *M = I->second;
6522 unsigned Index = ID - M->BaseIdentifierID;
6523 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
6524
6525 // All of the strings in the AST file are preceded by a 16-bit length.
6526 // Extract that 16-bit length to avoid having to execute strlen().
6527 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6528 // unsigned integers. This is important to avoid integer overflow when
6529 // we cast them to 'unsigned'.
6530 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
6531 unsigned StrLen = (((unsigned) StrLenPtr[0])
6532 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregor8222b892013-01-21 16:52:34 +00006533 IdentifiersLoaded[ID]
6534 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006535 if (DeserializationListener)
6536 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
6537 }
6538
6539 return IdentifiersLoaded[ID];
6540}
6541
Douglas Gregor8222b892013-01-21 16:52:34 +00006542IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
6543 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006544}
6545
6546IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
6547 if (LocalID < NUM_PREDEF_IDENT_IDS)
6548 return LocalID;
6549
6550 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6551 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6552 assert(I != M.IdentifierRemap.end()
6553 && "Invalid index into identifier index remap");
6554
6555 return LocalID + I->second;
6556}
6557
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00006558MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006559 if (ID == 0)
6560 return 0;
6561
6562 if (MacrosLoaded.empty()) {
6563 Error("no macro table in AST file");
6564 return 0;
6565 }
6566
6567 ID -= NUM_PREDEF_MACRO_IDS;
6568 if (!MacrosLoaded[ID]) {
6569 GlobalMacroMapType::iterator I
6570 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
6571 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
6572 ModuleFile *M = I->second;
6573 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00006574 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
6575
6576 if (DeserializationListener)
6577 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
6578 MacrosLoaded[ID]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006579 }
6580
6581 return MacrosLoaded[ID];
6582}
6583
6584MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
6585 if (LocalID < NUM_PREDEF_MACRO_IDS)
6586 return LocalID;
6587
6588 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6589 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
6590 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
6591
6592 return LocalID + I->second;
6593}
6594
6595serialization::SubmoduleID
6596ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
6597 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
6598 return LocalID;
6599
6600 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6601 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
6602 assert(I != M.SubmoduleRemap.end()
6603 && "Invalid index into submodule index remap");
6604
6605 return LocalID + I->second;
6606}
6607
6608Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
6609 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6610 assert(GlobalID == 0 && "Unhandled global submodule ID");
6611 return 0;
6612 }
6613
6614 if (GlobalID > SubmodulesLoaded.size()) {
6615 Error("submodule ID out of range in AST file");
6616 return 0;
6617 }
6618
6619 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
6620}
Douglas Gregorca2ab452013-01-12 01:29:50 +00006621
6622Module *ASTReader::getModule(unsigned ID) {
6623 return getSubmodule(ID);
6624}
6625
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006626Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
6627 return DecodeSelector(getGlobalSelectorID(M, LocalID));
6628}
6629
6630Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
6631 if (ID == 0)
6632 return Selector();
6633
6634 if (ID > SelectorsLoaded.size()) {
6635 Error("selector ID out of range in AST file");
6636 return Selector();
6637 }
6638
6639 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
6640 // Load this selector from the selector table.
6641 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
6642 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
6643 ModuleFile &M = *I->second;
6644 ASTSelectorLookupTrait Trait(*this, M);
6645 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
6646 SelectorsLoaded[ID - 1] =
6647 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
6648 if (DeserializationListener)
6649 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
6650 }
6651
6652 return SelectorsLoaded[ID - 1];
6653}
6654
6655Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
6656 return DecodeSelector(ID);
6657}
6658
6659uint32_t ASTReader::GetNumExternalSelectors() {
6660 // ID 0 (the null selector) is considered an external selector.
6661 return getTotalNumSelectors() + 1;
6662}
6663
6664serialization::SelectorID
6665ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
6666 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
6667 return LocalID;
6668
6669 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6670 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
6671 assert(I != M.SelectorRemap.end()
6672 && "Invalid index into selector index remap");
6673
6674 return LocalID + I->second;
6675}
6676
6677DeclarationName
6678ASTReader::ReadDeclarationName(ModuleFile &F,
6679 const RecordData &Record, unsigned &Idx) {
6680 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
6681 switch (Kind) {
6682 case DeclarationName::Identifier:
Douglas Gregor8222b892013-01-21 16:52:34 +00006683 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006684
6685 case DeclarationName::ObjCZeroArgSelector:
6686 case DeclarationName::ObjCOneArgSelector:
6687 case DeclarationName::ObjCMultiArgSelector:
6688 return DeclarationName(ReadSelector(F, Record, Idx));
6689
6690 case DeclarationName::CXXConstructorName:
6691 return Context.DeclarationNames.getCXXConstructorName(
6692 Context.getCanonicalType(readType(F, Record, Idx)));
6693
6694 case DeclarationName::CXXDestructorName:
6695 return Context.DeclarationNames.getCXXDestructorName(
6696 Context.getCanonicalType(readType(F, Record, Idx)));
6697
6698 case DeclarationName::CXXConversionFunctionName:
6699 return Context.DeclarationNames.getCXXConversionFunctionName(
6700 Context.getCanonicalType(readType(F, Record, Idx)));
6701
6702 case DeclarationName::CXXOperatorName:
6703 return Context.DeclarationNames.getCXXOperatorName(
6704 (OverloadedOperatorKind)Record[Idx++]);
6705
6706 case DeclarationName::CXXLiteralOperatorName:
6707 return Context.DeclarationNames.getCXXLiteralOperatorName(
6708 GetIdentifierInfo(F, Record, Idx));
6709
6710 case DeclarationName::CXXUsingDirective:
6711 return DeclarationName::getUsingDirectiveName();
6712 }
6713
6714 llvm_unreachable("Invalid NameKind!");
6715}
6716
6717void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
6718 DeclarationNameLoc &DNLoc,
6719 DeclarationName Name,
6720 const RecordData &Record, unsigned &Idx) {
6721 switch (Name.getNameKind()) {
6722 case DeclarationName::CXXConstructorName:
6723 case DeclarationName::CXXDestructorName:
6724 case DeclarationName::CXXConversionFunctionName:
6725 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
6726 break;
6727
6728 case DeclarationName::CXXOperatorName:
6729 DNLoc.CXXOperatorName.BeginOpNameLoc
6730 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6731 DNLoc.CXXOperatorName.EndOpNameLoc
6732 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6733 break;
6734
6735 case DeclarationName::CXXLiteralOperatorName:
6736 DNLoc.CXXLiteralOperatorName.OpNameLoc
6737 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6738 break;
6739
6740 case DeclarationName::Identifier:
6741 case DeclarationName::ObjCZeroArgSelector:
6742 case DeclarationName::ObjCOneArgSelector:
6743 case DeclarationName::ObjCMultiArgSelector:
6744 case DeclarationName::CXXUsingDirective:
6745 break;
6746 }
6747}
6748
6749void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
6750 DeclarationNameInfo &NameInfo,
6751 const RecordData &Record, unsigned &Idx) {
6752 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
6753 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
6754 DeclarationNameLoc DNLoc;
6755 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
6756 NameInfo.setInfo(DNLoc);
6757}
6758
6759void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
6760 const RecordData &Record, unsigned &Idx) {
6761 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
6762 unsigned NumTPLists = Record[Idx++];
6763 Info.NumTemplParamLists = NumTPLists;
6764 if (NumTPLists) {
6765 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
6766 for (unsigned i=0; i != NumTPLists; ++i)
6767 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
6768 }
6769}
6770
6771TemplateName
6772ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
6773 unsigned &Idx) {
6774 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
6775 switch (Kind) {
6776 case TemplateName::Template:
6777 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
6778
6779 case TemplateName::OverloadedTemplate: {
6780 unsigned size = Record[Idx++];
6781 UnresolvedSet<8> Decls;
6782 while (size--)
6783 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
6784
6785 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
6786 }
6787
6788 case TemplateName::QualifiedTemplate: {
6789 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6790 bool hasTemplKeyword = Record[Idx++];
6791 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
6792 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
6793 }
6794
6795 case TemplateName::DependentTemplate: {
6796 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6797 if (Record[Idx++]) // isIdentifier
6798 return Context.getDependentTemplateName(NNS,
6799 GetIdentifierInfo(F, Record,
6800 Idx));
6801 return Context.getDependentTemplateName(NNS,
6802 (OverloadedOperatorKind)Record[Idx++]);
6803 }
6804
6805 case TemplateName::SubstTemplateTemplateParm: {
6806 TemplateTemplateParmDecl *param
6807 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6808 if (!param) return TemplateName();
6809 TemplateName replacement = ReadTemplateName(F, Record, Idx);
6810 return Context.getSubstTemplateTemplateParm(param, replacement);
6811 }
6812
6813 case TemplateName::SubstTemplateTemplateParmPack: {
6814 TemplateTemplateParmDecl *Param
6815 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6816 if (!Param)
6817 return TemplateName();
6818
6819 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
6820 if (ArgPack.getKind() != TemplateArgument::Pack)
6821 return TemplateName();
6822
6823 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
6824 }
6825 }
6826
6827 llvm_unreachable("Unhandled template name kind!");
6828}
6829
6830TemplateArgument
6831ASTReader::ReadTemplateArgument(ModuleFile &F,
6832 const RecordData &Record, unsigned &Idx) {
6833 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
6834 switch (Kind) {
6835 case TemplateArgument::Null:
6836 return TemplateArgument();
6837 case TemplateArgument::Type:
6838 return TemplateArgument(readType(F, Record, Idx));
6839 case TemplateArgument::Declaration: {
6840 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
6841 bool ForReferenceParam = Record[Idx++];
6842 return TemplateArgument(D, ForReferenceParam);
6843 }
6844 case TemplateArgument::NullPtr:
6845 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
6846 case TemplateArgument::Integral: {
6847 llvm::APSInt Value = ReadAPSInt(Record, Idx);
6848 QualType T = readType(F, Record, Idx);
6849 return TemplateArgument(Context, Value, T);
6850 }
6851 case TemplateArgument::Template:
6852 return TemplateArgument(ReadTemplateName(F, Record, Idx));
6853 case TemplateArgument::TemplateExpansion: {
6854 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikiedc84cd52013-02-20 22:23:23 +00006855 Optional<unsigned> NumTemplateExpansions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006856 if (unsigned NumExpansions = Record[Idx++])
6857 NumTemplateExpansions = NumExpansions - 1;
6858 return TemplateArgument(Name, NumTemplateExpansions);
6859 }
6860 case TemplateArgument::Expression:
6861 return TemplateArgument(ReadExpr(F));
6862 case TemplateArgument::Pack: {
6863 unsigned NumArgs = Record[Idx++];
6864 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
6865 for (unsigned I = 0; I != NumArgs; ++I)
6866 Args[I] = ReadTemplateArgument(F, Record, Idx);
6867 return TemplateArgument(Args, NumArgs);
6868 }
6869 }
6870
6871 llvm_unreachable("Unhandled template argument kind!");
6872}
6873
6874TemplateParameterList *
6875ASTReader::ReadTemplateParameterList(ModuleFile &F,
6876 const RecordData &Record, unsigned &Idx) {
6877 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
6878 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
6879 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
6880
6881 unsigned NumParams = Record[Idx++];
6882 SmallVector<NamedDecl *, 16> Params;
6883 Params.reserve(NumParams);
6884 while (NumParams--)
6885 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
6886
6887 TemplateParameterList* TemplateParams =
6888 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
6889 Params.data(), Params.size(), RAngleLoc);
6890 return TemplateParams;
6891}
6892
6893void
6894ASTReader::
6895ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
6896 ModuleFile &F, const RecordData &Record,
6897 unsigned &Idx) {
6898 unsigned NumTemplateArgs = Record[Idx++];
6899 TemplArgs.reserve(NumTemplateArgs);
6900 while (NumTemplateArgs--)
6901 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
6902}
6903
6904/// \brief Read a UnresolvedSet structure.
6905void ASTReader::ReadUnresolvedSet(ModuleFile &F, ASTUnresolvedSet &Set,
6906 const RecordData &Record, unsigned &Idx) {
6907 unsigned NumDecls = Record[Idx++];
6908 Set.reserve(Context, NumDecls);
6909 while (NumDecls--) {
6910 NamedDecl *D = ReadDeclAs<NamedDecl>(F, Record, Idx);
6911 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
6912 Set.addDecl(Context, D, AS);
6913 }
6914}
6915
6916CXXBaseSpecifier
6917ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
6918 const RecordData &Record, unsigned &Idx) {
6919 bool isVirtual = static_cast<bool>(Record[Idx++]);
6920 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
6921 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
6922 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
6923 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
6924 SourceRange Range = ReadSourceRange(F, Record, Idx);
6925 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
6926 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
6927 EllipsisLoc);
6928 Result.setInheritConstructors(inheritConstructors);
6929 return Result;
6930}
6931
6932std::pair<CXXCtorInitializer **, unsigned>
6933ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
6934 unsigned &Idx) {
6935 CXXCtorInitializer **CtorInitializers = 0;
6936 unsigned NumInitializers = Record[Idx++];
6937 if (NumInitializers) {
6938 CtorInitializers
6939 = new (Context) CXXCtorInitializer*[NumInitializers];
6940 for (unsigned i=0; i != NumInitializers; ++i) {
6941 TypeSourceInfo *TInfo = 0;
6942 bool IsBaseVirtual = false;
6943 FieldDecl *Member = 0;
6944 IndirectFieldDecl *IndirectMember = 0;
6945
6946 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
6947 switch (Type) {
6948 case CTOR_INITIALIZER_BASE:
6949 TInfo = GetTypeSourceInfo(F, Record, Idx);
6950 IsBaseVirtual = Record[Idx++];
6951 break;
6952
6953 case CTOR_INITIALIZER_DELEGATING:
6954 TInfo = GetTypeSourceInfo(F, Record, Idx);
6955 break;
6956
6957 case CTOR_INITIALIZER_MEMBER:
6958 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
6959 break;
6960
6961 case CTOR_INITIALIZER_INDIRECT_MEMBER:
6962 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
6963 break;
6964 }
6965
6966 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
6967 Expr *Init = ReadExpr(F);
6968 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
6969 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
6970 bool IsWritten = Record[Idx++];
6971 unsigned SourceOrderOrNumArrayIndices;
6972 SmallVector<VarDecl *, 8> Indices;
6973 if (IsWritten) {
6974 SourceOrderOrNumArrayIndices = Record[Idx++];
6975 } else {
6976 SourceOrderOrNumArrayIndices = Record[Idx++];
6977 Indices.reserve(SourceOrderOrNumArrayIndices);
6978 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
6979 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
6980 }
6981
6982 CXXCtorInitializer *BOMInit;
6983 if (Type == CTOR_INITIALIZER_BASE) {
6984 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
6985 LParenLoc, Init, RParenLoc,
6986 MemberOrEllipsisLoc);
6987 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
6988 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
6989 Init, RParenLoc);
6990 } else if (IsWritten) {
6991 if (Member)
6992 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
6993 LParenLoc, Init, RParenLoc);
6994 else
6995 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
6996 MemberOrEllipsisLoc, LParenLoc,
6997 Init, RParenLoc);
6998 } else {
Argyrios Kyrtzidisf8f480f2013-05-30 23:59:46 +00006999 if (IndirectMember) {
7000 assert(Indices.empty() && "Indirect field improperly initialized");
7001 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7002 MemberOrEllipsisLoc, LParenLoc,
7003 Init, RParenLoc);
7004 } else {
7005 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7006 LParenLoc, Init, RParenLoc,
7007 Indices.data(), Indices.size());
7008 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007009 }
7010
7011 if (IsWritten)
7012 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7013 CtorInitializers[i] = BOMInit;
7014 }
7015 }
7016
7017 return std::make_pair(CtorInitializers, NumInitializers);
7018}
7019
7020NestedNameSpecifier *
7021ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7022 const RecordData &Record, unsigned &Idx) {
7023 unsigned N = Record[Idx++];
7024 NestedNameSpecifier *NNS = 0, *Prev = 0;
7025 for (unsigned I = 0; I != N; ++I) {
7026 NestedNameSpecifier::SpecifierKind Kind
7027 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7028 switch (Kind) {
7029 case NestedNameSpecifier::Identifier: {
7030 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7031 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7032 break;
7033 }
7034
7035 case NestedNameSpecifier::Namespace: {
7036 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7037 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7038 break;
7039 }
7040
7041 case NestedNameSpecifier::NamespaceAlias: {
7042 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7043 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7044 break;
7045 }
7046
7047 case NestedNameSpecifier::TypeSpec:
7048 case NestedNameSpecifier::TypeSpecWithTemplate: {
7049 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7050 if (!T)
7051 return 0;
7052
7053 bool Template = Record[Idx++];
7054 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7055 break;
7056 }
7057
7058 case NestedNameSpecifier::Global: {
7059 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7060 // No associated value, and there can't be a prefix.
7061 break;
7062 }
7063 }
7064 Prev = NNS;
7065 }
7066 return NNS;
7067}
7068
7069NestedNameSpecifierLoc
7070ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7071 unsigned &Idx) {
7072 unsigned N = Record[Idx++];
7073 NestedNameSpecifierLocBuilder Builder;
7074 for (unsigned I = 0; I != N; ++I) {
7075 NestedNameSpecifier::SpecifierKind Kind
7076 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7077 switch (Kind) {
7078 case NestedNameSpecifier::Identifier: {
7079 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7080 SourceRange Range = ReadSourceRange(F, Record, Idx);
7081 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7082 break;
7083 }
7084
7085 case NestedNameSpecifier::Namespace: {
7086 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7087 SourceRange Range = ReadSourceRange(F, Record, Idx);
7088 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7089 break;
7090 }
7091
7092 case NestedNameSpecifier::NamespaceAlias: {
7093 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7094 SourceRange Range = ReadSourceRange(F, Record, Idx);
7095 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7096 break;
7097 }
7098
7099 case NestedNameSpecifier::TypeSpec:
7100 case NestedNameSpecifier::TypeSpecWithTemplate: {
7101 bool Template = Record[Idx++];
7102 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7103 if (!T)
7104 return NestedNameSpecifierLoc();
7105 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7106
7107 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7108 Builder.Extend(Context,
7109 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7110 T->getTypeLoc(), ColonColonLoc);
7111 break;
7112 }
7113
7114 case NestedNameSpecifier::Global: {
7115 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7116 Builder.MakeGlobal(Context, ColonColonLoc);
7117 break;
7118 }
7119 }
7120 }
7121
7122 return Builder.getWithLocInContext(Context);
7123}
7124
7125SourceRange
7126ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7127 unsigned &Idx) {
7128 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7129 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7130 return SourceRange(beg, end);
7131}
7132
7133/// \brief Read an integral value
7134llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7135 unsigned BitWidth = Record[Idx++];
7136 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7137 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7138 Idx += NumWords;
7139 return Result;
7140}
7141
7142/// \brief Read a signed integral value
7143llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7144 bool isUnsigned = Record[Idx++];
7145 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7146}
7147
7148/// \brief Read a floating-point value
Tim Northover9ec55f22013-01-22 09:46:51 +00007149llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7150 const llvm::fltSemantics &Sem,
7151 unsigned &Idx) {
7152 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007153}
7154
7155// \brief Read a string
7156std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7157 unsigned Len = Record[Idx++];
7158 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7159 Idx += Len;
7160 return Result;
7161}
7162
7163VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7164 unsigned &Idx) {
7165 unsigned Major = Record[Idx++];
7166 unsigned Minor = Record[Idx++];
7167 unsigned Subminor = Record[Idx++];
7168 if (Minor == 0)
7169 return VersionTuple(Major);
7170 if (Subminor == 0)
7171 return VersionTuple(Major, Minor - 1);
7172 return VersionTuple(Major, Minor - 1, Subminor - 1);
7173}
7174
7175CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7176 const RecordData &Record,
7177 unsigned &Idx) {
7178 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7179 return CXXTemporary::Create(Context, Decl);
7180}
7181
7182DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +00007183 return Diag(CurrentImportLoc, DiagID);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007184}
7185
7186DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7187 return Diags.Report(Loc, DiagID);
7188}
7189
7190/// \brief Retrieve the identifier table associated with the
7191/// preprocessor.
7192IdentifierTable &ASTReader::getIdentifierTable() {
7193 return PP.getIdentifierTable();
7194}
7195
7196/// \brief Record that the given ID maps to the given switch-case
7197/// statement.
7198void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7199 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7200 "Already have a SwitchCase with this ID");
7201 (*CurrSwitchCaseStmts)[ID] = SC;
7202}
7203
7204/// \brief Retrieve the switch-case statement with the given ID.
7205SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7206 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7207 return (*CurrSwitchCaseStmts)[ID];
7208}
7209
7210void ASTReader::ClearSwitchCaseIDs() {
7211 CurrSwitchCaseStmts->clear();
7212}
7213
7214void ASTReader::ReadComments() {
7215 std::vector<RawComment *> Comments;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007216 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007217 serialization::ModuleFile *> >::iterator
7218 I = CommentsCursors.begin(),
7219 E = CommentsCursors.end();
7220 I != E; ++I) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007221 BitstreamCursor &Cursor = I->first;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007222 serialization::ModuleFile &F = *I->second;
7223 SavedStreamPosition SavedPosition(Cursor);
7224
7225 RecordData Record;
7226 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007227 llvm::BitstreamEntry Entry =
7228 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
7229
7230 switch (Entry.Kind) {
7231 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7232 case llvm::BitstreamEntry::Error:
7233 Error("malformed block record in AST file");
7234 return;
7235 case llvm::BitstreamEntry::EndBlock:
7236 goto NextCursor;
7237 case llvm::BitstreamEntry::Record:
7238 // The interesting case.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007239 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007240 }
7241
7242 // Read a record.
7243 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00007244 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007245 case COMMENTS_RAW_COMMENT: {
7246 unsigned Idx = 0;
7247 SourceRange SR = ReadSourceRange(F, Record, Idx);
7248 RawComment::CommentKind Kind =
7249 (RawComment::CommentKind) Record[Idx++];
7250 bool IsTrailingComment = Record[Idx++];
7251 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +00007252 Comments.push_back(new (Context) RawComment(
7253 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7254 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007255 break;
7256 }
7257 }
7258 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007259 NextCursor:;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007260 }
7261 Context.Comments.addCommentsToFront(Comments);
7262}
7263
7264void ASTReader::finishPendingActions() {
7265 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Argyrios Kyrtzidis7640b022013-02-16 00:48:59 +00007266 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007267 // If any identifiers with corresponding top-level declarations have
7268 // been loaded, load those declarations now.
Douglas Gregoraa945902013-02-18 15:53:43 +00007269 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> > TopLevelDecls;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007270 while (!PendingIdentifierInfos.empty()) {
Douglas Gregoraa945902013-02-18 15:53:43 +00007271 // FIXME: std::move
7272 IdentifierInfo *II = PendingIdentifierInfos.back().first;
7273 SmallVector<uint32_t, 4> DeclIDs = PendingIdentifierInfos.back().second;
Douglas Gregorcc9bdcb2013-02-19 18:26:28 +00007274 PendingIdentifierInfos.pop_back();
Douglas Gregoraa945902013-02-18 15:53:43 +00007275
7276 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007277 }
7278
7279 // Load pending declaration chains.
7280 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7281 loadPendingDeclChain(PendingDeclChains[I]);
7282 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
7283 }
7284 PendingDeclChains.clear();
7285
Douglas Gregoraa945902013-02-18 15:53:43 +00007286 // Make the most recent of the top-level declarations visible.
7287 for (llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >::iterator
7288 TLD = TopLevelDecls.begin(), TLDEnd = TopLevelDecls.end();
7289 TLD != TLDEnd; ++TLD) {
7290 IdentifierInfo *II = TLD->first;
7291 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidis0532df02013-04-26 21:33:35 +00007292 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregoraa945902013-02-18 15:53:43 +00007293 }
7294 }
7295
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007296 // Load any pending macro definitions.
7297 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00007298 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
7299 SmallVector<PendingMacroInfo, 2> GlobalIDs;
7300 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
7301 // Initialize the macro history from chained-PCHs ahead of module imports.
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00007302 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7303 ++IDIdx) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00007304 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7305 if (Info.M->Kind != MK_Module)
7306 resolvePendingMacro(II, Info);
7307 }
7308 // Handle module imports.
7309 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7310 ++IDIdx) {
7311 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7312 if (Info.M->Kind == MK_Module)
7313 resolvePendingMacro(II, Info);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007314 }
7315 }
7316 PendingMacroIDs.clear();
Argyrios Kyrtzidis7640b022013-02-16 00:48:59 +00007317
7318 // Wire up the DeclContexts for Decls that we delayed setting until
7319 // recursive loading is completed.
7320 while (!PendingDeclContextInfos.empty()) {
7321 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7322 PendingDeclContextInfos.pop_front();
7323 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7324 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7325 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7326 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007327 }
7328
7329 // If we deserialized any C++ or Objective-C class definitions, any
7330 // Objective-C protocol definitions, or any redeclarable templates, make sure
7331 // that all redeclarations point to the definitions. Note that this can only
7332 // happen now, after the redeclaration chains have been fully wired.
7333 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7334 DEnd = PendingDefinitions.end();
7335 D != DEnd; ++D) {
7336 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7337 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7338 // Make sure that the TagType points at the definition.
7339 const_cast<TagType*>(TagT)->decl = TD;
7340 }
7341
7342 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(*D)) {
7343 for (CXXRecordDecl::redecl_iterator R = RD->redecls_begin(),
7344 REnd = RD->redecls_end();
7345 R != REnd; ++R)
7346 cast<CXXRecordDecl>(*R)->DefinitionData = RD->DefinitionData;
7347
7348 }
7349
7350 continue;
7351 }
7352
7353 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
7354 // Make sure that the ObjCInterfaceType points at the definition.
7355 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7356 ->Decl = ID;
7357
7358 for (ObjCInterfaceDecl::redecl_iterator R = ID->redecls_begin(),
7359 REnd = ID->redecls_end();
7360 R != REnd; ++R)
7361 R->Data = ID->Data;
7362
7363 continue;
7364 }
7365
7366 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7367 for (ObjCProtocolDecl::redecl_iterator R = PD->redecls_begin(),
7368 REnd = PD->redecls_end();
7369 R != REnd; ++R)
7370 R->Data = PD->Data;
7371
7372 continue;
7373 }
7374
7375 RedeclarableTemplateDecl *RTD
7376 = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7377 for (RedeclarableTemplateDecl::redecl_iterator R = RTD->redecls_begin(),
7378 REnd = RTD->redecls_end();
7379 R != REnd; ++R)
7380 R->Common = RTD->Common;
7381 }
7382 PendingDefinitions.clear();
7383
7384 // Load the bodies of any functions or methods we've encountered. We do
7385 // this now (delayed) so that we can be sure that the declaration chains
7386 // have been fully wired up.
7387 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7388 PBEnd = PendingBodies.end();
7389 PB != PBEnd; ++PB) {
7390 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7391 // FIXME: Check for =delete/=default?
7392 // FIXME: Complain about ODR violations here?
7393 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7394 FD->setLazyBody(PB->second);
7395 continue;
7396 }
7397
7398 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7399 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7400 MD->setLazyBody(PB->second);
7401 }
7402 PendingBodies.clear();
7403}
7404
7405void ASTReader::FinishedDeserializing() {
7406 assert(NumCurrentElementsDeserializing &&
7407 "FinishedDeserializing not paired with StartedDeserializing");
7408 if (NumCurrentElementsDeserializing == 1) {
7409 // We decrease NumCurrentElementsDeserializing only after pending actions
7410 // are finished, to avoid recursively re-calling finishPendingActions().
7411 finishPendingActions();
7412 }
7413 --NumCurrentElementsDeserializing;
7414
7415 if (NumCurrentElementsDeserializing == 0 &&
7416 Consumer && !PassingDeclsToConsumer) {
7417 // Guard variable to avoid recursively redoing the process of passing
7418 // decls to consumer.
7419 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7420 true);
7421
7422 while (!InterestingDecls.empty()) {
7423 // We are not in recursive loading, so it's safe to pass the "interesting"
7424 // decls to the consumer.
7425 Decl *D = InterestingDecls.front();
7426 InterestingDecls.pop_front();
7427 PassInterestingDeclToConsumer(D);
7428 }
7429 }
7430}
7431
Argyrios Kyrtzidis0532df02013-04-26 21:33:35 +00007432void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
7433 D = cast<NamedDecl>(D->getMostRecentDecl());
7434
7435 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
7436 SemaObj->TUScope->AddDecl(D);
7437 } else if (SemaObj->TUScope) {
7438 // Adding the decl to IdResolver may have failed because it was already in
7439 // (even though it was not added in scope). If it is already in, make sure
7440 // it gets in the scope as well.
7441 if (std::find(SemaObj->IdResolver.begin(Name),
7442 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
7443 SemaObj->TUScope->AddDecl(D);
7444 }
7445}
7446
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007447ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7448 StringRef isysroot, bool DisableValidation,
Douglas Gregorf575d6e2013-01-25 00:45:27 +00007449 bool AllowASTWithCompilerErrors, bool UseGlobalIndex)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007450 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7451 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7452 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7453 Consumer(0), ModuleMgr(PP.getFileManager()),
7454 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregore1698072013-01-25 00:38:33 +00007455 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Douglas Gregorf575d6e2013-01-25 00:45:27 +00007456 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007457 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7458 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregore1698072013-01-25 00:38:33 +00007459 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7460 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
7461 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregor95fb36e2013-01-28 17:54:36 +00007462 NumMethodPoolLookups(0), NumMethodPoolHits(0),
7463 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
7464 TotalNumMethodPoolEntries(0),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007465 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
7466 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
7467 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
7468 PassingDeclsToConsumer(false),
7469 NumCXXBaseSpecifiersLoaded(0)
7470{
7471 SourceMgr.setExternalSLocEntrySource(this);
7472}
7473
7474ASTReader::~ASTReader() {
7475 for (DeclContextVisibleUpdatesPending::iterator
7476 I = PendingVisibleUpdates.begin(),
7477 E = PendingVisibleUpdates.end();
7478 I != E; ++I) {
7479 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
7480 F = I->second.end();
7481 J != F; ++J)
7482 delete J->first;
7483 }
7484}