blob: 55e333a17b6972103de76de9bc6941da06e5b832 [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,
260 std::string &SuggestedPredefines) {
261 // Check macro definitions.
262 MacroDefinitionsMap ASTFileMacros;
263 collectMacroDefinitions(PPOpts, ASTFileMacros);
264 MacroDefinitionsMap ExistingMacros;
265 SmallVector<StringRef, 4> ExistingMacroNames;
266 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
267
268 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
269 // Dig out the macro definition in the existing preprocessor options.
270 StringRef MacroName = ExistingMacroNames[I];
271 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
272
273 // Check whether we know anything about this macro name or not.
274 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
275 = ASTFileMacros.find(MacroName);
276 if (Known == ASTFileMacros.end()) {
277 // FIXME: Check whether this identifier was referenced anywhere in the
278 // AST file. If so, we should reject the AST file. Unfortunately, this
279 // information isn't in the control block. What shall we do about it?
280
281 if (Existing.second) {
282 SuggestedPredefines += "#undef ";
283 SuggestedPredefines += MacroName.str();
284 SuggestedPredefines += '\n';
285 } else {
286 SuggestedPredefines += "#define ";
287 SuggestedPredefines += MacroName.str();
288 SuggestedPredefines += ' ';
289 SuggestedPredefines += Existing.first.str();
290 SuggestedPredefines += '\n';
291 }
292 continue;
293 }
294
295 // If the macro was defined in one but undef'd in the other, we have a
296 // conflict.
297 if (Existing.second != Known->second.second) {
298 if (Diags) {
299 Diags->Report(diag::err_pch_macro_def_undef)
300 << MacroName << Known->second.second;
301 }
302 return true;
303 }
304
305 // If the macro was #undef'd in both, or if the macro bodies are identical,
306 // it's fine.
307 if (Existing.second || Existing.first == Known->second.first)
308 continue;
309
310 // The macro bodies differ; complain.
311 if (Diags) {
312 Diags->Report(diag::err_pch_macro_def_conflict)
313 << MacroName << Known->second.first << Existing.first;
314 }
315 return true;
316 }
317
318 // Check whether we're using predefines.
319 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
320 if (Diags) {
321 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
322 }
323 return true;
324 }
325
326 // Compute the #include and #include_macros lines we need.
327 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
328 StringRef File = ExistingPPOpts.Includes[I];
329 if (File == ExistingPPOpts.ImplicitPCHInclude)
330 continue;
331
332 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
333 != PPOpts.Includes.end())
334 continue;
335
336 SuggestedPredefines += "#include \"";
337 SuggestedPredefines +=
338 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
339 SuggestedPredefines += "\"\n";
340 }
341
342 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
343 StringRef File = ExistingPPOpts.MacroIncludes[I];
344 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
345 File)
346 != PPOpts.MacroIncludes.end())
347 continue;
348
349 SuggestedPredefines += "#__include_macros \"";
350 SuggestedPredefines +=
351 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
352 SuggestedPredefines += "\"\n##\n";
353 }
354
355 return false;
356}
357
358bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
359 bool Complain,
360 std::string &SuggestedPredefines) {
361 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
362
363 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
364 Complain? &Reader.Diags : 0,
365 PP.getFileManager(),
366 SuggestedPredefines);
367}
368
369void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
370 unsigned ID) {
371 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
372 ++NumHeaderInfos;
373}
374
375void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
376 PP.setCounterValue(Value);
377}
378
379//===----------------------------------------------------------------------===//
380// AST reader implementation
381//===----------------------------------------------------------------------===//
382
383void
384ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
385 DeserializationListener = Listener;
386}
387
388
389
390unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
391 return serialization::ComputeHash(Sel);
392}
393
394
395std::pair<unsigned, unsigned>
396ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
397 using namespace clang::io;
398 unsigned KeyLen = ReadUnalignedLE16(d);
399 unsigned DataLen = ReadUnalignedLE16(d);
400 return std::make_pair(KeyLen, DataLen);
401}
402
403ASTSelectorLookupTrait::internal_key_type
404ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
405 using namespace clang::io;
406 SelectorTable &SelTable = Reader.getContext().Selectors;
407 unsigned N = ReadUnalignedLE16(d);
408 IdentifierInfo *FirstII
Douglas Gregor8222b892013-01-21 16:52:34 +0000409 = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000410 if (N == 0)
411 return SelTable.getNullarySelector(FirstII);
412 else if (N == 1)
413 return SelTable.getUnarySelector(FirstII);
414
415 SmallVector<IdentifierInfo *, 16> Args;
416 Args.push_back(FirstII);
417 for (unsigned I = 1; I != N; ++I)
Douglas Gregor8222b892013-01-21 16:52:34 +0000418 Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000419
420 return SelTable.getSelector(N, Args.data());
421}
422
423ASTSelectorLookupTrait::data_type
424ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
425 unsigned DataLen) {
426 using namespace clang::io;
427
428 data_type Result;
429
430 Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
431 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
432 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
433
434 // Load instance methods
435 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
436 if (ObjCMethodDecl *Method
437 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
438 Result.Instance.push_back(Method);
439 }
440
441 // Load factory methods
442 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
443 if (ObjCMethodDecl *Method
444 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
445 Result.Factory.push_back(Method);
446 }
447
448 return Result;
449}
450
Douglas Gregor479633c2013-01-23 18:53:14 +0000451unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
452 return llvm::HashString(a);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000453}
454
455std::pair<unsigned, unsigned>
Douglas Gregor479633c2013-01-23 18:53:14 +0000456ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000457 using namespace clang::io;
458 unsigned DataLen = ReadUnalignedLE16(d);
459 unsigned KeyLen = ReadUnalignedLE16(d);
460 return std::make_pair(KeyLen, DataLen);
461}
462
Douglas Gregor479633c2013-01-23 18:53:14 +0000463ASTIdentifierLookupTraitBase::internal_key_type
464ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000465 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregor479633c2013-01-23 18:53:14 +0000466 return StringRef((const char*) d, n-1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000467}
468
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000469/// \brief Whether the given identifier is "interesting".
470static bool isInterestingIdentifier(IdentifierInfo &II) {
471 return II.isPoisoned() ||
472 II.isExtensionToken() ||
473 II.getObjCOrBuiltinID() ||
474 II.hasRevertedTokenIDToIdentifier() ||
475 II.hadMacroDefinition() ||
476 II.getFETokenInfo<void>();
477}
478
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000479IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
480 const unsigned char* d,
481 unsigned DataLen) {
482 using namespace clang::io;
483 unsigned RawID = ReadUnalignedLE32(d);
484 bool IsInteresting = RawID & 0x01;
485
486 // Wipe out the "is interesting" bit.
487 RawID = RawID >> 1;
488
489 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
490 if (!IsInteresting) {
491 // For uninteresting identifiers, just build the IdentifierInfo
492 // and associate it with the persistent ID.
493 IdentifierInfo *II = KnownII;
494 if (!II) {
Douglas Gregor479633c2013-01-23 18:53:14 +0000495 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000496 KnownII = II;
497 }
498 Reader.SetIdentifierInfo(ID, II);
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000499 if (!II->isFromAST()) {
500 bool WasInteresting = isInterestingIdentifier(*II);
501 II->setIsFromAST();
502 if (WasInteresting)
503 II->setChangedSinceDeserialization();
504 }
505 Reader.markIdentifierUpToDate(II);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000506 return II;
507 }
508
509 unsigned ObjCOrBuiltinID = ReadUnalignedLE16(d);
510 unsigned Bits = ReadUnalignedLE16(d);
511 bool CPlusPlusOperatorKeyword = Bits & 0x01;
512 Bits >>= 1;
513 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
514 Bits >>= 1;
515 bool Poisoned = Bits & 0x01;
516 Bits >>= 1;
517 bool ExtensionToken = Bits & 0x01;
518 Bits >>= 1;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000519 bool hasSubmoduleMacros = Bits & 0x01;
520 Bits >>= 1;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000521 bool hadMacroDefinition = Bits & 0x01;
522 Bits >>= 1;
523
524 assert(Bits == 0 && "Extra bits in the identifier?");
525 DataLen -= 8;
526
527 // Build the IdentifierInfo itself and link the identifier ID with
528 // the new IdentifierInfo.
529 IdentifierInfo *II = KnownII;
530 if (!II) {
Douglas Gregor479633c2013-01-23 18:53:14 +0000531 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000532 KnownII = II;
533 }
534 Reader.markIdentifierUpToDate(II);
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000535 if (!II->isFromAST()) {
536 bool WasInteresting = isInterestingIdentifier(*II);
537 II->setIsFromAST();
538 if (WasInteresting)
539 II->setChangedSinceDeserialization();
540 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000541
542 // Set or check the various bits in the IdentifierInfo structure.
543 // Token IDs are read-only.
Argyrios Kyrtzidis1ebefc72013-02-27 01:13:51 +0000544 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000545 II->RevertTokenIDToIdentifier();
546 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
547 assert(II->isExtensionToken() == ExtensionToken &&
548 "Incorrect extension token flag");
549 (void)ExtensionToken;
550 if (Poisoned)
551 II->setIsPoisoned(true);
552 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
553 "Incorrect C++ operator keyword flag");
554 (void)CPlusPlusOperatorKeyword;
555
556 // If this identifier is a macro, deserialize the macro
557 // definition.
558 if (hadMacroDefinition) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000559 uint32_t MacroDirectivesOffset = ReadUnalignedLE32(d);
560 DataLen -= 4;
561 SmallVector<uint32_t, 8> LocalMacroIDs;
562 if (hasSubmoduleMacros) {
563 while (uint32_t LocalMacroID = ReadUnalignedLE32(d)) {
564 DataLen -= 4;
565 LocalMacroIDs.push_back(LocalMacroID);
566 }
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +0000567 DataLen -= 4;
568 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000569
570 if (F.Kind == MK_Module) {
571 for (SmallVectorImpl<uint32_t>::iterator
572 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; ++I) {
573 MacroID MacID = Reader.getGlobalMacroID(F, *I);
574 Reader.addPendingMacroFromModule(II, &F, MacID, F.DirectImportLoc);
575 }
576 } else {
577 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
578 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000579 }
580
581 Reader.SetIdentifierInfo(ID, II);
582
583 // Read all of the declarations visible at global scope with this
584 // name.
585 if (DataLen > 0) {
586 SmallVector<uint32_t, 4> DeclIDs;
587 for (; DataLen > 0; DataLen -= 4)
588 DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
589 Reader.SetGloballyVisibleDecls(II, DeclIDs);
590 }
591
592 return II;
593}
594
595unsigned
596ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
597 llvm::FoldingSetNodeID ID;
598 ID.AddInteger(Key.Kind);
599
600 switch (Key.Kind) {
601 case DeclarationName::Identifier:
602 case DeclarationName::CXXLiteralOperatorName:
603 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
604 break;
605 case DeclarationName::ObjCZeroArgSelector:
606 case DeclarationName::ObjCOneArgSelector:
607 case DeclarationName::ObjCMultiArgSelector:
608 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
609 break;
610 case DeclarationName::CXXOperatorName:
611 ID.AddInteger((OverloadedOperatorKind)Key.Data);
612 break;
613 case DeclarationName::CXXConstructorName:
614 case DeclarationName::CXXDestructorName:
615 case DeclarationName::CXXConversionFunctionName:
616 case DeclarationName::CXXUsingDirective:
617 break;
618 }
619
620 return ID.ComputeHash();
621}
622
623ASTDeclContextNameLookupTrait::internal_key_type
624ASTDeclContextNameLookupTrait::GetInternalKey(
625 const external_key_type& Name) const {
626 DeclNameKey Key;
627 Key.Kind = Name.getNameKind();
628 switch (Name.getNameKind()) {
629 case DeclarationName::Identifier:
630 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
631 break;
632 case DeclarationName::ObjCZeroArgSelector:
633 case DeclarationName::ObjCOneArgSelector:
634 case DeclarationName::ObjCMultiArgSelector:
635 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
636 break;
637 case DeclarationName::CXXOperatorName:
638 Key.Data = Name.getCXXOverloadedOperator();
639 break;
640 case DeclarationName::CXXLiteralOperatorName:
641 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
642 break;
643 case DeclarationName::CXXConstructorName:
644 case DeclarationName::CXXDestructorName:
645 case DeclarationName::CXXConversionFunctionName:
646 case DeclarationName::CXXUsingDirective:
647 Key.Data = 0;
648 break;
649 }
650
651 return Key;
652}
653
654std::pair<unsigned, unsigned>
655ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
656 using namespace clang::io;
657 unsigned KeyLen = ReadUnalignedLE16(d);
658 unsigned DataLen = ReadUnalignedLE16(d);
659 return std::make_pair(KeyLen, DataLen);
660}
661
662ASTDeclContextNameLookupTrait::internal_key_type
663ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
664 using namespace clang::io;
665
666 DeclNameKey Key;
667 Key.Kind = (DeclarationName::NameKind)*d++;
668 switch (Key.Kind) {
669 case DeclarationName::Identifier:
670 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
671 break;
672 case DeclarationName::ObjCZeroArgSelector:
673 case DeclarationName::ObjCOneArgSelector:
674 case DeclarationName::ObjCMultiArgSelector:
675 Key.Data =
676 (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
677 .getAsOpaquePtr();
678 break;
679 case DeclarationName::CXXOperatorName:
680 Key.Data = *d++; // OverloadedOperatorKind
681 break;
682 case DeclarationName::CXXLiteralOperatorName:
683 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
684 break;
685 case DeclarationName::CXXConstructorName:
686 case DeclarationName::CXXDestructorName:
687 case DeclarationName::CXXConversionFunctionName:
688 case DeclarationName::CXXUsingDirective:
689 Key.Data = 0;
690 break;
691 }
692
693 return Key;
694}
695
696ASTDeclContextNameLookupTrait::data_type
697ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
698 const unsigned char* d,
699 unsigned DataLen) {
700 using namespace clang::io;
701 unsigned NumDecls = ReadUnalignedLE16(d);
Argyrios Kyrtzidise8b61cf2013-01-11 22:29:49 +0000702 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
703 const_cast<unsigned char *>(d));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000704 return std::make_pair(Start, Start + NumDecls);
705}
706
707bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000708 BitstreamCursor &Cursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000709 const std::pair<uint64_t, uint64_t> &Offsets,
710 DeclContextInfo &Info) {
711 SavedStreamPosition SavedPosition(Cursor);
712 // First the lexical decls.
713 if (Offsets.first != 0) {
714 Cursor.JumpToBit(Offsets.first);
715
716 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000717 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000718 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000719 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000720 if (RecCode != DECL_CONTEXT_LEXICAL) {
721 Error("Expected lexical block");
722 return true;
723 }
724
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000725 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
726 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000727 }
728
729 // Now the lookup table.
730 if (Offsets.second != 0) {
731 Cursor.JumpToBit(Offsets.second);
732
733 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000734 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000735 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000736 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000737 if (RecCode != DECL_CONTEXT_VISIBLE) {
738 Error("Expected visible lookup table block");
739 return true;
740 }
741 Info.NameLookupTableData
742 = ASTDeclContextNameLookupTable::Create(
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000743 (const unsigned char *)Blob.data() + Record[0],
744 (const unsigned char *)Blob.data(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000745 ASTDeclContextNameLookupTrait(*this, M));
746 }
747
748 return false;
749}
750
751void ASTReader::Error(StringRef Msg) {
752 Error(diag::err_fe_pch_malformed, Msg);
753}
754
755void ASTReader::Error(unsigned DiagID,
756 StringRef Arg1, StringRef Arg2) {
757 if (Diags.isDiagnosticInFlight())
758 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
759 else
760 Diag(DiagID) << Arg1 << Arg2;
761}
762
763//===----------------------------------------------------------------------===//
764// Source Manager Deserialization
765//===----------------------------------------------------------------------===//
766
767/// \brief Read the line table in the source manager block.
768/// \returns true if there was an error.
769bool ASTReader::ParseLineTable(ModuleFile &F,
770 SmallVectorImpl<uint64_t> &Record) {
771 unsigned Idx = 0;
772 LineTableInfo &LineTable = SourceMgr.getLineTable();
773
774 // Parse the file names
775 std::map<int, int> FileIDs;
776 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
777 // Extract the file name
778 unsigned FilenameLen = Record[Idx++];
779 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
780 Idx += FilenameLen;
781 MaybeAddSystemRootToFilename(F, Filename);
782 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
783 }
784
785 // Parse the line entries
786 std::vector<LineEntry> Entries;
787 while (Idx < Record.size()) {
788 int FID = Record[Idx++];
789 assert(FID >= 0 && "Serialized line entries for non-local file.");
790 // Remap FileID from 1-based old view.
791 FID += F.SLocEntryBaseID - 1;
792
793 // Extract the line entries
794 unsigned NumEntries = Record[Idx++];
795 assert(NumEntries && "Numentries is 00000");
796 Entries.clear();
797 Entries.reserve(NumEntries);
798 for (unsigned I = 0; I != NumEntries; ++I) {
799 unsigned FileOffset = Record[Idx++];
800 unsigned LineNo = Record[Idx++];
801 int FilenameID = FileIDs[Record[Idx++]];
802 SrcMgr::CharacteristicKind FileKind
803 = (SrcMgr::CharacteristicKind)Record[Idx++];
804 unsigned IncludeOffset = Record[Idx++];
805 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
806 FileKind, IncludeOffset));
807 }
808 LineTable.AddEntry(FileID::get(FID), Entries);
809 }
810
811 return false;
812}
813
814/// \brief Read a source manager block
815bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
816 using namespace SrcMgr;
817
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000818 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000819
820 // Set the source-location entry cursor to the current position in
821 // the stream. This cursor will be used to read the contents of the
822 // source manager block initially, and then lazily read
823 // source-location entries as needed.
824 SLocEntryCursor = F.Stream;
825
826 // The stream itself is going to skip over the source manager block.
827 if (F.Stream.SkipBlock()) {
828 Error("malformed block record in AST file");
829 return true;
830 }
831
832 // Enter the source manager block.
833 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
834 Error("malformed source manager block record in AST file");
835 return true;
836 }
837
838 RecordData Record;
839 while (true) {
Chris Lattner88bde502013-01-19 21:39:22 +0000840 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
841
842 switch (E.Kind) {
843 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
844 case llvm::BitstreamEntry::Error:
845 Error("malformed block record in AST file");
846 return true;
847 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000848 return false;
Chris Lattner88bde502013-01-19 21:39:22 +0000849 case llvm::BitstreamEntry::Record:
850 // The interesting case.
851 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000852 }
Chris Lattner88bde502013-01-19 21:39:22 +0000853
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000854 // Read a record.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000855 Record.clear();
Chris Lattner125eb3e2013-01-21 18:28:26 +0000856 StringRef Blob;
857 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000858 default: // Default behavior: ignore.
859 break;
860
861 case SM_SLOC_FILE_ENTRY:
862 case SM_SLOC_BUFFER_ENTRY:
863 case SM_SLOC_EXPANSION_ENTRY:
864 // Once we hit one of the source location entries, we're done.
865 return false;
866 }
867 }
868}
869
870/// \brief If a header file is not found at the path that we expect it to be
871/// and the PCH file was moved from its original location, try to resolve the
872/// file by assuming that header+PCH were moved together and the header is in
873/// the same place relative to the PCH.
874static std::string
875resolveFileRelativeToOriginalDir(const std::string &Filename,
876 const std::string &OriginalDir,
877 const std::string &CurrDir) {
878 assert(OriginalDir != CurrDir &&
879 "No point trying to resolve the file if the PCH dir didn't change");
880 using namespace llvm::sys;
881 SmallString<128> filePath(Filename);
882 fs::make_absolute(filePath);
883 assert(path::is_absolute(OriginalDir));
884 SmallString<128> currPCHPath(CurrDir);
885
886 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
887 fileDirE = path::end(path::parent_path(filePath));
888 path::const_iterator origDirI = path::begin(OriginalDir),
889 origDirE = path::end(OriginalDir);
890 // Skip the common path components from filePath and OriginalDir.
891 while (fileDirI != fileDirE && origDirI != origDirE &&
892 *fileDirI == *origDirI) {
893 ++fileDirI;
894 ++origDirI;
895 }
896 for (; origDirI != origDirE; ++origDirI)
897 path::append(currPCHPath, "..");
898 path::append(currPCHPath, fileDirI, fileDirE);
899 path::append(currPCHPath, path::filename(Filename));
900 return currPCHPath.str();
901}
902
903bool ASTReader::ReadSLocEntry(int ID) {
904 if (ID == 0)
905 return false;
906
907 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
908 Error("source location entry ID out-of-range for AST file");
909 return true;
910 }
911
912 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
913 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000914 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000915 unsigned BaseOffset = F->SLocEntryBaseOffset;
916
917 ++NumSLocEntriesRead;
Chris Lattner88bde502013-01-19 21:39:22 +0000918 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
919 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000920 Error("incorrectly-formatted source location entry in AST file");
921 return true;
922 }
Chris Lattner88bde502013-01-19 21:39:22 +0000923
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000924 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000925 StringRef Blob;
926 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000927 default:
928 Error("incorrectly-formatted source location entry in AST file");
929 return true;
930
931 case SM_SLOC_FILE_ENTRY: {
932 // We will detect whether a file changed and return 'Failure' for it, but
933 // we will also try to fail gracefully by setting up the SLocEntry.
934 unsigned InputID = Record[4];
935 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +0000936 const FileEntry *File = IF.getFile();
937 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000938
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +0000939 // Note that we only check if a File was returned. If it was out-of-date
940 // we have complained but we will continue creating a FileID to recover
941 // gracefully.
942 if (!File)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000943 return true;
944
945 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
946 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
947 // This is the module's main file.
948 IncludeLoc = getImportLocation(F);
949 }
950 SrcMgr::CharacteristicKind
951 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
952 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
953 ID, BaseOffset + Record[0]);
954 SrcMgr::FileInfo &FileInfo =
955 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
956 FileInfo.NumCreatedFIDs = Record[5];
957 if (Record[3])
958 FileInfo.setHasLineDirectives();
959
960 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
961 unsigned NumFileDecls = Record[7];
962 if (NumFileDecls) {
963 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
964 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
965 NumFileDecls));
966 }
967
968 const SrcMgr::ContentCache *ContentCache
969 = SourceMgr.getOrCreateContentCache(File,
970 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
971 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
972 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
973 unsigned Code = SLocEntryCursor.ReadCode();
974 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000975 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000976
977 if (RecCode != SM_SLOC_BUFFER_BLOB) {
978 Error("AST record has invalid code");
979 return true;
980 }
981
982 llvm::MemoryBuffer *Buffer
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000983 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000984 SourceMgr.overrideFileContents(File, Buffer);
985 }
986
987 break;
988 }
989
990 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000991 const char *Name = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000992 unsigned Offset = Record[0];
993 SrcMgr::CharacteristicKind
994 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
995 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
996 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
997 IncludeLoc = getImportLocation(F);
998 }
999 unsigned Code = SLocEntryCursor.ReadCode();
1000 Record.clear();
1001 unsigned RecCode
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001002 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001003
1004 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1005 Error("AST record has invalid code");
1006 return true;
1007 }
1008
1009 llvm::MemoryBuffer *Buffer
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001010 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001011 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
1012 BaseOffset + Offset, IncludeLoc);
1013 break;
1014 }
1015
1016 case SM_SLOC_EXPANSION_ENTRY: {
1017 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1018 SourceMgr.createExpansionLoc(SpellingLoc,
1019 ReadSourceLocation(*F, Record[2]),
1020 ReadSourceLocation(*F, Record[3]),
1021 Record[4],
1022 ID,
1023 BaseOffset + Record[0]);
1024 break;
1025 }
1026 }
1027
1028 return false;
1029}
1030
1031std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1032 if (ID == 0)
1033 return std::make_pair(SourceLocation(), "");
1034
1035 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1036 Error("source location entry ID out-of-range for AST file");
1037 return std::make_pair(SourceLocation(), "");
1038 }
1039
1040 // Find which module file this entry lands in.
1041 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1042 if (M->Kind != MK_Module)
1043 return std::make_pair(SourceLocation(), "");
1044
1045 // FIXME: Can we map this down to a particular submodule? That would be
1046 // ideal.
1047 return std::make_pair(M->ImportLoc, llvm::sys::path::stem(M->FileName));
1048}
1049
1050/// \brief Find the location where the module F is imported.
1051SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1052 if (F->ImportLoc.isValid())
1053 return F->ImportLoc;
1054
1055 // Otherwise we have a PCH. It's considered to be "imported" at the first
1056 // location of its includer.
1057 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1058 // Main file is the importer. We assume that it is the first entry in the
1059 // entry table. We can't ask the manager, because at the time of PCH loading
1060 // the main file entry doesn't exist yet.
1061 // The very first entry is the invalid instantiation loc, which takes up
1062 // offsets 0 and 1.
1063 return SourceLocation::getFromRawEncoding(2U);
1064 }
1065 //return F->Loaders[0]->FirstLoc;
1066 return F->ImportedBy[0]->FirstLoc;
1067}
1068
1069/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1070/// specified cursor. Read the abbreviations that are at the top of the block
1071/// and then leave the cursor pointing into the block.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001072bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001073 if (Cursor.EnterSubBlock(BlockID)) {
1074 Error("malformed block record in AST file");
1075 return Failure;
1076 }
1077
1078 while (true) {
1079 uint64_t Offset = Cursor.GetCurrentBitNo();
1080 unsigned Code = Cursor.ReadCode();
1081
1082 // We expect all abbrevs to be at the start of the block.
1083 if (Code != llvm::bitc::DEFINE_ABBREV) {
1084 Cursor.JumpToBit(Offset);
1085 return false;
1086 }
1087 Cursor.ReadAbbrevRecord();
1088 }
1089}
1090
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001091MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001092 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001093
1094 // Keep track of where we are in the stream, then jump back there
1095 // after reading this macro.
1096 SavedStreamPosition SavedPosition(Stream);
1097
1098 Stream.JumpToBit(Offset);
1099 RecordData Record;
1100 SmallVector<IdentifierInfo*, 16> MacroArgs;
1101 MacroInfo *Macro = 0;
1102
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001103 while (true) {
Chris Lattner99a5af02013-01-20 00:00:22 +00001104 // Advance to the next record, but if we get to the end of the block, don't
1105 // pop it (removing all the abbreviations from the cursor) since we want to
1106 // be able to reseek within the block and read entries.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001107 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattner99a5af02013-01-20 00:00:22 +00001108 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1109
1110 switch (Entry.Kind) {
1111 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1112 case llvm::BitstreamEntry::Error:
1113 Error("malformed block record in AST file");
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001114 return Macro;
Chris Lattner99a5af02013-01-20 00:00:22 +00001115 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001116 return Macro;
Chris Lattner99a5af02013-01-20 00:00:22 +00001117 case llvm::BitstreamEntry::Record:
1118 // The interesting case.
1119 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001120 }
1121
1122 // Read a record.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001123 Record.clear();
1124 PreprocessorRecordTypes RecType =
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001125 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001126 switch (RecType) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001127 case PP_MACRO_DIRECTIVE_HISTORY:
1128 return Macro;
1129
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001130 case PP_MACRO_OBJECT_LIKE:
1131 case PP_MACRO_FUNCTION_LIKE: {
1132 // If we already have a macro, that means that we've hit the end
1133 // of the definition of the macro we were looking for. We're
1134 // done.
1135 if (Macro)
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001136 return Macro;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001137
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001138 unsigned NextIndex = 1; // Skip identifier ID.
1139 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001140 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001141 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis8169b672013-01-07 19:16:23 +00001142 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001143 MI->setIsUsed(Record[NextIndex++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001144
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001145 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1146 // Decode function-like macro info.
1147 bool isC99VarArgs = Record[NextIndex++];
1148 bool isGNUVarArgs = Record[NextIndex++];
1149 bool hasCommaPasting = Record[NextIndex++];
1150 MacroArgs.clear();
1151 unsigned NumArgs = Record[NextIndex++];
1152 for (unsigned i = 0; i != NumArgs; ++i)
1153 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1154
1155 // Install function-like macro info.
1156 MI->setIsFunctionLike();
1157 if (isC99VarArgs) MI->setIsC99Varargs();
1158 if (isGNUVarArgs) MI->setIsGNUVarargs();
1159 if (hasCommaPasting) MI->setHasCommaPasting();
1160 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1161 PP.getPreprocessorAllocator());
1162 }
1163
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001164 // Remember that we saw this macro last so that we add the tokens that
1165 // form its body to it.
1166 Macro = MI;
1167
1168 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1169 Record[NextIndex]) {
1170 // We have a macro definition. Register the association
1171 PreprocessedEntityID
1172 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1173 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis0b849d32013-02-22 18:35:59 +00001174 PreprocessingRecord::PPEntityID
1175 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1176 MacroDefinition *PPDef =
1177 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1178 if (PPDef)
1179 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001180 }
1181
1182 ++NumMacrosRead;
1183 break;
1184 }
1185
1186 case PP_TOKEN: {
1187 // If we see a TOKEN before a PP_MACRO_*, then the file is
1188 // erroneous, just pretend we didn't see this.
1189 if (Macro == 0) break;
1190
1191 Token Tok;
1192 Tok.startToken();
1193 Tok.setLocation(ReadSourceLocation(F, Record[0]));
1194 Tok.setLength(Record[1]);
1195 if (IdentifierInfo *II = getLocalIdentifier(F, Record[2]))
1196 Tok.setIdentifierInfo(II);
1197 Tok.setKind((tok::TokenKind)Record[3]);
1198 Tok.setFlag((Token::TokenFlags)Record[4]);
1199 Macro->AddTokenToBody(Tok);
1200 break;
1201 }
1202 }
1203 }
1204}
1205
1206PreprocessedEntityID
1207ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1208 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1209 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1210 assert(I != M.PreprocessedEntityRemap.end()
1211 && "Invalid index into preprocessed entity index remap");
1212
1213 return LocalID + I->second;
1214}
1215
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001216unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1217 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001218}
1219
1220HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001221HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1222 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1223 FE->getName() };
1224 return ikey;
1225}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001226
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001227bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1228 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001229 return false;
1230
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001231 if (strcmp(a.Filename, b.Filename) == 0)
1232 return true;
1233
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001234 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis1c1508b2013-03-04 20:33:40 +00001235 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001236 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1237 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis1c1508b2013-03-04 20:33:40 +00001238 return (FEA && FEA == FEB);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001239}
1240
1241std::pair<unsigned, unsigned>
1242HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1243 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1244 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001245 return std::make_pair(KeyLen, DataLen);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001246}
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001247
1248HeaderFileInfoTrait::internal_key_type
1249HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1250 internal_key_type ikey;
1251 ikey.Size = off_t(clang::io::ReadUnalignedLE64(d));
1252 ikey.ModTime = time_t(clang::io::ReadUnalignedLE64(d));
1253 ikey.Filename = (const char *)d;
1254 return ikey;
1255}
1256
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001257HeaderFileInfoTrait::data_type
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001258HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001259 unsigned DataLen) {
1260 const unsigned char *End = d + DataLen;
1261 using namespace clang::io;
1262 HeaderFileInfo HFI;
1263 unsigned Flags = *d++;
1264 HFI.isImport = (Flags >> 5) & 0x01;
1265 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1266 HFI.DirInfo = (Flags >> 2) & 0x03;
1267 HFI.Resolved = (Flags >> 1) & 0x01;
1268 HFI.IndexHeaderMapHeader = Flags & 0x01;
1269 HFI.NumIncludes = ReadUnalignedLE16(d);
1270 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1271 ReadUnalignedLE32(d));
1272 if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1273 // The framework offset is 1 greater than the actual offset,
1274 // since 0 is used as an indicator for "no framework name".
1275 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1276 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1277 }
1278
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001279 if (d != End) {
1280 uint32_t LocalSMID = ReadUnalignedLE32(d);
1281 if (LocalSMID) {
1282 // This header is part of a module. Associate it with the module to enable
1283 // implicit module import.
1284 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1285 Module *Mod = Reader.getSubmodule(GlobalSMID);
1286 HFI.isModuleHeader = true;
1287 FileManager &FileMgr = Reader.getFileManager();
1288 ModuleMap &ModMap =
1289 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1290 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), /*Excluded=*/false);
1291 }
1292 }
1293
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001294 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1295 (void)End;
1296
1297 // This HeaderFileInfo was externally loaded.
1298 HFI.External = true;
1299 return HFI;
1300}
1301
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001302void ASTReader::addPendingMacroFromModule(IdentifierInfo *II,
1303 ModuleFile *M,
1304 GlobalMacroID GMacID,
1305 SourceLocation ImportLoc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001306 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001307 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, ImportLoc));
1308}
1309
1310void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1311 ModuleFile *M,
1312 uint64_t MacroDirectivesOffset) {
1313 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1314 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001315}
1316
1317void ASTReader::ReadDefinedMacros() {
1318 // Note that we are loading defined macros.
1319 Deserializing Macros(this);
1320
1321 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1322 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001323 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001324
1325 // If there was no preprocessor block, skip this file.
1326 if (!MacroCursor.getBitStreamReader())
1327 continue;
1328
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001329 BitstreamCursor Cursor = MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001330 Cursor.JumpToBit((*I)->MacroStartOffset);
1331
1332 RecordData Record;
1333 while (true) {
Chris Lattner88bde502013-01-19 21:39:22 +00001334 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1335
1336 switch (E.Kind) {
1337 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1338 case llvm::BitstreamEntry::Error:
1339 Error("malformed block record in AST file");
1340 return;
1341 case llvm::BitstreamEntry::EndBlock:
1342 goto NextCursor;
1343
1344 case llvm::BitstreamEntry::Record:
Chris Lattner88bde502013-01-19 21:39:22 +00001345 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001346 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattner88bde502013-01-19 21:39:22 +00001347 default: // Default behavior: ignore.
1348 break;
1349
1350 case PP_MACRO_OBJECT_LIKE:
1351 case PP_MACRO_FUNCTION_LIKE:
1352 getLocalIdentifier(**I, Record[0]);
1353 break;
1354
1355 case PP_TOKEN:
1356 // Ignore tokens.
1357 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001358 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001359 break;
1360 }
1361 }
Chris Lattner88bde502013-01-19 21:39:22 +00001362 NextCursor: ;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001363 }
1364}
1365
1366namespace {
1367 /// \brief Visitor class used to look up identifirs in an AST file.
1368 class IdentifierLookupVisitor {
1369 StringRef Name;
1370 unsigned PriorGeneration;
Douglas Gregore1698072013-01-25 00:38:33 +00001371 unsigned &NumIdentifierLookups;
1372 unsigned &NumIdentifierLookupHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001373 IdentifierInfo *Found;
Douglas Gregore1698072013-01-25 00:38:33 +00001374
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001375 public:
Douglas Gregore1698072013-01-25 00:38:33 +00001376 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1377 unsigned &NumIdentifierLookups,
1378 unsigned &NumIdentifierLookupHits)
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001379 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregore1698072013-01-25 00:38:33 +00001380 NumIdentifierLookups(NumIdentifierLookups),
1381 NumIdentifierLookupHits(NumIdentifierLookupHits),
1382 Found()
1383 {
1384 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001385
1386 static bool visit(ModuleFile &M, void *UserData) {
1387 IdentifierLookupVisitor *This
1388 = static_cast<IdentifierLookupVisitor *>(UserData);
1389
1390 // If we've already searched this module file, skip it now.
1391 if (M.Generation <= This->PriorGeneration)
1392 return true;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001393
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001394 ASTIdentifierLookupTable *IdTable
1395 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1396 if (!IdTable)
1397 return false;
1398
1399 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1400 M, This->Found);
Douglas Gregore1698072013-01-25 00:38:33 +00001401 ++This->NumIdentifierLookups;
1402 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001403 if (Pos == IdTable->end())
1404 return false;
1405
1406 // Dereferencing the iterator has the effect of building the
1407 // IdentifierInfo node and populating it with the various
1408 // declarations it needs.
Douglas Gregore1698072013-01-25 00:38:33 +00001409 ++This->NumIdentifierLookupHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001410 This->Found = *Pos;
1411 return true;
1412 }
1413
1414 // \brief Retrieve the identifier info found within the module
1415 // files.
1416 IdentifierInfo *getIdentifierInfo() const { return Found; }
1417 };
1418}
1419
1420void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1421 // Note that we are loading an identifier.
1422 Deserializing AnIdentifier(this);
1423
1424 unsigned PriorGeneration = 0;
1425 if (getContext().getLangOpts().Modules)
1426 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregor1a49d972013-01-25 01:03:03 +00001427
1428 // If there is a global index, look there first to determine which modules
1429 // provably do not have any results for this identifier.
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001430 GlobalModuleIndex::HitSet Hits;
1431 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001432 if (!loadGlobalIndex()) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001433 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1434 HitsPtr = &Hits;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001435 }
1436 }
1437
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001438 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregore1698072013-01-25 00:38:33 +00001439 NumIdentifierLookups,
1440 NumIdentifierLookupHits);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001441 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001442 markIdentifierUpToDate(&II);
1443}
1444
1445void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1446 if (!II)
1447 return;
1448
1449 II->setOutOfDate(false);
1450
1451 // Update the generation for this identifier.
1452 if (getContext().getLangOpts().Modules)
1453 IdentifierGeneration[II] = CurrentGeneration;
1454}
1455
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001456void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1457 const PendingMacroInfo &PMInfo) {
1458 assert(II);
1459
1460 if (PMInfo.M->Kind != MK_Module) {
1461 installPCHMacroDirectives(II, *PMInfo.M,
1462 PMInfo.PCHMacroData.MacroDirectivesOffset);
1463 return;
1464 }
1465
1466 // Module Macro.
1467
1468 GlobalMacroID GMacID = PMInfo.ModuleMacroData.GMacID;
1469 SourceLocation ImportLoc =
1470 SourceLocation::getFromRawEncoding(PMInfo.ModuleMacroData.ImportLoc);
1471
1472 assert(GMacID);
1473 // If this macro has already been loaded, don't do so again.
1474 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1475 return;
1476
1477 MacroInfo *MI = getMacro(GMacID);
1478 SubmoduleID SubModID = MI->getOwningModuleID();
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001479 MacroDirective *MD = PP.AllocateDefMacroDirective(MI, ImportLoc,
1480 /*isImported=*/true);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001481
1482 // Determine whether this macro definition is visible.
1483 bool Hidden = false;
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001484 Module *Owner = 0;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001485 if (SubModID) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001486 if ((Owner = getSubmodule(SubModID))) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001487 if (Owner->NameVisibility == Module::Hidden) {
1488 // The owning module is not visible, and this macro definition
1489 // should not be, either.
1490 Hidden = true;
1491
1492 // Note that this macro definition was hidden because its owning
1493 // module is not yet visible.
1494 HiddenNamesMap[Owner].push_back(HiddenName(II, MD));
1495 }
1496 }
1497 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001498
1499 if (!Hidden)
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001500 installImportedMacro(II, MD, Owner);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001501}
1502
1503void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1504 ModuleFile &M, uint64_t Offset) {
1505 assert(M.Kind != MK_Module);
1506
1507 BitstreamCursor &Cursor = M.MacroCursor;
1508 SavedStreamPosition SavedPosition(Cursor);
1509 Cursor.JumpToBit(Offset);
1510
1511 llvm::BitstreamEntry Entry =
1512 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1513 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1514 Error("malformed block record in AST file");
1515 return;
1516 }
1517
1518 RecordData Record;
1519 PreprocessorRecordTypes RecType =
1520 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1521 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1522 Error("malformed block record in AST file");
1523 return;
1524 }
1525
1526 // Deserialize the macro directives history in reverse source-order.
1527 MacroDirective *Latest = 0, *Earliest = 0;
1528 unsigned Idx = 0, N = Record.size();
1529 while (Idx < N) {
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001530 MacroDirective *MD = 0;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001531 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001532 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1533 switch (K) {
1534 case MacroDirective::MD_Define: {
1535 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1536 MacroInfo *MI = getMacro(GMacID);
1537 bool isImported = Record[Idx++];
1538 bool isAmbiguous = Record[Idx++];
1539 DefMacroDirective *DefMD =
1540 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1541 DefMD->setAmbiguous(isAmbiguous);
1542 MD = DefMD;
1543 break;
1544 }
1545 case MacroDirective::MD_Undefine:
1546 MD = PP.AllocateUndefMacroDirective(Loc);
1547 break;
1548 case MacroDirective::MD_Visibility: {
1549 bool isPublic = Record[Idx++];
1550 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1551 break;
1552 }
1553 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001554
1555 if (!Latest)
1556 Latest = MD;
1557 if (Earliest)
1558 Earliest->setPrevious(MD);
1559 Earliest = MD;
1560 }
1561
1562 PP.setLoadedMacroDirective(II, Latest);
1563}
1564
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001565/// \brief For the given macro definitions, check if they are both in system
1566/// modules and if one of the two is in the clang builtin headers.
1567static bool isSystemAndClangMacro(MacroInfo *PrevMI, MacroInfo *NewMI,
1568 Module *NewOwner, ASTReader &Reader) {
1569 assert(PrevMI && NewMI);
1570 if (!NewOwner)
1571 return false;
1572 Module *PrevOwner = 0;
1573 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1574 PrevOwner = Reader.getSubmodule(PrevModID);
1575 if (!PrevOwner)
1576 return false;
1577 if (PrevOwner == NewOwner)
1578 return false;
1579 if (!PrevOwner->IsSystem || !NewOwner->IsSystem)
1580 return false;
1581
1582 SourceManager &SM = Reader.getSourceManager();
1583 FileID PrevFID = SM.getFileID(PrevMI->getDefinitionLoc());
1584 FileID NewFID = SM.getFileID(NewMI->getDefinitionLoc());
1585 const FileEntry *PrevFE = SM.getFileEntryForID(PrevFID);
1586 const FileEntry *NewFE = SM.getFileEntryForID(NewFID);
1587 if (PrevFE == 0 || NewFE == 0)
1588 return false;
1589
1590 Preprocessor &PP = Reader.getPreprocessor();
1591 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
1592 const DirectoryEntry *BuiltinDir = ModMap.getBuiltinIncludeDir();
1593
1594 return (PrevFE->getDir() == BuiltinDir) != (NewFE->getDir() == BuiltinDir);
1595}
1596
1597void ASTReader::installImportedMacro(IdentifierInfo *II, MacroDirective *MD,
1598 Module *Owner) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001599 assert(II && MD);
1600
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001601 DefMacroDirective *DefMD = cast<DefMacroDirective>(MD);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001602 MacroDirective *Prev = PP.getMacroDirective(II);
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001603 if (Prev) {
1604 MacroDirective::DefInfo PrevDef = Prev->getDefinition();
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001605 MacroInfo *PrevMI = PrevDef.getMacroInfo();
1606 MacroInfo *NewMI = DefMD->getInfo();
1607 if (NewMI != PrevMI && !PrevMI->isIdenticalTo(*NewMI, PP)) {
1608 // Before marking the macros as ambiguous, check if this is a case where
1609 // the system macro uses a not identical definition compared to a macro
1610 // from the clang headers. For example:
1611 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1612 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
1613 // in which case don't mark them to avoid the "ambiguous macro expansion"
1614 // warning.
1615 // FIXME: This should go away if the system headers get "fixed" to use
1616 // identical definitions.
1617 if (!isSystemAndClangMacro(PrevMI, NewMI, Owner, *this)) {
1618 PrevDef.getDirective()->setAmbiguous(true);
1619 DefMD->setAmbiguous(true);
1620 }
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001621 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001622 }
1623
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001624 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001625}
1626
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001627InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001628 // If this ID is bogus, just return an empty input file.
1629 if (ID == 0 || ID > F.InputFilesLoaded.size())
1630 return InputFile();
1631
1632 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001633 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001634 return F.InputFilesLoaded[ID-1];
1635
1636 // Go find this input file.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001637 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001638 SavedStreamPosition SavedPosition(Cursor);
1639 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1640
1641 unsigned Code = Cursor.ReadCode();
1642 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001643 StringRef Blob;
1644 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001645 case INPUT_FILE: {
1646 unsigned StoredID = Record[0];
1647 assert(ID == StoredID && "Bogus stored ID or offset");
1648 (void)StoredID;
1649 off_t StoredSize = (off_t)Record[1];
1650 time_t StoredTime = (time_t)Record[2];
1651 bool Overridden = (bool)Record[3];
1652
1653 // Get the file entry for this input file.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001654 StringRef OrigFilename = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001655 std::string Filename = OrigFilename;
1656 MaybeAddSystemRootToFilename(F, Filename);
1657 const FileEntry *File
1658 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1659 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1660
1661 // If we didn't find the file, resolve it relative to the
1662 // original directory from which this AST file was created.
1663 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1664 F.OriginalDir != CurrentDir) {
1665 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1666 F.OriginalDir,
1667 CurrentDir);
1668 if (!Resolved.empty())
1669 File = FileMgr.getFile(Resolved);
1670 }
1671
1672 // For an overridden file, create a virtual file with the stored
1673 // size/timestamp.
1674 if (Overridden && File == 0) {
1675 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1676 }
1677
1678 if (File == 0) {
1679 if (Complain) {
1680 std::string ErrorStr = "could not find file '";
1681 ErrorStr += Filename;
1682 ErrorStr += "' referenced by AST file";
1683 Error(ErrorStr.c_str());
1684 }
1685 return InputFile();
1686 }
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001687
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001688 // Check if there was a request to override the contents of the file
1689 // that was part of the precompiled header. Overridding such a file
1690 // can lead to problems when lexing using the source locations from the
1691 // PCH.
1692 SourceManager &SM = getSourceManager();
1693 if (!Overridden && SM.isFileOverridden(File)) {
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001694 if (Complain)
1695 Error(diag::err_fe_pch_file_overridden, Filename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001696 // After emitting the diagnostic, recover by disabling the override so
1697 // that the original file will be used.
1698 SM.disableFileContentsOverride(File);
1699 // The FileEntry is a virtual file entry with the size of the contents
1700 // that would override the original contents. Set it to the original's
1701 // size/time.
1702 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1703 StoredSize, StoredTime);
1704 }
1705
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001706 bool IsOutOfDate = false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001707
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001708 // For an overridden file, there is nothing to validate.
1709 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001710#if !defined(LLVM_ON_WIN32)
1711 // In our regression testing, the Windows file system seems to
1712 // have inconsistent modification times that sometimes
1713 // erroneously trigger this error-handling path.
1714 || StoredTime != File->getModificationTime()
1715#endif
1716 )) {
Douglas Gregor677e15f2013-03-19 00:28:20 +00001717 if (Complain) {
Argyrios Kyrtzidisf8f373f2013-03-08 20:42:38 +00001718 Error(diag::err_fe_pch_file_modified, Filename, F.FileName);
Douglas Gregor677e15f2013-03-19 00:28:20 +00001719 }
1720
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001721 IsOutOfDate = true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001722 }
1723
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001724 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
1725
1726 // Note that we've loaded this input file.
1727 F.InputFilesLoaded[ID-1] = IF;
1728 return IF;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001729 }
1730 }
1731
1732 return InputFile();
1733}
1734
1735const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
1736 ModuleFile &M = ModuleMgr.getPrimaryModule();
1737 std::string Filename = filenameStrRef;
1738 MaybeAddSystemRootToFilename(M, Filename);
1739 const FileEntry *File = FileMgr.getFile(Filename);
1740 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
1741 M.OriginalDir != CurrentDir) {
1742 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1743 M.OriginalDir,
1744 CurrentDir);
1745 if (!resolved.empty())
1746 File = FileMgr.getFile(resolved);
1747 }
1748
1749 return File;
1750}
1751
1752/// \brief If we are loading a relocatable PCH file, and the filename is
1753/// not an absolute path, add the system root to the beginning of the file
1754/// name.
1755void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
1756 std::string &Filename) {
1757 // If this is not a relocatable PCH file, there's nothing to do.
1758 if (!M.RelocatablePCH)
1759 return;
1760
1761 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
1762 return;
1763
1764 if (isysroot.empty()) {
1765 // If no system root was given, default to '/'
1766 Filename.insert(Filename.begin(), '/');
1767 return;
1768 }
1769
1770 unsigned Length = isysroot.size();
1771 if (isysroot[Length - 1] != '/')
1772 Filename.insert(Filename.begin(), '/');
1773
1774 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
1775}
1776
1777ASTReader::ASTReadResult
1778ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001779 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001780 unsigned ClientLoadCapabilities) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001781 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001782
1783 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
1784 Error("malformed block record in AST file");
1785 return Failure;
1786 }
1787
1788 // Read all of the records and blocks in the control block.
1789 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00001790 while (1) {
1791 llvm::BitstreamEntry Entry = Stream.advance();
1792
1793 switch (Entry.Kind) {
1794 case llvm::BitstreamEntry::Error:
1795 Error("malformed block record in AST file");
1796 return Failure;
1797 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001798 // Validate all of the non-system input files.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001799 if (!DisableValidation) {
1800 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001801 // All user input files reside at the index range [0, Record[1]).
1802 // Record is the one from INPUT_FILE_OFFSETS.
1803 for (unsigned I = 0, N = Record[1]; I < N; ++I) {
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001804 InputFile IF = getInputFile(F, I+1, Complain);
1805 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001806 return OutOfDate;
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001807 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001808 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001809 return Success;
Chris Lattner88bde502013-01-19 21:39:22 +00001810
1811 case llvm::BitstreamEntry::SubBlock:
1812 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001813 case INPUT_FILES_BLOCK_ID:
1814 F.InputFilesCursor = Stream;
1815 if (Stream.SkipBlock() || // Skip with the main cursor
1816 // Read the abbreviations
1817 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
1818 Error("malformed block record in AST file");
1819 return Failure;
1820 }
1821 continue;
Chris Lattner88bde502013-01-19 21:39:22 +00001822
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001823 default:
Chris Lattner88bde502013-01-19 21:39:22 +00001824 if (Stream.SkipBlock()) {
1825 Error("malformed block record in AST file");
1826 return Failure;
1827 }
1828 continue;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001829 }
Chris Lattner88bde502013-01-19 21:39:22 +00001830
1831 case llvm::BitstreamEntry::Record:
1832 // The interesting case.
1833 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001834 }
1835
1836 // Read and process a record.
1837 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001838 StringRef Blob;
1839 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001840 case METADATA: {
1841 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1842 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
1843 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1844 : diag::warn_pch_version_too_new);
1845 return VersionMismatch;
1846 }
1847
1848 bool hasErrors = Record[5];
1849 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
1850 Diag(diag::err_pch_with_compiler_errors);
1851 return HadErrors;
1852 }
1853
1854 F.RelocatablePCH = Record[4];
1855
1856 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001857 StringRef ASTBranch = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001858 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
1859 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
1860 Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
1861 return VersionMismatch;
1862 }
1863 break;
1864 }
1865
1866 case IMPORTS: {
1867 // Load each of the imported PCH files.
1868 unsigned Idx = 0, N = Record.size();
1869 while (Idx < N) {
1870 // Read information about the AST file.
1871 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
1872 // The import location will be the local one for now; we will adjust
1873 // all import locations of module imports after the global source
1874 // location info are setup.
1875 SourceLocation ImportLoc =
1876 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor677e15f2013-03-19 00:28:20 +00001877 off_t StoredSize = (off_t)Record[Idx++];
1878 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001879 unsigned Length = Record[Idx++];
1880 SmallString<128> ImportedFile(Record.begin() + Idx,
1881 Record.begin() + Idx + Length);
1882 Idx += Length;
1883
1884 // Load the AST file.
1885 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor677e15f2013-03-19 00:28:20 +00001886 StoredSize, StoredModTime,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001887 ClientLoadCapabilities)) {
1888 case Failure: return Failure;
1889 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregorac39f132013-03-19 00:38:50 +00001890 case Missing:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001891 case OutOfDate: return OutOfDate;
1892 case VersionMismatch: return VersionMismatch;
1893 case ConfigurationMismatch: return ConfigurationMismatch;
1894 case HadErrors: return HadErrors;
1895 case Success: break;
1896 }
1897 }
1898 break;
1899 }
1900
1901 case LANGUAGE_OPTIONS: {
1902 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
1903 if (Listener && &F == *ModuleMgr.begin() &&
1904 ParseLanguageOptions(Record, Complain, *Listener) &&
1905 !DisableValidation)
1906 return ConfigurationMismatch;
1907 break;
1908 }
1909
1910 case TARGET_OPTIONS: {
1911 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1912 if (Listener && &F == *ModuleMgr.begin() &&
1913 ParseTargetOptions(Record, Complain, *Listener) &&
1914 !DisableValidation)
1915 return ConfigurationMismatch;
1916 break;
1917 }
1918
1919 case DIAGNOSTIC_OPTIONS: {
1920 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1921 if (Listener && &F == *ModuleMgr.begin() &&
1922 ParseDiagnosticOptions(Record, Complain, *Listener) &&
1923 !DisableValidation)
1924 return ConfigurationMismatch;
1925 break;
1926 }
1927
1928 case FILE_SYSTEM_OPTIONS: {
1929 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1930 if (Listener && &F == *ModuleMgr.begin() &&
1931 ParseFileSystemOptions(Record, Complain, *Listener) &&
1932 !DisableValidation)
1933 return ConfigurationMismatch;
1934 break;
1935 }
1936
1937 case HEADER_SEARCH_OPTIONS: {
1938 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1939 if (Listener && &F == *ModuleMgr.begin() &&
1940 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
1941 !DisableValidation)
1942 return ConfigurationMismatch;
1943 break;
1944 }
1945
1946 case PREPROCESSOR_OPTIONS: {
1947 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1948 if (Listener && &F == *ModuleMgr.begin() &&
1949 ParsePreprocessorOptions(Record, Complain, *Listener,
1950 SuggestedPredefines) &&
1951 !DisableValidation)
1952 return ConfigurationMismatch;
1953 break;
1954 }
1955
1956 case ORIGINAL_FILE:
1957 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001958 F.ActualOriginalSourceFileName = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001959 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
1960 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
1961 break;
1962
1963 case ORIGINAL_FILE_ID:
1964 F.OriginalSourceFileID = FileID::get(Record[0]);
1965 break;
1966
1967 case ORIGINAL_PCH_DIR:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001968 F.OriginalDir = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001969 break;
1970
1971 case INPUT_FILE_OFFSETS:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001972 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001973 F.InputFilesLoaded.resize(Record[0]);
1974 break;
1975 }
1976 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001977}
1978
1979bool ASTReader::ReadASTBlock(ModuleFile &F) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001980 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001981
1982 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
1983 Error("malformed block record in AST file");
1984 return true;
1985 }
1986
1987 // Read all of the records and blocks for the AST file.
1988 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00001989 while (1) {
1990 llvm::BitstreamEntry Entry = Stream.advance();
1991
1992 switch (Entry.Kind) {
1993 case llvm::BitstreamEntry::Error:
1994 Error("error at end of module block in AST file");
1995 return true;
1996 case llvm::BitstreamEntry::EndBlock: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001997 DeclContext *DC = Context.getTranslationUnitDecl();
1998 if (!DC->hasExternalVisibleStorage() && DC->hasExternalLexicalStorage())
1999 DC->setMustBuildLookupTable();
Chris Lattner88bde502013-01-19 21:39:22 +00002000
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002001 return false;
2002 }
Chris Lattner88bde502013-01-19 21:39:22 +00002003 case llvm::BitstreamEntry::SubBlock:
2004 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002005 case DECLTYPES_BLOCK_ID:
2006 // We lazily load the decls block, but we want to set up the
2007 // DeclsCursor cursor to point into it. Clone our current bitcode
2008 // cursor to it, enter the block and read the abbrevs in that block.
2009 // With the main cursor, we just skip over it.
2010 F.DeclsCursor = Stream;
2011 if (Stream.SkipBlock() || // Skip with the main cursor.
2012 // Read the abbrevs.
2013 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2014 Error("malformed block record in AST file");
2015 return true;
2016 }
2017 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002018
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002019 case DECL_UPDATES_BLOCK_ID:
2020 if (Stream.SkipBlock()) {
2021 Error("malformed block record in AST file");
2022 return true;
2023 }
2024 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002025
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002026 case PREPROCESSOR_BLOCK_ID:
2027 F.MacroCursor = Stream;
2028 if (!PP.getExternalSource())
2029 PP.setExternalSource(this);
Chris Lattner88bde502013-01-19 21:39:22 +00002030
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002031 if (Stream.SkipBlock() ||
2032 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2033 Error("malformed block record in AST file");
2034 return true;
2035 }
2036 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2037 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002038
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002039 case PREPROCESSOR_DETAIL_BLOCK_ID:
2040 F.PreprocessorDetailCursor = Stream;
2041 if (Stream.SkipBlock() ||
Chris Lattner88bde502013-01-19 21:39:22 +00002042 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002043 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattner88bde502013-01-19 21:39:22 +00002044 Error("malformed preprocessor detail record in AST file");
2045 return true;
2046 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002047 F.PreprocessorDetailStartOffset
Chris Lattner88bde502013-01-19 21:39:22 +00002048 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2049
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002050 if (!PP.getPreprocessingRecord())
2051 PP.createPreprocessingRecord();
2052 if (!PP.getPreprocessingRecord()->getExternalSource())
2053 PP.getPreprocessingRecord()->SetExternalSource(*this);
2054 break;
2055
2056 case SOURCE_MANAGER_BLOCK_ID:
2057 if (ReadSourceManagerBlock(F))
2058 return true;
2059 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002060
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002061 case SUBMODULE_BLOCK_ID:
2062 if (ReadSubmoduleBlock(F))
2063 return true;
2064 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002065
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002066 case COMMENTS_BLOCK_ID: {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00002067 BitstreamCursor C = Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002068 if (Stream.SkipBlock() ||
2069 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2070 Error("malformed comments block in AST file");
2071 return true;
2072 }
2073 CommentsCursors.push_back(std::make_pair(C, &F));
2074 break;
2075 }
Chris Lattner88bde502013-01-19 21:39:22 +00002076
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002077 default:
Chris Lattner88bde502013-01-19 21:39:22 +00002078 if (Stream.SkipBlock()) {
2079 Error("malformed block record in AST file");
2080 return true;
2081 }
2082 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002083 }
2084 continue;
Chris Lattner88bde502013-01-19 21:39:22 +00002085
2086 case llvm::BitstreamEntry::Record:
2087 // The interesting case.
2088 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002089 }
2090
2091 // Read and process a record.
2092 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002093 StringRef Blob;
2094 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002095 default: // Default behavior: ignore.
2096 break;
2097
2098 case TYPE_OFFSET: {
2099 if (F.LocalNumTypes != 0) {
2100 Error("duplicate TYPE_OFFSET record in AST file");
2101 return true;
2102 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002103 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002104 F.LocalNumTypes = Record[0];
2105 unsigned LocalBaseTypeIndex = Record[1];
2106 F.BaseTypeIndex = getTotalNumTypes();
2107
2108 if (F.LocalNumTypes > 0) {
2109 // Introduce the global -> local mapping for types within this module.
2110 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2111
2112 // Introduce the local -> global mapping for types within this module.
2113 F.TypeRemap.insertOrReplace(
2114 std::make_pair(LocalBaseTypeIndex,
2115 F.BaseTypeIndex - LocalBaseTypeIndex));
2116
2117 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2118 }
2119 break;
2120 }
2121
2122 case DECL_OFFSET: {
2123 if (F.LocalNumDecls != 0) {
2124 Error("duplicate DECL_OFFSET record in AST file");
2125 return true;
2126 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002127 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002128 F.LocalNumDecls = Record[0];
2129 unsigned LocalBaseDeclID = Record[1];
2130 F.BaseDeclID = getTotalNumDecls();
2131
2132 if (F.LocalNumDecls > 0) {
2133 // Introduce the global -> local mapping for declarations within this
2134 // module.
2135 GlobalDeclMap.insert(
2136 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2137
2138 // Introduce the local -> global mapping for declarations within this
2139 // module.
2140 F.DeclRemap.insertOrReplace(
2141 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2142
2143 // Introduce the global -> local mapping for declarations within this
2144 // module.
2145 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2146
2147 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2148 }
2149 break;
2150 }
2151
2152 case TU_UPDATE_LEXICAL: {
2153 DeclContext *TU = Context.getTranslationUnitDecl();
2154 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002155 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002156 Info.NumLexicalDecls
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002157 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002158 TU->setHasExternalLexicalStorage(true);
2159 break;
2160 }
2161
2162 case UPDATE_VISIBLE: {
2163 unsigned Idx = 0;
2164 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2165 ASTDeclContextNameLookupTable *Table =
2166 ASTDeclContextNameLookupTable::Create(
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002167 (const unsigned char *)Blob.data() + Record[Idx++],
2168 (const unsigned char *)Blob.data(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002169 ASTDeclContextNameLookupTrait(*this, F));
2170 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2171 DeclContext *TU = Context.getTranslationUnitDecl();
2172 F.DeclContextInfos[TU].NameLookupTableData = Table;
2173 TU->setHasExternalVisibleStorage(true);
2174 } else
2175 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2176 break;
2177 }
2178
2179 case IDENTIFIER_TABLE:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002180 F.IdentifierTableData = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002181 if (Record[0]) {
2182 F.IdentifierLookupTable
2183 = ASTIdentifierLookupTable::Create(
2184 (const unsigned char *)F.IdentifierTableData + Record[0],
2185 (const unsigned char *)F.IdentifierTableData,
2186 ASTIdentifierLookupTrait(*this, F));
2187
2188 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2189 }
2190 break;
2191
2192 case IDENTIFIER_OFFSET: {
2193 if (F.LocalNumIdentifiers != 0) {
2194 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2195 return true;
2196 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002197 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002198 F.LocalNumIdentifiers = Record[0];
2199 unsigned LocalBaseIdentifierID = Record[1];
2200 F.BaseIdentifierID = getTotalNumIdentifiers();
2201
2202 if (F.LocalNumIdentifiers > 0) {
2203 // Introduce the global -> local mapping for identifiers within this
2204 // module.
2205 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2206 &F));
2207
2208 // Introduce the local -> global mapping for identifiers within this
2209 // module.
2210 F.IdentifierRemap.insertOrReplace(
2211 std::make_pair(LocalBaseIdentifierID,
2212 F.BaseIdentifierID - LocalBaseIdentifierID));
2213
2214 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2215 + F.LocalNumIdentifiers);
2216 }
2217 break;
2218 }
2219
2220 case EXTERNAL_DEFINITIONS:
2221 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2222 ExternalDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2223 break;
2224
2225 case SPECIAL_TYPES:
Douglas Gregorf5cfc892013-02-01 23:45:03 +00002226 if (SpecialTypes.empty()) {
2227 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2228 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2229 break;
2230 }
2231
2232 if (SpecialTypes.size() != Record.size()) {
2233 Error("invalid special-types record");
2234 return true;
2235 }
2236
2237 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2238 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2239 if (!SpecialTypes[I])
2240 SpecialTypes[I] = ID;
2241 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2242 // merge step?
2243 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002244 break;
2245
2246 case STATISTICS:
2247 TotalNumStatements += Record[0];
2248 TotalNumMacros += Record[1];
2249 TotalLexicalDeclContexts += Record[2];
2250 TotalVisibleDeclContexts += Record[3];
2251 break;
2252
2253 case UNUSED_FILESCOPED_DECLS:
2254 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2255 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2256 break;
2257
2258 case DELEGATING_CTORS:
2259 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2260 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2261 break;
2262
2263 case WEAK_UNDECLARED_IDENTIFIERS:
2264 if (Record.size() % 4 != 0) {
2265 Error("invalid weak identifiers record");
2266 return true;
2267 }
2268
2269 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2270 // files. This isn't the way to do it :)
2271 WeakUndeclaredIdentifiers.clear();
2272
2273 // Translate the weak, undeclared identifiers into global IDs.
2274 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2275 WeakUndeclaredIdentifiers.push_back(
2276 getGlobalIdentifierID(F, Record[I++]));
2277 WeakUndeclaredIdentifiers.push_back(
2278 getGlobalIdentifierID(F, Record[I++]));
2279 WeakUndeclaredIdentifiers.push_back(
2280 ReadSourceLocation(F, Record, I).getRawEncoding());
2281 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2282 }
2283 break;
2284
Richard Smith5ea6ef42013-01-10 23:43:47 +00002285 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002286 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith5ea6ef42013-01-10 23:43:47 +00002287 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002288 break;
2289
2290 case SELECTOR_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002291 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002292 F.LocalNumSelectors = Record[0];
2293 unsigned LocalBaseSelectorID = Record[1];
2294 F.BaseSelectorID = getTotalNumSelectors();
2295
2296 if (F.LocalNumSelectors > 0) {
2297 // Introduce the global -> local mapping for selectors within this
2298 // module.
2299 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2300
2301 // Introduce the local -> global mapping for selectors within this
2302 // module.
2303 F.SelectorRemap.insertOrReplace(
2304 std::make_pair(LocalBaseSelectorID,
2305 F.BaseSelectorID - LocalBaseSelectorID));
2306
2307 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2308 }
2309 break;
2310 }
2311
2312 case METHOD_POOL:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002313 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002314 if (Record[0])
2315 F.SelectorLookupTable
2316 = ASTSelectorLookupTable::Create(
2317 F.SelectorLookupTableData + Record[0],
2318 F.SelectorLookupTableData,
2319 ASTSelectorLookupTrait(*this, F));
2320 TotalNumMethodPoolEntries += Record[1];
2321 break;
2322
2323 case REFERENCED_SELECTOR_POOL:
2324 if (!Record.empty()) {
2325 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2326 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2327 Record[Idx++]));
2328 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2329 getRawEncoding());
2330 }
2331 }
2332 break;
2333
2334 case PP_COUNTER_VALUE:
2335 if (!Record.empty() && Listener)
2336 Listener->ReadCounter(F, Record[0]);
2337 break;
2338
2339 case FILE_SORTED_DECLS:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002340 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002341 F.NumFileSortedDecls = Record[0];
2342 break;
2343
2344 case SOURCE_LOCATION_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002345 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002346 F.LocalNumSLocEntries = Record[0];
2347 unsigned SLocSpaceSize = Record[1];
2348 llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2349 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2350 SLocSpaceSize);
2351 // Make our entry in the range map. BaseID is negative and growing, so
2352 // we invert it. Because we invert it, though, we need the other end of
2353 // the range.
2354 unsigned RangeStart =
2355 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2356 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2357 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2358
2359 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2360 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2361 GlobalSLocOffsetMap.insert(
2362 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2363 - SLocSpaceSize,&F));
2364
2365 // Initialize the remapping table.
2366 // Invalid stays invalid.
2367 F.SLocRemap.insert(std::make_pair(0U, 0));
2368 // This module. Base was 2 when being compiled.
2369 F.SLocRemap.insert(std::make_pair(2U,
2370 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2371
2372 TotalNumSLocEntries += F.LocalNumSLocEntries;
2373 break;
2374 }
2375
2376 case MODULE_OFFSET_MAP: {
2377 // Additional remapping information.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002378 const unsigned char *Data = (const unsigned char*)Blob.data();
2379 const unsigned char *DataEnd = Data + Blob.size();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002380
2381 // Continuous range maps we may be updating in our module.
2382 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2383 ContinuousRangeMap<uint32_t, int, 2>::Builder
2384 IdentifierRemap(F.IdentifierRemap);
2385 ContinuousRangeMap<uint32_t, int, 2>::Builder
2386 MacroRemap(F.MacroRemap);
2387 ContinuousRangeMap<uint32_t, int, 2>::Builder
2388 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2389 ContinuousRangeMap<uint32_t, int, 2>::Builder
2390 SubmoduleRemap(F.SubmoduleRemap);
2391 ContinuousRangeMap<uint32_t, int, 2>::Builder
2392 SelectorRemap(F.SelectorRemap);
2393 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2394 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2395
2396 while(Data < DataEnd) {
2397 uint16_t Len = io::ReadUnalignedLE16(Data);
2398 StringRef Name = StringRef((const char*)Data, Len);
2399 Data += Len;
2400 ModuleFile *OM = ModuleMgr.lookup(Name);
2401 if (!OM) {
2402 Error("SourceLocation remap refers to unknown module");
2403 return true;
2404 }
2405
2406 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2407 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2408 uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
2409 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2410 uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
2411 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2412 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2413 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2414
2415 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2416 SLocRemap.insert(std::make_pair(SLocOffset,
2417 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2418 IdentifierRemap.insert(
2419 std::make_pair(IdentifierIDOffset,
2420 OM->BaseIdentifierID - IdentifierIDOffset));
2421 MacroRemap.insert(std::make_pair(MacroIDOffset,
2422 OM->BaseMacroID - MacroIDOffset));
2423 PreprocessedEntityRemap.insert(
2424 std::make_pair(PreprocessedEntityIDOffset,
2425 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2426 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2427 OM->BaseSubmoduleID - SubmoduleIDOffset));
2428 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2429 OM->BaseSelectorID - SelectorIDOffset));
2430 DeclRemap.insert(std::make_pair(DeclIDOffset,
2431 OM->BaseDeclID - DeclIDOffset));
2432
2433 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2434 OM->BaseTypeIndex - TypeIndexOffset));
2435
2436 // Global -> local mappings.
2437 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2438 }
2439 break;
2440 }
2441
2442 case SOURCE_MANAGER_LINE_TABLE:
2443 if (ParseLineTable(F, Record))
2444 return true;
2445 break;
2446
2447 case SOURCE_LOCATION_PRELOADS: {
2448 // Need to transform from the local view (1-based IDs) to the global view,
2449 // which is based off F.SLocEntryBaseID.
2450 if (!F.PreloadSLocEntries.empty()) {
2451 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2452 return true;
2453 }
2454
2455 F.PreloadSLocEntries.swap(Record);
2456 break;
2457 }
2458
2459 case EXT_VECTOR_DECLS:
2460 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2461 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2462 break;
2463
2464 case VTABLE_USES:
2465 if (Record.size() % 3 != 0) {
2466 Error("Invalid VTABLE_USES record");
2467 return true;
2468 }
2469
2470 // Later tables overwrite earlier ones.
2471 // FIXME: Modules will have some trouble with this. This is clearly not
2472 // the right way to do this.
2473 VTableUses.clear();
2474
2475 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2476 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2477 VTableUses.push_back(
2478 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2479 VTableUses.push_back(Record[Idx++]);
2480 }
2481 break;
2482
2483 case DYNAMIC_CLASSES:
2484 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2485 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2486 break;
2487
2488 case PENDING_IMPLICIT_INSTANTIATIONS:
2489 if (PendingInstantiations.size() % 2 != 0) {
2490 Error("Invalid existing PendingInstantiations");
2491 return true;
2492 }
2493
2494 if (Record.size() % 2 != 0) {
2495 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2496 return true;
2497 }
2498
2499 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2500 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2501 PendingInstantiations.push_back(
2502 ReadSourceLocation(F, Record, I).getRawEncoding());
2503 }
2504 break;
2505
2506 case SEMA_DECL_REFS:
2507 // Later tables overwrite earlier ones.
2508 // FIXME: Modules will have some trouble with this.
2509 SemaDeclRefs.clear();
2510 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2511 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2512 break;
2513
2514 case PPD_ENTITIES_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002515 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2516 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2517 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002518
2519 unsigned LocalBasePreprocessedEntityID = Record[0];
2520
2521 unsigned StartingID;
2522 if (!PP.getPreprocessingRecord())
2523 PP.createPreprocessingRecord();
2524 if (!PP.getPreprocessingRecord()->getExternalSource())
2525 PP.getPreprocessingRecord()->SetExternalSource(*this);
2526 StartingID
2527 = PP.getPreprocessingRecord()
2528 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2529 F.BasePreprocessedEntityID = StartingID;
2530
2531 if (F.NumPreprocessedEntities > 0) {
2532 // Introduce the global -> local mapping for preprocessed entities in
2533 // this module.
2534 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2535
2536 // Introduce the local -> global mapping for preprocessed entities in
2537 // this module.
2538 F.PreprocessedEntityRemap.insertOrReplace(
2539 std::make_pair(LocalBasePreprocessedEntityID,
2540 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2541 }
2542
2543 break;
2544 }
2545
2546 case DECL_UPDATE_OFFSETS: {
2547 if (Record.size() % 2 != 0) {
2548 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2549 return true;
2550 }
2551 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2552 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2553 .push_back(std::make_pair(&F, Record[I+1]));
2554 break;
2555 }
2556
2557 case DECL_REPLACEMENTS: {
2558 if (Record.size() % 3 != 0) {
2559 Error("invalid DECL_REPLACEMENTS block in AST file");
2560 return true;
2561 }
2562 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2563 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2564 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2565 break;
2566 }
2567
2568 case OBJC_CATEGORIES_MAP: {
2569 if (F.LocalNumObjCCategoriesInMap != 0) {
2570 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2571 return true;
2572 }
2573
2574 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002575 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002576 break;
2577 }
2578
2579 case OBJC_CATEGORIES:
2580 F.ObjCCategories.swap(Record);
2581 break;
2582
2583 case CXX_BASE_SPECIFIER_OFFSETS: {
2584 if (F.LocalNumCXXBaseSpecifiers != 0) {
2585 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2586 return true;
2587 }
2588
2589 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002590 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002591 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2592 break;
2593 }
2594
2595 case DIAG_PRAGMA_MAPPINGS:
2596 if (F.PragmaDiagMappings.empty())
2597 F.PragmaDiagMappings.swap(Record);
2598 else
2599 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2600 Record.begin(), Record.end());
2601 break;
2602
2603 case CUDA_SPECIAL_DECL_REFS:
2604 // Later tables overwrite earlier ones.
2605 // FIXME: Modules will have trouble with this.
2606 CUDASpecialDeclRefs.clear();
2607 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2608 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2609 break;
2610
2611 case HEADER_SEARCH_TABLE: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002612 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002613 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002614 if (Record[0]) {
2615 F.HeaderFileInfoTable
2616 = HeaderFileInfoLookupTable::Create(
2617 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2618 (const unsigned char *)F.HeaderFileInfoTableData,
2619 HeaderFileInfoTrait(*this, F,
2620 &PP.getHeaderSearchInfo(),
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002621 Blob.data() + Record[2]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002622
2623 PP.getHeaderSearchInfo().SetExternalSource(this);
2624 if (!PP.getHeaderSearchInfo().getExternalLookup())
2625 PP.getHeaderSearchInfo().SetExternalLookup(this);
2626 }
2627 break;
2628 }
2629
2630 case FP_PRAGMA_OPTIONS:
2631 // Later tables overwrite earlier ones.
2632 FPPragmaOptions.swap(Record);
2633 break;
2634
2635 case OPENCL_EXTENSIONS:
2636 // Later tables overwrite earlier ones.
2637 OpenCLExtensions.swap(Record);
2638 break;
2639
2640 case TENTATIVE_DEFINITIONS:
2641 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2642 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2643 break;
2644
2645 case KNOWN_NAMESPACES:
2646 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2647 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2648 break;
Nick Lewycky01a41142013-01-26 00:35:08 +00002649
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002650 case UNDEFINED_BUT_USED:
2651 if (UndefinedButUsed.size() % 2 != 0) {
2652 Error("Invalid existing UndefinedButUsed");
Nick Lewycky01a41142013-01-26 00:35:08 +00002653 return true;
2654 }
2655
2656 if (Record.size() % 2 != 0) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002657 Error("invalid undefined-but-used record");
Nick Lewycky01a41142013-01-26 00:35:08 +00002658 return true;
2659 }
2660 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002661 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
2662 UndefinedButUsed.push_back(
Nick Lewycky01a41142013-01-26 00:35:08 +00002663 ReadSourceLocation(F, Record, I).getRawEncoding());
2664 }
2665 break;
2666
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002667 case IMPORTED_MODULES: {
2668 if (F.Kind != MK_Module) {
2669 // If we aren't loading a module (which has its own exports), make
2670 // all of the imported modules visible.
2671 // FIXME: Deal with macros-only imports.
2672 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2673 if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
2674 ImportedModules.push_back(GlobalID);
2675 }
2676 }
2677 break;
2678 }
2679
2680 case LOCAL_REDECLARATIONS: {
2681 F.RedeclarationChains.swap(Record);
2682 break;
2683 }
2684
2685 case LOCAL_REDECLARATIONS_MAP: {
2686 if (F.LocalNumRedeclarationsInMap != 0) {
2687 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
2688 return true;
2689 }
2690
2691 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002692 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002693 break;
2694 }
2695
2696 case MERGED_DECLARATIONS: {
2697 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
2698 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
2699 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
2700 for (unsigned N = Record[Idx++]; N > 0; --N)
2701 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
2702 }
2703 break;
2704 }
2705
2706 case MACRO_OFFSET: {
2707 if (F.LocalNumMacros != 0) {
2708 Error("duplicate MACRO_OFFSET record in AST file");
2709 return true;
2710 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002711 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002712 F.LocalNumMacros = Record[0];
2713 unsigned LocalBaseMacroID = Record[1];
2714 F.BaseMacroID = getTotalNumMacros();
2715
2716 if (F.LocalNumMacros > 0) {
2717 // Introduce the global -> local mapping for macros within this module.
2718 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
2719
2720 // Introduce the local -> global mapping for macros within this module.
2721 F.MacroRemap.insertOrReplace(
2722 std::make_pair(LocalBaseMacroID,
2723 F.BaseMacroID - LocalBaseMacroID));
2724
2725 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
2726 }
2727 break;
2728 }
2729
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00002730 case MACRO_TABLE: {
2731 // FIXME: Not used yet.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002732 break;
2733 }
2734 }
2735 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002736}
2737
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002738/// \brief Move the given method to the back of the global list of methods.
2739static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
2740 // Find the entry for this selector in the method pool.
2741 Sema::GlobalMethodPool::iterator Known
2742 = S.MethodPool.find(Method->getSelector());
2743 if (Known == S.MethodPool.end())
2744 return;
2745
2746 // Retrieve the appropriate method list.
2747 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
2748 : Known->second.second;
2749 bool Found = false;
2750 for (ObjCMethodList *List = &Start; List; List = List->Next) {
2751 if (!Found) {
2752 if (List->Method == Method) {
2753 Found = true;
2754 } else {
2755 // Keep searching.
2756 continue;
2757 }
2758 }
2759
2760 if (List->Next)
2761 List->Method = List->Next->Method;
2762 else
2763 List->Method = Method;
2764 }
2765}
2766
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00002767void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002768 for (unsigned I = 0, N = Names.size(); I != N; ++I) {
2769 switch (Names[I].getKind()) {
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002770 case HiddenName::Declaration: {
2771 Decl *D = Names[I].getDecl();
2772 bool wasHidden = D->Hidden;
2773 D->Hidden = false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002774
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002775 if (wasHidden && SemaObj) {
2776 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
2777 moveMethodToBackOfGlobalList(*SemaObj, Method);
2778 }
2779 }
2780 break;
2781 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002782 case HiddenName::MacroVisibility: {
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00002783 std::pair<IdentifierInfo *, MacroDirective *> Macro = Names[I].getMacro();
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00002784 installImportedMacro(Macro.first, Macro.second, Owner);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002785 break;
2786 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002787 }
2788 }
2789}
2790
2791void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis5ebcb202013-02-01 16:36:12 +00002792 Module::NameVisibilityKind NameVisibility,
Douglas Gregor906d66a2013-03-20 21:10:35 +00002793 SourceLocation ImportLoc,
2794 bool Complain) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002795 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002796 SmallVector<Module *, 4> Stack;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002797 Stack.push_back(Mod);
2798 while (!Stack.empty()) {
2799 Mod = Stack.back();
2800 Stack.pop_back();
2801
2802 if (NameVisibility <= Mod->NameVisibility) {
2803 // This module already has this level of visibility (or greater), so
2804 // there is nothing more to do.
2805 continue;
2806 }
2807
2808 if (!Mod->isAvailable()) {
2809 // Modules that aren't available cannot be made visible.
2810 continue;
2811 }
2812
2813 // Update the module's name visibility.
2814 Mod->NameVisibility = NameVisibility;
2815
2816 // If we've already deserialized any names from this module,
2817 // mark them as visible.
2818 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
2819 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00002820 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002821 HiddenNamesMap.erase(Hidden);
2822 }
2823
2824 // Push any non-explicit submodules onto the stack to be marked as
2825 // visible.
2826 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2827 SubEnd = Mod->submodule_end();
2828 Sub != SubEnd; ++Sub) {
2829 if (!(*Sub)->IsExplicit && Visited.insert(*Sub))
2830 Stack.push_back(*Sub);
2831 }
2832
2833 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis21a00042013-02-19 19:34:40 +00002834 SmallVector<Module *, 16> Exports;
2835 Mod->getExportedModules(Exports);
2836 for (SmallVectorImpl<Module *>::iterator
2837 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
2838 Module *Exported = *I;
2839 if (Visited.insert(Exported))
2840 Stack.push_back(Exported);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002841 }
Douglas Gregor906d66a2013-03-20 21:10:35 +00002842
2843 // Detect any conflicts.
2844 if (Complain) {
2845 assert(ImportLoc.isValid() && "Missing import location");
2846 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
2847 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
2848 Diag(ImportLoc, diag::warn_module_conflict)
2849 << Mod->getFullModuleName()
2850 << Mod->Conflicts[I].Other->getFullModuleName()
2851 << Mod->Conflicts[I].Message;
2852 // FIXME: Need note where the other module was imported.
2853 }
2854 }
2855 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002856 }
2857}
2858
Douglas Gregor1a49d972013-01-25 01:03:03 +00002859bool ASTReader::loadGlobalIndex() {
2860 if (GlobalIndex)
2861 return false;
2862
2863 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
2864 !Context.getLangOpts().Modules)
2865 return true;
2866
2867 // Try to load the global index.
2868 TriedLoadingGlobalIndex = true;
2869 StringRef ModuleCachePath
2870 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
2871 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor677e15f2013-03-19 00:28:20 +00002872 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregor1a49d972013-01-25 01:03:03 +00002873 if (!Result.first)
2874 return true;
2875
2876 GlobalIndex.reset(Result.first);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00002877 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregor1a49d972013-01-25 01:03:03 +00002878 return false;
2879}
2880
2881bool ASTReader::isGlobalIndexUnavailable() const {
2882 return Context.getLangOpts().Modules && UseGlobalIndex &&
2883 !hasGlobalIndex() && TriedLoadingGlobalIndex;
2884}
2885
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002886ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
2887 ModuleKind Type,
2888 SourceLocation ImportLoc,
2889 unsigned ClientLoadCapabilities) {
2890 // Bump the generation number.
2891 unsigned PreviousGeneration = CurrentGeneration++;
2892
2893 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002894 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002895 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
2896 /*ImportedBy=*/0, Loaded,
Douglas Gregor677e15f2013-03-19 00:28:20 +00002897 0, 0,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002898 ClientLoadCapabilities)) {
2899 case Failure:
Douglas Gregor677e15f2013-03-19 00:28:20 +00002900 case Missing:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002901 case OutOfDate:
2902 case VersionMismatch:
2903 case ConfigurationMismatch:
2904 case HadErrors:
Douglas Gregor677e15f2013-03-19 00:28:20 +00002905 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
2906 Context.getLangOpts().Modules
2907 ? &PP.getHeaderSearchInfo().getModuleMap()
2908 : 0);
Douglas Gregor1a49d972013-01-25 01:03:03 +00002909
2910 // If we find that any modules are unusable, the global index is going
2911 // to be out-of-date. Just remove it.
2912 GlobalIndex.reset();
Douglas Gregor188bdcd2013-01-25 23:32:03 +00002913 ModuleMgr.setGlobalIndex(0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002914 return ReadResult;
2915
2916 case Success:
2917 break;
2918 }
2919
2920 // Here comes stuff that we only do once the entire chain is loaded.
2921
2922 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002923 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
2924 MEnd = Loaded.end();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002925 M != MEnd; ++M) {
2926 ModuleFile &F = *M->Mod;
2927
2928 // Read the AST block.
2929 if (ReadASTBlock(F))
2930 return Failure;
2931
2932 // Once read, set the ModuleFile bit base offset and update the size in
2933 // bits of all files we've seen.
2934 F.GlobalBitOffset = TotalModulesSizeInBits;
2935 TotalModulesSizeInBits += F.SizeInBits;
2936 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
2937
2938 // Preload SLocEntries.
2939 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
2940 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
2941 // Load it through the SourceManager and don't call ReadSLocEntry()
2942 // directly because the entry may have already been loaded in which case
2943 // calling ReadSLocEntry() directly would trigger an assertion in
2944 // SourceManager.
2945 SourceMgr.getLoadedSLocEntryByID(Index);
2946 }
2947 }
2948
Douglas Gregorfa69fc12013-03-22 18:50:14 +00002949 // Setup the import locations and notify the module manager that we've
2950 // committed to these module files.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002951 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
2952 MEnd = Loaded.end();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002953 M != MEnd; ++M) {
2954 ModuleFile &F = *M->Mod;
Douglas Gregorfa69fc12013-03-22 18:50:14 +00002955
2956 ModuleMgr.moduleFileAccepted(&F);
2957
2958 // Set the import location.
Argyrios Kyrtzidis8b136d82013-02-01 16:36:14 +00002959 F.DirectImportLoc = ImportLoc;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002960 if (!M->ImportedBy)
2961 F.ImportLoc = M->ImportLoc;
2962 else
2963 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
2964 M->ImportLoc.getRawEncoding());
2965 }
2966
2967 // Mark all of the identifiers in the identifier table as being out of date,
2968 // so that various accessors know to check the loaded modules when the
2969 // identifier is used.
2970 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
2971 IdEnd = PP.getIdentifierTable().end();
2972 Id != IdEnd; ++Id)
2973 Id->second->setOutOfDate(true);
2974
2975 // Resolve any unresolved module exports.
Douglas Gregor906d66a2013-03-20 21:10:35 +00002976 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
2977 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002978 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
2979 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregor906d66a2013-03-20 21:10:35 +00002980
2981 switch (Unresolved.Kind) {
2982 case UnresolvedModuleRef::Conflict:
2983 if (ResolvedMod) {
2984 Module::Conflict Conflict;
2985 Conflict.Other = ResolvedMod;
2986 Conflict.Message = Unresolved.String.str();
2987 Unresolved.Mod->Conflicts.push_back(Conflict);
2988 }
2989 continue;
2990
2991 case UnresolvedModuleRef::Import:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002992 if (ResolvedMod)
2993 Unresolved.Mod->Imports.push_back(ResolvedMod);
2994 continue;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002995
Douglas Gregor906d66a2013-03-20 21:10:35 +00002996 case UnresolvedModuleRef::Export:
2997 if (ResolvedMod || Unresolved.IsWildcard)
2998 Unresolved.Mod->Exports.push_back(
2999 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3000 continue;
3001 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003002 }
Douglas Gregor906d66a2013-03-20 21:10:35 +00003003 UnresolvedModuleRefs.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003004
3005 InitializeContext();
3006
3007 if (DeserializationListener)
3008 DeserializationListener->ReaderInitialized(this);
3009
3010 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3011 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3012 PrimaryModule.OriginalSourceFileID
3013 = FileID::get(PrimaryModule.SLocEntryBaseID
3014 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3015
3016 // If this AST file is a precompiled preamble, then set the
3017 // preamble file ID of the source manager to the file source file
3018 // from which the preamble was built.
3019 if (Type == MK_Preamble) {
3020 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3021 } else if (Type == MK_MainFile) {
3022 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3023 }
3024 }
3025
3026 // For any Objective-C class definitions we have already loaded, make sure
3027 // that we load any additional categories.
3028 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3029 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3030 ObjCClassesLoaded[I],
3031 PreviousGeneration);
3032 }
Douglas Gregor1a49d972013-01-25 01:03:03 +00003033
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003034 return Success;
3035}
3036
3037ASTReader::ASTReadResult
3038ASTReader::ReadASTCore(StringRef FileName,
3039 ModuleKind Type,
3040 SourceLocation ImportLoc,
3041 ModuleFile *ImportedBy,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003042 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor677e15f2013-03-19 00:28:20 +00003043 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003044 unsigned ClientLoadCapabilities) {
3045 ModuleFile *M;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003046 std::string ErrorStr;
Douglas Gregor677e15f2013-03-19 00:28:20 +00003047 ModuleManager::AddModuleResult AddResult
3048 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3049 CurrentGeneration, ExpectedSize, ExpectedModTime,
3050 M, ErrorStr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003051
Douglas Gregor677e15f2013-03-19 00:28:20 +00003052 switch (AddResult) {
3053 case ModuleManager::AlreadyLoaded:
3054 return Success;
3055
3056 case ModuleManager::NewlyLoaded:
3057 // Load module file below.
3058 break;
3059
3060 case ModuleManager::Missing:
3061 // The module file was missing; if the client handle handle, that, return
3062 // it.
3063 if (ClientLoadCapabilities & ARR_Missing)
3064 return Missing;
3065
3066 // Otherwise, return an error.
3067 {
3068 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3069 + ErrorStr;
3070 Error(Msg);
3071 }
3072 return Failure;
3073
3074 case ModuleManager::OutOfDate:
3075 // We couldn't load the module file because it is out-of-date. If the
3076 // client can handle out-of-date, return it.
3077 if (ClientLoadCapabilities & ARR_OutOfDate)
3078 return OutOfDate;
3079
3080 // Otherwise, return an error.
3081 {
3082 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3083 + ErrorStr;
3084 Error(Msg);
3085 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003086 return Failure;
3087 }
3088
Douglas Gregor677e15f2013-03-19 00:28:20 +00003089 assert(M && "Missing module file");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003090
3091 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3092 // module?
3093 if (FileName != "-") {
3094 CurrentDir = llvm::sys::path::parent_path(FileName);
3095 if (CurrentDir.empty()) CurrentDir = ".";
3096 }
3097
3098 ModuleFile &F = *M;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003099 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003100 Stream.init(F.StreamFile);
3101 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3102
3103 // Sniff for the signature.
3104 if (Stream.Read(8) != 'C' ||
3105 Stream.Read(8) != 'P' ||
3106 Stream.Read(8) != 'C' ||
3107 Stream.Read(8) != 'H') {
3108 Diag(diag::err_not_a_pch_file) << FileName;
3109 return Failure;
3110 }
3111
3112 // This is used for compatibility with older PCH formats.
3113 bool HaveReadControlBlock = false;
3114
Chris Lattner99a5af02013-01-20 00:00:22 +00003115 while (1) {
3116 llvm::BitstreamEntry Entry = Stream.advance();
3117
3118 switch (Entry.Kind) {
3119 case llvm::BitstreamEntry::Error:
3120 case llvm::BitstreamEntry::EndBlock:
3121 case llvm::BitstreamEntry::Record:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003122 Error("invalid record at top-level of AST file");
3123 return Failure;
Chris Lattner99a5af02013-01-20 00:00:22 +00003124
3125 case llvm::BitstreamEntry::SubBlock:
3126 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003127 }
3128
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003129 // We only know the control subblock ID.
Chris Lattner99a5af02013-01-20 00:00:22 +00003130 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003131 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3132 if (Stream.ReadBlockInfoBlock()) {
3133 Error("malformed BlockInfoBlock in AST file");
3134 return Failure;
3135 }
3136 break;
3137 case CONTROL_BLOCK_ID:
3138 HaveReadControlBlock = true;
3139 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
3140 case Success:
3141 break;
3142
3143 case Failure: return Failure;
Douglas Gregor677e15f2013-03-19 00:28:20 +00003144 case Missing: return Missing;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003145 case OutOfDate: return OutOfDate;
3146 case VersionMismatch: return VersionMismatch;
3147 case ConfigurationMismatch: return ConfigurationMismatch;
3148 case HadErrors: return HadErrors;
3149 }
3150 break;
3151 case AST_BLOCK_ID:
3152 if (!HaveReadControlBlock) {
3153 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3154 Diag(diag::warn_pch_version_too_old);
3155 return VersionMismatch;
3156 }
3157
3158 // Record that we've loaded this module.
3159 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3160 return Success;
3161
3162 default:
3163 if (Stream.SkipBlock()) {
3164 Error("malformed block record in AST file");
3165 return Failure;
3166 }
3167 break;
3168 }
3169 }
3170
3171 return Success;
3172}
3173
3174void ASTReader::InitializeContext() {
3175 // If there's a listener, notify them that we "read" the translation unit.
3176 if (DeserializationListener)
3177 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3178 Context.getTranslationUnitDecl());
3179
3180 // Make sure we load the declaration update records for the translation unit,
3181 // if there are any.
3182 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3183 Context.getTranslationUnitDecl());
3184
3185 // FIXME: Find a better way to deal with collisions between these
3186 // built-in types. Right now, we just ignore the problem.
3187
3188 // Load the special types.
3189 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3190 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3191 if (!Context.CFConstantStringTypeDecl)
3192 Context.setCFConstantStringType(GetType(String));
3193 }
3194
3195 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3196 QualType FileType = GetType(File);
3197 if (FileType.isNull()) {
3198 Error("FILE type is NULL");
3199 return;
3200 }
3201
3202 if (!Context.FILEDecl) {
3203 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3204 Context.setFILEDecl(Typedef->getDecl());
3205 else {
3206 const TagType *Tag = FileType->getAs<TagType>();
3207 if (!Tag) {
3208 Error("Invalid FILE type in AST file");
3209 return;
3210 }
3211 Context.setFILEDecl(Tag->getDecl());
3212 }
3213 }
3214 }
3215
3216 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3217 QualType Jmp_bufType = GetType(Jmp_buf);
3218 if (Jmp_bufType.isNull()) {
3219 Error("jmp_buf type is NULL");
3220 return;
3221 }
3222
3223 if (!Context.jmp_bufDecl) {
3224 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3225 Context.setjmp_bufDecl(Typedef->getDecl());
3226 else {
3227 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3228 if (!Tag) {
3229 Error("Invalid jmp_buf type in AST file");
3230 return;
3231 }
3232 Context.setjmp_bufDecl(Tag->getDecl());
3233 }
3234 }
3235 }
3236
3237 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3238 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3239 if (Sigjmp_bufType.isNull()) {
3240 Error("sigjmp_buf type is NULL");
3241 return;
3242 }
3243
3244 if (!Context.sigjmp_bufDecl) {
3245 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3246 Context.setsigjmp_bufDecl(Typedef->getDecl());
3247 else {
3248 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3249 assert(Tag && "Invalid sigjmp_buf type in AST file");
3250 Context.setsigjmp_bufDecl(Tag->getDecl());
3251 }
3252 }
3253 }
3254
3255 if (unsigned ObjCIdRedef
3256 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3257 if (Context.ObjCIdRedefinitionType.isNull())
3258 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3259 }
3260
3261 if (unsigned ObjCClassRedef
3262 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3263 if (Context.ObjCClassRedefinitionType.isNull())
3264 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3265 }
3266
3267 if (unsigned ObjCSelRedef
3268 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3269 if (Context.ObjCSelRedefinitionType.isNull())
3270 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3271 }
3272
3273 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3274 QualType Ucontext_tType = GetType(Ucontext_t);
3275 if (Ucontext_tType.isNull()) {
3276 Error("ucontext_t type is NULL");
3277 return;
3278 }
3279
3280 if (!Context.ucontext_tDecl) {
3281 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3282 Context.setucontext_tDecl(Typedef->getDecl());
3283 else {
3284 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3285 assert(Tag && "Invalid ucontext_t type in AST file");
3286 Context.setucontext_tDecl(Tag->getDecl());
3287 }
3288 }
3289 }
3290 }
3291
3292 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3293
3294 // If there were any CUDA special declarations, deserialize them.
3295 if (!CUDASpecialDeclRefs.empty()) {
3296 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3297 Context.setcudaConfigureCallDecl(
3298 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3299 }
3300
3301 // Re-export any modules that were imported by a non-module AST file.
3302 for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3303 if (Module *Imported = getSubmodule(ImportedModules[I]))
Argyrios Kyrtzidis5ebcb202013-02-01 16:36:12 +00003304 makeModuleVisible(Imported, Module::AllVisible,
Douglas Gregor906d66a2013-03-20 21:10:35 +00003305 /*ImportLoc=*/SourceLocation(),
3306 /*Complain=*/false);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003307 }
3308 ImportedModules.clear();
3309}
3310
3311void ASTReader::finalizeForWriting() {
3312 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3313 HiddenEnd = HiddenNamesMap.end();
3314 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00003315 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003316 }
3317 HiddenNamesMap.clear();
3318}
3319
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003320/// SkipCursorToControlBlock - Given a cursor at the start of an AST file, scan
3321/// ahead and drop the cursor into the start of the CONTROL_BLOCK, returning
3322/// false on success and true on failure.
3323static bool SkipCursorToControlBlock(BitstreamCursor &Cursor) {
3324 while (1) {
3325 llvm::BitstreamEntry Entry = Cursor.advance();
3326 switch (Entry.Kind) {
3327 case llvm::BitstreamEntry::Error:
3328 case llvm::BitstreamEntry::EndBlock:
3329 return true;
3330
3331 case llvm::BitstreamEntry::Record:
3332 // Ignore top-level records.
3333 Cursor.skipRecord(Entry.ID);
3334 break;
3335
3336 case llvm::BitstreamEntry::SubBlock:
3337 if (Entry.ID == CONTROL_BLOCK_ID) {
3338 if (Cursor.EnterSubBlock(CONTROL_BLOCK_ID))
3339 return true;
3340 // Found it!
3341 return false;
3342 }
3343
3344 if (Cursor.SkipBlock())
3345 return true;
3346 }
3347 }
3348}
3349
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003350/// \brief Retrieve the name of the original source file name
3351/// directly from the AST file, without actually loading the AST
3352/// file.
3353std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3354 FileManager &FileMgr,
3355 DiagnosticsEngine &Diags) {
3356 // Open the AST file.
3357 std::string ErrStr;
3358 OwningPtr<llvm::MemoryBuffer> Buffer;
3359 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3360 if (!Buffer) {
3361 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3362 return std::string();
3363 }
3364
3365 // Initialize the stream
3366 llvm::BitstreamReader StreamFile;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003367 BitstreamCursor Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003368 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3369 (const unsigned char *)Buffer->getBufferEnd());
3370 Stream.init(StreamFile);
3371
3372 // Sniff for the signature.
3373 if (Stream.Read(8) != 'C' ||
3374 Stream.Read(8) != 'P' ||
3375 Stream.Read(8) != 'C' ||
3376 Stream.Read(8) != 'H') {
3377 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3378 return std::string();
3379 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003380
Chris Lattner88bde502013-01-19 21:39:22 +00003381 // Scan for the CONTROL_BLOCK_ID block.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003382 if (SkipCursorToControlBlock(Stream)) {
3383 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3384 return std::string();
Chris Lattner88bde502013-01-19 21:39:22 +00003385 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003386
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003387 // Scan for ORIGINAL_FILE inside the control block.
3388 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00003389 while (1) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003390 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattner88bde502013-01-19 21:39:22 +00003391 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3392 return std::string();
3393
3394 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3395 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3396 return std::string();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003397 }
Chris Lattner88bde502013-01-19 21:39:22 +00003398
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003399 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003400 StringRef Blob;
3401 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3402 return Blob.str();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003403 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003404}
3405
3406namespace {
3407 class SimplePCHValidator : public ASTReaderListener {
3408 const LangOptions &ExistingLangOpts;
3409 const TargetOptions &ExistingTargetOpts;
3410 const PreprocessorOptions &ExistingPPOpts;
3411 FileManager &FileMgr;
3412
3413 public:
3414 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3415 const TargetOptions &ExistingTargetOpts,
3416 const PreprocessorOptions &ExistingPPOpts,
3417 FileManager &FileMgr)
3418 : ExistingLangOpts(ExistingLangOpts),
3419 ExistingTargetOpts(ExistingTargetOpts),
3420 ExistingPPOpts(ExistingPPOpts),
3421 FileMgr(FileMgr)
3422 {
3423 }
3424
3425 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
3426 bool Complain) {
3427 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3428 }
3429 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
3430 bool Complain) {
3431 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3432 }
3433 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3434 bool Complain,
3435 std::string &SuggestedPredefines) {
3436 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
3437 SuggestedPredefines);
3438 }
3439 };
3440}
3441
3442bool ASTReader::readASTFileControlBlock(StringRef Filename,
3443 FileManager &FileMgr,
3444 ASTReaderListener &Listener) {
3445 // Open the AST file.
3446 std::string ErrStr;
3447 OwningPtr<llvm::MemoryBuffer> Buffer;
3448 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3449 if (!Buffer) {
3450 return true;
3451 }
3452
3453 // Initialize the stream
3454 llvm::BitstreamReader StreamFile;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003455 BitstreamCursor Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003456 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3457 (const unsigned char *)Buffer->getBufferEnd());
3458 Stream.init(StreamFile);
3459
3460 // Sniff for the signature.
3461 if (Stream.Read(8) != 'C' ||
3462 Stream.Read(8) != 'P' ||
3463 Stream.Read(8) != 'C' ||
3464 Stream.Read(8) != 'H') {
3465 return true;
3466 }
3467
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003468 // Scan for the CONTROL_BLOCK_ID block.
3469 if (SkipCursorToControlBlock(Stream))
3470 return true;
3471
3472 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003473 RecordData Record;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003474 while (1) {
3475 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3476 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3477 return false;
3478
3479 if (Entry.Kind != llvm::BitstreamEntry::Record)
3480 return true;
3481
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003482 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003483 StringRef Blob;
3484 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003485 switch ((ControlRecordTypes)RecCode) {
3486 case METADATA: {
3487 if (Record[0] != VERSION_MAJOR)
3488 return true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003489
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003490 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003491 if (StringRef(CurBranch) != Blob)
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003492 return true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003493
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003494 break;
3495 }
3496 case LANGUAGE_OPTIONS:
3497 if (ParseLanguageOptions(Record, false, Listener))
3498 return true;
3499 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003500
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003501 case TARGET_OPTIONS:
3502 if (ParseTargetOptions(Record, false, Listener))
3503 return true;
3504 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003505
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003506 case DIAGNOSTIC_OPTIONS:
3507 if (ParseDiagnosticOptions(Record, false, Listener))
3508 return true;
3509 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003510
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003511 case FILE_SYSTEM_OPTIONS:
3512 if (ParseFileSystemOptions(Record, false, Listener))
3513 return true;
3514 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003515
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003516 case HEADER_SEARCH_OPTIONS:
3517 if (ParseHeaderSearchOptions(Record, false, Listener))
3518 return true;
3519 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003520
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003521 case PREPROCESSOR_OPTIONS: {
3522 std::string IgnoredSuggestedPredefines;
3523 if (ParsePreprocessorOptions(Record, false, Listener,
3524 IgnoredSuggestedPredefines))
3525 return true;
3526 break;
3527 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003528
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003529 default:
3530 // No other validation to perform.
3531 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003532 }
3533 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003534}
3535
3536
3537bool ASTReader::isAcceptableASTFile(StringRef Filename,
3538 FileManager &FileMgr,
3539 const LangOptions &LangOpts,
3540 const TargetOptions &TargetOpts,
3541 const PreprocessorOptions &PPOpts) {
3542 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3543 return !readASTFileControlBlock(Filename, FileMgr, validator);
3544}
3545
3546bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
3547 // Enter the submodule block.
3548 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3549 Error("malformed submodule block record in AST file");
3550 return true;
3551 }
3552
3553 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
3554 bool First = true;
3555 Module *CurrentModule = 0;
3556 RecordData Record;
3557 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003558 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
3559
3560 switch (Entry.Kind) {
3561 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
3562 case llvm::BitstreamEntry::Error:
3563 Error("malformed block record in AST file");
3564 return true;
3565 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003566 return false;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003567 case llvm::BitstreamEntry::Record:
3568 // The interesting case.
3569 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003570 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003571
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003572 // Read a record.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003573 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003574 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003575 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003576 default: // Default behavior: ignore.
3577 break;
3578
3579 case SUBMODULE_DEFINITION: {
3580 if (First) {
3581 Error("missing submodule metadata record at beginning of block");
3582 return true;
3583 }
3584
Douglas Gregor970e4412013-03-20 03:59:18 +00003585 if (Record.size() < 8) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003586 Error("malformed module definition");
3587 return true;
3588 }
3589
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003590 StringRef Name = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003591 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
3592 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[1]);
3593 bool IsFramework = Record[2];
3594 bool IsExplicit = Record[3];
3595 bool IsSystem = Record[4];
3596 bool InferSubmodules = Record[5];
3597 bool InferExplicitSubmodules = Record[6];
3598 bool InferExportWildcard = Record[7];
Douglas Gregor970e4412013-03-20 03:59:18 +00003599 bool ConfigMacrosExhaustive = Record[8];
3600
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003601 Module *ParentModule = 0;
3602 if (Parent)
3603 ParentModule = getSubmodule(Parent);
3604
3605 // Retrieve this (sub)module from the module map, creating it if
3606 // necessary.
3607 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
3608 IsFramework,
3609 IsExplicit).first;
3610 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
3611 if (GlobalIndex >= SubmodulesLoaded.size() ||
3612 SubmodulesLoaded[GlobalIndex]) {
3613 Error("too many submodules");
3614 return true;
3615 }
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003616
Douglas Gregor677e15f2013-03-19 00:28:20 +00003617 if (!ParentModule) {
3618 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
3619 if (CurFile != F.File) {
3620 if (!Diags.isDiagnosticInFlight()) {
3621 Diag(diag::err_module_file_conflict)
3622 << CurrentModule->getTopLevelModuleName()
3623 << CurFile->getName()
3624 << F.File->getName();
3625 }
3626 return true;
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003627 }
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003628 }
Douglas Gregor677e15f2013-03-19 00:28:20 +00003629
3630 CurrentModule->setASTFile(F.File);
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003631 }
Douglas Gregor677e15f2013-03-19 00:28:20 +00003632
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003633 CurrentModule->IsFromModuleFile = true;
3634 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
3635 CurrentModule->InferSubmodules = InferSubmodules;
3636 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
3637 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor970e4412013-03-20 03:59:18 +00003638 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003639 if (DeserializationListener)
3640 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
3641
3642 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003643
Douglas Gregor906d66a2013-03-20 21:10:35 +00003644 // Clear out data that will be replaced by what is the module file.
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003645 CurrentModule->LinkLibraries.clear();
Douglas Gregor970e4412013-03-20 03:59:18 +00003646 CurrentModule->ConfigMacros.clear();
Douglas Gregor906d66a2013-03-20 21:10:35 +00003647 CurrentModule->UnresolvedConflicts.clear();
3648 CurrentModule->Conflicts.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003649 break;
3650 }
3651
3652 case SUBMODULE_UMBRELLA_HEADER: {
3653 if (First) {
3654 Error("missing submodule metadata record at beginning of block");
3655 return true;
3656 }
3657
3658 if (!CurrentModule)
3659 break;
3660
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003661 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003662 if (!CurrentModule->getUmbrellaHeader())
3663 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
3664 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
3665 Error("mismatched umbrella headers in submodule");
3666 return true;
3667 }
3668 }
3669 break;
3670 }
3671
3672 case SUBMODULE_HEADER: {
3673 if (First) {
3674 Error("missing submodule metadata record at beginning of block");
3675 return true;
3676 }
3677
3678 if (!CurrentModule)
3679 break;
3680
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00003681 // We lazily associate headers with their modules via the HeaderInfoTable.
3682 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
3683 // of complete filenames or remove it entirely.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003684 break;
3685 }
3686
3687 case SUBMODULE_EXCLUDED_HEADER: {
3688 if (First) {
3689 Error("missing submodule metadata record at beginning of block");
3690 return true;
3691 }
3692
3693 if (!CurrentModule)
3694 break;
3695
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00003696 // We lazily associate headers with their modules via the HeaderInfoTable.
3697 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
3698 // of complete filenames or remove it entirely.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003699 break;
3700 }
3701
3702 case SUBMODULE_TOPHEADER: {
3703 if (First) {
3704 Error("missing submodule metadata record at beginning of block");
3705 return true;
3706 }
3707
3708 if (!CurrentModule)
3709 break;
3710
Argyrios Kyrtzidisc1d22392013-03-13 21:13:43 +00003711 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003712 break;
3713 }
3714
3715 case SUBMODULE_UMBRELLA_DIR: {
3716 if (First) {
3717 Error("missing submodule metadata record at beginning of block");
3718 return true;
3719 }
3720
3721 if (!CurrentModule)
3722 break;
3723
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003724 if (const DirectoryEntry *Umbrella
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003725 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003726 if (!CurrentModule->getUmbrellaDir())
3727 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
3728 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
3729 Error("mismatched umbrella directories in submodule");
3730 return true;
3731 }
3732 }
3733 break;
3734 }
3735
3736 case SUBMODULE_METADATA: {
3737 if (!First) {
3738 Error("submodule metadata record not at beginning of block");
3739 return true;
3740 }
3741 First = false;
3742
3743 F.BaseSubmoduleID = getTotalNumSubmodules();
3744 F.LocalNumSubmodules = Record[0];
3745 unsigned LocalBaseSubmoduleID = Record[1];
3746 if (F.LocalNumSubmodules > 0) {
3747 // Introduce the global -> local mapping for submodules within this
3748 // module.
3749 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
3750
3751 // Introduce the local -> global mapping for submodules within this
3752 // module.
3753 F.SubmoduleRemap.insertOrReplace(
3754 std::make_pair(LocalBaseSubmoduleID,
3755 F.BaseSubmoduleID - LocalBaseSubmoduleID));
3756
3757 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
3758 }
3759 break;
3760 }
3761
3762 case SUBMODULE_IMPORTS: {
3763 if (First) {
3764 Error("missing submodule metadata record at beginning of block");
3765 return true;
3766 }
3767
3768 if (!CurrentModule)
3769 break;
3770
3771 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregor906d66a2013-03-20 21:10:35 +00003772 UnresolvedModuleRef Unresolved;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003773 Unresolved.File = &F;
3774 Unresolved.Mod = CurrentModule;
3775 Unresolved.ID = Record[Idx];
Douglas Gregor906d66a2013-03-20 21:10:35 +00003776 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003777 Unresolved.IsWildcard = false;
Douglas Gregor906d66a2013-03-20 21:10:35 +00003778 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003779 }
3780 break;
3781 }
3782
3783 case SUBMODULE_EXPORTS: {
3784 if (First) {
3785 Error("missing submodule metadata record at beginning of block");
3786 return true;
3787 }
3788
3789 if (!CurrentModule)
3790 break;
3791
3792 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregor906d66a2013-03-20 21:10:35 +00003793 UnresolvedModuleRef Unresolved;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003794 Unresolved.File = &F;
3795 Unresolved.Mod = CurrentModule;
3796 Unresolved.ID = Record[Idx];
Douglas Gregor906d66a2013-03-20 21:10:35 +00003797 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003798 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregor906d66a2013-03-20 21:10:35 +00003799 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003800 }
3801
3802 // Once we've loaded the set of exports, there's no reason to keep
3803 // the parsed, unresolved exports around.
3804 CurrentModule->UnresolvedExports.clear();
3805 break;
3806 }
3807 case SUBMODULE_REQUIRES: {
3808 if (First) {
3809 Error("missing submodule metadata record at beginning of block");
3810 return true;
3811 }
3812
3813 if (!CurrentModule)
3814 break;
3815
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003816 CurrentModule->addRequirement(Blob, Context.getLangOpts(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003817 Context.getTargetInfo());
3818 break;
3819 }
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003820
3821 case SUBMODULE_LINK_LIBRARY:
3822 if (First) {
3823 Error("missing submodule metadata record at beginning of block");
3824 return true;
3825 }
3826
3827 if (!CurrentModule)
3828 break;
3829
3830 CurrentModule->LinkLibraries.push_back(
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003831 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003832 break;
Douglas Gregor63a72682013-03-20 00:22:05 +00003833
3834 case SUBMODULE_CONFIG_MACRO:
3835 if (First) {
3836 Error("missing submodule metadata record at beginning of block");
3837 return true;
3838 }
3839
3840 if (!CurrentModule)
3841 break;
3842
3843 CurrentModule->ConfigMacros.push_back(Blob.str());
3844 break;
Douglas Gregor906d66a2013-03-20 21:10:35 +00003845
3846 case SUBMODULE_CONFLICT: {
3847 if (First) {
3848 Error("missing submodule metadata record at beginning of block");
3849 return true;
3850 }
3851
3852 if (!CurrentModule)
3853 break;
3854
3855 UnresolvedModuleRef Unresolved;
3856 Unresolved.File = &F;
3857 Unresolved.Mod = CurrentModule;
3858 Unresolved.ID = Record[0];
3859 Unresolved.Kind = UnresolvedModuleRef::Conflict;
3860 Unresolved.IsWildcard = false;
3861 Unresolved.String = Blob;
3862 UnresolvedModuleRefs.push_back(Unresolved);
3863 break;
3864 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003865 }
3866 }
3867}
3868
3869/// \brief Parse the record that corresponds to a LangOptions data
3870/// structure.
3871///
3872/// This routine parses the language options from the AST file and then gives
3873/// them to the AST listener if one is set.
3874///
3875/// \returns true if the listener deems the file unacceptable, false otherwise.
3876bool ASTReader::ParseLanguageOptions(const RecordData &Record,
3877 bool Complain,
3878 ASTReaderListener &Listener) {
3879 LangOptions LangOpts;
3880 unsigned Idx = 0;
3881#define LANGOPT(Name, Bits, Default, Description) \
3882 LangOpts.Name = Record[Idx++];
3883#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
3884 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
3885#include "clang/Basic/LangOptions.def"
Will Dietz4f45bc02013-01-18 11:30:38 +00003886#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
3887#include "clang/Basic/Sanitizers.def"
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003888
3889 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
3890 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
3891 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
3892
3893 unsigned Length = Record[Idx++];
3894 LangOpts.CurrentModule.assign(Record.begin() + Idx,
3895 Record.begin() + Idx + Length);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +00003896
3897 Idx += Length;
3898
3899 // Comment options.
3900 for (unsigned N = Record[Idx++]; N; --N) {
3901 LangOpts.CommentOpts.BlockCommandNames.push_back(
3902 ReadString(Record, Idx));
3903 }
3904
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003905 return Listener.ReadLanguageOptions(LangOpts, Complain);
3906}
3907
3908bool ASTReader::ParseTargetOptions(const RecordData &Record,
3909 bool Complain,
3910 ASTReaderListener &Listener) {
3911 unsigned Idx = 0;
3912 TargetOptions TargetOpts;
3913 TargetOpts.Triple = ReadString(Record, Idx);
3914 TargetOpts.CPU = ReadString(Record, Idx);
3915 TargetOpts.ABI = ReadString(Record, Idx);
3916 TargetOpts.CXXABI = ReadString(Record, Idx);
3917 TargetOpts.LinkerVersion = ReadString(Record, Idx);
3918 for (unsigned N = Record[Idx++]; N; --N) {
3919 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
3920 }
3921 for (unsigned N = Record[Idx++]; N; --N) {
3922 TargetOpts.Features.push_back(ReadString(Record, Idx));
3923 }
3924
3925 return Listener.ReadTargetOptions(TargetOpts, Complain);
3926}
3927
3928bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
3929 ASTReaderListener &Listener) {
3930 DiagnosticOptions DiagOpts;
3931 unsigned Idx = 0;
3932#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
3933#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
3934 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
3935#include "clang/Basic/DiagnosticOptions.def"
3936
3937 for (unsigned N = Record[Idx++]; N; --N) {
3938 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
3939 }
3940
3941 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
3942}
3943
3944bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
3945 ASTReaderListener &Listener) {
3946 FileSystemOptions FSOpts;
3947 unsigned Idx = 0;
3948 FSOpts.WorkingDir = ReadString(Record, Idx);
3949 return Listener.ReadFileSystemOptions(FSOpts, Complain);
3950}
3951
3952bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
3953 bool Complain,
3954 ASTReaderListener &Listener) {
3955 HeaderSearchOptions HSOpts;
3956 unsigned Idx = 0;
3957 HSOpts.Sysroot = ReadString(Record, Idx);
3958
3959 // Include entries.
3960 for (unsigned N = Record[Idx++]; N; --N) {
3961 std::string Path = ReadString(Record, Idx);
3962 frontend::IncludeDirGroup Group
3963 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003964 bool IsFramework = Record[Idx++];
3965 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003966 HSOpts.UserEntries.push_back(
Daniel Dunbar59fd6352013-01-30 00:34:26 +00003967 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003968 }
3969
3970 // System header prefixes.
3971 for (unsigned N = Record[Idx++]; N; --N) {
3972 std::string Prefix = ReadString(Record, Idx);
3973 bool IsSystemHeader = Record[Idx++];
3974 HSOpts.SystemHeaderPrefixes.push_back(
3975 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
3976 }
3977
3978 HSOpts.ResourceDir = ReadString(Record, Idx);
3979 HSOpts.ModuleCachePath = ReadString(Record, Idx);
3980 HSOpts.DisableModuleHash = Record[Idx++];
3981 HSOpts.UseBuiltinIncludes = Record[Idx++];
3982 HSOpts.UseStandardSystemIncludes = Record[Idx++];
3983 HSOpts.UseStandardCXXIncludes = Record[Idx++];
3984 HSOpts.UseLibcxx = Record[Idx++];
3985
3986 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
3987}
3988
3989bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
3990 bool Complain,
3991 ASTReaderListener &Listener,
3992 std::string &SuggestedPredefines) {
3993 PreprocessorOptions PPOpts;
3994 unsigned Idx = 0;
3995
3996 // Macro definitions/undefs
3997 for (unsigned N = Record[Idx++]; N; --N) {
3998 std::string Macro = ReadString(Record, Idx);
3999 bool IsUndef = Record[Idx++];
4000 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4001 }
4002
4003 // Includes
4004 for (unsigned N = Record[Idx++]; N; --N) {
4005 PPOpts.Includes.push_back(ReadString(Record, Idx));
4006 }
4007
4008 // Macro Includes
4009 for (unsigned N = Record[Idx++]; N; --N) {
4010 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4011 }
4012
4013 PPOpts.UsePredefines = Record[Idx++];
4014 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4015 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4016 PPOpts.ObjCXXARCStandardLibrary =
4017 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4018 SuggestedPredefines.clear();
4019 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4020 SuggestedPredefines);
4021}
4022
4023std::pair<ModuleFile *, unsigned>
4024ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4025 GlobalPreprocessedEntityMapType::iterator
4026 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4027 assert(I != GlobalPreprocessedEntityMap.end() &&
4028 "Corrupted global preprocessed entity map");
4029 ModuleFile *M = I->second;
4030 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4031 return std::make_pair(M, LocalIndex);
4032}
4033
4034std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4035ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4036 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4037 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4038 Mod.NumPreprocessedEntities);
4039
4040 return std::make_pair(PreprocessingRecord::iterator(),
4041 PreprocessingRecord::iterator());
4042}
4043
4044std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4045ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4046 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4047 ModuleDeclIterator(this, &Mod,
4048 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4049}
4050
4051PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4052 PreprocessedEntityID PPID = Index+1;
4053 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4054 ModuleFile &M = *PPInfo.first;
4055 unsigned LocalIndex = PPInfo.second;
4056 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4057
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004058 if (!PP.getPreprocessingRecord()) {
4059 Error("no preprocessing record");
4060 return 0;
4061 }
4062
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004063 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4064 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4065
4066 llvm::BitstreamEntry Entry =
4067 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4068 if (Entry.Kind != llvm::BitstreamEntry::Record)
4069 return 0;
4070
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004071 // Read the record.
4072 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4073 ReadSourceLocation(M, PPOffs.End));
4074 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004075 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004076 RecordData Record;
4077 PreprocessorDetailRecordTypes RecType =
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004078 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4079 Entry.ID, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004080 switch (RecType) {
4081 case PPD_MACRO_EXPANSION: {
4082 bool isBuiltin = Record[0];
4083 IdentifierInfo *Name = 0;
4084 MacroDefinition *Def = 0;
4085 if (isBuiltin)
4086 Name = getLocalIdentifier(M, Record[1]);
4087 else {
4088 PreprocessedEntityID
4089 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4090 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4091 }
4092
4093 MacroExpansion *ME;
4094 if (isBuiltin)
4095 ME = new (PPRec) MacroExpansion(Name, Range);
4096 else
4097 ME = new (PPRec) MacroExpansion(Def, Range);
4098
4099 return ME;
4100 }
4101
4102 case PPD_MACRO_DEFINITION: {
4103 // Decode the identifier info and then check again; if the macro is
4104 // still defined and associated with the identifier,
4105 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4106 MacroDefinition *MD
4107 = new (PPRec) MacroDefinition(II, Range);
4108
4109 if (DeserializationListener)
4110 DeserializationListener->MacroDefinitionRead(PPID, MD);
4111
4112 return MD;
4113 }
4114
4115 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004116 const char *FullFileNameStart = Blob.data() + Record[0];
4117 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004118 const FileEntry *File = 0;
4119 if (!FullFileName.empty())
4120 File = PP.getFileManager().getFile(FullFileName);
4121
4122 // FIXME: Stable encoding
4123 InclusionDirective::InclusionKind Kind
4124 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4125 InclusionDirective *ID
4126 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004127 StringRef(Blob.data(), Record[0]),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004128 Record[1], Record[3],
4129 File,
4130 Range);
4131 return ID;
4132 }
4133 }
4134
4135 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4136}
4137
4138/// \brief \arg SLocMapI points at a chunk of a module that contains no
4139/// preprocessed entities or the entities it contains are not the ones we are
4140/// looking for. Find the next module that contains entities and return the ID
4141/// of the first entry.
4142PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4143 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4144 ++SLocMapI;
4145 for (GlobalSLocOffsetMapType::const_iterator
4146 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4147 ModuleFile &M = *SLocMapI->second;
4148 if (M.NumPreprocessedEntities)
4149 return M.BasePreprocessedEntityID;
4150 }
4151
4152 return getTotalNumPreprocessedEntities();
4153}
4154
4155namespace {
4156
4157template <unsigned PPEntityOffset::*PPLoc>
4158struct PPEntityComp {
4159 const ASTReader &Reader;
4160 ModuleFile &M;
4161
4162 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4163
4164 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4165 SourceLocation LHS = getLoc(L);
4166 SourceLocation RHS = getLoc(R);
4167 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4168 }
4169
4170 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4171 SourceLocation LHS = getLoc(L);
4172 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4173 }
4174
4175 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4176 SourceLocation RHS = getLoc(R);
4177 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4178 }
4179
4180 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4181 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4182 }
4183};
4184
4185}
4186
4187/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4188PreprocessedEntityID
4189ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4190 if (SourceMgr.isLocalSourceLocation(BLoc))
4191 return getTotalNumPreprocessedEntities();
4192
4193 GlobalSLocOffsetMapType::const_iterator
4194 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00004195 BLoc.getOffset() - 1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004196 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4197 "Corrupted global sloc offset map");
4198
4199 if (SLocMapI->second->NumPreprocessedEntities == 0)
4200 return findNextPreprocessedEntity(SLocMapI);
4201
4202 ModuleFile &M = *SLocMapI->second;
4203 typedef const PPEntityOffset *pp_iterator;
4204 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4205 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4206
4207 size_t Count = M.NumPreprocessedEntities;
4208 size_t Half;
4209 pp_iterator First = pp_begin;
4210 pp_iterator PPI;
4211
4212 // Do a binary search manually instead of using std::lower_bound because
4213 // The end locations of entities may be unordered (when a macro expansion
4214 // is inside another macro argument), but for this case it is not important
4215 // whether we get the first macro expansion or its containing macro.
4216 while (Count > 0) {
4217 Half = Count/2;
4218 PPI = First;
4219 std::advance(PPI, Half);
4220 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4221 BLoc)){
4222 First = PPI;
4223 ++First;
4224 Count = Count - Half - 1;
4225 } else
4226 Count = Half;
4227 }
4228
4229 if (PPI == pp_end)
4230 return findNextPreprocessedEntity(SLocMapI);
4231
4232 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4233}
4234
4235/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4236PreprocessedEntityID
4237ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4238 if (SourceMgr.isLocalSourceLocation(ELoc))
4239 return getTotalNumPreprocessedEntities();
4240
4241 GlobalSLocOffsetMapType::const_iterator
4242 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00004243 ELoc.getOffset() - 1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004244 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4245 "Corrupted global sloc offset map");
4246
4247 if (SLocMapI->second->NumPreprocessedEntities == 0)
4248 return findNextPreprocessedEntity(SLocMapI);
4249
4250 ModuleFile &M = *SLocMapI->second;
4251 typedef const PPEntityOffset *pp_iterator;
4252 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4253 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4254 pp_iterator PPI =
4255 std::upper_bound(pp_begin, pp_end, ELoc,
4256 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4257
4258 if (PPI == pp_end)
4259 return findNextPreprocessedEntity(SLocMapI);
4260
4261 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4262}
4263
4264/// \brief Returns a pair of [Begin, End) indices of preallocated
4265/// preprocessed entities that \arg Range encompasses.
4266std::pair<unsigned, unsigned>
4267 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4268 if (Range.isInvalid())
4269 return std::make_pair(0,0);
4270 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4271
4272 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4273 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4274 return std::make_pair(BeginID, EndID);
4275}
4276
4277/// \brief Optionally returns true or false if the preallocated preprocessed
4278/// entity with index \arg Index came from file \arg FID.
David Blaikiedc84cd52013-02-20 22:23:23 +00004279Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004280 FileID FID) {
4281 if (FID.isInvalid())
4282 return false;
4283
4284 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4285 ModuleFile &M = *PPInfo.first;
4286 unsigned LocalIndex = PPInfo.second;
4287 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4288
4289 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4290 if (Loc.isInvalid())
4291 return false;
4292
4293 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4294 return true;
4295 else
4296 return false;
4297}
4298
4299namespace {
4300 /// \brief Visitor used to search for information about a header file.
4301 class HeaderFileInfoVisitor {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004302 const FileEntry *FE;
4303
David Blaikiedc84cd52013-02-20 22:23:23 +00004304 Optional<HeaderFileInfo> HFI;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004305
4306 public:
Argyrios Kyrtzidis36592b12013-03-06 18:12:44 +00004307 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4308 : FE(FE) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004309
4310 static bool visit(ModuleFile &M, void *UserData) {
4311 HeaderFileInfoVisitor *This
4312 = static_cast<HeaderFileInfoVisitor *>(UserData);
4313
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004314 HeaderFileInfoLookupTable *Table
4315 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4316 if (!Table)
4317 return false;
4318
4319 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00004320 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004321 if (Pos == Table->end())
4322 return false;
4323
4324 This->HFI = *Pos;
4325 return true;
4326 }
4327
David Blaikiedc84cd52013-02-20 22:23:23 +00004328 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004329 };
4330}
4331
4332HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis36592b12013-03-06 18:12:44 +00004333 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004334 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
David Blaikiedc84cd52013-02-20 22:23:23 +00004335 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004336 if (Listener)
4337 Listener->ReadHeaderFileInfo(*HFI, FE->getUID());
4338 return *HFI;
4339 }
4340
4341 return HeaderFileInfo();
4342}
4343
4344void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4345 // FIXME: Make it work properly with modules.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004346 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004347 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4348 ModuleFile &F = *(*I);
4349 unsigned Idx = 0;
4350 DiagStates.clear();
4351 assert(!Diag.DiagStates.empty());
4352 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4353 while (Idx < F.PragmaDiagMappings.size()) {
4354 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4355 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4356 if (DiagStateID != 0) {
4357 Diag.DiagStatePoints.push_back(
4358 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4359 FullSourceLoc(Loc, SourceMgr)));
4360 continue;
4361 }
4362
4363 assert(DiagStateID == 0);
4364 // A new DiagState was created here.
4365 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4366 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4367 DiagStates.push_back(NewState);
4368 Diag.DiagStatePoints.push_back(
4369 DiagnosticsEngine::DiagStatePoint(NewState,
4370 FullSourceLoc(Loc, SourceMgr)));
4371 while (1) {
4372 assert(Idx < F.PragmaDiagMappings.size() &&
4373 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4374 if (Idx >= F.PragmaDiagMappings.size()) {
4375 break; // Something is messed up but at least avoid infinite loop in
4376 // release build.
4377 }
4378 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4379 if (DiagID == (unsigned)-1) {
4380 break; // no more diag/map pairs for this location.
4381 }
4382 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4383 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4384 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4385 }
4386 }
4387 }
4388}
4389
4390/// \brief Get the correct cursor and offset for loading a type.
4391ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4392 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4393 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4394 ModuleFile *M = I->second;
4395 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4396}
4397
4398/// \brief Read and return the type with the given index..
4399///
4400/// The index is the type ID, shifted and minus the number of predefs. This
4401/// routine actually reads the record corresponding to the type at the given
4402/// location. It is a helper routine for GetType, which deals with reading type
4403/// IDs.
4404QualType ASTReader::readTypeRecord(unsigned Index) {
4405 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004406 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004407
4408 // Keep track of where we are in the stream, then jump back there
4409 // after reading this type.
4410 SavedStreamPosition SavedPosition(DeclsCursor);
4411
4412 ReadingKindTracker ReadingKind(Read_Type, *this);
4413
4414 // Note that we are loading a type record.
4415 Deserializing AType(this);
4416
4417 unsigned Idx = 0;
4418 DeclsCursor.JumpToBit(Loc.Offset);
4419 RecordData Record;
4420 unsigned Code = DeclsCursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004421 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004422 case TYPE_EXT_QUAL: {
4423 if (Record.size() != 2) {
4424 Error("Incorrect encoding of extended qualifier type");
4425 return QualType();
4426 }
4427 QualType Base = readType(*Loc.F, Record, Idx);
4428 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4429 return Context.getQualifiedType(Base, Quals);
4430 }
4431
4432 case TYPE_COMPLEX: {
4433 if (Record.size() != 1) {
4434 Error("Incorrect encoding of complex type");
4435 return QualType();
4436 }
4437 QualType ElemType = readType(*Loc.F, Record, Idx);
4438 return Context.getComplexType(ElemType);
4439 }
4440
4441 case TYPE_POINTER: {
4442 if (Record.size() != 1) {
4443 Error("Incorrect encoding of pointer type");
4444 return QualType();
4445 }
4446 QualType PointeeType = readType(*Loc.F, Record, Idx);
4447 return Context.getPointerType(PointeeType);
4448 }
4449
4450 case TYPE_BLOCK_POINTER: {
4451 if (Record.size() != 1) {
4452 Error("Incorrect encoding of block pointer type");
4453 return QualType();
4454 }
4455 QualType PointeeType = readType(*Loc.F, Record, Idx);
4456 return Context.getBlockPointerType(PointeeType);
4457 }
4458
4459 case TYPE_LVALUE_REFERENCE: {
4460 if (Record.size() != 2) {
4461 Error("Incorrect encoding of lvalue reference type");
4462 return QualType();
4463 }
4464 QualType PointeeType = readType(*Loc.F, Record, Idx);
4465 return Context.getLValueReferenceType(PointeeType, Record[1]);
4466 }
4467
4468 case TYPE_RVALUE_REFERENCE: {
4469 if (Record.size() != 1) {
4470 Error("Incorrect encoding of rvalue reference type");
4471 return QualType();
4472 }
4473 QualType PointeeType = readType(*Loc.F, Record, Idx);
4474 return Context.getRValueReferenceType(PointeeType);
4475 }
4476
4477 case TYPE_MEMBER_POINTER: {
4478 if (Record.size() != 2) {
4479 Error("Incorrect encoding of member pointer type");
4480 return QualType();
4481 }
4482 QualType PointeeType = readType(*Loc.F, Record, Idx);
4483 QualType ClassType = readType(*Loc.F, Record, Idx);
4484 if (PointeeType.isNull() || ClassType.isNull())
4485 return QualType();
4486
4487 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4488 }
4489
4490 case TYPE_CONSTANT_ARRAY: {
4491 QualType ElementType = readType(*Loc.F, Record, Idx);
4492 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4493 unsigned IndexTypeQuals = Record[2];
4494 unsigned Idx = 3;
4495 llvm::APInt Size = ReadAPInt(Record, Idx);
4496 return Context.getConstantArrayType(ElementType, Size,
4497 ASM, IndexTypeQuals);
4498 }
4499
4500 case TYPE_INCOMPLETE_ARRAY: {
4501 QualType ElementType = readType(*Loc.F, Record, Idx);
4502 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4503 unsigned IndexTypeQuals = Record[2];
4504 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4505 }
4506
4507 case TYPE_VARIABLE_ARRAY: {
4508 QualType ElementType = readType(*Loc.F, Record, Idx);
4509 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4510 unsigned IndexTypeQuals = Record[2];
4511 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4512 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
4513 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
4514 ASM, IndexTypeQuals,
4515 SourceRange(LBLoc, RBLoc));
4516 }
4517
4518 case TYPE_VECTOR: {
4519 if (Record.size() != 3) {
4520 Error("incorrect encoding of vector type in AST file");
4521 return QualType();
4522 }
4523
4524 QualType ElementType = readType(*Loc.F, Record, Idx);
4525 unsigned NumElements = Record[1];
4526 unsigned VecKind = Record[2];
4527 return Context.getVectorType(ElementType, NumElements,
4528 (VectorType::VectorKind)VecKind);
4529 }
4530
4531 case TYPE_EXT_VECTOR: {
4532 if (Record.size() != 3) {
4533 Error("incorrect encoding of extended vector type in AST file");
4534 return QualType();
4535 }
4536
4537 QualType ElementType = readType(*Loc.F, Record, Idx);
4538 unsigned NumElements = Record[1];
4539 return Context.getExtVectorType(ElementType, NumElements);
4540 }
4541
4542 case TYPE_FUNCTION_NO_PROTO: {
4543 if (Record.size() != 6) {
4544 Error("incorrect encoding of no-proto function type");
4545 return QualType();
4546 }
4547 QualType ResultType = readType(*Loc.F, Record, Idx);
4548 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
4549 (CallingConv)Record[4], Record[5]);
4550 return Context.getFunctionNoProtoType(ResultType, Info);
4551 }
4552
4553 case TYPE_FUNCTION_PROTO: {
4554 QualType ResultType = readType(*Loc.F, Record, Idx);
4555
4556 FunctionProtoType::ExtProtoInfo EPI;
4557 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
4558 /*hasregparm*/ Record[2],
4559 /*regparm*/ Record[3],
4560 static_cast<CallingConv>(Record[4]),
4561 /*produces*/ Record[5]);
4562
4563 unsigned Idx = 6;
4564 unsigned NumParams = Record[Idx++];
4565 SmallVector<QualType, 16> ParamTypes;
4566 for (unsigned I = 0; I != NumParams; ++I)
4567 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
4568
4569 EPI.Variadic = Record[Idx++];
4570 EPI.HasTrailingReturn = Record[Idx++];
4571 EPI.TypeQuals = Record[Idx++];
4572 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
4573 ExceptionSpecificationType EST =
4574 static_cast<ExceptionSpecificationType>(Record[Idx++]);
4575 EPI.ExceptionSpecType = EST;
4576 SmallVector<QualType, 2> Exceptions;
4577 if (EST == EST_Dynamic) {
4578 EPI.NumExceptions = Record[Idx++];
4579 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
4580 Exceptions.push_back(readType(*Loc.F, Record, Idx));
4581 EPI.Exceptions = Exceptions.data();
4582 } else if (EST == EST_ComputedNoexcept) {
4583 EPI.NoexceptExpr = ReadExpr(*Loc.F);
4584 } else if (EST == EST_Uninstantiated) {
4585 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4586 EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4587 } else if (EST == EST_Unevaluated) {
4588 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4589 }
Jordan Rosebea522f2013-03-08 21:51:21 +00004590 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004591 }
4592
4593 case TYPE_UNRESOLVED_USING: {
4594 unsigned Idx = 0;
4595 return Context.getTypeDeclType(
4596 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
4597 }
4598
4599 case TYPE_TYPEDEF: {
4600 if (Record.size() != 2) {
4601 Error("incorrect encoding of typedef type");
4602 return QualType();
4603 }
4604 unsigned Idx = 0;
4605 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
4606 QualType Canonical = readType(*Loc.F, Record, Idx);
4607 if (!Canonical.isNull())
4608 Canonical = Context.getCanonicalType(Canonical);
4609 return Context.getTypedefType(Decl, Canonical);
4610 }
4611
4612 case TYPE_TYPEOF_EXPR:
4613 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
4614
4615 case TYPE_TYPEOF: {
4616 if (Record.size() != 1) {
4617 Error("incorrect encoding of typeof(type) in AST file");
4618 return QualType();
4619 }
4620 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4621 return Context.getTypeOfType(UnderlyingType);
4622 }
4623
4624 case TYPE_DECLTYPE: {
4625 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4626 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
4627 }
4628
4629 case TYPE_UNARY_TRANSFORM: {
4630 QualType BaseType = readType(*Loc.F, Record, Idx);
4631 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4632 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
4633 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
4634 }
4635
4636 case TYPE_AUTO:
4637 return Context.getAutoType(readType(*Loc.F, Record, Idx));
4638
4639 case TYPE_RECORD: {
4640 if (Record.size() != 2) {
4641 Error("incorrect encoding of record type");
4642 return QualType();
4643 }
4644 unsigned Idx = 0;
4645 bool IsDependent = Record[Idx++];
4646 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
4647 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
4648 QualType T = Context.getRecordType(RD);
4649 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4650 return T;
4651 }
4652
4653 case TYPE_ENUM: {
4654 if (Record.size() != 2) {
4655 Error("incorrect encoding of enum type");
4656 return QualType();
4657 }
4658 unsigned Idx = 0;
4659 bool IsDependent = Record[Idx++];
4660 QualType T
4661 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
4662 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4663 return T;
4664 }
4665
4666 case TYPE_ATTRIBUTED: {
4667 if (Record.size() != 3) {
4668 Error("incorrect encoding of attributed type");
4669 return QualType();
4670 }
4671 QualType modifiedType = readType(*Loc.F, Record, Idx);
4672 QualType equivalentType = readType(*Loc.F, Record, Idx);
4673 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
4674 return Context.getAttributedType(kind, modifiedType, equivalentType);
4675 }
4676
4677 case TYPE_PAREN: {
4678 if (Record.size() != 1) {
4679 Error("incorrect encoding of paren type");
4680 return QualType();
4681 }
4682 QualType InnerType = readType(*Loc.F, Record, Idx);
4683 return Context.getParenType(InnerType);
4684 }
4685
4686 case TYPE_PACK_EXPANSION: {
4687 if (Record.size() != 2) {
4688 Error("incorrect encoding of pack expansion type");
4689 return QualType();
4690 }
4691 QualType Pattern = readType(*Loc.F, Record, Idx);
4692 if (Pattern.isNull())
4693 return QualType();
David Blaikiedc84cd52013-02-20 22:23:23 +00004694 Optional<unsigned> NumExpansions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004695 if (Record[1])
4696 NumExpansions = Record[1] - 1;
4697 return Context.getPackExpansionType(Pattern, NumExpansions);
4698 }
4699
4700 case TYPE_ELABORATED: {
4701 unsigned Idx = 0;
4702 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4703 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4704 QualType NamedType = readType(*Loc.F, Record, Idx);
4705 return Context.getElaboratedType(Keyword, NNS, NamedType);
4706 }
4707
4708 case TYPE_OBJC_INTERFACE: {
4709 unsigned Idx = 0;
4710 ObjCInterfaceDecl *ItfD
4711 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
4712 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
4713 }
4714
4715 case TYPE_OBJC_OBJECT: {
4716 unsigned Idx = 0;
4717 QualType Base = readType(*Loc.F, Record, Idx);
4718 unsigned NumProtos = Record[Idx++];
4719 SmallVector<ObjCProtocolDecl*, 4> Protos;
4720 for (unsigned I = 0; I != NumProtos; ++I)
4721 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
4722 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
4723 }
4724
4725 case TYPE_OBJC_OBJECT_POINTER: {
4726 unsigned Idx = 0;
4727 QualType Pointee = readType(*Loc.F, Record, Idx);
4728 return Context.getObjCObjectPointerType(Pointee);
4729 }
4730
4731 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
4732 unsigned Idx = 0;
4733 QualType Parm = readType(*Loc.F, Record, Idx);
4734 QualType Replacement = readType(*Loc.F, Record, Idx);
4735 return
4736 Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
4737 Replacement);
4738 }
4739
4740 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
4741 unsigned Idx = 0;
4742 QualType Parm = readType(*Loc.F, Record, Idx);
4743 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
4744 return Context.getSubstTemplateTypeParmPackType(
4745 cast<TemplateTypeParmType>(Parm),
4746 ArgPack);
4747 }
4748
4749 case TYPE_INJECTED_CLASS_NAME: {
4750 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
4751 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
4752 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
4753 // for AST reading, too much interdependencies.
4754 return
4755 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
4756 }
4757
4758 case TYPE_TEMPLATE_TYPE_PARM: {
4759 unsigned Idx = 0;
4760 unsigned Depth = Record[Idx++];
4761 unsigned Index = Record[Idx++];
4762 bool Pack = Record[Idx++];
4763 TemplateTypeParmDecl *D
4764 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
4765 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
4766 }
4767
4768 case TYPE_DEPENDENT_NAME: {
4769 unsigned Idx = 0;
4770 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4771 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4772 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4773 QualType Canon = readType(*Loc.F, Record, Idx);
4774 if (!Canon.isNull())
4775 Canon = Context.getCanonicalType(Canon);
4776 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
4777 }
4778
4779 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
4780 unsigned Idx = 0;
4781 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4782 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4783 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4784 unsigned NumArgs = Record[Idx++];
4785 SmallVector<TemplateArgument, 8> Args;
4786 Args.reserve(NumArgs);
4787 while (NumArgs--)
4788 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
4789 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
4790 Args.size(), Args.data());
4791 }
4792
4793 case TYPE_DEPENDENT_SIZED_ARRAY: {
4794 unsigned Idx = 0;
4795
4796 // ArrayType
4797 QualType ElementType = readType(*Loc.F, Record, Idx);
4798 ArrayType::ArraySizeModifier ASM
4799 = (ArrayType::ArraySizeModifier)Record[Idx++];
4800 unsigned IndexTypeQuals = Record[Idx++];
4801
4802 // DependentSizedArrayType
4803 Expr *NumElts = ReadExpr(*Loc.F);
4804 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
4805
4806 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
4807 IndexTypeQuals, Brackets);
4808 }
4809
4810 case TYPE_TEMPLATE_SPECIALIZATION: {
4811 unsigned Idx = 0;
4812 bool IsDependent = Record[Idx++];
4813 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
4814 SmallVector<TemplateArgument, 8> Args;
4815 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
4816 QualType Underlying = readType(*Loc.F, Record, Idx);
4817 QualType T;
4818 if (Underlying.isNull())
4819 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
4820 Args.size());
4821 else
4822 T = Context.getTemplateSpecializationType(Name, Args.data(),
4823 Args.size(), Underlying);
4824 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4825 return T;
4826 }
4827
4828 case TYPE_ATOMIC: {
4829 if (Record.size() != 1) {
4830 Error("Incorrect encoding of atomic type");
4831 return QualType();
4832 }
4833 QualType ValueType = readType(*Loc.F, Record, Idx);
4834 return Context.getAtomicType(ValueType);
4835 }
4836 }
4837 llvm_unreachable("Invalid TypeCode!");
4838}
4839
4840class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
4841 ASTReader &Reader;
4842 ModuleFile &F;
4843 const ASTReader::RecordData &Record;
4844 unsigned &Idx;
4845
4846 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
4847 unsigned &I) {
4848 return Reader.ReadSourceLocation(F, R, I);
4849 }
4850
4851 template<typename T>
4852 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
4853 return Reader.ReadDeclAs<T>(F, Record, Idx);
4854 }
4855
4856public:
4857 TypeLocReader(ASTReader &Reader, ModuleFile &F,
4858 const ASTReader::RecordData &Record, unsigned &Idx)
4859 : Reader(Reader), F(F), Record(Record), Idx(Idx)
4860 { }
4861
4862 // We want compile-time assurance that we've enumerated all of
4863 // these, so unfortunately we have to declare them first, then
4864 // define them out-of-line.
4865#define ABSTRACT_TYPELOC(CLASS, PARENT)
4866#define TYPELOC(CLASS, PARENT) \
4867 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
4868#include "clang/AST/TypeLocNodes.def"
4869
4870 void VisitFunctionTypeLoc(FunctionTypeLoc);
4871 void VisitArrayTypeLoc(ArrayTypeLoc);
4872};
4873
4874void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4875 // nothing to do
4876}
4877void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4878 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
4879 if (TL.needsExtraLocalData()) {
4880 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
4881 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
4882 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
4883 TL.setModeAttr(Record[Idx++]);
4884 }
4885}
4886void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
4887 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4888}
4889void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
4890 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4891}
4892void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
4893 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
4894}
4895void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
4896 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
4897}
4898void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
4899 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
4900}
4901void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
4902 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4903 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4904}
4905void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
4906 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
4907 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
4908 if (Record[Idx++])
4909 TL.setSizeExpr(Reader.ReadExpr(F));
4910 else
4911 TL.setSizeExpr(0);
4912}
4913void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
4914 VisitArrayTypeLoc(TL);
4915}
4916void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
4917 VisitArrayTypeLoc(TL);
4918}
4919void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
4920 VisitArrayTypeLoc(TL);
4921}
4922void TypeLocReader::VisitDependentSizedArrayTypeLoc(
4923 DependentSizedArrayTypeLoc TL) {
4924 VisitArrayTypeLoc(TL);
4925}
4926void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
4927 DependentSizedExtVectorTypeLoc TL) {
4928 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4929}
4930void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
4931 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4932}
4933void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
4934 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4935}
4936void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
4937 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
4938 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4939 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4940 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
4941 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
4942 TL.setArg(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
4943 }
4944}
4945void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
4946 VisitFunctionTypeLoc(TL);
4947}
4948void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
4949 VisitFunctionTypeLoc(TL);
4950}
4951void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
4952 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4953}
4954void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
4955 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4956}
4957void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
4958 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
4959 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4960 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4961}
4962void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
4963 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
4964 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4965 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4966 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4967}
4968void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
4969 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4970}
4971void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
4972 TL.setKWLoc(ReadSourceLocation(Record, Idx));
4973 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4974 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4975 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4976}
4977void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
4978 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4979}
4980void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
4981 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4982}
4983void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
4984 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4985}
4986void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4987 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
4988 if (TL.hasAttrOperand()) {
4989 SourceRange range;
4990 range.setBegin(ReadSourceLocation(Record, Idx));
4991 range.setEnd(ReadSourceLocation(Record, Idx));
4992 TL.setAttrOperandParensRange(range);
4993 }
4994 if (TL.hasAttrExprOperand()) {
4995 if (Record[Idx++])
4996 TL.setAttrExprOperand(Reader.ReadExpr(F));
4997 else
4998 TL.setAttrExprOperand(0);
4999 } else if (TL.hasAttrEnumOperand())
5000 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5001}
5002void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5003 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5004}
5005void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5006 SubstTemplateTypeParmTypeLoc TL) {
5007 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5008}
5009void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5010 SubstTemplateTypeParmPackTypeLoc TL) {
5011 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5012}
5013void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5014 TemplateSpecializationTypeLoc TL) {
5015 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5016 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5017 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5018 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5019 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5020 TL.setArgLocInfo(i,
5021 Reader.GetTemplateArgumentLocInfo(F,
5022 TL.getTypePtr()->getArg(i).getKind(),
5023 Record, Idx));
5024}
5025void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5026 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5027 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5028}
5029void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5030 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5031 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5032}
5033void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5034 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5035}
5036void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5037 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5038 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5039 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5040}
5041void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5042 DependentTemplateSpecializationTypeLoc TL) {
5043 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5044 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5045 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5046 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5047 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5048 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5049 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5050 TL.setArgLocInfo(I,
5051 Reader.GetTemplateArgumentLocInfo(F,
5052 TL.getTypePtr()->getArg(I).getKind(),
5053 Record, Idx));
5054}
5055void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5056 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5057}
5058void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5059 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5060}
5061void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5062 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5063 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5064 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5065 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5066 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5067}
5068void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5069 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5070}
5071void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5072 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5073 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5074 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5075}
5076
5077TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5078 const RecordData &Record,
5079 unsigned &Idx) {
5080 QualType InfoTy = readType(F, Record, Idx);
5081 if (InfoTy.isNull())
5082 return 0;
5083
5084 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5085 TypeLocReader TLR(*this, F, Record, Idx);
5086 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5087 TLR.Visit(TL);
5088 return TInfo;
5089}
5090
5091QualType ASTReader::GetType(TypeID ID) {
5092 unsigned FastQuals = ID & Qualifiers::FastMask;
5093 unsigned Index = ID >> Qualifiers::FastWidth;
5094
5095 if (Index < NUM_PREDEF_TYPE_IDS) {
5096 QualType T;
5097 switch ((PredefinedTypeIDs)Index) {
5098 case PREDEF_TYPE_NULL_ID: return QualType();
5099 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5100 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5101
5102 case PREDEF_TYPE_CHAR_U_ID:
5103 case PREDEF_TYPE_CHAR_S_ID:
5104 // FIXME: Check that the signedness of CharTy is correct!
5105 T = Context.CharTy;
5106 break;
5107
5108 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5109 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5110 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5111 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5112 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5113 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5114 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5115 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5116 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5117 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5118 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5119 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5120 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5121 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5122 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5123 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5124 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5125 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5126 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5127 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5128 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5129 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5130 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5131 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5132 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5133 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5134 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5135 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeib13621d2012-12-18 14:38:23 +00005136 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5137 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5138 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5139 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5140 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5141 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei21f18c42013-02-07 10:55:47 +00005142 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00005143 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005144 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5145
5146 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5147 T = Context.getAutoRRefDeductType();
5148 break;
5149
5150 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5151 T = Context.ARCUnbridgedCastTy;
5152 break;
5153
5154 case PREDEF_TYPE_VA_LIST_TAG:
5155 T = Context.getVaListTagType();
5156 break;
5157
5158 case PREDEF_TYPE_BUILTIN_FN:
5159 T = Context.BuiltinFnTy;
5160 break;
5161 }
5162
5163 assert(!T.isNull() && "Unknown predefined type");
5164 return T.withFastQualifiers(FastQuals);
5165 }
5166
5167 Index -= NUM_PREDEF_TYPE_IDS;
5168 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5169 if (TypesLoaded[Index].isNull()) {
5170 TypesLoaded[Index] = readTypeRecord(Index);
5171 if (TypesLoaded[Index].isNull())
5172 return QualType();
5173
5174 TypesLoaded[Index]->setFromAST();
5175 if (DeserializationListener)
5176 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5177 TypesLoaded[Index]);
5178 }
5179
5180 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5181}
5182
5183QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5184 return GetType(getGlobalTypeID(F, LocalID));
5185}
5186
5187serialization::TypeID
5188ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5189 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5190 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5191
5192 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5193 return LocalID;
5194
5195 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5196 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5197 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5198
5199 unsigned GlobalIndex = LocalIndex + I->second;
5200 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5201}
5202
5203TemplateArgumentLocInfo
5204ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5205 TemplateArgument::ArgKind Kind,
5206 const RecordData &Record,
5207 unsigned &Index) {
5208 switch (Kind) {
5209 case TemplateArgument::Expression:
5210 return ReadExpr(F);
5211 case TemplateArgument::Type:
5212 return GetTypeSourceInfo(F, Record, Index);
5213 case TemplateArgument::Template: {
5214 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5215 Index);
5216 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5217 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5218 SourceLocation());
5219 }
5220 case TemplateArgument::TemplateExpansion: {
5221 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5222 Index);
5223 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5224 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5225 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5226 EllipsisLoc);
5227 }
5228 case TemplateArgument::Null:
5229 case TemplateArgument::Integral:
5230 case TemplateArgument::Declaration:
5231 case TemplateArgument::NullPtr:
5232 case TemplateArgument::Pack:
5233 // FIXME: Is this right?
5234 return TemplateArgumentLocInfo();
5235 }
5236 llvm_unreachable("unexpected template argument loc");
5237}
5238
5239TemplateArgumentLoc
5240ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5241 const RecordData &Record, unsigned &Index) {
5242 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5243
5244 if (Arg.getKind() == TemplateArgument::Expression) {
5245 if (Record[Index++]) // bool InfoHasSameExpr.
5246 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5247 }
5248 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5249 Record, Index));
5250}
5251
5252Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5253 return GetDecl(ID);
5254}
5255
5256uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5257 unsigned &Idx){
5258 if (Idx >= Record.size())
5259 return 0;
5260
5261 unsigned LocalID = Record[Idx++];
5262 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5263}
5264
5265CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5266 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00005267 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005268 SavedStreamPosition SavedPosition(Cursor);
5269 Cursor.JumpToBit(Loc.Offset);
5270 ReadingKindTracker ReadingKind(Read_Decl, *this);
5271 RecordData Record;
5272 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00005273 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005274 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5275 Error("Malformed AST file: missing C++ base specifiers");
5276 return 0;
5277 }
5278
5279 unsigned Idx = 0;
5280 unsigned NumBases = Record[Idx++];
5281 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5282 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5283 for (unsigned I = 0; I != NumBases; ++I)
5284 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5285 return Bases;
5286}
5287
5288serialization::DeclID
5289ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5290 if (LocalID < NUM_PREDEF_DECL_IDS)
5291 return LocalID;
5292
5293 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5294 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5295 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5296
5297 return LocalID + I->second;
5298}
5299
5300bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5301 ModuleFile &M) const {
5302 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5303 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5304 return &M == I->second;
5305}
5306
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005307ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005308 if (!D->isFromASTFile())
5309 return 0;
5310 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5311 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5312 return I->second;
5313}
5314
5315SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5316 if (ID < NUM_PREDEF_DECL_IDS)
5317 return SourceLocation();
5318
5319 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5320
5321 if (Index > DeclsLoaded.size()) {
5322 Error("declaration ID out-of-range for AST file");
5323 return SourceLocation();
5324 }
5325
5326 if (Decl *D = DeclsLoaded[Index])
5327 return D->getLocation();
5328
5329 unsigned RawLocation = 0;
5330 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5331 return ReadSourceLocation(*Rec.F, RawLocation);
5332}
5333
5334Decl *ASTReader::GetDecl(DeclID ID) {
5335 if (ID < NUM_PREDEF_DECL_IDS) {
5336 switch ((PredefinedDeclIDs)ID) {
5337 case PREDEF_DECL_NULL_ID:
5338 return 0;
5339
5340 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5341 return Context.getTranslationUnitDecl();
5342
5343 case PREDEF_DECL_OBJC_ID_ID:
5344 return Context.getObjCIdDecl();
5345
5346 case PREDEF_DECL_OBJC_SEL_ID:
5347 return Context.getObjCSelDecl();
5348
5349 case PREDEF_DECL_OBJC_CLASS_ID:
5350 return Context.getObjCClassDecl();
5351
5352 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5353 return Context.getObjCProtocolDecl();
5354
5355 case PREDEF_DECL_INT_128_ID:
5356 return Context.getInt128Decl();
5357
5358 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5359 return Context.getUInt128Decl();
5360
5361 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5362 return Context.getObjCInstanceTypeDecl();
5363
5364 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5365 return Context.getBuiltinVaListDecl();
5366 }
5367 }
5368
5369 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5370
5371 if (Index >= DeclsLoaded.size()) {
5372 assert(0 && "declaration ID out-of-range for AST file");
5373 Error("declaration ID out-of-range for AST file");
5374 return 0;
5375 }
5376
5377 if (!DeclsLoaded[Index]) {
5378 ReadDeclRecord(ID);
5379 if (DeserializationListener)
5380 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5381 }
5382
5383 return DeclsLoaded[Index];
5384}
5385
5386DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5387 DeclID GlobalID) {
5388 if (GlobalID < NUM_PREDEF_DECL_IDS)
5389 return GlobalID;
5390
5391 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5392 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5393 ModuleFile *Owner = I->second;
5394
5395 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5396 = M.GlobalToLocalDeclIDs.find(Owner);
5397 if (Pos == M.GlobalToLocalDeclIDs.end())
5398 return 0;
5399
5400 return GlobalID - Owner->BaseDeclID + Pos->second;
5401}
5402
5403serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5404 const RecordData &Record,
5405 unsigned &Idx) {
5406 if (Idx >= Record.size()) {
5407 Error("Corrupted AST file");
5408 return 0;
5409 }
5410
5411 return getGlobalDeclID(F, Record[Idx++]);
5412}
5413
5414/// \brief Resolve the offset of a statement into a statement.
5415///
5416/// This operation will read a new statement from the external
5417/// source each time it is called, and is meant to be used via a
5418/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5419Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5420 // Switch case IDs are per Decl.
5421 ClearSwitchCaseIDs();
5422
5423 // Offset here is a global offset across the entire chain.
5424 RecordLocation Loc = getLocalBitOffset(Offset);
5425 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5426 return ReadStmtFromStream(*Loc.F);
5427}
5428
5429namespace {
5430 class FindExternalLexicalDeclsVisitor {
5431 ASTReader &Reader;
5432 const DeclContext *DC;
5433 bool (*isKindWeWant)(Decl::Kind);
5434
5435 SmallVectorImpl<Decl*> &Decls;
5436 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5437
5438 public:
5439 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5440 bool (*isKindWeWant)(Decl::Kind),
5441 SmallVectorImpl<Decl*> &Decls)
5442 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5443 {
5444 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5445 PredefsVisited[I] = false;
5446 }
5447
5448 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5449 if (Preorder)
5450 return false;
5451
5452 FindExternalLexicalDeclsVisitor *This
5453 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5454
5455 ModuleFile::DeclContextInfosMap::iterator Info
5456 = M.DeclContextInfos.find(This->DC);
5457 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5458 return false;
5459
5460 // Load all of the declaration IDs
5461 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5462 *IDE = ID + Info->second.NumLexicalDecls;
5463 ID != IDE; ++ID) {
5464 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5465 continue;
5466
5467 // Don't add predefined declarations to the lexical context more
5468 // than once.
5469 if (ID->second < NUM_PREDEF_DECL_IDS) {
5470 if (This->PredefsVisited[ID->second])
5471 continue;
5472
5473 This->PredefsVisited[ID->second] = true;
5474 }
5475
5476 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5477 if (!This->DC->isDeclInLexicalTraversal(D))
5478 This->Decls.push_back(D);
5479 }
5480 }
5481
5482 return false;
5483 }
5484 };
5485}
5486
5487ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
5488 bool (*isKindWeWant)(Decl::Kind),
5489 SmallVectorImpl<Decl*> &Decls) {
5490 // There might be lexical decls in multiple modules, for the TU at
5491 // least. Walk all of the modules in the order they were loaded.
5492 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5493 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
5494 ++NumLexicalDeclContextsRead;
5495 return ELR_Success;
5496}
5497
5498namespace {
5499
5500class DeclIDComp {
5501 ASTReader &Reader;
5502 ModuleFile &Mod;
5503
5504public:
5505 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
5506
5507 bool operator()(LocalDeclID L, LocalDeclID R) const {
5508 SourceLocation LHS = getLocation(L);
5509 SourceLocation RHS = getLocation(R);
5510 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5511 }
5512
5513 bool operator()(SourceLocation LHS, LocalDeclID R) const {
5514 SourceLocation RHS = getLocation(R);
5515 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5516 }
5517
5518 bool operator()(LocalDeclID L, SourceLocation RHS) const {
5519 SourceLocation LHS = getLocation(L);
5520 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5521 }
5522
5523 SourceLocation getLocation(LocalDeclID ID) const {
5524 return Reader.getSourceManager().getFileLoc(
5525 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
5526 }
5527};
5528
5529}
5530
5531void ASTReader::FindFileRegionDecls(FileID File,
5532 unsigned Offset, unsigned Length,
5533 SmallVectorImpl<Decl *> &Decls) {
5534 SourceManager &SM = getSourceManager();
5535
5536 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
5537 if (I == FileDeclIDs.end())
5538 return;
5539
5540 FileDeclsInfo &DInfo = I->second;
5541 if (DInfo.Decls.empty())
5542 return;
5543
5544 SourceLocation
5545 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
5546 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
5547
5548 DeclIDComp DIDComp(*this, *DInfo.Mod);
5549 ArrayRef<serialization::LocalDeclID>::iterator
5550 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5551 BeginLoc, DIDComp);
5552 if (BeginIt != DInfo.Decls.begin())
5553 --BeginIt;
5554
5555 // If we are pointing at a top-level decl inside an objc container, we need
5556 // to backtrack until we find it otherwise we will fail to report that the
5557 // region overlaps with an objc container.
5558 while (BeginIt != DInfo.Decls.begin() &&
5559 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
5560 ->isTopLevelDeclInObjCContainer())
5561 --BeginIt;
5562
5563 ArrayRef<serialization::LocalDeclID>::iterator
5564 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5565 EndLoc, DIDComp);
5566 if (EndIt != DInfo.Decls.end())
5567 ++EndIt;
5568
5569 for (ArrayRef<serialization::LocalDeclID>::iterator
5570 DIt = BeginIt; DIt != EndIt; ++DIt)
5571 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
5572}
5573
5574namespace {
5575 /// \brief ModuleFile visitor used to perform name lookup into a
5576 /// declaration context.
5577 class DeclContextNameLookupVisitor {
5578 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005579 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005580 DeclarationName Name;
5581 SmallVectorImpl<NamedDecl *> &Decls;
5582
5583 public:
5584 DeclContextNameLookupVisitor(ASTReader &Reader,
5585 SmallVectorImpl<const DeclContext *> &Contexts,
5586 DeclarationName Name,
5587 SmallVectorImpl<NamedDecl *> &Decls)
5588 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
5589
5590 static bool visit(ModuleFile &M, void *UserData) {
5591 DeclContextNameLookupVisitor *This
5592 = static_cast<DeclContextNameLookupVisitor *>(UserData);
5593
5594 // Check whether we have any visible declaration information for
5595 // this context in this module.
5596 ModuleFile::DeclContextInfosMap::iterator Info;
5597 bool FoundInfo = false;
5598 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5599 Info = M.DeclContextInfos.find(This->Contexts[I]);
5600 if (Info != M.DeclContextInfos.end() &&
5601 Info->second.NameLookupTableData) {
5602 FoundInfo = true;
5603 break;
5604 }
5605 }
5606
5607 if (!FoundInfo)
5608 return false;
5609
5610 // Look for this name within this module.
5611 ASTDeclContextNameLookupTable *LookupTable =
5612 Info->second.NameLookupTableData;
5613 ASTDeclContextNameLookupTable::iterator Pos
5614 = LookupTable->find(This->Name);
5615 if (Pos == LookupTable->end())
5616 return false;
5617
5618 bool FoundAnything = false;
5619 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
5620 for (; Data.first != Data.second; ++Data.first) {
5621 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
5622 if (!ND)
5623 continue;
5624
5625 if (ND->getDeclName() != This->Name) {
5626 // A name might be null because the decl's redeclarable part is
5627 // currently read before reading its name. The lookup is triggered by
5628 // building that decl (likely indirectly), and so it is later in the
5629 // sense of "already existing" and can be ignored here.
5630 continue;
5631 }
5632
5633 // Record this declaration.
5634 FoundAnything = true;
5635 This->Decls.push_back(ND);
5636 }
5637
5638 return FoundAnything;
5639 }
5640 };
5641}
5642
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005643/// \brief Retrieve the "definitive" module file for the definition of the
5644/// given declaration context, if there is one.
5645///
5646/// The "definitive" module file is the only place where we need to look to
5647/// find information about the declarations within the given declaration
5648/// context. For example, C++ and Objective-C classes, C structs/unions, and
5649/// Objective-C protocols, categories, and extensions are all defined in a
5650/// single place in the source code, so they have definitive module files
5651/// associated with them. C++ namespaces, on the other hand, can have
5652/// definitions in multiple different module files.
5653///
5654/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
5655/// NDEBUG checking.
5656static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
5657 ASTReader &Reader) {
Douglas Gregore0d20662013-01-22 17:08:30 +00005658 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
5659 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005660
5661 return 0;
5662}
5663
Richard Smith3646c682013-02-07 03:30:24 +00005664bool
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005665ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
5666 DeclarationName Name) {
5667 assert(DC->hasExternalVisibleStorage() &&
5668 "DeclContext has no visible decls in storage");
5669 if (!Name)
Richard Smith3646c682013-02-07 03:30:24 +00005670 return false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005671
5672 SmallVector<NamedDecl *, 64> Decls;
5673
5674 // Compute the declaration contexts we need to look into. Multiple such
5675 // declaration contexts occur when two declaration contexts from disjoint
5676 // modules get merged, e.g., when two namespaces with the same name are
5677 // independently defined in separate modules.
5678 SmallVector<const DeclContext *, 2> Contexts;
5679 Contexts.push_back(DC);
5680
5681 if (DC->isNamespace()) {
5682 MergedDeclsMap::iterator Merged
5683 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5684 if (Merged != MergedDecls.end()) {
5685 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5686 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5687 }
5688 }
5689
5690 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005691
5692 // If we can definitively determine which module file to look into,
5693 // only look there. Otherwise, look in all module files.
5694 ModuleFile *Definitive;
5695 if (Contexts.size() == 1 &&
5696 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
5697 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
5698 } else {
5699 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
5700 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005701 ++NumVisibleDeclContextsRead;
5702 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith3646c682013-02-07 03:30:24 +00005703 return !Decls.empty();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005704}
5705
5706namespace {
5707 /// \brief ModuleFile visitor used to retrieve all visible names in a
5708 /// declaration context.
5709 class DeclContextAllNamesVisitor {
5710 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005711 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005712 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > &Decls;
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005713 bool VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005714
5715 public:
5716 DeclContextAllNamesVisitor(ASTReader &Reader,
5717 SmallVectorImpl<const DeclContext *> &Contexts,
5718 llvm::DenseMap<DeclarationName,
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005719 SmallVector<NamedDecl *, 8> > &Decls,
5720 bool VisitAll)
5721 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005722
5723 static bool visit(ModuleFile &M, void *UserData) {
5724 DeclContextAllNamesVisitor *This
5725 = static_cast<DeclContextAllNamesVisitor *>(UserData);
5726
5727 // Check whether we have any visible declaration information for
5728 // this context in this module.
5729 ModuleFile::DeclContextInfosMap::iterator Info;
5730 bool FoundInfo = false;
5731 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5732 Info = M.DeclContextInfos.find(This->Contexts[I]);
5733 if (Info != M.DeclContextInfos.end() &&
5734 Info->second.NameLookupTableData) {
5735 FoundInfo = true;
5736 break;
5737 }
5738 }
5739
5740 if (!FoundInfo)
5741 return false;
5742
5743 ASTDeclContextNameLookupTable *LookupTable =
5744 Info->second.NameLookupTableData;
5745 bool FoundAnything = false;
5746 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregora6b00fc2013-01-23 22:38:11 +00005747 I = LookupTable->data_begin(), E = LookupTable->data_end();
5748 I != E;
5749 ++I) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005750 ASTDeclContextNameLookupTrait::data_type Data = *I;
5751 for (; Data.first != Data.second; ++Data.first) {
5752 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
5753 *Data.first);
5754 if (!ND)
5755 continue;
5756
5757 // Record this declaration.
5758 FoundAnything = true;
5759 This->Decls[ND->getDeclName()].push_back(ND);
5760 }
5761 }
5762
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005763 return FoundAnything && !This->VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005764 }
5765 };
5766}
5767
5768void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
5769 if (!DC->hasExternalVisibleStorage())
5770 return;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005771 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > Decls;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005772
5773 // Compute the declaration contexts we need to look into. Multiple such
5774 // declaration contexts occur when two declaration contexts from disjoint
5775 // modules get merged, e.g., when two namespaces with the same name are
5776 // independently defined in separate modules.
5777 SmallVector<const DeclContext *, 2> Contexts;
5778 Contexts.push_back(DC);
5779
5780 if (DC->isNamespace()) {
5781 MergedDeclsMap::iterator Merged
5782 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5783 if (Merged != MergedDecls.end()) {
5784 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5785 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5786 }
5787 }
5788
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005789 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
5790 /*VisitAll=*/DC->isFileContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005791 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
5792 ++NumVisibleDeclContextsRead;
5793
5794 for (llvm::DenseMap<DeclarationName,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005795 SmallVector<NamedDecl *, 8> >::iterator
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005796 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
5797 SetExternalVisibleDeclsForName(DC, I->first, I->second);
5798 }
5799 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
5800}
5801
5802/// \brief Under non-PCH compilation the consumer receives the objc methods
5803/// before receiving the implementation, and codegen depends on this.
5804/// We simulate this by deserializing and passing to consumer the methods of the
5805/// implementation before passing the deserialized implementation decl.
5806static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
5807 ASTConsumer *Consumer) {
5808 assert(ImplD && Consumer);
5809
5810 for (ObjCImplDecl::method_iterator
5811 I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
5812 Consumer->HandleInterestingDecl(DeclGroupRef(*I));
5813
5814 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
5815}
5816
5817void ASTReader::PassInterestingDeclsToConsumer() {
5818 assert(Consumer);
5819 while (!InterestingDecls.empty()) {
5820 Decl *D = InterestingDecls.front();
5821 InterestingDecls.pop_front();
5822
5823 PassInterestingDeclToConsumer(D);
5824 }
5825}
5826
5827void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
5828 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5829 PassObjCImplDeclToConsumer(ImplD, Consumer);
5830 else
5831 Consumer->HandleInterestingDecl(DeclGroupRef(D));
5832}
5833
5834void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
5835 this->Consumer = Consumer;
5836
5837 if (!Consumer)
5838 return;
5839
5840 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
5841 // Force deserialization of this decl, which will cause it to be queued for
5842 // passing to the consumer.
5843 GetDecl(ExternalDefinitions[I]);
5844 }
5845 ExternalDefinitions.clear();
5846
5847 PassInterestingDeclsToConsumer();
5848}
5849
5850void ASTReader::PrintStats() {
5851 std::fprintf(stderr, "*** AST File Statistics:\n");
5852
5853 unsigned NumTypesLoaded
5854 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
5855 QualType());
5856 unsigned NumDeclsLoaded
5857 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
5858 (Decl *)0);
5859 unsigned NumIdentifiersLoaded
5860 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
5861 IdentifiersLoaded.end(),
5862 (IdentifierInfo *)0);
5863 unsigned NumMacrosLoaded
5864 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
5865 MacrosLoaded.end(),
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00005866 (MacroInfo *)0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005867 unsigned NumSelectorsLoaded
5868 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
5869 SelectorsLoaded.end(),
5870 Selector());
5871
5872 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
5873 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
5874 NumSLocEntriesRead, TotalNumSLocEntries,
5875 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
5876 if (!TypesLoaded.empty())
5877 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
5878 NumTypesLoaded, (unsigned)TypesLoaded.size(),
5879 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
5880 if (!DeclsLoaded.empty())
5881 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
5882 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
5883 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
5884 if (!IdentifiersLoaded.empty())
5885 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
5886 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
5887 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
5888 if (!MacrosLoaded.empty())
5889 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5890 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
5891 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
5892 if (!SelectorsLoaded.empty())
5893 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
5894 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
5895 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
5896 if (TotalNumStatements)
5897 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
5898 NumStatementsRead, TotalNumStatements,
5899 ((float)NumStatementsRead/TotalNumStatements * 100));
5900 if (TotalNumMacros)
5901 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5902 NumMacrosRead, TotalNumMacros,
5903 ((float)NumMacrosRead/TotalNumMacros * 100));
5904 if (TotalLexicalDeclContexts)
5905 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
5906 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
5907 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
5908 * 100));
5909 if (TotalVisibleDeclContexts)
5910 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
5911 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
5912 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
5913 * 100));
5914 if (TotalNumMethodPoolEntries) {
5915 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
5916 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
5917 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
5918 * 100));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005919 }
Douglas Gregor95fb36e2013-01-28 17:54:36 +00005920 if (NumMethodPoolLookups) {
5921 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
5922 NumMethodPoolHits, NumMethodPoolLookups,
5923 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
5924 }
5925 if (NumMethodPoolTableLookups) {
5926 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
5927 NumMethodPoolTableHits, NumMethodPoolTableLookups,
5928 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
5929 * 100.0));
5930 }
5931
Douglas Gregore1698072013-01-25 00:38:33 +00005932 if (NumIdentifierLookupHits) {
5933 std::fprintf(stderr,
5934 " %u / %u identifier table lookups succeeded (%f%%)\n",
5935 NumIdentifierLookupHits, NumIdentifierLookups,
5936 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
5937 }
5938
Douglas Gregor1a49d972013-01-25 01:03:03 +00005939 if (GlobalIndex) {
5940 std::fprintf(stderr, "\n");
5941 GlobalIndex->printStats();
5942 }
5943
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005944 std::fprintf(stderr, "\n");
5945 dump();
5946 std::fprintf(stderr, "\n");
5947}
5948
5949template<typename Key, typename ModuleFile, unsigned InitialCapacity>
5950static void
5951dumpModuleIDMap(StringRef Name,
5952 const ContinuousRangeMap<Key, ModuleFile *,
5953 InitialCapacity> &Map) {
5954 if (Map.begin() == Map.end())
5955 return;
5956
5957 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
5958 llvm::errs() << Name << ":\n";
5959 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
5960 I != IEnd; ++I) {
5961 llvm::errs() << " " << I->first << " -> " << I->second->FileName
5962 << "\n";
5963 }
5964}
5965
5966void ASTReader::dump() {
5967 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
5968 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
5969 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
5970 dumpModuleIDMap("Global type map", GlobalTypeMap);
5971 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
5972 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
5973 dumpModuleIDMap("Global macro map", GlobalMacroMap);
5974 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
5975 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
5976 dumpModuleIDMap("Global preprocessed entity map",
5977 GlobalPreprocessedEntityMap);
5978
5979 llvm::errs() << "\n*** PCH/Modules Loaded:";
5980 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
5981 MEnd = ModuleMgr.end();
5982 M != MEnd; ++M)
5983 (*M)->dump();
5984}
5985
5986/// Return the amount of memory used by memory buffers, breaking down
5987/// by heap-backed versus mmap'ed memory.
5988void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
5989 for (ModuleConstIterator I = ModuleMgr.begin(),
5990 E = ModuleMgr.end(); I != E; ++I) {
5991 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
5992 size_t bytes = buf->getBufferSize();
5993 switch (buf->getBufferKind()) {
5994 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
5995 sizes.malloc_bytes += bytes;
5996 break;
5997 case llvm::MemoryBuffer::MemoryBuffer_MMap:
5998 sizes.mmap_bytes += bytes;
5999 break;
6000 }
6001 }
6002 }
6003}
6004
6005void ASTReader::InitializeSema(Sema &S) {
6006 SemaObj = &S;
6007 S.addExternalSource(this);
6008
6009 // Makes sure any declarations that were deserialized "too early"
6010 // still get added to the identifier's declaration chains.
6011 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Douglas Gregoraa945902013-02-18 15:53:43 +00006012 NamedDecl *ND = cast<NamedDecl>(PreloadedDecls[I]->getMostRecentDecl());
6013 SemaObj->pushExternalDeclIntoScope(ND, PreloadedDecls[I]->getDeclName());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006014 }
6015 PreloadedDecls.clear();
6016
6017 // Load the offsets of the declarations that Sema references.
6018 // They will be lazily deserialized when needed.
6019 if (!SemaDeclRefs.empty()) {
6020 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
6021 if (!SemaObj->StdNamespace)
6022 SemaObj->StdNamespace = SemaDeclRefs[0];
6023 if (!SemaObj->StdBadAlloc)
6024 SemaObj->StdBadAlloc = SemaDeclRefs[1];
6025 }
6026
6027 if (!FPPragmaOptions.empty()) {
6028 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6029 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6030 }
6031
6032 if (!OpenCLExtensions.empty()) {
6033 unsigned I = 0;
6034#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6035#include "clang/Basic/OpenCLExtensions.def"
6036
6037 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6038 }
6039}
6040
6041IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6042 // Note that we are loading an identifier.
6043 Deserializing AnIdentifier(this);
Douglas Gregor1a49d972013-01-25 01:03:03 +00006044 StringRef Name(NameStart, NameEnd - NameStart);
6045
6046 // If there is a global index, look there first to determine which modules
6047 // provably do not have any results for this identifier.
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006048 GlobalModuleIndex::HitSet Hits;
6049 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregor1a49d972013-01-25 01:03:03 +00006050 if (!loadGlobalIndex()) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006051 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6052 HitsPtr = &Hits;
Douglas Gregor1a49d972013-01-25 01:03:03 +00006053 }
6054 }
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006055 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregore1698072013-01-25 00:38:33 +00006056 NumIdentifierLookups,
6057 NumIdentifierLookupHits);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006058 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006059 IdentifierInfo *II = Visitor.getIdentifierInfo();
6060 markIdentifierUpToDate(II);
6061 return II;
6062}
6063
6064namespace clang {
6065 /// \brief An identifier-lookup iterator that enumerates all of the
6066 /// identifiers stored within a set of AST files.
6067 class ASTIdentifierIterator : public IdentifierIterator {
6068 /// \brief The AST reader whose identifiers are being enumerated.
6069 const ASTReader &Reader;
6070
6071 /// \brief The current index into the chain of AST files stored in
6072 /// the AST reader.
6073 unsigned Index;
6074
6075 /// \brief The current position within the identifier lookup table
6076 /// of the current AST file.
6077 ASTIdentifierLookupTable::key_iterator Current;
6078
6079 /// \brief The end position within the identifier lookup table of
6080 /// the current AST file.
6081 ASTIdentifierLookupTable::key_iterator End;
6082
6083 public:
6084 explicit ASTIdentifierIterator(const ASTReader &Reader);
6085
6086 virtual StringRef Next();
6087 };
6088}
6089
6090ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6091 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6092 ASTIdentifierLookupTable *IdTable
6093 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6094 Current = IdTable->key_begin();
6095 End = IdTable->key_end();
6096}
6097
6098StringRef ASTIdentifierIterator::Next() {
6099 while (Current == End) {
6100 // If we have exhausted all of our AST files, we're done.
6101 if (Index == 0)
6102 return StringRef();
6103
6104 --Index;
6105 ASTIdentifierLookupTable *IdTable
6106 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6107 IdentifierLookupTable;
6108 Current = IdTable->key_begin();
6109 End = IdTable->key_end();
6110 }
6111
6112 // We have any identifiers remaining in the current AST file; return
6113 // the next one.
Douglas Gregor479633c2013-01-23 18:53:14 +00006114 StringRef Result = *Current;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006115 ++Current;
Douglas Gregor479633c2013-01-23 18:53:14 +00006116 return Result;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006117}
6118
6119IdentifierIterator *ASTReader::getIdentifiers() const {
6120 return new ASTIdentifierIterator(*this);
6121}
6122
6123namespace clang { namespace serialization {
6124 class ReadMethodPoolVisitor {
6125 ASTReader &Reader;
6126 Selector Sel;
6127 unsigned PriorGeneration;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006128 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6129 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006130
6131 public:
6132 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6133 unsigned PriorGeneration)
6134 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) { }
6135
6136 static bool visit(ModuleFile &M, void *UserData) {
6137 ReadMethodPoolVisitor *This
6138 = static_cast<ReadMethodPoolVisitor *>(UserData);
6139
6140 if (!M.SelectorLookupTable)
6141 return false;
6142
6143 // If we've already searched this module file, skip it now.
6144 if (M.Generation <= This->PriorGeneration)
6145 return true;
6146
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006147 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006148 ASTSelectorLookupTable *PoolTable
6149 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6150 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6151 if (Pos == PoolTable->end())
6152 return false;
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006153
6154 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006155 ++This->Reader.NumSelectorsRead;
6156 // FIXME: Not quite happy with the statistics here. We probably should
6157 // disable this tracking when called via LoadSelector.
6158 // Also, should entries without methods count as misses?
6159 ++This->Reader.NumMethodPoolEntriesRead;
6160 ASTSelectorLookupTrait::data_type Data = *Pos;
6161 if (This->Reader.DeserializationListener)
6162 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6163 This->Sel);
6164
6165 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6166 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6167 return true;
6168 }
6169
6170 /// \brief Retrieve the instance methods found by this visitor.
6171 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6172 return InstanceMethods;
6173 }
6174
6175 /// \brief Retrieve the instance methods found by this visitor.
6176 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6177 return FactoryMethods;
6178 }
6179 };
6180} } // end namespace clang::serialization
6181
6182/// \brief Add the given set of methods to the method list.
6183static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6184 ObjCMethodList &List) {
6185 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6186 S.addMethodToGlobalList(&List, Methods[I]);
6187 }
6188}
6189
6190void ASTReader::ReadMethodPool(Selector Sel) {
6191 // Get the selector generation and update it to the current generation.
6192 unsigned &Generation = SelectorGeneration[Sel];
6193 unsigned PriorGeneration = Generation;
6194 Generation = CurrentGeneration;
6195
6196 // Search for methods defined with this selector.
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006197 ++NumMethodPoolLookups;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006198 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6199 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6200
6201 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006202 Visitor.getFactoryMethods().empty())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006203 return;
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006204
6205 ++NumMethodPoolHits;
6206
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006207 if (!getSema())
6208 return;
6209
6210 Sema &S = *getSema();
6211 Sema::GlobalMethodPool::iterator Pos
6212 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6213
6214 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6215 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
6216}
6217
6218void ASTReader::ReadKnownNamespaces(
6219 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6220 Namespaces.clear();
6221
6222 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6223 if (NamespaceDecl *Namespace
6224 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6225 Namespaces.push_back(Namespace);
6226 }
6227}
6228
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006229void ASTReader::ReadUndefinedButUsed(
Nick Lewycky995e26b2013-01-31 03:23:57 +00006230 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006231 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6232 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky01a41142013-01-26 00:35:08 +00006233 SourceLocation Loc =
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006234 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky01a41142013-01-26 00:35:08 +00006235 Undefined.insert(std::make_pair(D, Loc));
6236 }
6237}
Nick Lewycky01a41142013-01-26 00:35:08 +00006238
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006239void ASTReader::ReadTentativeDefinitions(
6240 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6241 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6242 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6243 if (Var)
6244 TentativeDefs.push_back(Var);
6245 }
6246 TentativeDefinitions.clear();
6247}
6248
6249void ASTReader::ReadUnusedFileScopedDecls(
6250 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6251 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6252 DeclaratorDecl *D
6253 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6254 if (D)
6255 Decls.push_back(D);
6256 }
6257 UnusedFileScopedDecls.clear();
6258}
6259
6260void ASTReader::ReadDelegatingConstructors(
6261 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6262 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6263 CXXConstructorDecl *D
6264 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6265 if (D)
6266 Decls.push_back(D);
6267 }
6268 DelegatingCtorDecls.clear();
6269}
6270
6271void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6272 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6273 TypedefNameDecl *D
6274 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6275 if (D)
6276 Decls.push_back(D);
6277 }
6278 ExtVectorDecls.clear();
6279}
6280
6281void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6282 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6283 CXXRecordDecl *D
6284 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6285 if (D)
6286 Decls.push_back(D);
6287 }
6288 DynamicClasses.clear();
6289}
6290
6291void
Richard Smith5ea6ef42013-01-10 23:43:47 +00006292ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6293 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6294 NamedDecl *D
6295 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006296 if (D)
6297 Decls.push_back(D);
6298 }
Richard Smith5ea6ef42013-01-10 23:43:47 +00006299 LocallyScopedExternCDecls.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006300}
6301
6302void ASTReader::ReadReferencedSelectors(
6303 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6304 if (ReferencedSelectorsData.empty())
6305 return;
6306
6307 // If there are @selector references added them to its pool. This is for
6308 // implementation of -Wselector.
6309 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6310 unsigned I = 0;
6311 while (I < DataSize) {
6312 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6313 SourceLocation SelLoc
6314 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6315 Sels.push_back(std::make_pair(Sel, SelLoc));
6316 }
6317 ReferencedSelectorsData.clear();
6318}
6319
6320void ASTReader::ReadWeakUndeclaredIdentifiers(
6321 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6322 if (WeakUndeclaredIdentifiers.empty())
6323 return;
6324
6325 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6326 IdentifierInfo *WeakId
6327 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6328 IdentifierInfo *AliasId
6329 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6330 SourceLocation Loc
6331 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6332 bool Used = WeakUndeclaredIdentifiers[I++];
6333 WeakInfo WI(AliasId, Loc);
6334 WI.setUsed(Used);
6335 WeakIDs.push_back(std::make_pair(WeakId, WI));
6336 }
6337 WeakUndeclaredIdentifiers.clear();
6338}
6339
6340void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6341 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6342 ExternalVTableUse VT;
6343 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6344 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6345 VT.DefinitionRequired = VTableUses[Idx++];
6346 VTables.push_back(VT);
6347 }
6348
6349 VTableUses.clear();
6350}
6351
6352void ASTReader::ReadPendingInstantiations(
6353 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6354 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6355 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6356 SourceLocation Loc
6357 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6358
6359 Pending.push_back(std::make_pair(D, Loc));
6360 }
6361 PendingInstantiations.clear();
6362}
6363
6364void ASTReader::LoadSelector(Selector Sel) {
6365 // It would be complicated to avoid reading the methods anyway. So don't.
6366 ReadMethodPool(Sel);
6367}
6368
6369void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6370 assert(ID && "Non-zero identifier ID required");
6371 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6372 IdentifiersLoaded[ID - 1] = II;
6373 if (DeserializationListener)
6374 DeserializationListener->IdentifierRead(ID, II);
6375}
6376
6377/// \brief Set the globally-visible declarations associated with the given
6378/// identifier.
6379///
6380/// If the AST reader is currently in a state where the given declaration IDs
6381/// cannot safely be resolved, they are queued until it is safe to resolve
6382/// them.
6383///
6384/// \param II an IdentifierInfo that refers to one or more globally-visible
6385/// declarations.
6386///
6387/// \param DeclIDs the set of declaration IDs with the name @p II that are
6388/// visible at global scope.
6389///
Douglas Gregoraa945902013-02-18 15:53:43 +00006390/// \param Decls if non-null, this vector will be populated with the set of
6391/// deserialized declarations. These declarations will not be pushed into
6392/// scope.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006393void
6394ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6395 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregoraa945902013-02-18 15:53:43 +00006396 SmallVectorImpl<Decl *> *Decls) {
6397 if (NumCurrentElementsDeserializing && !Decls) {
6398 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006399 return;
6400 }
6401
6402 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6403 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6404 if (SemaObj) {
Douglas Gregoraa945902013-02-18 15:53:43 +00006405 // If we're simply supposed to record the declarations, do so now.
6406 if (Decls) {
6407 Decls->push_back(D);
6408 continue;
6409 }
6410
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006411 // Introduce this declaration into the translation-unit scope
6412 // and add it to the declaration chain for this identifier, so
6413 // that (unqualified) name lookup will find it.
Douglas Gregoraa945902013-02-18 15:53:43 +00006414 NamedDecl *ND = cast<NamedDecl>(D->getMostRecentDecl());
6415 SemaObj->pushExternalDeclIntoScope(ND, II);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006416 } else {
6417 // Queue this declaration so that it will be added to the
6418 // translation unit scope and identifier's declaration chain
6419 // once a Sema object is known.
6420 PreloadedDecls.push_back(D);
6421 }
6422 }
6423}
6424
Douglas Gregor8222b892013-01-21 16:52:34 +00006425IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006426 if (ID == 0)
6427 return 0;
6428
6429 if (IdentifiersLoaded.empty()) {
6430 Error("no identifier table in AST file");
6431 return 0;
6432 }
6433
6434 ID -= 1;
6435 if (!IdentifiersLoaded[ID]) {
6436 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6437 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
6438 ModuleFile *M = I->second;
6439 unsigned Index = ID - M->BaseIdentifierID;
6440 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
6441
6442 // All of the strings in the AST file are preceded by a 16-bit length.
6443 // Extract that 16-bit length to avoid having to execute strlen().
6444 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6445 // unsigned integers. This is important to avoid integer overflow when
6446 // we cast them to 'unsigned'.
6447 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
6448 unsigned StrLen = (((unsigned) StrLenPtr[0])
6449 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregor8222b892013-01-21 16:52:34 +00006450 IdentifiersLoaded[ID]
6451 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006452 if (DeserializationListener)
6453 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
6454 }
6455
6456 return IdentifiersLoaded[ID];
6457}
6458
Douglas Gregor8222b892013-01-21 16:52:34 +00006459IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
6460 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006461}
6462
6463IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
6464 if (LocalID < NUM_PREDEF_IDENT_IDS)
6465 return LocalID;
6466
6467 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6468 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6469 assert(I != M.IdentifierRemap.end()
6470 && "Invalid index into identifier index remap");
6471
6472 return LocalID + I->second;
6473}
6474
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00006475MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006476 if (ID == 0)
6477 return 0;
6478
6479 if (MacrosLoaded.empty()) {
6480 Error("no macro table in AST file");
6481 return 0;
6482 }
6483
6484 ID -= NUM_PREDEF_MACRO_IDS;
6485 if (!MacrosLoaded[ID]) {
6486 GlobalMacroMapType::iterator I
6487 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
6488 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
6489 ModuleFile *M = I->second;
6490 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00006491 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
6492
6493 if (DeserializationListener)
6494 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
6495 MacrosLoaded[ID]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006496 }
6497
6498 return MacrosLoaded[ID];
6499}
6500
6501MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
6502 if (LocalID < NUM_PREDEF_MACRO_IDS)
6503 return LocalID;
6504
6505 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6506 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
6507 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
6508
6509 return LocalID + I->second;
6510}
6511
6512serialization::SubmoduleID
6513ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
6514 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
6515 return LocalID;
6516
6517 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6518 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
6519 assert(I != M.SubmoduleRemap.end()
6520 && "Invalid index into submodule index remap");
6521
6522 return LocalID + I->second;
6523}
6524
6525Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
6526 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6527 assert(GlobalID == 0 && "Unhandled global submodule ID");
6528 return 0;
6529 }
6530
6531 if (GlobalID > SubmodulesLoaded.size()) {
6532 Error("submodule ID out of range in AST file");
6533 return 0;
6534 }
6535
6536 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
6537}
Douglas Gregorca2ab452013-01-12 01:29:50 +00006538
6539Module *ASTReader::getModule(unsigned ID) {
6540 return getSubmodule(ID);
6541}
6542
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006543Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
6544 return DecodeSelector(getGlobalSelectorID(M, LocalID));
6545}
6546
6547Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
6548 if (ID == 0)
6549 return Selector();
6550
6551 if (ID > SelectorsLoaded.size()) {
6552 Error("selector ID out of range in AST file");
6553 return Selector();
6554 }
6555
6556 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
6557 // Load this selector from the selector table.
6558 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
6559 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
6560 ModuleFile &M = *I->second;
6561 ASTSelectorLookupTrait Trait(*this, M);
6562 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
6563 SelectorsLoaded[ID - 1] =
6564 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
6565 if (DeserializationListener)
6566 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
6567 }
6568
6569 return SelectorsLoaded[ID - 1];
6570}
6571
6572Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
6573 return DecodeSelector(ID);
6574}
6575
6576uint32_t ASTReader::GetNumExternalSelectors() {
6577 // ID 0 (the null selector) is considered an external selector.
6578 return getTotalNumSelectors() + 1;
6579}
6580
6581serialization::SelectorID
6582ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
6583 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
6584 return LocalID;
6585
6586 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6587 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
6588 assert(I != M.SelectorRemap.end()
6589 && "Invalid index into selector index remap");
6590
6591 return LocalID + I->second;
6592}
6593
6594DeclarationName
6595ASTReader::ReadDeclarationName(ModuleFile &F,
6596 const RecordData &Record, unsigned &Idx) {
6597 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
6598 switch (Kind) {
6599 case DeclarationName::Identifier:
Douglas Gregor8222b892013-01-21 16:52:34 +00006600 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006601
6602 case DeclarationName::ObjCZeroArgSelector:
6603 case DeclarationName::ObjCOneArgSelector:
6604 case DeclarationName::ObjCMultiArgSelector:
6605 return DeclarationName(ReadSelector(F, Record, Idx));
6606
6607 case DeclarationName::CXXConstructorName:
6608 return Context.DeclarationNames.getCXXConstructorName(
6609 Context.getCanonicalType(readType(F, Record, Idx)));
6610
6611 case DeclarationName::CXXDestructorName:
6612 return Context.DeclarationNames.getCXXDestructorName(
6613 Context.getCanonicalType(readType(F, Record, Idx)));
6614
6615 case DeclarationName::CXXConversionFunctionName:
6616 return Context.DeclarationNames.getCXXConversionFunctionName(
6617 Context.getCanonicalType(readType(F, Record, Idx)));
6618
6619 case DeclarationName::CXXOperatorName:
6620 return Context.DeclarationNames.getCXXOperatorName(
6621 (OverloadedOperatorKind)Record[Idx++]);
6622
6623 case DeclarationName::CXXLiteralOperatorName:
6624 return Context.DeclarationNames.getCXXLiteralOperatorName(
6625 GetIdentifierInfo(F, Record, Idx));
6626
6627 case DeclarationName::CXXUsingDirective:
6628 return DeclarationName::getUsingDirectiveName();
6629 }
6630
6631 llvm_unreachable("Invalid NameKind!");
6632}
6633
6634void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
6635 DeclarationNameLoc &DNLoc,
6636 DeclarationName Name,
6637 const RecordData &Record, unsigned &Idx) {
6638 switch (Name.getNameKind()) {
6639 case DeclarationName::CXXConstructorName:
6640 case DeclarationName::CXXDestructorName:
6641 case DeclarationName::CXXConversionFunctionName:
6642 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
6643 break;
6644
6645 case DeclarationName::CXXOperatorName:
6646 DNLoc.CXXOperatorName.BeginOpNameLoc
6647 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6648 DNLoc.CXXOperatorName.EndOpNameLoc
6649 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6650 break;
6651
6652 case DeclarationName::CXXLiteralOperatorName:
6653 DNLoc.CXXLiteralOperatorName.OpNameLoc
6654 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6655 break;
6656
6657 case DeclarationName::Identifier:
6658 case DeclarationName::ObjCZeroArgSelector:
6659 case DeclarationName::ObjCOneArgSelector:
6660 case DeclarationName::ObjCMultiArgSelector:
6661 case DeclarationName::CXXUsingDirective:
6662 break;
6663 }
6664}
6665
6666void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
6667 DeclarationNameInfo &NameInfo,
6668 const RecordData &Record, unsigned &Idx) {
6669 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
6670 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
6671 DeclarationNameLoc DNLoc;
6672 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
6673 NameInfo.setInfo(DNLoc);
6674}
6675
6676void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
6677 const RecordData &Record, unsigned &Idx) {
6678 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
6679 unsigned NumTPLists = Record[Idx++];
6680 Info.NumTemplParamLists = NumTPLists;
6681 if (NumTPLists) {
6682 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
6683 for (unsigned i=0; i != NumTPLists; ++i)
6684 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
6685 }
6686}
6687
6688TemplateName
6689ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
6690 unsigned &Idx) {
6691 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
6692 switch (Kind) {
6693 case TemplateName::Template:
6694 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
6695
6696 case TemplateName::OverloadedTemplate: {
6697 unsigned size = Record[Idx++];
6698 UnresolvedSet<8> Decls;
6699 while (size--)
6700 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
6701
6702 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
6703 }
6704
6705 case TemplateName::QualifiedTemplate: {
6706 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6707 bool hasTemplKeyword = Record[Idx++];
6708 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
6709 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
6710 }
6711
6712 case TemplateName::DependentTemplate: {
6713 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6714 if (Record[Idx++]) // isIdentifier
6715 return Context.getDependentTemplateName(NNS,
6716 GetIdentifierInfo(F, Record,
6717 Idx));
6718 return Context.getDependentTemplateName(NNS,
6719 (OverloadedOperatorKind)Record[Idx++]);
6720 }
6721
6722 case TemplateName::SubstTemplateTemplateParm: {
6723 TemplateTemplateParmDecl *param
6724 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6725 if (!param) return TemplateName();
6726 TemplateName replacement = ReadTemplateName(F, Record, Idx);
6727 return Context.getSubstTemplateTemplateParm(param, replacement);
6728 }
6729
6730 case TemplateName::SubstTemplateTemplateParmPack: {
6731 TemplateTemplateParmDecl *Param
6732 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6733 if (!Param)
6734 return TemplateName();
6735
6736 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
6737 if (ArgPack.getKind() != TemplateArgument::Pack)
6738 return TemplateName();
6739
6740 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
6741 }
6742 }
6743
6744 llvm_unreachable("Unhandled template name kind!");
6745}
6746
6747TemplateArgument
6748ASTReader::ReadTemplateArgument(ModuleFile &F,
6749 const RecordData &Record, unsigned &Idx) {
6750 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
6751 switch (Kind) {
6752 case TemplateArgument::Null:
6753 return TemplateArgument();
6754 case TemplateArgument::Type:
6755 return TemplateArgument(readType(F, Record, Idx));
6756 case TemplateArgument::Declaration: {
6757 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
6758 bool ForReferenceParam = Record[Idx++];
6759 return TemplateArgument(D, ForReferenceParam);
6760 }
6761 case TemplateArgument::NullPtr:
6762 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
6763 case TemplateArgument::Integral: {
6764 llvm::APSInt Value = ReadAPSInt(Record, Idx);
6765 QualType T = readType(F, Record, Idx);
6766 return TemplateArgument(Context, Value, T);
6767 }
6768 case TemplateArgument::Template:
6769 return TemplateArgument(ReadTemplateName(F, Record, Idx));
6770 case TemplateArgument::TemplateExpansion: {
6771 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikiedc84cd52013-02-20 22:23:23 +00006772 Optional<unsigned> NumTemplateExpansions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006773 if (unsigned NumExpansions = Record[Idx++])
6774 NumTemplateExpansions = NumExpansions - 1;
6775 return TemplateArgument(Name, NumTemplateExpansions);
6776 }
6777 case TemplateArgument::Expression:
6778 return TemplateArgument(ReadExpr(F));
6779 case TemplateArgument::Pack: {
6780 unsigned NumArgs = Record[Idx++];
6781 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
6782 for (unsigned I = 0; I != NumArgs; ++I)
6783 Args[I] = ReadTemplateArgument(F, Record, Idx);
6784 return TemplateArgument(Args, NumArgs);
6785 }
6786 }
6787
6788 llvm_unreachable("Unhandled template argument kind!");
6789}
6790
6791TemplateParameterList *
6792ASTReader::ReadTemplateParameterList(ModuleFile &F,
6793 const RecordData &Record, unsigned &Idx) {
6794 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
6795 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
6796 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
6797
6798 unsigned NumParams = Record[Idx++];
6799 SmallVector<NamedDecl *, 16> Params;
6800 Params.reserve(NumParams);
6801 while (NumParams--)
6802 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
6803
6804 TemplateParameterList* TemplateParams =
6805 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
6806 Params.data(), Params.size(), RAngleLoc);
6807 return TemplateParams;
6808}
6809
6810void
6811ASTReader::
6812ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
6813 ModuleFile &F, const RecordData &Record,
6814 unsigned &Idx) {
6815 unsigned NumTemplateArgs = Record[Idx++];
6816 TemplArgs.reserve(NumTemplateArgs);
6817 while (NumTemplateArgs--)
6818 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
6819}
6820
6821/// \brief Read a UnresolvedSet structure.
6822void ASTReader::ReadUnresolvedSet(ModuleFile &F, ASTUnresolvedSet &Set,
6823 const RecordData &Record, unsigned &Idx) {
6824 unsigned NumDecls = Record[Idx++];
6825 Set.reserve(Context, NumDecls);
6826 while (NumDecls--) {
6827 NamedDecl *D = ReadDeclAs<NamedDecl>(F, Record, Idx);
6828 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
6829 Set.addDecl(Context, D, AS);
6830 }
6831}
6832
6833CXXBaseSpecifier
6834ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
6835 const RecordData &Record, unsigned &Idx) {
6836 bool isVirtual = static_cast<bool>(Record[Idx++]);
6837 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
6838 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
6839 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
6840 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
6841 SourceRange Range = ReadSourceRange(F, Record, Idx);
6842 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
6843 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
6844 EllipsisLoc);
6845 Result.setInheritConstructors(inheritConstructors);
6846 return Result;
6847}
6848
6849std::pair<CXXCtorInitializer **, unsigned>
6850ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
6851 unsigned &Idx) {
6852 CXXCtorInitializer **CtorInitializers = 0;
6853 unsigned NumInitializers = Record[Idx++];
6854 if (NumInitializers) {
6855 CtorInitializers
6856 = new (Context) CXXCtorInitializer*[NumInitializers];
6857 for (unsigned i=0; i != NumInitializers; ++i) {
6858 TypeSourceInfo *TInfo = 0;
6859 bool IsBaseVirtual = false;
6860 FieldDecl *Member = 0;
6861 IndirectFieldDecl *IndirectMember = 0;
6862
6863 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
6864 switch (Type) {
6865 case CTOR_INITIALIZER_BASE:
6866 TInfo = GetTypeSourceInfo(F, Record, Idx);
6867 IsBaseVirtual = Record[Idx++];
6868 break;
6869
6870 case CTOR_INITIALIZER_DELEGATING:
6871 TInfo = GetTypeSourceInfo(F, Record, Idx);
6872 break;
6873
6874 case CTOR_INITIALIZER_MEMBER:
6875 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
6876 break;
6877
6878 case CTOR_INITIALIZER_INDIRECT_MEMBER:
6879 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
6880 break;
6881 }
6882
6883 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
6884 Expr *Init = ReadExpr(F);
6885 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
6886 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
6887 bool IsWritten = Record[Idx++];
6888 unsigned SourceOrderOrNumArrayIndices;
6889 SmallVector<VarDecl *, 8> Indices;
6890 if (IsWritten) {
6891 SourceOrderOrNumArrayIndices = Record[Idx++];
6892 } else {
6893 SourceOrderOrNumArrayIndices = Record[Idx++];
6894 Indices.reserve(SourceOrderOrNumArrayIndices);
6895 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
6896 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
6897 }
6898
6899 CXXCtorInitializer *BOMInit;
6900 if (Type == CTOR_INITIALIZER_BASE) {
6901 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
6902 LParenLoc, Init, RParenLoc,
6903 MemberOrEllipsisLoc);
6904 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
6905 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
6906 Init, RParenLoc);
6907 } else if (IsWritten) {
6908 if (Member)
6909 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
6910 LParenLoc, Init, RParenLoc);
6911 else
6912 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
6913 MemberOrEllipsisLoc, LParenLoc,
6914 Init, RParenLoc);
6915 } else {
6916 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
6917 LParenLoc, Init, RParenLoc,
6918 Indices.data(), Indices.size());
6919 }
6920
6921 if (IsWritten)
6922 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
6923 CtorInitializers[i] = BOMInit;
6924 }
6925 }
6926
6927 return std::make_pair(CtorInitializers, NumInitializers);
6928}
6929
6930NestedNameSpecifier *
6931ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
6932 const RecordData &Record, unsigned &Idx) {
6933 unsigned N = Record[Idx++];
6934 NestedNameSpecifier *NNS = 0, *Prev = 0;
6935 for (unsigned I = 0; I != N; ++I) {
6936 NestedNameSpecifier::SpecifierKind Kind
6937 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6938 switch (Kind) {
6939 case NestedNameSpecifier::Identifier: {
6940 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
6941 NNS = NestedNameSpecifier::Create(Context, Prev, II);
6942 break;
6943 }
6944
6945 case NestedNameSpecifier::Namespace: {
6946 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
6947 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
6948 break;
6949 }
6950
6951 case NestedNameSpecifier::NamespaceAlias: {
6952 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
6953 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
6954 break;
6955 }
6956
6957 case NestedNameSpecifier::TypeSpec:
6958 case NestedNameSpecifier::TypeSpecWithTemplate: {
6959 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
6960 if (!T)
6961 return 0;
6962
6963 bool Template = Record[Idx++];
6964 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
6965 break;
6966 }
6967
6968 case NestedNameSpecifier::Global: {
6969 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
6970 // No associated value, and there can't be a prefix.
6971 break;
6972 }
6973 }
6974 Prev = NNS;
6975 }
6976 return NNS;
6977}
6978
6979NestedNameSpecifierLoc
6980ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
6981 unsigned &Idx) {
6982 unsigned N = Record[Idx++];
6983 NestedNameSpecifierLocBuilder Builder;
6984 for (unsigned I = 0; I != N; ++I) {
6985 NestedNameSpecifier::SpecifierKind Kind
6986 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6987 switch (Kind) {
6988 case NestedNameSpecifier::Identifier: {
6989 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
6990 SourceRange Range = ReadSourceRange(F, Record, Idx);
6991 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
6992 break;
6993 }
6994
6995 case NestedNameSpecifier::Namespace: {
6996 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
6997 SourceRange Range = ReadSourceRange(F, Record, Idx);
6998 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
6999 break;
7000 }
7001
7002 case NestedNameSpecifier::NamespaceAlias: {
7003 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7004 SourceRange Range = ReadSourceRange(F, Record, Idx);
7005 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7006 break;
7007 }
7008
7009 case NestedNameSpecifier::TypeSpec:
7010 case NestedNameSpecifier::TypeSpecWithTemplate: {
7011 bool Template = Record[Idx++];
7012 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7013 if (!T)
7014 return NestedNameSpecifierLoc();
7015 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7016
7017 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7018 Builder.Extend(Context,
7019 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7020 T->getTypeLoc(), ColonColonLoc);
7021 break;
7022 }
7023
7024 case NestedNameSpecifier::Global: {
7025 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7026 Builder.MakeGlobal(Context, ColonColonLoc);
7027 break;
7028 }
7029 }
7030 }
7031
7032 return Builder.getWithLocInContext(Context);
7033}
7034
7035SourceRange
7036ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7037 unsigned &Idx) {
7038 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7039 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7040 return SourceRange(beg, end);
7041}
7042
7043/// \brief Read an integral value
7044llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7045 unsigned BitWidth = Record[Idx++];
7046 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7047 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7048 Idx += NumWords;
7049 return Result;
7050}
7051
7052/// \brief Read a signed integral value
7053llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7054 bool isUnsigned = Record[Idx++];
7055 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7056}
7057
7058/// \brief Read a floating-point value
Tim Northover9ec55f22013-01-22 09:46:51 +00007059llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7060 const llvm::fltSemantics &Sem,
7061 unsigned &Idx) {
7062 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007063}
7064
7065// \brief Read a string
7066std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7067 unsigned Len = Record[Idx++];
7068 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7069 Idx += Len;
7070 return Result;
7071}
7072
7073VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7074 unsigned &Idx) {
7075 unsigned Major = Record[Idx++];
7076 unsigned Minor = Record[Idx++];
7077 unsigned Subminor = Record[Idx++];
7078 if (Minor == 0)
7079 return VersionTuple(Major);
7080 if (Subminor == 0)
7081 return VersionTuple(Major, Minor - 1);
7082 return VersionTuple(Major, Minor - 1, Subminor - 1);
7083}
7084
7085CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7086 const RecordData &Record,
7087 unsigned &Idx) {
7088 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7089 return CXXTemporary::Create(Context, Decl);
7090}
7091
7092DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
7093 return Diag(SourceLocation(), DiagID);
7094}
7095
7096DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7097 return Diags.Report(Loc, DiagID);
7098}
7099
7100/// \brief Retrieve the identifier table associated with the
7101/// preprocessor.
7102IdentifierTable &ASTReader::getIdentifierTable() {
7103 return PP.getIdentifierTable();
7104}
7105
7106/// \brief Record that the given ID maps to the given switch-case
7107/// statement.
7108void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7109 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7110 "Already have a SwitchCase with this ID");
7111 (*CurrSwitchCaseStmts)[ID] = SC;
7112}
7113
7114/// \brief Retrieve the switch-case statement with the given ID.
7115SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7116 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7117 return (*CurrSwitchCaseStmts)[ID];
7118}
7119
7120void ASTReader::ClearSwitchCaseIDs() {
7121 CurrSwitchCaseStmts->clear();
7122}
7123
7124void ASTReader::ReadComments() {
7125 std::vector<RawComment *> Comments;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007126 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007127 serialization::ModuleFile *> >::iterator
7128 I = CommentsCursors.begin(),
7129 E = CommentsCursors.end();
7130 I != E; ++I) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007131 BitstreamCursor &Cursor = I->first;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007132 serialization::ModuleFile &F = *I->second;
7133 SavedStreamPosition SavedPosition(Cursor);
7134
7135 RecordData Record;
7136 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007137 llvm::BitstreamEntry Entry =
7138 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
7139
7140 switch (Entry.Kind) {
7141 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7142 case llvm::BitstreamEntry::Error:
7143 Error("malformed block record in AST file");
7144 return;
7145 case llvm::BitstreamEntry::EndBlock:
7146 goto NextCursor;
7147 case llvm::BitstreamEntry::Record:
7148 // The interesting case.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007149 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007150 }
7151
7152 // Read a record.
7153 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00007154 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007155 case COMMENTS_RAW_COMMENT: {
7156 unsigned Idx = 0;
7157 SourceRange SR = ReadSourceRange(F, Record, Idx);
7158 RawComment::CommentKind Kind =
7159 (RawComment::CommentKind) Record[Idx++];
7160 bool IsTrailingComment = Record[Idx++];
7161 bool IsAlmostTrailingComment = Record[Idx++];
7162 Comments.push_back(new (Context) RawComment(SR, Kind,
7163 IsTrailingComment,
7164 IsAlmostTrailingComment));
7165 break;
7166 }
7167 }
7168 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007169 NextCursor:;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007170 }
7171 Context.Comments.addCommentsToFront(Comments);
7172}
7173
7174void ASTReader::finishPendingActions() {
7175 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Argyrios Kyrtzidis7640b022013-02-16 00:48:59 +00007176 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007177 // If any identifiers with corresponding top-level declarations have
7178 // been loaded, load those declarations now.
Douglas Gregoraa945902013-02-18 15:53:43 +00007179 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> > TopLevelDecls;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007180 while (!PendingIdentifierInfos.empty()) {
Douglas Gregoraa945902013-02-18 15:53:43 +00007181 // FIXME: std::move
7182 IdentifierInfo *II = PendingIdentifierInfos.back().first;
7183 SmallVector<uint32_t, 4> DeclIDs = PendingIdentifierInfos.back().second;
Douglas Gregorcc9bdcb2013-02-19 18:26:28 +00007184 PendingIdentifierInfos.pop_back();
Douglas Gregoraa945902013-02-18 15:53:43 +00007185
7186 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007187 }
7188
7189 // Load pending declaration chains.
7190 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7191 loadPendingDeclChain(PendingDeclChains[I]);
7192 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
7193 }
7194 PendingDeclChains.clear();
7195
Douglas Gregoraa945902013-02-18 15:53:43 +00007196 // Make the most recent of the top-level declarations visible.
7197 for (llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >::iterator
7198 TLD = TopLevelDecls.begin(), TLDEnd = TopLevelDecls.end();
7199 TLD != TLDEnd; ++TLD) {
7200 IdentifierInfo *II = TLD->first;
7201 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
7202 NamedDecl *ND = cast<NamedDecl>(TLD->second[I]->getMostRecentDecl());
7203 SemaObj->pushExternalDeclIntoScope(ND, II);
7204 }
7205 }
7206
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007207 // Load any pending macro definitions.
7208 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00007209 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
7210 SmallVector<PendingMacroInfo, 2> GlobalIDs;
7211 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
7212 // Initialize the macro history from chained-PCHs ahead of module imports.
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00007213 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7214 ++IDIdx) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00007215 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7216 if (Info.M->Kind != MK_Module)
7217 resolvePendingMacro(II, Info);
7218 }
7219 // Handle module imports.
7220 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7221 ++IDIdx) {
7222 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7223 if (Info.M->Kind == MK_Module)
7224 resolvePendingMacro(II, Info);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007225 }
7226 }
7227 PendingMacroIDs.clear();
Argyrios Kyrtzidis7640b022013-02-16 00:48:59 +00007228
7229 // Wire up the DeclContexts for Decls that we delayed setting until
7230 // recursive loading is completed.
7231 while (!PendingDeclContextInfos.empty()) {
7232 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7233 PendingDeclContextInfos.pop_front();
7234 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7235 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7236 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7237 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007238 }
7239
7240 // If we deserialized any C++ or Objective-C class definitions, any
7241 // Objective-C protocol definitions, or any redeclarable templates, make sure
7242 // that all redeclarations point to the definitions. Note that this can only
7243 // happen now, after the redeclaration chains have been fully wired.
7244 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7245 DEnd = PendingDefinitions.end();
7246 D != DEnd; ++D) {
7247 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7248 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7249 // Make sure that the TagType points at the definition.
7250 const_cast<TagType*>(TagT)->decl = TD;
7251 }
7252
7253 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(*D)) {
7254 for (CXXRecordDecl::redecl_iterator R = RD->redecls_begin(),
7255 REnd = RD->redecls_end();
7256 R != REnd; ++R)
7257 cast<CXXRecordDecl>(*R)->DefinitionData = RD->DefinitionData;
7258
7259 }
7260
7261 continue;
7262 }
7263
7264 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
7265 // Make sure that the ObjCInterfaceType points at the definition.
7266 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7267 ->Decl = ID;
7268
7269 for (ObjCInterfaceDecl::redecl_iterator R = ID->redecls_begin(),
7270 REnd = ID->redecls_end();
7271 R != REnd; ++R)
7272 R->Data = ID->Data;
7273
7274 continue;
7275 }
7276
7277 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7278 for (ObjCProtocolDecl::redecl_iterator R = PD->redecls_begin(),
7279 REnd = PD->redecls_end();
7280 R != REnd; ++R)
7281 R->Data = PD->Data;
7282
7283 continue;
7284 }
7285
7286 RedeclarableTemplateDecl *RTD
7287 = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7288 for (RedeclarableTemplateDecl::redecl_iterator R = RTD->redecls_begin(),
7289 REnd = RTD->redecls_end();
7290 R != REnd; ++R)
7291 R->Common = RTD->Common;
7292 }
7293 PendingDefinitions.clear();
7294
7295 // Load the bodies of any functions or methods we've encountered. We do
7296 // this now (delayed) so that we can be sure that the declaration chains
7297 // have been fully wired up.
7298 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7299 PBEnd = PendingBodies.end();
7300 PB != PBEnd; ++PB) {
7301 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7302 // FIXME: Check for =delete/=default?
7303 // FIXME: Complain about ODR violations here?
7304 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7305 FD->setLazyBody(PB->second);
7306 continue;
7307 }
7308
7309 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7310 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7311 MD->setLazyBody(PB->second);
7312 }
7313 PendingBodies.clear();
7314}
7315
7316void ASTReader::FinishedDeserializing() {
7317 assert(NumCurrentElementsDeserializing &&
7318 "FinishedDeserializing not paired with StartedDeserializing");
7319 if (NumCurrentElementsDeserializing == 1) {
7320 // We decrease NumCurrentElementsDeserializing only after pending actions
7321 // are finished, to avoid recursively re-calling finishPendingActions().
7322 finishPendingActions();
7323 }
7324 --NumCurrentElementsDeserializing;
7325
7326 if (NumCurrentElementsDeserializing == 0 &&
7327 Consumer && !PassingDeclsToConsumer) {
7328 // Guard variable to avoid recursively redoing the process of passing
7329 // decls to consumer.
7330 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7331 true);
7332
7333 while (!InterestingDecls.empty()) {
7334 // We are not in recursive loading, so it's safe to pass the "interesting"
7335 // decls to the consumer.
7336 Decl *D = InterestingDecls.front();
7337 InterestingDecls.pop_front();
7338 PassInterestingDeclToConsumer(D);
7339 }
7340 }
7341}
7342
7343ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7344 StringRef isysroot, bool DisableValidation,
Douglas Gregorf575d6e2013-01-25 00:45:27 +00007345 bool AllowASTWithCompilerErrors, bool UseGlobalIndex)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007346 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7347 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7348 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7349 Consumer(0), ModuleMgr(PP.getFileManager()),
7350 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregore1698072013-01-25 00:38:33 +00007351 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Douglas Gregorf575d6e2013-01-25 00:45:27 +00007352 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007353 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7354 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregore1698072013-01-25 00:38:33 +00007355 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7356 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
7357 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregor95fb36e2013-01-28 17:54:36 +00007358 NumMethodPoolLookups(0), NumMethodPoolHits(0),
7359 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
7360 TotalNumMethodPoolEntries(0),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007361 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
7362 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
7363 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
7364 PassingDeclsToConsumer(false),
7365 NumCXXBaseSpecifiersLoaded(0)
7366{
7367 SourceMgr.setExternalSLocEntrySource(this);
7368}
7369
7370ASTReader::~ASTReader() {
7371 for (DeclContextVisibleUpdatesPending::iterator
7372 I = PendingVisibleUpdates.begin(),
7373 E = PendingVisibleUpdates.end();
7374 I != E; ++I) {
7375 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
7376 F = I->second.end();
7377 J != F; ++J)
7378 delete J->first;
7379 }
7380}