blob: 4c2d2197e498a3b1dce0315978ce94fcb58720ec [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
Douglas Gregorc544ba02013-03-27 16:47:18 +00003490 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003491 return true;
Douglas Gregorc544ba02013-03-27 16:47:18 +00003492
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003493 break;
3494 }
3495 case LANGUAGE_OPTIONS:
3496 if (ParseLanguageOptions(Record, false, Listener))
3497 return true;
3498 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003499
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003500 case TARGET_OPTIONS:
3501 if (ParseTargetOptions(Record, false, Listener))
3502 return true;
3503 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003504
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003505 case DIAGNOSTIC_OPTIONS:
3506 if (ParseDiagnosticOptions(Record, false, Listener))
3507 return true;
3508 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003509
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003510 case FILE_SYSTEM_OPTIONS:
3511 if (ParseFileSystemOptions(Record, false, Listener))
3512 return true;
3513 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003514
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003515 case HEADER_SEARCH_OPTIONS:
3516 if (ParseHeaderSearchOptions(Record, false, Listener))
3517 return true;
3518 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003519
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003520 case PREPROCESSOR_OPTIONS: {
3521 std::string IgnoredSuggestedPredefines;
3522 if (ParsePreprocessorOptions(Record, false, Listener,
3523 IgnoredSuggestedPredefines))
3524 return true;
3525 break;
3526 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003527
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003528 default:
3529 // No other validation to perform.
3530 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003531 }
3532 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003533}
3534
3535
3536bool ASTReader::isAcceptableASTFile(StringRef Filename,
3537 FileManager &FileMgr,
3538 const LangOptions &LangOpts,
3539 const TargetOptions &TargetOpts,
3540 const PreprocessorOptions &PPOpts) {
3541 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3542 return !readASTFileControlBlock(Filename, FileMgr, validator);
3543}
3544
3545bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
3546 // Enter the submodule block.
3547 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3548 Error("malformed submodule block record in AST file");
3549 return true;
3550 }
3551
3552 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
3553 bool First = true;
3554 Module *CurrentModule = 0;
3555 RecordData Record;
3556 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003557 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
3558
3559 switch (Entry.Kind) {
3560 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
3561 case llvm::BitstreamEntry::Error:
3562 Error("malformed block record in AST file");
3563 return true;
3564 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003565 return false;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003566 case llvm::BitstreamEntry::Record:
3567 // The interesting case.
3568 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003569 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003570
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003571 // Read a record.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003572 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003573 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003574 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003575 default: // Default behavior: ignore.
3576 break;
3577
3578 case SUBMODULE_DEFINITION: {
3579 if (First) {
3580 Error("missing submodule metadata record at beginning of block");
3581 return true;
3582 }
3583
Douglas Gregor970e4412013-03-20 03:59:18 +00003584 if (Record.size() < 8) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003585 Error("malformed module definition");
3586 return true;
3587 }
3588
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003589 StringRef Name = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003590 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
3591 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[1]);
3592 bool IsFramework = Record[2];
3593 bool IsExplicit = Record[3];
3594 bool IsSystem = Record[4];
3595 bool InferSubmodules = Record[5];
3596 bool InferExplicitSubmodules = Record[6];
3597 bool InferExportWildcard = Record[7];
Douglas Gregor970e4412013-03-20 03:59:18 +00003598 bool ConfigMacrosExhaustive = Record[8];
3599
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003600 Module *ParentModule = 0;
3601 if (Parent)
3602 ParentModule = getSubmodule(Parent);
3603
3604 // Retrieve this (sub)module from the module map, creating it if
3605 // necessary.
3606 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
3607 IsFramework,
3608 IsExplicit).first;
3609 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
3610 if (GlobalIndex >= SubmodulesLoaded.size() ||
3611 SubmodulesLoaded[GlobalIndex]) {
3612 Error("too many submodules");
3613 return true;
3614 }
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003615
Douglas Gregor677e15f2013-03-19 00:28:20 +00003616 if (!ParentModule) {
3617 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
3618 if (CurFile != F.File) {
3619 if (!Diags.isDiagnosticInFlight()) {
3620 Diag(diag::err_module_file_conflict)
3621 << CurrentModule->getTopLevelModuleName()
3622 << CurFile->getName()
3623 << F.File->getName();
3624 }
3625 return true;
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003626 }
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003627 }
Douglas Gregor677e15f2013-03-19 00:28:20 +00003628
3629 CurrentModule->setASTFile(F.File);
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003630 }
Douglas Gregor677e15f2013-03-19 00:28:20 +00003631
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003632 CurrentModule->IsFromModuleFile = true;
3633 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
3634 CurrentModule->InferSubmodules = InferSubmodules;
3635 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
3636 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor970e4412013-03-20 03:59:18 +00003637 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003638 if (DeserializationListener)
3639 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
3640
3641 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003642
Douglas Gregor906d66a2013-03-20 21:10:35 +00003643 // Clear out data that will be replaced by what is the module file.
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003644 CurrentModule->LinkLibraries.clear();
Douglas Gregor970e4412013-03-20 03:59:18 +00003645 CurrentModule->ConfigMacros.clear();
Douglas Gregor906d66a2013-03-20 21:10:35 +00003646 CurrentModule->UnresolvedConflicts.clear();
3647 CurrentModule->Conflicts.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003648 break;
3649 }
3650
3651 case SUBMODULE_UMBRELLA_HEADER: {
3652 if (First) {
3653 Error("missing submodule metadata record at beginning of block");
3654 return true;
3655 }
3656
3657 if (!CurrentModule)
3658 break;
3659
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003660 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003661 if (!CurrentModule->getUmbrellaHeader())
3662 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
3663 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
3664 Error("mismatched umbrella headers in submodule");
3665 return true;
3666 }
3667 }
3668 break;
3669 }
3670
3671 case SUBMODULE_HEADER: {
3672 if (First) {
3673 Error("missing submodule metadata record at beginning of block");
3674 return true;
3675 }
3676
3677 if (!CurrentModule)
3678 break;
3679
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00003680 // We lazily associate headers with their modules via the HeaderInfoTable.
3681 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
3682 // of complete filenames or remove it entirely.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003683 break;
3684 }
3685
3686 case SUBMODULE_EXCLUDED_HEADER: {
3687 if (First) {
3688 Error("missing submodule metadata record at beginning of block");
3689 return true;
3690 }
3691
3692 if (!CurrentModule)
3693 break;
3694
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00003695 // We lazily associate headers with their modules via the HeaderInfoTable.
3696 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
3697 // of complete filenames or remove it entirely.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003698 break;
3699 }
3700
3701 case SUBMODULE_TOPHEADER: {
3702 if (First) {
3703 Error("missing submodule metadata record at beginning of block");
3704 return true;
3705 }
3706
3707 if (!CurrentModule)
3708 break;
3709
Argyrios Kyrtzidisc1d22392013-03-13 21:13:43 +00003710 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003711 break;
3712 }
3713
3714 case SUBMODULE_UMBRELLA_DIR: {
3715 if (First) {
3716 Error("missing submodule metadata record at beginning of block");
3717 return true;
3718 }
3719
3720 if (!CurrentModule)
3721 break;
3722
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003723 if (const DirectoryEntry *Umbrella
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003724 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003725 if (!CurrentModule->getUmbrellaDir())
3726 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
3727 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
3728 Error("mismatched umbrella directories in submodule");
3729 return true;
3730 }
3731 }
3732 break;
3733 }
3734
3735 case SUBMODULE_METADATA: {
3736 if (!First) {
3737 Error("submodule metadata record not at beginning of block");
3738 return true;
3739 }
3740 First = false;
3741
3742 F.BaseSubmoduleID = getTotalNumSubmodules();
3743 F.LocalNumSubmodules = Record[0];
3744 unsigned LocalBaseSubmoduleID = Record[1];
3745 if (F.LocalNumSubmodules > 0) {
3746 // Introduce the global -> local mapping for submodules within this
3747 // module.
3748 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
3749
3750 // Introduce the local -> global mapping for submodules within this
3751 // module.
3752 F.SubmoduleRemap.insertOrReplace(
3753 std::make_pair(LocalBaseSubmoduleID,
3754 F.BaseSubmoduleID - LocalBaseSubmoduleID));
3755
3756 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
3757 }
3758 break;
3759 }
3760
3761 case SUBMODULE_IMPORTS: {
3762 if (First) {
3763 Error("missing submodule metadata record at beginning of block");
3764 return true;
3765 }
3766
3767 if (!CurrentModule)
3768 break;
3769
3770 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregor906d66a2013-03-20 21:10:35 +00003771 UnresolvedModuleRef Unresolved;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003772 Unresolved.File = &F;
3773 Unresolved.Mod = CurrentModule;
3774 Unresolved.ID = Record[Idx];
Douglas Gregor906d66a2013-03-20 21:10:35 +00003775 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003776 Unresolved.IsWildcard = false;
Douglas Gregor906d66a2013-03-20 21:10:35 +00003777 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003778 }
3779 break;
3780 }
3781
3782 case SUBMODULE_EXPORTS: {
3783 if (First) {
3784 Error("missing submodule metadata record at beginning of block");
3785 return true;
3786 }
3787
3788 if (!CurrentModule)
3789 break;
3790
3791 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregor906d66a2013-03-20 21:10:35 +00003792 UnresolvedModuleRef Unresolved;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003793 Unresolved.File = &F;
3794 Unresolved.Mod = CurrentModule;
3795 Unresolved.ID = Record[Idx];
Douglas Gregor906d66a2013-03-20 21:10:35 +00003796 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003797 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregor906d66a2013-03-20 21:10:35 +00003798 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003799 }
3800
3801 // Once we've loaded the set of exports, there's no reason to keep
3802 // the parsed, unresolved exports around.
3803 CurrentModule->UnresolvedExports.clear();
3804 break;
3805 }
3806 case SUBMODULE_REQUIRES: {
3807 if (First) {
3808 Error("missing submodule metadata record at beginning of block");
3809 return true;
3810 }
3811
3812 if (!CurrentModule)
3813 break;
3814
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003815 CurrentModule->addRequirement(Blob, Context.getLangOpts(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003816 Context.getTargetInfo());
3817 break;
3818 }
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003819
3820 case SUBMODULE_LINK_LIBRARY:
3821 if (First) {
3822 Error("missing submodule metadata record at beginning of block");
3823 return true;
3824 }
3825
3826 if (!CurrentModule)
3827 break;
3828
3829 CurrentModule->LinkLibraries.push_back(
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003830 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003831 break;
Douglas Gregor63a72682013-03-20 00:22:05 +00003832
3833 case SUBMODULE_CONFIG_MACRO:
3834 if (First) {
3835 Error("missing submodule metadata record at beginning of block");
3836 return true;
3837 }
3838
3839 if (!CurrentModule)
3840 break;
3841
3842 CurrentModule->ConfigMacros.push_back(Blob.str());
3843 break;
Douglas Gregor906d66a2013-03-20 21:10:35 +00003844
3845 case SUBMODULE_CONFLICT: {
3846 if (First) {
3847 Error("missing submodule metadata record at beginning of block");
3848 return true;
3849 }
3850
3851 if (!CurrentModule)
3852 break;
3853
3854 UnresolvedModuleRef Unresolved;
3855 Unresolved.File = &F;
3856 Unresolved.Mod = CurrentModule;
3857 Unresolved.ID = Record[0];
3858 Unresolved.Kind = UnresolvedModuleRef::Conflict;
3859 Unresolved.IsWildcard = false;
3860 Unresolved.String = Blob;
3861 UnresolvedModuleRefs.push_back(Unresolved);
3862 break;
3863 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003864 }
3865 }
3866}
3867
3868/// \brief Parse the record that corresponds to a LangOptions data
3869/// structure.
3870///
3871/// This routine parses the language options from the AST file and then gives
3872/// them to the AST listener if one is set.
3873///
3874/// \returns true if the listener deems the file unacceptable, false otherwise.
3875bool ASTReader::ParseLanguageOptions(const RecordData &Record,
3876 bool Complain,
3877 ASTReaderListener &Listener) {
3878 LangOptions LangOpts;
3879 unsigned Idx = 0;
3880#define LANGOPT(Name, Bits, Default, Description) \
3881 LangOpts.Name = Record[Idx++];
3882#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
3883 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
3884#include "clang/Basic/LangOptions.def"
Will Dietz4f45bc02013-01-18 11:30:38 +00003885#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
3886#include "clang/Basic/Sanitizers.def"
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003887
3888 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
3889 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
3890 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
3891
3892 unsigned Length = Record[Idx++];
3893 LangOpts.CurrentModule.assign(Record.begin() + Idx,
3894 Record.begin() + Idx + Length);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +00003895
3896 Idx += Length;
3897
3898 // Comment options.
3899 for (unsigned N = Record[Idx++]; N; --N) {
3900 LangOpts.CommentOpts.BlockCommandNames.push_back(
3901 ReadString(Record, Idx));
3902 }
3903
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003904 return Listener.ReadLanguageOptions(LangOpts, Complain);
3905}
3906
3907bool ASTReader::ParseTargetOptions(const RecordData &Record,
3908 bool Complain,
3909 ASTReaderListener &Listener) {
3910 unsigned Idx = 0;
3911 TargetOptions TargetOpts;
3912 TargetOpts.Triple = ReadString(Record, Idx);
3913 TargetOpts.CPU = ReadString(Record, Idx);
3914 TargetOpts.ABI = ReadString(Record, Idx);
3915 TargetOpts.CXXABI = ReadString(Record, Idx);
3916 TargetOpts.LinkerVersion = ReadString(Record, Idx);
3917 for (unsigned N = Record[Idx++]; N; --N) {
3918 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
3919 }
3920 for (unsigned N = Record[Idx++]; N; --N) {
3921 TargetOpts.Features.push_back(ReadString(Record, Idx));
3922 }
3923
3924 return Listener.ReadTargetOptions(TargetOpts, Complain);
3925}
3926
3927bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
3928 ASTReaderListener &Listener) {
3929 DiagnosticOptions DiagOpts;
3930 unsigned Idx = 0;
3931#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
3932#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
3933 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
3934#include "clang/Basic/DiagnosticOptions.def"
3935
3936 for (unsigned N = Record[Idx++]; N; --N) {
3937 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
3938 }
3939
3940 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
3941}
3942
3943bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
3944 ASTReaderListener &Listener) {
3945 FileSystemOptions FSOpts;
3946 unsigned Idx = 0;
3947 FSOpts.WorkingDir = ReadString(Record, Idx);
3948 return Listener.ReadFileSystemOptions(FSOpts, Complain);
3949}
3950
3951bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
3952 bool Complain,
3953 ASTReaderListener &Listener) {
3954 HeaderSearchOptions HSOpts;
3955 unsigned Idx = 0;
3956 HSOpts.Sysroot = ReadString(Record, Idx);
3957
3958 // Include entries.
3959 for (unsigned N = Record[Idx++]; N; --N) {
3960 std::string Path = ReadString(Record, Idx);
3961 frontend::IncludeDirGroup Group
3962 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003963 bool IsFramework = Record[Idx++];
3964 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003965 HSOpts.UserEntries.push_back(
Daniel Dunbar59fd6352013-01-30 00:34:26 +00003966 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003967 }
3968
3969 // System header prefixes.
3970 for (unsigned N = Record[Idx++]; N; --N) {
3971 std::string Prefix = ReadString(Record, Idx);
3972 bool IsSystemHeader = Record[Idx++];
3973 HSOpts.SystemHeaderPrefixes.push_back(
3974 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
3975 }
3976
3977 HSOpts.ResourceDir = ReadString(Record, Idx);
3978 HSOpts.ModuleCachePath = ReadString(Record, Idx);
3979 HSOpts.DisableModuleHash = Record[Idx++];
3980 HSOpts.UseBuiltinIncludes = Record[Idx++];
3981 HSOpts.UseStandardSystemIncludes = Record[Idx++];
3982 HSOpts.UseStandardCXXIncludes = Record[Idx++];
3983 HSOpts.UseLibcxx = Record[Idx++];
3984
3985 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
3986}
3987
3988bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
3989 bool Complain,
3990 ASTReaderListener &Listener,
3991 std::string &SuggestedPredefines) {
3992 PreprocessorOptions PPOpts;
3993 unsigned Idx = 0;
3994
3995 // Macro definitions/undefs
3996 for (unsigned N = Record[Idx++]; N; --N) {
3997 std::string Macro = ReadString(Record, Idx);
3998 bool IsUndef = Record[Idx++];
3999 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4000 }
4001
4002 // Includes
4003 for (unsigned N = Record[Idx++]; N; --N) {
4004 PPOpts.Includes.push_back(ReadString(Record, Idx));
4005 }
4006
4007 // Macro Includes
4008 for (unsigned N = Record[Idx++]; N; --N) {
4009 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4010 }
4011
4012 PPOpts.UsePredefines = Record[Idx++];
4013 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4014 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4015 PPOpts.ObjCXXARCStandardLibrary =
4016 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4017 SuggestedPredefines.clear();
4018 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4019 SuggestedPredefines);
4020}
4021
4022std::pair<ModuleFile *, unsigned>
4023ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4024 GlobalPreprocessedEntityMapType::iterator
4025 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4026 assert(I != GlobalPreprocessedEntityMap.end() &&
4027 "Corrupted global preprocessed entity map");
4028 ModuleFile *M = I->second;
4029 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4030 return std::make_pair(M, LocalIndex);
4031}
4032
4033std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4034ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4035 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4036 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4037 Mod.NumPreprocessedEntities);
4038
4039 return std::make_pair(PreprocessingRecord::iterator(),
4040 PreprocessingRecord::iterator());
4041}
4042
4043std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4044ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4045 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4046 ModuleDeclIterator(this, &Mod,
4047 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4048}
4049
4050PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4051 PreprocessedEntityID PPID = Index+1;
4052 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4053 ModuleFile &M = *PPInfo.first;
4054 unsigned LocalIndex = PPInfo.second;
4055 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4056
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004057 if (!PP.getPreprocessingRecord()) {
4058 Error("no preprocessing record");
4059 return 0;
4060 }
4061
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004062 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4063 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4064
4065 llvm::BitstreamEntry Entry =
4066 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4067 if (Entry.Kind != llvm::BitstreamEntry::Record)
4068 return 0;
4069
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004070 // Read the record.
4071 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4072 ReadSourceLocation(M, PPOffs.End));
4073 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004074 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004075 RecordData Record;
4076 PreprocessorDetailRecordTypes RecType =
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004077 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4078 Entry.ID, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004079 switch (RecType) {
4080 case PPD_MACRO_EXPANSION: {
4081 bool isBuiltin = Record[0];
4082 IdentifierInfo *Name = 0;
4083 MacroDefinition *Def = 0;
4084 if (isBuiltin)
4085 Name = getLocalIdentifier(M, Record[1]);
4086 else {
4087 PreprocessedEntityID
4088 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4089 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4090 }
4091
4092 MacroExpansion *ME;
4093 if (isBuiltin)
4094 ME = new (PPRec) MacroExpansion(Name, Range);
4095 else
4096 ME = new (PPRec) MacroExpansion(Def, Range);
4097
4098 return ME;
4099 }
4100
4101 case PPD_MACRO_DEFINITION: {
4102 // Decode the identifier info and then check again; if the macro is
4103 // still defined and associated with the identifier,
4104 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4105 MacroDefinition *MD
4106 = new (PPRec) MacroDefinition(II, Range);
4107
4108 if (DeserializationListener)
4109 DeserializationListener->MacroDefinitionRead(PPID, MD);
4110
4111 return MD;
4112 }
4113
4114 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004115 const char *FullFileNameStart = Blob.data() + Record[0];
4116 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004117 const FileEntry *File = 0;
4118 if (!FullFileName.empty())
4119 File = PP.getFileManager().getFile(FullFileName);
4120
4121 // FIXME: Stable encoding
4122 InclusionDirective::InclusionKind Kind
4123 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4124 InclusionDirective *ID
4125 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004126 StringRef(Blob.data(), Record[0]),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004127 Record[1], Record[3],
4128 File,
4129 Range);
4130 return ID;
4131 }
4132 }
4133
4134 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4135}
4136
4137/// \brief \arg SLocMapI points at a chunk of a module that contains no
4138/// preprocessed entities or the entities it contains are not the ones we are
4139/// looking for. Find the next module that contains entities and return the ID
4140/// of the first entry.
4141PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4142 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4143 ++SLocMapI;
4144 for (GlobalSLocOffsetMapType::const_iterator
4145 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4146 ModuleFile &M = *SLocMapI->second;
4147 if (M.NumPreprocessedEntities)
4148 return M.BasePreprocessedEntityID;
4149 }
4150
4151 return getTotalNumPreprocessedEntities();
4152}
4153
4154namespace {
4155
4156template <unsigned PPEntityOffset::*PPLoc>
4157struct PPEntityComp {
4158 const ASTReader &Reader;
4159 ModuleFile &M;
4160
4161 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4162
4163 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4164 SourceLocation LHS = getLoc(L);
4165 SourceLocation RHS = getLoc(R);
4166 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4167 }
4168
4169 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4170 SourceLocation LHS = getLoc(L);
4171 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4172 }
4173
4174 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4175 SourceLocation RHS = getLoc(R);
4176 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4177 }
4178
4179 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4180 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4181 }
4182};
4183
4184}
4185
4186/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4187PreprocessedEntityID
4188ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4189 if (SourceMgr.isLocalSourceLocation(BLoc))
4190 return getTotalNumPreprocessedEntities();
4191
4192 GlobalSLocOffsetMapType::const_iterator
4193 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00004194 BLoc.getOffset() - 1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004195 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4196 "Corrupted global sloc offset map");
4197
4198 if (SLocMapI->second->NumPreprocessedEntities == 0)
4199 return findNextPreprocessedEntity(SLocMapI);
4200
4201 ModuleFile &M = *SLocMapI->second;
4202 typedef const PPEntityOffset *pp_iterator;
4203 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4204 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4205
4206 size_t Count = M.NumPreprocessedEntities;
4207 size_t Half;
4208 pp_iterator First = pp_begin;
4209 pp_iterator PPI;
4210
4211 // Do a binary search manually instead of using std::lower_bound because
4212 // The end locations of entities may be unordered (when a macro expansion
4213 // is inside another macro argument), but for this case it is not important
4214 // whether we get the first macro expansion or its containing macro.
4215 while (Count > 0) {
4216 Half = Count/2;
4217 PPI = First;
4218 std::advance(PPI, Half);
4219 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4220 BLoc)){
4221 First = PPI;
4222 ++First;
4223 Count = Count - Half - 1;
4224 } else
4225 Count = Half;
4226 }
4227
4228 if (PPI == pp_end)
4229 return findNextPreprocessedEntity(SLocMapI);
4230
4231 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4232}
4233
4234/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4235PreprocessedEntityID
4236ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4237 if (SourceMgr.isLocalSourceLocation(ELoc))
4238 return getTotalNumPreprocessedEntities();
4239
4240 GlobalSLocOffsetMapType::const_iterator
4241 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00004242 ELoc.getOffset() - 1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004243 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4244 "Corrupted global sloc offset map");
4245
4246 if (SLocMapI->second->NumPreprocessedEntities == 0)
4247 return findNextPreprocessedEntity(SLocMapI);
4248
4249 ModuleFile &M = *SLocMapI->second;
4250 typedef const PPEntityOffset *pp_iterator;
4251 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4252 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4253 pp_iterator PPI =
4254 std::upper_bound(pp_begin, pp_end, ELoc,
4255 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4256
4257 if (PPI == pp_end)
4258 return findNextPreprocessedEntity(SLocMapI);
4259
4260 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4261}
4262
4263/// \brief Returns a pair of [Begin, End) indices of preallocated
4264/// preprocessed entities that \arg Range encompasses.
4265std::pair<unsigned, unsigned>
4266 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4267 if (Range.isInvalid())
4268 return std::make_pair(0,0);
4269 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4270
4271 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4272 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4273 return std::make_pair(BeginID, EndID);
4274}
4275
4276/// \brief Optionally returns true or false if the preallocated preprocessed
4277/// entity with index \arg Index came from file \arg FID.
David Blaikiedc84cd52013-02-20 22:23:23 +00004278Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004279 FileID FID) {
4280 if (FID.isInvalid())
4281 return false;
4282
4283 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4284 ModuleFile &M = *PPInfo.first;
4285 unsigned LocalIndex = PPInfo.second;
4286 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4287
4288 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4289 if (Loc.isInvalid())
4290 return false;
4291
4292 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4293 return true;
4294 else
4295 return false;
4296}
4297
4298namespace {
4299 /// \brief Visitor used to search for information about a header file.
4300 class HeaderFileInfoVisitor {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004301 const FileEntry *FE;
4302
David Blaikiedc84cd52013-02-20 22:23:23 +00004303 Optional<HeaderFileInfo> HFI;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004304
4305 public:
Argyrios Kyrtzidis36592b12013-03-06 18:12:44 +00004306 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4307 : FE(FE) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004308
4309 static bool visit(ModuleFile &M, void *UserData) {
4310 HeaderFileInfoVisitor *This
4311 = static_cast<HeaderFileInfoVisitor *>(UserData);
4312
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004313 HeaderFileInfoLookupTable *Table
4314 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4315 if (!Table)
4316 return false;
4317
4318 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00004319 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004320 if (Pos == Table->end())
4321 return false;
4322
4323 This->HFI = *Pos;
4324 return true;
4325 }
4326
David Blaikiedc84cd52013-02-20 22:23:23 +00004327 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004328 };
4329}
4330
4331HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis36592b12013-03-06 18:12:44 +00004332 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004333 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
David Blaikiedc84cd52013-02-20 22:23:23 +00004334 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004335 if (Listener)
4336 Listener->ReadHeaderFileInfo(*HFI, FE->getUID());
4337 return *HFI;
4338 }
4339
4340 return HeaderFileInfo();
4341}
4342
4343void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4344 // FIXME: Make it work properly with modules.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004345 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004346 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4347 ModuleFile &F = *(*I);
4348 unsigned Idx = 0;
4349 DiagStates.clear();
4350 assert(!Diag.DiagStates.empty());
4351 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4352 while (Idx < F.PragmaDiagMappings.size()) {
4353 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4354 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4355 if (DiagStateID != 0) {
4356 Diag.DiagStatePoints.push_back(
4357 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4358 FullSourceLoc(Loc, SourceMgr)));
4359 continue;
4360 }
4361
4362 assert(DiagStateID == 0);
4363 // A new DiagState was created here.
4364 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4365 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4366 DiagStates.push_back(NewState);
4367 Diag.DiagStatePoints.push_back(
4368 DiagnosticsEngine::DiagStatePoint(NewState,
4369 FullSourceLoc(Loc, SourceMgr)));
4370 while (1) {
4371 assert(Idx < F.PragmaDiagMappings.size() &&
4372 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4373 if (Idx >= F.PragmaDiagMappings.size()) {
4374 break; // Something is messed up but at least avoid infinite loop in
4375 // release build.
4376 }
4377 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4378 if (DiagID == (unsigned)-1) {
4379 break; // no more diag/map pairs for this location.
4380 }
4381 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4382 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4383 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4384 }
4385 }
4386 }
4387}
4388
4389/// \brief Get the correct cursor and offset for loading a type.
4390ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4391 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4392 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4393 ModuleFile *M = I->second;
4394 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4395}
4396
4397/// \brief Read and return the type with the given index..
4398///
4399/// The index is the type ID, shifted and minus the number of predefs. This
4400/// routine actually reads the record corresponding to the type at the given
4401/// location. It is a helper routine for GetType, which deals with reading type
4402/// IDs.
4403QualType ASTReader::readTypeRecord(unsigned Index) {
4404 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004405 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004406
4407 // Keep track of where we are in the stream, then jump back there
4408 // after reading this type.
4409 SavedStreamPosition SavedPosition(DeclsCursor);
4410
4411 ReadingKindTracker ReadingKind(Read_Type, *this);
4412
4413 // Note that we are loading a type record.
4414 Deserializing AType(this);
4415
4416 unsigned Idx = 0;
4417 DeclsCursor.JumpToBit(Loc.Offset);
4418 RecordData Record;
4419 unsigned Code = DeclsCursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004420 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004421 case TYPE_EXT_QUAL: {
4422 if (Record.size() != 2) {
4423 Error("Incorrect encoding of extended qualifier type");
4424 return QualType();
4425 }
4426 QualType Base = readType(*Loc.F, Record, Idx);
4427 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4428 return Context.getQualifiedType(Base, Quals);
4429 }
4430
4431 case TYPE_COMPLEX: {
4432 if (Record.size() != 1) {
4433 Error("Incorrect encoding of complex type");
4434 return QualType();
4435 }
4436 QualType ElemType = readType(*Loc.F, Record, Idx);
4437 return Context.getComplexType(ElemType);
4438 }
4439
4440 case TYPE_POINTER: {
4441 if (Record.size() != 1) {
4442 Error("Incorrect encoding of pointer type");
4443 return QualType();
4444 }
4445 QualType PointeeType = readType(*Loc.F, Record, Idx);
4446 return Context.getPointerType(PointeeType);
4447 }
4448
4449 case TYPE_BLOCK_POINTER: {
4450 if (Record.size() != 1) {
4451 Error("Incorrect encoding of block pointer type");
4452 return QualType();
4453 }
4454 QualType PointeeType = readType(*Loc.F, Record, Idx);
4455 return Context.getBlockPointerType(PointeeType);
4456 }
4457
4458 case TYPE_LVALUE_REFERENCE: {
4459 if (Record.size() != 2) {
4460 Error("Incorrect encoding of lvalue reference type");
4461 return QualType();
4462 }
4463 QualType PointeeType = readType(*Loc.F, Record, Idx);
4464 return Context.getLValueReferenceType(PointeeType, Record[1]);
4465 }
4466
4467 case TYPE_RVALUE_REFERENCE: {
4468 if (Record.size() != 1) {
4469 Error("Incorrect encoding of rvalue reference type");
4470 return QualType();
4471 }
4472 QualType PointeeType = readType(*Loc.F, Record, Idx);
4473 return Context.getRValueReferenceType(PointeeType);
4474 }
4475
4476 case TYPE_MEMBER_POINTER: {
4477 if (Record.size() != 2) {
4478 Error("Incorrect encoding of member pointer type");
4479 return QualType();
4480 }
4481 QualType PointeeType = readType(*Loc.F, Record, Idx);
4482 QualType ClassType = readType(*Loc.F, Record, Idx);
4483 if (PointeeType.isNull() || ClassType.isNull())
4484 return QualType();
4485
4486 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4487 }
4488
4489 case TYPE_CONSTANT_ARRAY: {
4490 QualType ElementType = readType(*Loc.F, Record, Idx);
4491 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4492 unsigned IndexTypeQuals = Record[2];
4493 unsigned Idx = 3;
4494 llvm::APInt Size = ReadAPInt(Record, Idx);
4495 return Context.getConstantArrayType(ElementType, Size,
4496 ASM, IndexTypeQuals);
4497 }
4498
4499 case TYPE_INCOMPLETE_ARRAY: {
4500 QualType ElementType = readType(*Loc.F, Record, Idx);
4501 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4502 unsigned IndexTypeQuals = Record[2];
4503 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4504 }
4505
4506 case TYPE_VARIABLE_ARRAY: {
4507 QualType ElementType = readType(*Loc.F, Record, Idx);
4508 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4509 unsigned IndexTypeQuals = Record[2];
4510 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4511 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
4512 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
4513 ASM, IndexTypeQuals,
4514 SourceRange(LBLoc, RBLoc));
4515 }
4516
4517 case TYPE_VECTOR: {
4518 if (Record.size() != 3) {
4519 Error("incorrect encoding of vector type in AST file");
4520 return QualType();
4521 }
4522
4523 QualType ElementType = readType(*Loc.F, Record, Idx);
4524 unsigned NumElements = Record[1];
4525 unsigned VecKind = Record[2];
4526 return Context.getVectorType(ElementType, NumElements,
4527 (VectorType::VectorKind)VecKind);
4528 }
4529
4530 case TYPE_EXT_VECTOR: {
4531 if (Record.size() != 3) {
4532 Error("incorrect encoding of extended vector type in AST file");
4533 return QualType();
4534 }
4535
4536 QualType ElementType = readType(*Loc.F, Record, Idx);
4537 unsigned NumElements = Record[1];
4538 return Context.getExtVectorType(ElementType, NumElements);
4539 }
4540
4541 case TYPE_FUNCTION_NO_PROTO: {
4542 if (Record.size() != 6) {
4543 Error("incorrect encoding of no-proto function type");
4544 return QualType();
4545 }
4546 QualType ResultType = readType(*Loc.F, Record, Idx);
4547 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
4548 (CallingConv)Record[4], Record[5]);
4549 return Context.getFunctionNoProtoType(ResultType, Info);
4550 }
4551
4552 case TYPE_FUNCTION_PROTO: {
4553 QualType ResultType = readType(*Loc.F, Record, Idx);
4554
4555 FunctionProtoType::ExtProtoInfo EPI;
4556 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
4557 /*hasregparm*/ Record[2],
4558 /*regparm*/ Record[3],
4559 static_cast<CallingConv>(Record[4]),
4560 /*produces*/ Record[5]);
4561
4562 unsigned Idx = 6;
4563 unsigned NumParams = Record[Idx++];
4564 SmallVector<QualType, 16> ParamTypes;
4565 for (unsigned I = 0; I != NumParams; ++I)
4566 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
4567
4568 EPI.Variadic = Record[Idx++];
4569 EPI.HasTrailingReturn = Record[Idx++];
4570 EPI.TypeQuals = Record[Idx++];
4571 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
4572 ExceptionSpecificationType EST =
4573 static_cast<ExceptionSpecificationType>(Record[Idx++]);
4574 EPI.ExceptionSpecType = EST;
4575 SmallVector<QualType, 2> Exceptions;
4576 if (EST == EST_Dynamic) {
4577 EPI.NumExceptions = Record[Idx++];
4578 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
4579 Exceptions.push_back(readType(*Loc.F, Record, Idx));
4580 EPI.Exceptions = Exceptions.data();
4581 } else if (EST == EST_ComputedNoexcept) {
4582 EPI.NoexceptExpr = ReadExpr(*Loc.F);
4583 } else if (EST == EST_Uninstantiated) {
4584 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4585 EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4586 } else if (EST == EST_Unevaluated) {
4587 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4588 }
Jordan Rosebea522f2013-03-08 21:51:21 +00004589 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004590 }
4591
4592 case TYPE_UNRESOLVED_USING: {
4593 unsigned Idx = 0;
4594 return Context.getTypeDeclType(
4595 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
4596 }
4597
4598 case TYPE_TYPEDEF: {
4599 if (Record.size() != 2) {
4600 Error("incorrect encoding of typedef type");
4601 return QualType();
4602 }
4603 unsigned Idx = 0;
4604 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
4605 QualType Canonical = readType(*Loc.F, Record, Idx);
4606 if (!Canonical.isNull())
4607 Canonical = Context.getCanonicalType(Canonical);
4608 return Context.getTypedefType(Decl, Canonical);
4609 }
4610
4611 case TYPE_TYPEOF_EXPR:
4612 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
4613
4614 case TYPE_TYPEOF: {
4615 if (Record.size() != 1) {
4616 Error("incorrect encoding of typeof(type) in AST file");
4617 return QualType();
4618 }
4619 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4620 return Context.getTypeOfType(UnderlyingType);
4621 }
4622
4623 case TYPE_DECLTYPE: {
4624 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4625 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
4626 }
4627
4628 case TYPE_UNARY_TRANSFORM: {
4629 QualType BaseType = readType(*Loc.F, Record, Idx);
4630 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4631 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
4632 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
4633 }
4634
4635 case TYPE_AUTO:
4636 return Context.getAutoType(readType(*Loc.F, Record, Idx));
4637
4638 case TYPE_RECORD: {
4639 if (Record.size() != 2) {
4640 Error("incorrect encoding of record type");
4641 return QualType();
4642 }
4643 unsigned Idx = 0;
4644 bool IsDependent = Record[Idx++];
4645 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
4646 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
4647 QualType T = Context.getRecordType(RD);
4648 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4649 return T;
4650 }
4651
4652 case TYPE_ENUM: {
4653 if (Record.size() != 2) {
4654 Error("incorrect encoding of enum type");
4655 return QualType();
4656 }
4657 unsigned Idx = 0;
4658 bool IsDependent = Record[Idx++];
4659 QualType T
4660 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
4661 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4662 return T;
4663 }
4664
4665 case TYPE_ATTRIBUTED: {
4666 if (Record.size() != 3) {
4667 Error("incorrect encoding of attributed type");
4668 return QualType();
4669 }
4670 QualType modifiedType = readType(*Loc.F, Record, Idx);
4671 QualType equivalentType = readType(*Loc.F, Record, Idx);
4672 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
4673 return Context.getAttributedType(kind, modifiedType, equivalentType);
4674 }
4675
4676 case TYPE_PAREN: {
4677 if (Record.size() != 1) {
4678 Error("incorrect encoding of paren type");
4679 return QualType();
4680 }
4681 QualType InnerType = readType(*Loc.F, Record, Idx);
4682 return Context.getParenType(InnerType);
4683 }
4684
4685 case TYPE_PACK_EXPANSION: {
4686 if (Record.size() != 2) {
4687 Error("incorrect encoding of pack expansion type");
4688 return QualType();
4689 }
4690 QualType Pattern = readType(*Loc.F, Record, Idx);
4691 if (Pattern.isNull())
4692 return QualType();
David Blaikiedc84cd52013-02-20 22:23:23 +00004693 Optional<unsigned> NumExpansions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004694 if (Record[1])
4695 NumExpansions = Record[1] - 1;
4696 return Context.getPackExpansionType(Pattern, NumExpansions);
4697 }
4698
4699 case TYPE_ELABORATED: {
4700 unsigned Idx = 0;
4701 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4702 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4703 QualType NamedType = readType(*Loc.F, Record, Idx);
4704 return Context.getElaboratedType(Keyword, NNS, NamedType);
4705 }
4706
4707 case TYPE_OBJC_INTERFACE: {
4708 unsigned Idx = 0;
4709 ObjCInterfaceDecl *ItfD
4710 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
4711 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
4712 }
4713
4714 case TYPE_OBJC_OBJECT: {
4715 unsigned Idx = 0;
4716 QualType Base = readType(*Loc.F, Record, Idx);
4717 unsigned NumProtos = Record[Idx++];
4718 SmallVector<ObjCProtocolDecl*, 4> Protos;
4719 for (unsigned I = 0; I != NumProtos; ++I)
4720 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
4721 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
4722 }
4723
4724 case TYPE_OBJC_OBJECT_POINTER: {
4725 unsigned Idx = 0;
4726 QualType Pointee = readType(*Loc.F, Record, Idx);
4727 return Context.getObjCObjectPointerType(Pointee);
4728 }
4729
4730 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
4731 unsigned Idx = 0;
4732 QualType Parm = readType(*Loc.F, Record, Idx);
4733 QualType Replacement = readType(*Loc.F, Record, Idx);
4734 return
4735 Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
4736 Replacement);
4737 }
4738
4739 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
4740 unsigned Idx = 0;
4741 QualType Parm = readType(*Loc.F, Record, Idx);
4742 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
4743 return Context.getSubstTemplateTypeParmPackType(
4744 cast<TemplateTypeParmType>(Parm),
4745 ArgPack);
4746 }
4747
4748 case TYPE_INJECTED_CLASS_NAME: {
4749 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
4750 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
4751 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
4752 // for AST reading, too much interdependencies.
4753 return
4754 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
4755 }
4756
4757 case TYPE_TEMPLATE_TYPE_PARM: {
4758 unsigned Idx = 0;
4759 unsigned Depth = Record[Idx++];
4760 unsigned Index = Record[Idx++];
4761 bool Pack = Record[Idx++];
4762 TemplateTypeParmDecl *D
4763 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
4764 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
4765 }
4766
4767 case TYPE_DEPENDENT_NAME: {
4768 unsigned Idx = 0;
4769 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4770 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4771 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4772 QualType Canon = readType(*Loc.F, Record, Idx);
4773 if (!Canon.isNull())
4774 Canon = Context.getCanonicalType(Canon);
4775 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
4776 }
4777
4778 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
4779 unsigned Idx = 0;
4780 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4781 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4782 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4783 unsigned NumArgs = Record[Idx++];
4784 SmallVector<TemplateArgument, 8> Args;
4785 Args.reserve(NumArgs);
4786 while (NumArgs--)
4787 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
4788 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
4789 Args.size(), Args.data());
4790 }
4791
4792 case TYPE_DEPENDENT_SIZED_ARRAY: {
4793 unsigned Idx = 0;
4794
4795 // ArrayType
4796 QualType ElementType = readType(*Loc.F, Record, Idx);
4797 ArrayType::ArraySizeModifier ASM
4798 = (ArrayType::ArraySizeModifier)Record[Idx++];
4799 unsigned IndexTypeQuals = Record[Idx++];
4800
4801 // DependentSizedArrayType
4802 Expr *NumElts = ReadExpr(*Loc.F);
4803 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
4804
4805 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
4806 IndexTypeQuals, Brackets);
4807 }
4808
4809 case TYPE_TEMPLATE_SPECIALIZATION: {
4810 unsigned Idx = 0;
4811 bool IsDependent = Record[Idx++];
4812 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
4813 SmallVector<TemplateArgument, 8> Args;
4814 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
4815 QualType Underlying = readType(*Loc.F, Record, Idx);
4816 QualType T;
4817 if (Underlying.isNull())
4818 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
4819 Args.size());
4820 else
4821 T = Context.getTemplateSpecializationType(Name, Args.data(),
4822 Args.size(), Underlying);
4823 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4824 return T;
4825 }
4826
4827 case TYPE_ATOMIC: {
4828 if (Record.size() != 1) {
4829 Error("Incorrect encoding of atomic type");
4830 return QualType();
4831 }
4832 QualType ValueType = readType(*Loc.F, Record, Idx);
4833 return Context.getAtomicType(ValueType);
4834 }
4835 }
4836 llvm_unreachable("Invalid TypeCode!");
4837}
4838
4839class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
4840 ASTReader &Reader;
4841 ModuleFile &F;
4842 const ASTReader::RecordData &Record;
4843 unsigned &Idx;
4844
4845 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
4846 unsigned &I) {
4847 return Reader.ReadSourceLocation(F, R, I);
4848 }
4849
4850 template<typename T>
4851 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
4852 return Reader.ReadDeclAs<T>(F, Record, Idx);
4853 }
4854
4855public:
4856 TypeLocReader(ASTReader &Reader, ModuleFile &F,
4857 const ASTReader::RecordData &Record, unsigned &Idx)
4858 : Reader(Reader), F(F), Record(Record), Idx(Idx)
4859 { }
4860
4861 // We want compile-time assurance that we've enumerated all of
4862 // these, so unfortunately we have to declare them first, then
4863 // define them out-of-line.
4864#define ABSTRACT_TYPELOC(CLASS, PARENT)
4865#define TYPELOC(CLASS, PARENT) \
4866 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
4867#include "clang/AST/TypeLocNodes.def"
4868
4869 void VisitFunctionTypeLoc(FunctionTypeLoc);
4870 void VisitArrayTypeLoc(ArrayTypeLoc);
4871};
4872
4873void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4874 // nothing to do
4875}
4876void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4877 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
4878 if (TL.needsExtraLocalData()) {
4879 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
4880 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
4881 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
4882 TL.setModeAttr(Record[Idx++]);
4883 }
4884}
4885void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
4886 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4887}
4888void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
4889 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4890}
4891void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
4892 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
4893}
4894void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
4895 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
4896}
4897void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
4898 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
4899}
4900void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
4901 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4902 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4903}
4904void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
4905 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
4906 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
4907 if (Record[Idx++])
4908 TL.setSizeExpr(Reader.ReadExpr(F));
4909 else
4910 TL.setSizeExpr(0);
4911}
4912void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
4913 VisitArrayTypeLoc(TL);
4914}
4915void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
4916 VisitArrayTypeLoc(TL);
4917}
4918void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
4919 VisitArrayTypeLoc(TL);
4920}
4921void TypeLocReader::VisitDependentSizedArrayTypeLoc(
4922 DependentSizedArrayTypeLoc TL) {
4923 VisitArrayTypeLoc(TL);
4924}
4925void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
4926 DependentSizedExtVectorTypeLoc TL) {
4927 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4928}
4929void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
4930 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4931}
4932void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
4933 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4934}
4935void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
4936 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
4937 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4938 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4939 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
4940 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
4941 TL.setArg(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
4942 }
4943}
4944void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
4945 VisitFunctionTypeLoc(TL);
4946}
4947void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
4948 VisitFunctionTypeLoc(TL);
4949}
4950void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
4951 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4952}
4953void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
4954 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4955}
4956void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
4957 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
4958 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4959 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4960}
4961void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
4962 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
4963 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4964 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4965 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4966}
4967void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
4968 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4969}
4970void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
4971 TL.setKWLoc(ReadSourceLocation(Record, Idx));
4972 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4973 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4974 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4975}
4976void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
4977 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4978}
4979void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
4980 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4981}
4982void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
4983 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4984}
4985void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4986 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
4987 if (TL.hasAttrOperand()) {
4988 SourceRange range;
4989 range.setBegin(ReadSourceLocation(Record, Idx));
4990 range.setEnd(ReadSourceLocation(Record, Idx));
4991 TL.setAttrOperandParensRange(range);
4992 }
4993 if (TL.hasAttrExprOperand()) {
4994 if (Record[Idx++])
4995 TL.setAttrExprOperand(Reader.ReadExpr(F));
4996 else
4997 TL.setAttrExprOperand(0);
4998 } else if (TL.hasAttrEnumOperand())
4999 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5000}
5001void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5002 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5003}
5004void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5005 SubstTemplateTypeParmTypeLoc TL) {
5006 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5007}
5008void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5009 SubstTemplateTypeParmPackTypeLoc TL) {
5010 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5011}
5012void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5013 TemplateSpecializationTypeLoc TL) {
5014 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5015 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5016 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5017 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5018 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5019 TL.setArgLocInfo(i,
5020 Reader.GetTemplateArgumentLocInfo(F,
5021 TL.getTypePtr()->getArg(i).getKind(),
5022 Record, Idx));
5023}
5024void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5025 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5026 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5027}
5028void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5029 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5030 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5031}
5032void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5033 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5034}
5035void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5036 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5037 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5038 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5039}
5040void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5041 DependentTemplateSpecializationTypeLoc TL) {
5042 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5043 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5044 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5045 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5046 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5047 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5048 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5049 TL.setArgLocInfo(I,
5050 Reader.GetTemplateArgumentLocInfo(F,
5051 TL.getTypePtr()->getArg(I).getKind(),
5052 Record, Idx));
5053}
5054void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5055 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5056}
5057void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5058 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5059}
5060void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5061 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5062 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5063 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5064 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5065 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5066}
5067void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5068 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5069}
5070void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5071 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5072 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5073 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5074}
5075
5076TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5077 const RecordData &Record,
5078 unsigned &Idx) {
5079 QualType InfoTy = readType(F, Record, Idx);
5080 if (InfoTy.isNull())
5081 return 0;
5082
5083 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5084 TypeLocReader TLR(*this, F, Record, Idx);
5085 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5086 TLR.Visit(TL);
5087 return TInfo;
5088}
5089
5090QualType ASTReader::GetType(TypeID ID) {
5091 unsigned FastQuals = ID & Qualifiers::FastMask;
5092 unsigned Index = ID >> Qualifiers::FastWidth;
5093
5094 if (Index < NUM_PREDEF_TYPE_IDS) {
5095 QualType T;
5096 switch ((PredefinedTypeIDs)Index) {
5097 case PREDEF_TYPE_NULL_ID: return QualType();
5098 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5099 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5100
5101 case PREDEF_TYPE_CHAR_U_ID:
5102 case PREDEF_TYPE_CHAR_S_ID:
5103 // FIXME: Check that the signedness of CharTy is correct!
5104 T = Context.CharTy;
5105 break;
5106
5107 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5108 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5109 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5110 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5111 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5112 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5113 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5114 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5115 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5116 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5117 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5118 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5119 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5120 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5121 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5122 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5123 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5124 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5125 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5126 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5127 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5128 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5129 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5130 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5131 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5132 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5133 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5134 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeib13621d2012-12-18 14:38:23 +00005135 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5136 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5137 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5138 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5139 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5140 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei21f18c42013-02-07 10:55:47 +00005141 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00005142 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005143 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5144
5145 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5146 T = Context.getAutoRRefDeductType();
5147 break;
5148
5149 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5150 T = Context.ARCUnbridgedCastTy;
5151 break;
5152
5153 case PREDEF_TYPE_VA_LIST_TAG:
5154 T = Context.getVaListTagType();
5155 break;
5156
5157 case PREDEF_TYPE_BUILTIN_FN:
5158 T = Context.BuiltinFnTy;
5159 break;
5160 }
5161
5162 assert(!T.isNull() && "Unknown predefined type");
5163 return T.withFastQualifiers(FastQuals);
5164 }
5165
5166 Index -= NUM_PREDEF_TYPE_IDS;
5167 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5168 if (TypesLoaded[Index].isNull()) {
5169 TypesLoaded[Index] = readTypeRecord(Index);
5170 if (TypesLoaded[Index].isNull())
5171 return QualType();
5172
5173 TypesLoaded[Index]->setFromAST();
5174 if (DeserializationListener)
5175 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5176 TypesLoaded[Index]);
5177 }
5178
5179 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5180}
5181
5182QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5183 return GetType(getGlobalTypeID(F, LocalID));
5184}
5185
5186serialization::TypeID
5187ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5188 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5189 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5190
5191 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5192 return LocalID;
5193
5194 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5195 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5196 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5197
5198 unsigned GlobalIndex = LocalIndex + I->second;
5199 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5200}
5201
5202TemplateArgumentLocInfo
5203ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5204 TemplateArgument::ArgKind Kind,
5205 const RecordData &Record,
5206 unsigned &Index) {
5207 switch (Kind) {
5208 case TemplateArgument::Expression:
5209 return ReadExpr(F);
5210 case TemplateArgument::Type:
5211 return GetTypeSourceInfo(F, Record, Index);
5212 case TemplateArgument::Template: {
5213 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5214 Index);
5215 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5216 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5217 SourceLocation());
5218 }
5219 case TemplateArgument::TemplateExpansion: {
5220 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5221 Index);
5222 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5223 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5224 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5225 EllipsisLoc);
5226 }
5227 case TemplateArgument::Null:
5228 case TemplateArgument::Integral:
5229 case TemplateArgument::Declaration:
5230 case TemplateArgument::NullPtr:
5231 case TemplateArgument::Pack:
5232 // FIXME: Is this right?
5233 return TemplateArgumentLocInfo();
5234 }
5235 llvm_unreachable("unexpected template argument loc");
5236}
5237
5238TemplateArgumentLoc
5239ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5240 const RecordData &Record, unsigned &Index) {
5241 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5242
5243 if (Arg.getKind() == TemplateArgument::Expression) {
5244 if (Record[Index++]) // bool InfoHasSameExpr.
5245 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5246 }
5247 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5248 Record, Index));
5249}
5250
5251Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5252 return GetDecl(ID);
5253}
5254
5255uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5256 unsigned &Idx){
5257 if (Idx >= Record.size())
5258 return 0;
5259
5260 unsigned LocalID = Record[Idx++];
5261 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5262}
5263
5264CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5265 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00005266 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005267 SavedStreamPosition SavedPosition(Cursor);
5268 Cursor.JumpToBit(Loc.Offset);
5269 ReadingKindTracker ReadingKind(Read_Decl, *this);
5270 RecordData Record;
5271 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00005272 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005273 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5274 Error("Malformed AST file: missing C++ base specifiers");
5275 return 0;
5276 }
5277
5278 unsigned Idx = 0;
5279 unsigned NumBases = Record[Idx++];
5280 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5281 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5282 for (unsigned I = 0; I != NumBases; ++I)
5283 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5284 return Bases;
5285}
5286
5287serialization::DeclID
5288ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5289 if (LocalID < NUM_PREDEF_DECL_IDS)
5290 return LocalID;
5291
5292 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5293 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5294 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5295
5296 return LocalID + I->second;
5297}
5298
5299bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5300 ModuleFile &M) const {
5301 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5302 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5303 return &M == I->second;
5304}
5305
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005306ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005307 if (!D->isFromASTFile())
5308 return 0;
5309 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5310 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5311 return I->second;
5312}
5313
5314SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5315 if (ID < NUM_PREDEF_DECL_IDS)
5316 return SourceLocation();
5317
5318 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5319
5320 if (Index > DeclsLoaded.size()) {
5321 Error("declaration ID out-of-range for AST file");
5322 return SourceLocation();
5323 }
5324
5325 if (Decl *D = DeclsLoaded[Index])
5326 return D->getLocation();
5327
5328 unsigned RawLocation = 0;
5329 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5330 return ReadSourceLocation(*Rec.F, RawLocation);
5331}
5332
5333Decl *ASTReader::GetDecl(DeclID ID) {
5334 if (ID < NUM_PREDEF_DECL_IDS) {
5335 switch ((PredefinedDeclIDs)ID) {
5336 case PREDEF_DECL_NULL_ID:
5337 return 0;
5338
5339 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5340 return Context.getTranslationUnitDecl();
5341
5342 case PREDEF_DECL_OBJC_ID_ID:
5343 return Context.getObjCIdDecl();
5344
5345 case PREDEF_DECL_OBJC_SEL_ID:
5346 return Context.getObjCSelDecl();
5347
5348 case PREDEF_DECL_OBJC_CLASS_ID:
5349 return Context.getObjCClassDecl();
5350
5351 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5352 return Context.getObjCProtocolDecl();
5353
5354 case PREDEF_DECL_INT_128_ID:
5355 return Context.getInt128Decl();
5356
5357 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5358 return Context.getUInt128Decl();
5359
5360 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5361 return Context.getObjCInstanceTypeDecl();
5362
5363 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5364 return Context.getBuiltinVaListDecl();
5365 }
5366 }
5367
5368 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5369
5370 if (Index >= DeclsLoaded.size()) {
5371 assert(0 && "declaration ID out-of-range for AST file");
5372 Error("declaration ID out-of-range for AST file");
5373 return 0;
5374 }
5375
5376 if (!DeclsLoaded[Index]) {
5377 ReadDeclRecord(ID);
5378 if (DeserializationListener)
5379 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5380 }
5381
5382 return DeclsLoaded[Index];
5383}
5384
5385DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5386 DeclID GlobalID) {
5387 if (GlobalID < NUM_PREDEF_DECL_IDS)
5388 return GlobalID;
5389
5390 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5391 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5392 ModuleFile *Owner = I->second;
5393
5394 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5395 = M.GlobalToLocalDeclIDs.find(Owner);
5396 if (Pos == M.GlobalToLocalDeclIDs.end())
5397 return 0;
5398
5399 return GlobalID - Owner->BaseDeclID + Pos->second;
5400}
5401
5402serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5403 const RecordData &Record,
5404 unsigned &Idx) {
5405 if (Idx >= Record.size()) {
5406 Error("Corrupted AST file");
5407 return 0;
5408 }
5409
5410 return getGlobalDeclID(F, Record[Idx++]);
5411}
5412
5413/// \brief Resolve the offset of a statement into a statement.
5414///
5415/// This operation will read a new statement from the external
5416/// source each time it is called, and is meant to be used via a
5417/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5418Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5419 // Switch case IDs are per Decl.
5420 ClearSwitchCaseIDs();
5421
5422 // Offset here is a global offset across the entire chain.
5423 RecordLocation Loc = getLocalBitOffset(Offset);
5424 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5425 return ReadStmtFromStream(*Loc.F);
5426}
5427
5428namespace {
5429 class FindExternalLexicalDeclsVisitor {
5430 ASTReader &Reader;
5431 const DeclContext *DC;
5432 bool (*isKindWeWant)(Decl::Kind);
5433
5434 SmallVectorImpl<Decl*> &Decls;
5435 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5436
5437 public:
5438 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5439 bool (*isKindWeWant)(Decl::Kind),
5440 SmallVectorImpl<Decl*> &Decls)
5441 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5442 {
5443 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5444 PredefsVisited[I] = false;
5445 }
5446
5447 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5448 if (Preorder)
5449 return false;
5450
5451 FindExternalLexicalDeclsVisitor *This
5452 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5453
5454 ModuleFile::DeclContextInfosMap::iterator Info
5455 = M.DeclContextInfos.find(This->DC);
5456 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5457 return false;
5458
5459 // Load all of the declaration IDs
5460 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5461 *IDE = ID + Info->second.NumLexicalDecls;
5462 ID != IDE; ++ID) {
5463 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5464 continue;
5465
5466 // Don't add predefined declarations to the lexical context more
5467 // than once.
5468 if (ID->second < NUM_PREDEF_DECL_IDS) {
5469 if (This->PredefsVisited[ID->second])
5470 continue;
5471
5472 This->PredefsVisited[ID->second] = true;
5473 }
5474
5475 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5476 if (!This->DC->isDeclInLexicalTraversal(D))
5477 This->Decls.push_back(D);
5478 }
5479 }
5480
5481 return false;
5482 }
5483 };
5484}
5485
5486ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
5487 bool (*isKindWeWant)(Decl::Kind),
5488 SmallVectorImpl<Decl*> &Decls) {
5489 // There might be lexical decls in multiple modules, for the TU at
5490 // least. Walk all of the modules in the order they were loaded.
5491 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5492 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
5493 ++NumLexicalDeclContextsRead;
5494 return ELR_Success;
5495}
5496
5497namespace {
5498
5499class DeclIDComp {
5500 ASTReader &Reader;
5501 ModuleFile &Mod;
5502
5503public:
5504 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
5505
5506 bool operator()(LocalDeclID L, LocalDeclID R) const {
5507 SourceLocation LHS = getLocation(L);
5508 SourceLocation RHS = getLocation(R);
5509 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5510 }
5511
5512 bool operator()(SourceLocation LHS, LocalDeclID R) const {
5513 SourceLocation RHS = getLocation(R);
5514 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5515 }
5516
5517 bool operator()(LocalDeclID L, SourceLocation RHS) const {
5518 SourceLocation LHS = getLocation(L);
5519 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5520 }
5521
5522 SourceLocation getLocation(LocalDeclID ID) const {
5523 return Reader.getSourceManager().getFileLoc(
5524 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
5525 }
5526};
5527
5528}
5529
5530void ASTReader::FindFileRegionDecls(FileID File,
5531 unsigned Offset, unsigned Length,
5532 SmallVectorImpl<Decl *> &Decls) {
5533 SourceManager &SM = getSourceManager();
5534
5535 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
5536 if (I == FileDeclIDs.end())
5537 return;
5538
5539 FileDeclsInfo &DInfo = I->second;
5540 if (DInfo.Decls.empty())
5541 return;
5542
5543 SourceLocation
5544 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
5545 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
5546
5547 DeclIDComp DIDComp(*this, *DInfo.Mod);
5548 ArrayRef<serialization::LocalDeclID>::iterator
5549 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5550 BeginLoc, DIDComp);
5551 if (BeginIt != DInfo.Decls.begin())
5552 --BeginIt;
5553
5554 // If we are pointing at a top-level decl inside an objc container, we need
5555 // to backtrack until we find it otherwise we will fail to report that the
5556 // region overlaps with an objc container.
5557 while (BeginIt != DInfo.Decls.begin() &&
5558 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
5559 ->isTopLevelDeclInObjCContainer())
5560 --BeginIt;
5561
5562 ArrayRef<serialization::LocalDeclID>::iterator
5563 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5564 EndLoc, DIDComp);
5565 if (EndIt != DInfo.Decls.end())
5566 ++EndIt;
5567
5568 for (ArrayRef<serialization::LocalDeclID>::iterator
5569 DIt = BeginIt; DIt != EndIt; ++DIt)
5570 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
5571}
5572
5573namespace {
5574 /// \brief ModuleFile visitor used to perform name lookup into a
5575 /// declaration context.
5576 class DeclContextNameLookupVisitor {
5577 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005578 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005579 DeclarationName Name;
5580 SmallVectorImpl<NamedDecl *> &Decls;
5581
5582 public:
5583 DeclContextNameLookupVisitor(ASTReader &Reader,
5584 SmallVectorImpl<const DeclContext *> &Contexts,
5585 DeclarationName Name,
5586 SmallVectorImpl<NamedDecl *> &Decls)
5587 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
5588
5589 static bool visit(ModuleFile &M, void *UserData) {
5590 DeclContextNameLookupVisitor *This
5591 = static_cast<DeclContextNameLookupVisitor *>(UserData);
5592
5593 // Check whether we have any visible declaration information for
5594 // this context in this module.
5595 ModuleFile::DeclContextInfosMap::iterator Info;
5596 bool FoundInfo = false;
5597 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5598 Info = M.DeclContextInfos.find(This->Contexts[I]);
5599 if (Info != M.DeclContextInfos.end() &&
5600 Info->second.NameLookupTableData) {
5601 FoundInfo = true;
5602 break;
5603 }
5604 }
5605
5606 if (!FoundInfo)
5607 return false;
5608
5609 // Look for this name within this module.
5610 ASTDeclContextNameLookupTable *LookupTable =
5611 Info->second.NameLookupTableData;
5612 ASTDeclContextNameLookupTable::iterator Pos
5613 = LookupTable->find(This->Name);
5614 if (Pos == LookupTable->end())
5615 return false;
5616
5617 bool FoundAnything = false;
5618 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
5619 for (; Data.first != Data.second; ++Data.first) {
5620 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
5621 if (!ND)
5622 continue;
5623
5624 if (ND->getDeclName() != This->Name) {
5625 // A name might be null because the decl's redeclarable part is
5626 // currently read before reading its name. The lookup is triggered by
5627 // building that decl (likely indirectly), and so it is later in the
5628 // sense of "already existing" and can be ignored here.
5629 continue;
5630 }
5631
5632 // Record this declaration.
5633 FoundAnything = true;
5634 This->Decls.push_back(ND);
5635 }
5636
5637 return FoundAnything;
5638 }
5639 };
5640}
5641
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005642/// \brief Retrieve the "definitive" module file for the definition of the
5643/// given declaration context, if there is one.
5644///
5645/// The "definitive" module file is the only place where we need to look to
5646/// find information about the declarations within the given declaration
5647/// context. For example, C++ and Objective-C classes, C structs/unions, and
5648/// Objective-C protocols, categories, and extensions are all defined in a
5649/// single place in the source code, so they have definitive module files
5650/// associated with them. C++ namespaces, on the other hand, can have
5651/// definitions in multiple different module files.
5652///
5653/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
5654/// NDEBUG checking.
5655static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
5656 ASTReader &Reader) {
Douglas Gregore0d20662013-01-22 17:08:30 +00005657 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
5658 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005659
5660 return 0;
5661}
5662
Richard Smith3646c682013-02-07 03:30:24 +00005663bool
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005664ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
5665 DeclarationName Name) {
5666 assert(DC->hasExternalVisibleStorage() &&
5667 "DeclContext has no visible decls in storage");
5668 if (!Name)
Richard Smith3646c682013-02-07 03:30:24 +00005669 return false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005670
5671 SmallVector<NamedDecl *, 64> Decls;
5672
5673 // Compute the declaration contexts we need to look into. Multiple such
5674 // declaration contexts occur when two declaration contexts from disjoint
5675 // modules get merged, e.g., when two namespaces with the same name are
5676 // independently defined in separate modules.
5677 SmallVector<const DeclContext *, 2> Contexts;
5678 Contexts.push_back(DC);
5679
5680 if (DC->isNamespace()) {
5681 MergedDeclsMap::iterator Merged
5682 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5683 if (Merged != MergedDecls.end()) {
5684 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5685 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5686 }
5687 }
5688
5689 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005690
5691 // If we can definitively determine which module file to look into,
5692 // only look there. Otherwise, look in all module files.
5693 ModuleFile *Definitive;
5694 if (Contexts.size() == 1 &&
5695 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
5696 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
5697 } else {
5698 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
5699 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005700 ++NumVisibleDeclContextsRead;
5701 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith3646c682013-02-07 03:30:24 +00005702 return !Decls.empty();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005703}
5704
5705namespace {
5706 /// \brief ModuleFile visitor used to retrieve all visible names in a
5707 /// declaration context.
5708 class DeclContextAllNamesVisitor {
5709 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005710 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005711 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > &Decls;
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005712 bool VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005713
5714 public:
5715 DeclContextAllNamesVisitor(ASTReader &Reader,
5716 SmallVectorImpl<const DeclContext *> &Contexts,
5717 llvm::DenseMap<DeclarationName,
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005718 SmallVector<NamedDecl *, 8> > &Decls,
5719 bool VisitAll)
5720 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005721
5722 static bool visit(ModuleFile &M, void *UserData) {
5723 DeclContextAllNamesVisitor *This
5724 = static_cast<DeclContextAllNamesVisitor *>(UserData);
5725
5726 // Check whether we have any visible declaration information for
5727 // this context in this module.
5728 ModuleFile::DeclContextInfosMap::iterator Info;
5729 bool FoundInfo = false;
5730 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5731 Info = M.DeclContextInfos.find(This->Contexts[I]);
5732 if (Info != M.DeclContextInfos.end() &&
5733 Info->second.NameLookupTableData) {
5734 FoundInfo = true;
5735 break;
5736 }
5737 }
5738
5739 if (!FoundInfo)
5740 return false;
5741
5742 ASTDeclContextNameLookupTable *LookupTable =
5743 Info->second.NameLookupTableData;
5744 bool FoundAnything = false;
5745 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregora6b00fc2013-01-23 22:38:11 +00005746 I = LookupTable->data_begin(), E = LookupTable->data_end();
5747 I != E;
5748 ++I) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005749 ASTDeclContextNameLookupTrait::data_type Data = *I;
5750 for (; Data.first != Data.second; ++Data.first) {
5751 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
5752 *Data.first);
5753 if (!ND)
5754 continue;
5755
5756 // Record this declaration.
5757 FoundAnything = true;
5758 This->Decls[ND->getDeclName()].push_back(ND);
5759 }
5760 }
5761
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005762 return FoundAnything && !This->VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005763 }
5764 };
5765}
5766
5767void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
5768 if (!DC->hasExternalVisibleStorage())
5769 return;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005770 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > Decls;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005771
5772 // Compute the declaration contexts we need to look into. Multiple such
5773 // declaration contexts occur when two declaration contexts from disjoint
5774 // modules get merged, e.g., when two namespaces with the same name are
5775 // independently defined in separate modules.
5776 SmallVector<const DeclContext *, 2> Contexts;
5777 Contexts.push_back(DC);
5778
5779 if (DC->isNamespace()) {
5780 MergedDeclsMap::iterator Merged
5781 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5782 if (Merged != MergedDecls.end()) {
5783 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5784 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5785 }
5786 }
5787
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005788 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
5789 /*VisitAll=*/DC->isFileContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005790 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
5791 ++NumVisibleDeclContextsRead;
5792
5793 for (llvm::DenseMap<DeclarationName,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005794 SmallVector<NamedDecl *, 8> >::iterator
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005795 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
5796 SetExternalVisibleDeclsForName(DC, I->first, I->second);
5797 }
5798 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
5799}
5800
5801/// \brief Under non-PCH compilation the consumer receives the objc methods
5802/// before receiving the implementation, and codegen depends on this.
5803/// We simulate this by deserializing and passing to consumer the methods of the
5804/// implementation before passing the deserialized implementation decl.
5805static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
5806 ASTConsumer *Consumer) {
5807 assert(ImplD && Consumer);
5808
5809 for (ObjCImplDecl::method_iterator
5810 I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
5811 Consumer->HandleInterestingDecl(DeclGroupRef(*I));
5812
5813 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
5814}
5815
5816void ASTReader::PassInterestingDeclsToConsumer() {
5817 assert(Consumer);
5818 while (!InterestingDecls.empty()) {
5819 Decl *D = InterestingDecls.front();
5820 InterestingDecls.pop_front();
5821
5822 PassInterestingDeclToConsumer(D);
5823 }
5824}
5825
5826void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
5827 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5828 PassObjCImplDeclToConsumer(ImplD, Consumer);
5829 else
5830 Consumer->HandleInterestingDecl(DeclGroupRef(D));
5831}
5832
5833void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
5834 this->Consumer = Consumer;
5835
5836 if (!Consumer)
5837 return;
5838
5839 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
5840 // Force deserialization of this decl, which will cause it to be queued for
5841 // passing to the consumer.
5842 GetDecl(ExternalDefinitions[I]);
5843 }
5844 ExternalDefinitions.clear();
5845
5846 PassInterestingDeclsToConsumer();
5847}
5848
5849void ASTReader::PrintStats() {
5850 std::fprintf(stderr, "*** AST File Statistics:\n");
5851
5852 unsigned NumTypesLoaded
5853 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
5854 QualType());
5855 unsigned NumDeclsLoaded
5856 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
5857 (Decl *)0);
5858 unsigned NumIdentifiersLoaded
5859 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
5860 IdentifiersLoaded.end(),
5861 (IdentifierInfo *)0);
5862 unsigned NumMacrosLoaded
5863 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
5864 MacrosLoaded.end(),
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00005865 (MacroInfo *)0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005866 unsigned NumSelectorsLoaded
5867 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
5868 SelectorsLoaded.end(),
5869 Selector());
5870
5871 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
5872 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
5873 NumSLocEntriesRead, TotalNumSLocEntries,
5874 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
5875 if (!TypesLoaded.empty())
5876 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
5877 NumTypesLoaded, (unsigned)TypesLoaded.size(),
5878 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
5879 if (!DeclsLoaded.empty())
5880 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
5881 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
5882 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
5883 if (!IdentifiersLoaded.empty())
5884 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
5885 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
5886 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
5887 if (!MacrosLoaded.empty())
5888 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5889 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
5890 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
5891 if (!SelectorsLoaded.empty())
5892 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
5893 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
5894 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
5895 if (TotalNumStatements)
5896 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
5897 NumStatementsRead, TotalNumStatements,
5898 ((float)NumStatementsRead/TotalNumStatements * 100));
5899 if (TotalNumMacros)
5900 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5901 NumMacrosRead, TotalNumMacros,
5902 ((float)NumMacrosRead/TotalNumMacros * 100));
5903 if (TotalLexicalDeclContexts)
5904 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
5905 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
5906 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
5907 * 100));
5908 if (TotalVisibleDeclContexts)
5909 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
5910 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
5911 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
5912 * 100));
5913 if (TotalNumMethodPoolEntries) {
5914 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
5915 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
5916 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
5917 * 100));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005918 }
Douglas Gregor95fb36e2013-01-28 17:54:36 +00005919 if (NumMethodPoolLookups) {
5920 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
5921 NumMethodPoolHits, NumMethodPoolLookups,
5922 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
5923 }
5924 if (NumMethodPoolTableLookups) {
5925 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
5926 NumMethodPoolTableHits, NumMethodPoolTableLookups,
5927 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
5928 * 100.0));
5929 }
5930
Douglas Gregore1698072013-01-25 00:38:33 +00005931 if (NumIdentifierLookupHits) {
5932 std::fprintf(stderr,
5933 " %u / %u identifier table lookups succeeded (%f%%)\n",
5934 NumIdentifierLookupHits, NumIdentifierLookups,
5935 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
5936 }
5937
Douglas Gregor1a49d972013-01-25 01:03:03 +00005938 if (GlobalIndex) {
5939 std::fprintf(stderr, "\n");
5940 GlobalIndex->printStats();
5941 }
5942
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005943 std::fprintf(stderr, "\n");
5944 dump();
5945 std::fprintf(stderr, "\n");
5946}
5947
5948template<typename Key, typename ModuleFile, unsigned InitialCapacity>
5949static void
5950dumpModuleIDMap(StringRef Name,
5951 const ContinuousRangeMap<Key, ModuleFile *,
5952 InitialCapacity> &Map) {
5953 if (Map.begin() == Map.end())
5954 return;
5955
5956 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
5957 llvm::errs() << Name << ":\n";
5958 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
5959 I != IEnd; ++I) {
5960 llvm::errs() << " " << I->first << " -> " << I->second->FileName
5961 << "\n";
5962 }
5963}
5964
5965void ASTReader::dump() {
5966 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
5967 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
5968 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
5969 dumpModuleIDMap("Global type map", GlobalTypeMap);
5970 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
5971 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
5972 dumpModuleIDMap("Global macro map", GlobalMacroMap);
5973 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
5974 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
5975 dumpModuleIDMap("Global preprocessed entity map",
5976 GlobalPreprocessedEntityMap);
5977
5978 llvm::errs() << "\n*** PCH/Modules Loaded:";
5979 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
5980 MEnd = ModuleMgr.end();
5981 M != MEnd; ++M)
5982 (*M)->dump();
5983}
5984
5985/// Return the amount of memory used by memory buffers, breaking down
5986/// by heap-backed versus mmap'ed memory.
5987void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
5988 for (ModuleConstIterator I = ModuleMgr.begin(),
5989 E = ModuleMgr.end(); I != E; ++I) {
5990 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
5991 size_t bytes = buf->getBufferSize();
5992 switch (buf->getBufferKind()) {
5993 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
5994 sizes.malloc_bytes += bytes;
5995 break;
5996 case llvm::MemoryBuffer::MemoryBuffer_MMap:
5997 sizes.mmap_bytes += bytes;
5998 break;
5999 }
6000 }
6001 }
6002}
6003
6004void ASTReader::InitializeSema(Sema &S) {
6005 SemaObj = &S;
6006 S.addExternalSource(this);
6007
6008 // Makes sure any declarations that were deserialized "too early"
6009 // still get added to the identifier's declaration chains.
6010 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Douglas Gregoraa945902013-02-18 15:53:43 +00006011 NamedDecl *ND = cast<NamedDecl>(PreloadedDecls[I]->getMostRecentDecl());
6012 SemaObj->pushExternalDeclIntoScope(ND, PreloadedDecls[I]->getDeclName());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006013 }
6014 PreloadedDecls.clear();
6015
6016 // Load the offsets of the declarations that Sema references.
6017 // They will be lazily deserialized when needed.
6018 if (!SemaDeclRefs.empty()) {
6019 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
6020 if (!SemaObj->StdNamespace)
6021 SemaObj->StdNamespace = SemaDeclRefs[0];
6022 if (!SemaObj->StdBadAlloc)
6023 SemaObj->StdBadAlloc = SemaDeclRefs[1];
6024 }
6025
6026 if (!FPPragmaOptions.empty()) {
6027 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6028 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6029 }
6030
6031 if (!OpenCLExtensions.empty()) {
6032 unsigned I = 0;
6033#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6034#include "clang/Basic/OpenCLExtensions.def"
6035
6036 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6037 }
6038}
6039
6040IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6041 // Note that we are loading an identifier.
6042 Deserializing AnIdentifier(this);
Douglas Gregor1a49d972013-01-25 01:03:03 +00006043 StringRef Name(NameStart, NameEnd - NameStart);
6044
6045 // If there is a global index, look there first to determine which modules
6046 // provably do not have any results for this identifier.
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006047 GlobalModuleIndex::HitSet Hits;
6048 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregor1a49d972013-01-25 01:03:03 +00006049 if (!loadGlobalIndex()) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006050 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6051 HitsPtr = &Hits;
Douglas Gregor1a49d972013-01-25 01:03:03 +00006052 }
6053 }
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006054 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregore1698072013-01-25 00:38:33 +00006055 NumIdentifierLookups,
6056 NumIdentifierLookupHits);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006057 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006058 IdentifierInfo *II = Visitor.getIdentifierInfo();
6059 markIdentifierUpToDate(II);
6060 return II;
6061}
6062
6063namespace clang {
6064 /// \brief An identifier-lookup iterator that enumerates all of the
6065 /// identifiers stored within a set of AST files.
6066 class ASTIdentifierIterator : public IdentifierIterator {
6067 /// \brief The AST reader whose identifiers are being enumerated.
6068 const ASTReader &Reader;
6069
6070 /// \brief The current index into the chain of AST files stored in
6071 /// the AST reader.
6072 unsigned Index;
6073
6074 /// \brief The current position within the identifier lookup table
6075 /// of the current AST file.
6076 ASTIdentifierLookupTable::key_iterator Current;
6077
6078 /// \brief The end position within the identifier lookup table of
6079 /// the current AST file.
6080 ASTIdentifierLookupTable::key_iterator End;
6081
6082 public:
6083 explicit ASTIdentifierIterator(const ASTReader &Reader);
6084
6085 virtual StringRef Next();
6086 };
6087}
6088
6089ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6090 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6091 ASTIdentifierLookupTable *IdTable
6092 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6093 Current = IdTable->key_begin();
6094 End = IdTable->key_end();
6095}
6096
6097StringRef ASTIdentifierIterator::Next() {
6098 while (Current == End) {
6099 // If we have exhausted all of our AST files, we're done.
6100 if (Index == 0)
6101 return StringRef();
6102
6103 --Index;
6104 ASTIdentifierLookupTable *IdTable
6105 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6106 IdentifierLookupTable;
6107 Current = IdTable->key_begin();
6108 End = IdTable->key_end();
6109 }
6110
6111 // We have any identifiers remaining in the current AST file; return
6112 // the next one.
Douglas Gregor479633c2013-01-23 18:53:14 +00006113 StringRef Result = *Current;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006114 ++Current;
Douglas Gregor479633c2013-01-23 18:53:14 +00006115 return Result;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006116}
6117
6118IdentifierIterator *ASTReader::getIdentifiers() const {
6119 return new ASTIdentifierIterator(*this);
6120}
6121
6122namespace clang { namespace serialization {
6123 class ReadMethodPoolVisitor {
6124 ASTReader &Reader;
6125 Selector Sel;
6126 unsigned PriorGeneration;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006127 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6128 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006129
6130 public:
6131 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6132 unsigned PriorGeneration)
6133 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) { }
6134
6135 static bool visit(ModuleFile &M, void *UserData) {
6136 ReadMethodPoolVisitor *This
6137 = static_cast<ReadMethodPoolVisitor *>(UserData);
6138
6139 if (!M.SelectorLookupTable)
6140 return false;
6141
6142 // If we've already searched this module file, skip it now.
6143 if (M.Generation <= This->PriorGeneration)
6144 return true;
6145
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006146 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006147 ASTSelectorLookupTable *PoolTable
6148 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6149 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6150 if (Pos == PoolTable->end())
6151 return false;
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006152
6153 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006154 ++This->Reader.NumSelectorsRead;
6155 // FIXME: Not quite happy with the statistics here. We probably should
6156 // disable this tracking when called via LoadSelector.
6157 // Also, should entries without methods count as misses?
6158 ++This->Reader.NumMethodPoolEntriesRead;
6159 ASTSelectorLookupTrait::data_type Data = *Pos;
6160 if (This->Reader.DeserializationListener)
6161 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6162 This->Sel);
6163
6164 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6165 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6166 return true;
6167 }
6168
6169 /// \brief Retrieve the instance methods found by this visitor.
6170 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6171 return InstanceMethods;
6172 }
6173
6174 /// \brief Retrieve the instance methods found by this visitor.
6175 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6176 return FactoryMethods;
6177 }
6178 };
6179} } // end namespace clang::serialization
6180
6181/// \brief Add the given set of methods to the method list.
6182static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6183 ObjCMethodList &List) {
6184 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6185 S.addMethodToGlobalList(&List, Methods[I]);
6186 }
6187}
6188
6189void ASTReader::ReadMethodPool(Selector Sel) {
6190 // Get the selector generation and update it to the current generation.
6191 unsigned &Generation = SelectorGeneration[Sel];
6192 unsigned PriorGeneration = Generation;
6193 Generation = CurrentGeneration;
6194
6195 // Search for methods defined with this selector.
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006196 ++NumMethodPoolLookups;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006197 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6198 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6199
6200 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006201 Visitor.getFactoryMethods().empty())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006202 return;
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006203
6204 ++NumMethodPoolHits;
6205
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006206 if (!getSema())
6207 return;
6208
6209 Sema &S = *getSema();
6210 Sema::GlobalMethodPool::iterator Pos
6211 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6212
6213 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6214 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
6215}
6216
6217void ASTReader::ReadKnownNamespaces(
6218 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6219 Namespaces.clear();
6220
6221 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6222 if (NamespaceDecl *Namespace
6223 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6224 Namespaces.push_back(Namespace);
6225 }
6226}
6227
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006228void ASTReader::ReadUndefinedButUsed(
Nick Lewycky995e26b2013-01-31 03:23:57 +00006229 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006230 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6231 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky01a41142013-01-26 00:35:08 +00006232 SourceLocation Loc =
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006233 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky01a41142013-01-26 00:35:08 +00006234 Undefined.insert(std::make_pair(D, Loc));
6235 }
6236}
Nick Lewycky01a41142013-01-26 00:35:08 +00006237
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006238void ASTReader::ReadTentativeDefinitions(
6239 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6240 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6241 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6242 if (Var)
6243 TentativeDefs.push_back(Var);
6244 }
6245 TentativeDefinitions.clear();
6246}
6247
6248void ASTReader::ReadUnusedFileScopedDecls(
6249 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6250 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6251 DeclaratorDecl *D
6252 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6253 if (D)
6254 Decls.push_back(D);
6255 }
6256 UnusedFileScopedDecls.clear();
6257}
6258
6259void ASTReader::ReadDelegatingConstructors(
6260 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6261 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6262 CXXConstructorDecl *D
6263 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6264 if (D)
6265 Decls.push_back(D);
6266 }
6267 DelegatingCtorDecls.clear();
6268}
6269
6270void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6271 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6272 TypedefNameDecl *D
6273 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6274 if (D)
6275 Decls.push_back(D);
6276 }
6277 ExtVectorDecls.clear();
6278}
6279
6280void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6281 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6282 CXXRecordDecl *D
6283 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6284 if (D)
6285 Decls.push_back(D);
6286 }
6287 DynamicClasses.clear();
6288}
6289
6290void
Richard Smith5ea6ef42013-01-10 23:43:47 +00006291ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6292 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6293 NamedDecl *D
6294 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006295 if (D)
6296 Decls.push_back(D);
6297 }
Richard Smith5ea6ef42013-01-10 23:43:47 +00006298 LocallyScopedExternCDecls.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006299}
6300
6301void ASTReader::ReadReferencedSelectors(
6302 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6303 if (ReferencedSelectorsData.empty())
6304 return;
6305
6306 // If there are @selector references added them to its pool. This is for
6307 // implementation of -Wselector.
6308 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6309 unsigned I = 0;
6310 while (I < DataSize) {
6311 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6312 SourceLocation SelLoc
6313 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6314 Sels.push_back(std::make_pair(Sel, SelLoc));
6315 }
6316 ReferencedSelectorsData.clear();
6317}
6318
6319void ASTReader::ReadWeakUndeclaredIdentifiers(
6320 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6321 if (WeakUndeclaredIdentifiers.empty())
6322 return;
6323
6324 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6325 IdentifierInfo *WeakId
6326 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6327 IdentifierInfo *AliasId
6328 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6329 SourceLocation Loc
6330 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6331 bool Used = WeakUndeclaredIdentifiers[I++];
6332 WeakInfo WI(AliasId, Loc);
6333 WI.setUsed(Used);
6334 WeakIDs.push_back(std::make_pair(WeakId, WI));
6335 }
6336 WeakUndeclaredIdentifiers.clear();
6337}
6338
6339void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6340 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6341 ExternalVTableUse VT;
6342 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6343 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6344 VT.DefinitionRequired = VTableUses[Idx++];
6345 VTables.push_back(VT);
6346 }
6347
6348 VTableUses.clear();
6349}
6350
6351void ASTReader::ReadPendingInstantiations(
6352 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6353 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6354 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6355 SourceLocation Loc
6356 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6357
6358 Pending.push_back(std::make_pair(D, Loc));
6359 }
6360 PendingInstantiations.clear();
6361}
6362
6363void ASTReader::LoadSelector(Selector Sel) {
6364 // It would be complicated to avoid reading the methods anyway. So don't.
6365 ReadMethodPool(Sel);
6366}
6367
6368void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6369 assert(ID && "Non-zero identifier ID required");
6370 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6371 IdentifiersLoaded[ID - 1] = II;
6372 if (DeserializationListener)
6373 DeserializationListener->IdentifierRead(ID, II);
6374}
6375
6376/// \brief Set the globally-visible declarations associated with the given
6377/// identifier.
6378///
6379/// If the AST reader is currently in a state where the given declaration IDs
6380/// cannot safely be resolved, they are queued until it is safe to resolve
6381/// them.
6382///
6383/// \param II an IdentifierInfo that refers to one or more globally-visible
6384/// declarations.
6385///
6386/// \param DeclIDs the set of declaration IDs with the name @p II that are
6387/// visible at global scope.
6388///
Douglas Gregoraa945902013-02-18 15:53:43 +00006389/// \param Decls if non-null, this vector will be populated with the set of
6390/// deserialized declarations. These declarations will not be pushed into
6391/// scope.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006392void
6393ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6394 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregoraa945902013-02-18 15:53:43 +00006395 SmallVectorImpl<Decl *> *Decls) {
6396 if (NumCurrentElementsDeserializing && !Decls) {
6397 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006398 return;
6399 }
6400
6401 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6402 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6403 if (SemaObj) {
Douglas Gregoraa945902013-02-18 15:53:43 +00006404 // If we're simply supposed to record the declarations, do so now.
6405 if (Decls) {
6406 Decls->push_back(D);
6407 continue;
6408 }
6409
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006410 // Introduce this declaration into the translation-unit scope
6411 // and add it to the declaration chain for this identifier, so
6412 // that (unqualified) name lookup will find it.
Douglas Gregoraa945902013-02-18 15:53:43 +00006413 NamedDecl *ND = cast<NamedDecl>(D->getMostRecentDecl());
6414 SemaObj->pushExternalDeclIntoScope(ND, II);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006415 } else {
6416 // Queue this declaration so that it will be added to the
6417 // translation unit scope and identifier's declaration chain
6418 // once a Sema object is known.
6419 PreloadedDecls.push_back(D);
6420 }
6421 }
6422}
6423
Douglas Gregor8222b892013-01-21 16:52:34 +00006424IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006425 if (ID == 0)
6426 return 0;
6427
6428 if (IdentifiersLoaded.empty()) {
6429 Error("no identifier table in AST file");
6430 return 0;
6431 }
6432
6433 ID -= 1;
6434 if (!IdentifiersLoaded[ID]) {
6435 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6436 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
6437 ModuleFile *M = I->second;
6438 unsigned Index = ID - M->BaseIdentifierID;
6439 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
6440
6441 // All of the strings in the AST file are preceded by a 16-bit length.
6442 // Extract that 16-bit length to avoid having to execute strlen().
6443 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6444 // unsigned integers. This is important to avoid integer overflow when
6445 // we cast them to 'unsigned'.
6446 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
6447 unsigned StrLen = (((unsigned) StrLenPtr[0])
6448 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregor8222b892013-01-21 16:52:34 +00006449 IdentifiersLoaded[ID]
6450 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006451 if (DeserializationListener)
6452 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
6453 }
6454
6455 return IdentifiersLoaded[ID];
6456}
6457
Douglas Gregor8222b892013-01-21 16:52:34 +00006458IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
6459 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006460}
6461
6462IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
6463 if (LocalID < NUM_PREDEF_IDENT_IDS)
6464 return LocalID;
6465
6466 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6467 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6468 assert(I != M.IdentifierRemap.end()
6469 && "Invalid index into identifier index remap");
6470
6471 return LocalID + I->second;
6472}
6473
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00006474MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006475 if (ID == 0)
6476 return 0;
6477
6478 if (MacrosLoaded.empty()) {
6479 Error("no macro table in AST file");
6480 return 0;
6481 }
6482
6483 ID -= NUM_PREDEF_MACRO_IDS;
6484 if (!MacrosLoaded[ID]) {
6485 GlobalMacroMapType::iterator I
6486 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
6487 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
6488 ModuleFile *M = I->second;
6489 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00006490 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
6491
6492 if (DeserializationListener)
6493 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
6494 MacrosLoaded[ID]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006495 }
6496
6497 return MacrosLoaded[ID];
6498}
6499
6500MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
6501 if (LocalID < NUM_PREDEF_MACRO_IDS)
6502 return LocalID;
6503
6504 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6505 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
6506 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
6507
6508 return LocalID + I->second;
6509}
6510
6511serialization::SubmoduleID
6512ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
6513 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
6514 return LocalID;
6515
6516 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6517 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
6518 assert(I != M.SubmoduleRemap.end()
6519 && "Invalid index into submodule index remap");
6520
6521 return LocalID + I->second;
6522}
6523
6524Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
6525 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6526 assert(GlobalID == 0 && "Unhandled global submodule ID");
6527 return 0;
6528 }
6529
6530 if (GlobalID > SubmodulesLoaded.size()) {
6531 Error("submodule ID out of range in AST file");
6532 return 0;
6533 }
6534
6535 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
6536}
Douglas Gregorca2ab452013-01-12 01:29:50 +00006537
6538Module *ASTReader::getModule(unsigned ID) {
6539 return getSubmodule(ID);
6540}
6541
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006542Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
6543 return DecodeSelector(getGlobalSelectorID(M, LocalID));
6544}
6545
6546Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
6547 if (ID == 0)
6548 return Selector();
6549
6550 if (ID > SelectorsLoaded.size()) {
6551 Error("selector ID out of range in AST file");
6552 return Selector();
6553 }
6554
6555 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
6556 // Load this selector from the selector table.
6557 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
6558 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
6559 ModuleFile &M = *I->second;
6560 ASTSelectorLookupTrait Trait(*this, M);
6561 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
6562 SelectorsLoaded[ID - 1] =
6563 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
6564 if (DeserializationListener)
6565 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
6566 }
6567
6568 return SelectorsLoaded[ID - 1];
6569}
6570
6571Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
6572 return DecodeSelector(ID);
6573}
6574
6575uint32_t ASTReader::GetNumExternalSelectors() {
6576 // ID 0 (the null selector) is considered an external selector.
6577 return getTotalNumSelectors() + 1;
6578}
6579
6580serialization::SelectorID
6581ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
6582 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
6583 return LocalID;
6584
6585 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6586 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
6587 assert(I != M.SelectorRemap.end()
6588 && "Invalid index into selector index remap");
6589
6590 return LocalID + I->second;
6591}
6592
6593DeclarationName
6594ASTReader::ReadDeclarationName(ModuleFile &F,
6595 const RecordData &Record, unsigned &Idx) {
6596 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
6597 switch (Kind) {
6598 case DeclarationName::Identifier:
Douglas Gregor8222b892013-01-21 16:52:34 +00006599 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006600
6601 case DeclarationName::ObjCZeroArgSelector:
6602 case DeclarationName::ObjCOneArgSelector:
6603 case DeclarationName::ObjCMultiArgSelector:
6604 return DeclarationName(ReadSelector(F, Record, Idx));
6605
6606 case DeclarationName::CXXConstructorName:
6607 return Context.DeclarationNames.getCXXConstructorName(
6608 Context.getCanonicalType(readType(F, Record, Idx)));
6609
6610 case DeclarationName::CXXDestructorName:
6611 return Context.DeclarationNames.getCXXDestructorName(
6612 Context.getCanonicalType(readType(F, Record, Idx)));
6613
6614 case DeclarationName::CXXConversionFunctionName:
6615 return Context.DeclarationNames.getCXXConversionFunctionName(
6616 Context.getCanonicalType(readType(F, Record, Idx)));
6617
6618 case DeclarationName::CXXOperatorName:
6619 return Context.DeclarationNames.getCXXOperatorName(
6620 (OverloadedOperatorKind)Record[Idx++]);
6621
6622 case DeclarationName::CXXLiteralOperatorName:
6623 return Context.DeclarationNames.getCXXLiteralOperatorName(
6624 GetIdentifierInfo(F, Record, Idx));
6625
6626 case DeclarationName::CXXUsingDirective:
6627 return DeclarationName::getUsingDirectiveName();
6628 }
6629
6630 llvm_unreachable("Invalid NameKind!");
6631}
6632
6633void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
6634 DeclarationNameLoc &DNLoc,
6635 DeclarationName Name,
6636 const RecordData &Record, unsigned &Idx) {
6637 switch (Name.getNameKind()) {
6638 case DeclarationName::CXXConstructorName:
6639 case DeclarationName::CXXDestructorName:
6640 case DeclarationName::CXXConversionFunctionName:
6641 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
6642 break;
6643
6644 case DeclarationName::CXXOperatorName:
6645 DNLoc.CXXOperatorName.BeginOpNameLoc
6646 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6647 DNLoc.CXXOperatorName.EndOpNameLoc
6648 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6649 break;
6650
6651 case DeclarationName::CXXLiteralOperatorName:
6652 DNLoc.CXXLiteralOperatorName.OpNameLoc
6653 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6654 break;
6655
6656 case DeclarationName::Identifier:
6657 case DeclarationName::ObjCZeroArgSelector:
6658 case DeclarationName::ObjCOneArgSelector:
6659 case DeclarationName::ObjCMultiArgSelector:
6660 case DeclarationName::CXXUsingDirective:
6661 break;
6662 }
6663}
6664
6665void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
6666 DeclarationNameInfo &NameInfo,
6667 const RecordData &Record, unsigned &Idx) {
6668 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
6669 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
6670 DeclarationNameLoc DNLoc;
6671 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
6672 NameInfo.setInfo(DNLoc);
6673}
6674
6675void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
6676 const RecordData &Record, unsigned &Idx) {
6677 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
6678 unsigned NumTPLists = Record[Idx++];
6679 Info.NumTemplParamLists = NumTPLists;
6680 if (NumTPLists) {
6681 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
6682 for (unsigned i=0; i != NumTPLists; ++i)
6683 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
6684 }
6685}
6686
6687TemplateName
6688ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
6689 unsigned &Idx) {
6690 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
6691 switch (Kind) {
6692 case TemplateName::Template:
6693 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
6694
6695 case TemplateName::OverloadedTemplate: {
6696 unsigned size = Record[Idx++];
6697 UnresolvedSet<8> Decls;
6698 while (size--)
6699 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
6700
6701 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
6702 }
6703
6704 case TemplateName::QualifiedTemplate: {
6705 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6706 bool hasTemplKeyword = Record[Idx++];
6707 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
6708 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
6709 }
6710
6711 case TemplateName::DependentTemplate: {
6712 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6713 if (Record[Idx++]) // isIdentifier
6714 return Context.getDependentTemplateName(NNS,
6715 GetIdentifierInfo(F, Record,
6716 Idx));
6717 return Context.getDependentTemplateName(NNS,
6718 (OverloadedOperatorKind)Record[Idx++]);
6719 }
6720
6721 case TemplateName::SubstTemplateTemplateParm: {
6722 TemplateTemplateParmDecl *param
6723 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6724 if (!param) return TemplateName();
6725 TemplateName replacement = ReadTemplateName(F, Record, Idx);
6726 return Context.getSubstTemplateTemplateParm(param, replacement);
6727 }
6728
6729 case TemplateName::SubstTemplateTemplateParmPack: {
6730 TemplateTemplateParmDecl *Param
6731 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6732 if (!Param)
6733 return TemplateName();
6734
6735 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
6736 if (ArgPack.getKind() != TemplateArgument::Pack)
6737 return TemplateName();
6738
6739 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
6740 }
6741 }
6742
6743 llvm_unreachable("Unhandled template name kind!");
6744}
6745
6746TemplateArgument
6747ASTReader::ReadTemplateArgument(ModuleFile &F,
6748 const RecordData &Record, unsigned &Idx) {
6749 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
6750 switch (Kind) {
6751 case TemplateArgument::Null:
6752 return TemplateArgument();
6753 case TemplateArgument::Type:
6754 return TemplateArgument(readType(F, Record, Idx));
6755 case TemplateArgument::Declaration: {
6756 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
6757 bool ForReferenceParam = Record[Idx++];
6758 return TemplateArgument(D, ForReferenceParam);
6759 }
6760 case TemplateArgument::NullPtr:
6761 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
6762 case TemplateArgument::Integral: {
6763 llvm::APSInt Value = ReadAPSInt(Record, Idx);
6764 QualType T = readType(F, Record, Idx);
6765 return TemplateArgument(Context, Value, T);
6766 }
6767 case TemplateArgument::Template:
6768 return TemplateArgument(ReadTemplateName(F, Record, Idx));
6769 case TemplateArgument::TemplateExpansion: {
6770 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikiedc84cd52013-02-20 22:23:23 +00006771 Optional<unsigned> NumTemplateExpansions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006772 if (unsigned NumExpansions = Record[Idx++])
6773 NumTemplateExpansions = NumExpansions - 1;
6774 return TemplateArgument(Name, NumTemplateExpansions);
6775 }
6776 case TemplateArgument::Expression:
6777 return TemplateArgument(ReadExpr(F));
6778 case TemplateArgument::Pack: {
6779 unsigned NumArgs = Record[Idx++];
6780 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
6781 for (unsigned I = 0; I != NumArgs; ++I)
6782 Args[I] = ReadTemplateArgument(F, Record, Idx);
6783 return TemplateArgument(Args, NumArgs);
6784 }
6785 }
6786
6787 llvm_unreachable("Unhandled template argument kind!");
6788}
6789
6790TemplateParameterList *
6791ASTReader::ReadTemplateParameterList(ModuleFile &F,
6792 const RecordData &Record, unsigned &Idx) {
6793 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
6794 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
6795 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
6796
6797 unsigned NumParams = Record[Idx++];
6798 SmallVector<NamedDecl *, 16> Params;
6799 Params.reserve(NumParams);
6800 while (NumParams--)
6801 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
6802
6803 TemplateParameterList* TemplateParams =
6804 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
6805 Params.data(), Params.size(), RAngleLoc);
6806 return TemplateParams;
6807}
6808
6809void
6810ASTReader::
6811ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
6812 ModuleFile &F, const RecordData &Record,
6813 unsigned &Idx) {
6814 unsigned NumTemplateArgs = Record[Idx++];
6815 TemplArgs.reserve(NumTemplateArgs);
6816 while (NumTemplateArgs--)
6817 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
6818}
6819
6820/// \brief Read a UnresolvedSet structure.
6821void ASTReader::ReadUnresolvedSet(ModuleFile &F, ASTUnresolvedSet &Set,
6822 const RecordData &Record, unsigned &Idx) {
6823 unsigned NumDecls = Record[Idx++];
6824 Set.reserve(Context, NumDecls);
6825 while (NumDecls--) {
6826 NamedDecl *D = ReadDeclAs<NamedDecl>(F, Record, Idx);
6827 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
6828 Set.addDecl(Context, D, AS);
6829 }
6830}
6831
6832CXXBaseSpecifier
6833ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
6834 const RecordData &Record, unsigned &Idx) {
6835 bool isVirtual = static_cast<bool>(Record[Idx++]);
6836 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
6837 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
6838 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
6839 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
6840 SourceRange Range = ReadSourceRange(F, Record, Idx);
6841 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
6842 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
6843 EllipsisLoc);
6844 Result.setInheritConstructors(inheritConstructors);
6845 return Result;
6846}
6847
6848std::pair<CXXCtorInitializer **, unsigned>
6849ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
6850 unsigned &Idx) {
6851 CXXCtorInitializer **CtorInitializers = 0;
6852 unsigned NumInitializers = Record[Idx++];
6853 if (NumInitializers) {
6854 CtorInitializers
6855 = new (Context) CXXCtorInitializer*[NumInitializers];
6856 for (unsigned i=0; i != NumInitializers; ++i) {
6857 TypeSourceInfo *TInfo = 0;
6858 bool IsBaseVirtual = false;
6859 FieldDecl *Member = 0;
6860 IndirectFieldDecl *IndirectMember = 0;
6861
6862 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
6863 switch (Type) {
6864 case CTOR_INITIALIZER_BASE:
6865 TInfo = GetTypeSourceInfo(F, Record, Idx);
6866 IsBaseVirtual = Record[Idx++];
6867 break;
6868
6869 case CTOR_INITIALIZER_DELEGATING:
6870 TInfo = GetTypeSourceInfo(F, Record, Idx);
6871 break;
6872
6873 case CTOR_INITIALIZER_MEMBER:
6874 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
6875 break;
6876
6877 case CTOR_INITIALIZER_INDIRECT_MEMBER:
6878 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
6879 break;
6880 }
6881
6882 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
6883 Expr *Init = ReadExpr(F);
6884 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
6885 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
6886 bool IsWritten = Record[Idx++];
6887 unsigned SourceOrderOrNumArrayIndices;
6888 SmallVector<VarDecl *, 8> Indices;
6889 if (IsWritten) {
6890 SourceOrderOrNumArrayIndices = Record[Idx++];
6891 } else {
6892 SourceOrderOrNumArrayIndices = Record[Idx++];
6893 Indices.reserve(SourceOrderOrNumArrayIndices);
6894 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
6895 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
6896 }
6897
6898 CXXCtorInitializer *BOMInit;
6899 if (Type == CTOR_INITIALIZER_BASE) {
6900 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
6901 LParenLoc, Init, RParenLoc,
6902 MemberOrEllipsisLoc);
6903 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
6904 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
6905 Init, RParenLoc);
6906 } else if (IsWritten) {
6907 if (Member)
6908 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
6909 LParenLoc, Init, RParenLoc);
6910 else
6911 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
6912 MemberOrEllipsisLoc, LParenLoc,
6913 Init, RParenLoc);
6914 } else {
6915 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
6916 LParenLoc, Init, RParenLoc,
6917 Indices.data(), Indices.size());
6918 }
6919
6920 if (IsWritten)
6921 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
6922 CtorInitializers[i] = BOMInit;
6923 }
6924 }
6925
6926 return std::make_pair(CtorInitializers, NumInitializers);
6927}
6928
6929NestedNameSpecifier *
6930ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
6931 const RecordData &Record, unsigned &Idx) {
6932 unsigned N = Record[Idx++];
6933 NestedNameSpecifier *NNS = 0, *Prev = 0;
6934 for (unsigned I = 0; I != N; ++I) {
6935 NestedNameSpecifier::SpecifierKind Kind
6936 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6937 switch (Kind) {
6938 case NestedNameSpecifier::Identifier: {
6939 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
6940 NNS = NestedNameSpecifier::Create(Context, Prev, II);
6941 break;
6942 }
6943
6944 case NestedNameSpecifier::Namespace: {
6945 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
6946 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
6947 break;
6948 }
6949
6950 case NestedNameSpecifier::NamespaceAlias: {
6951 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
6952 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
6953 break;
6954 }
6955
6956 case NestedNameSpecifier::TypeSpec:
6957 case NestedNameSpecifier::TypeSpecWithTemplate: {
6958 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
6959 if (!T)
6960 return 0;
6961
6962 bool Template = Record[Idx++];
6963 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
6964 break;
6965 }
6966
6967 case NestedNameSpecifier::Global: {
6968 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
6969 // No associated value, and there can't be a prefix.
6970 break;
6971 }
6972 }
6973 Prev = NNS;
6974 }
6975 return NNS;
6976}
6977
6978NestedNameSpecifierLoc
6979ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
6980 unsigned &Idx) {
6981 unsigned N = Record[Idx++];
6982 NestedNameSpecifierLocBuilder Builder;
6983 for (unsigned I = 0; I != N; ++I) {
6984 NestedNameSpecifier::SpecifierKind Kind
6985 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6986 switch (Kind) {
6987 case NestedNameSpecifier::Identifier: {
6988 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
6989 SourceRange Range = ReadSourceRange(F, Record, Idx);
6990 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
6991 break;
6992 }
6993
6994 case NestedNameSpecifier::Namespace: {
6995 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
6996 SourceRange Range = ReadSourceRange(F, Record, Idx);
6997 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
6998 break;
6999 }
7000
7001 case NestedNameSpecifier::NamespaceAlias: {
7002 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7003 SourceRange Range = ReadSourceRange(F, Record, Idx);
7004 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7005 break;
7006 }
7007
7008 case NestedNameSpecifier::TypeSpec:
7009 case NestedNameSpecifier::TypeSpecWithTemplate: {
7010 bool Template = Record[Idx++];
7011 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7012 if (!T)
7013 return NestedNameSpecifierLoc();
7014 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7015
7016 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7017 Builder.Extend(Context,
7018 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7019 T->getTypeLoc(), ColonColonLoc);
7020 break;
7021 }
7022
7023 case NestedNameSpecifier::Global: {
7024 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7025 Builder.MakeGlobal(Context, ColonColonLoc);
7026 break;
7027 }
7028 }
7029 }
7030
7031 return Builder.getWithLocInContext(Context);
7032}
7033
7034SourceRange
7035ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7036 unsigned &Idx) {
7037 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7038 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7039 return SourceRange(beg, end);
7040}
7041
7042/// \brief Read an integral value
7043llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7044 unsigned BitWidth = Record[Idx++];
7045 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7046 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7047 Idx += NumWords;
7048 return Result;
7049}
7050
7051/// \brief Read a signed integral value
7052llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7053 bool isUnsigned = Record[Idx++];
7054 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7055}
7056
7057/// \brief Read a floating-point value
Tim Northover9ec55f22013-01-22 09:46:51 +00007058llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7059 const llvm::fltSemantics &Sem,
7060 unsigned &Idx) {
7061 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007062}
7063
7064// \brief Read a string
7065std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7066 unsigned Len = Record[Idx++];
7067 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7068 Idx += Len;
7069 return Result;
7070}
7071
7072VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7073 unsigned &Idx) {
7074 unsigned Major = Record[Idx++];
7075 unsigned Minor = Record[Idx++];
7076 unsigned Subminor = Record[Idx++];
7077 if (Minor == 0)
7078 return VersionTuple(Major);
7079 if (Subminor == 0)
7080 return VersionTuple(Major, Minor - 1);
7081 return VersionTuple(Major, Minor - 1, Subminor - 1);
7082}
7083
7084CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7085 const RecordData &Record,
7086 unsigned &Idx) {
7087 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7088 return CXXTemporary::Create(Context, Decl);
7089}
7090
7091DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
7092 return Diag(SourceLocation(), DiagID);
7093}
7094
7095DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7096 return Diags.Report(Loc, DiagID);
7097}
7098
7099/// \brief Retrieve the identifier table associated with the
7100/// preprocessor.
7101IdentifierTable &ASTReader::getIdentifierTable() {
7102 return PP.getIdentifierTable();
7103}
7104
7105/// \brief Record that the given ID maps to the given switch-case
7106/// statement.
7107void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7108 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7109 "Already have a SwitchCase with this ID");
7110 (*CurrSwitchCaseStmts)[ID] = SC;
7111}
7112
7113/// \brief Retrieve the switch-case statement with the given ID.
7114SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7115 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7116 return (*CurrSwitchCaseStmts)[ID];
7117}
7118
7119void ASTReader::ClearSwitchCaseIDs() {
7120 CurrSwitchCaseStmts->clear();
7121}
7122
7123void ASTReader::ReadComments() {
7124 std::vector<RawComment *> Comments;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007125 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007126 serialization::ModuleFile *> >::iterator
7127 I = CommentsCursors.begin(),
7128 E = CommentsCursors.end();
7129 I != E; ++I) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007130 BitstreamCursor &Cursor = I->first;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007131 serialization::ModuleFile &F = *I->second;
7132 SavedStreamPosition SavedPosition(Cursor);
7133
7134 RecordData Record;
7135 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007136 llvm::BitstreamEntry Entry =
7137 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
7138
7139 switch (Entry.Kind) {
7140 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7141 case llvm::BitstreamEntry::Error:
7142 Error("malformed block record in AST file");
7143 return;
7144 case llvm::BitstreamEntry::EndBlock:
7145 goto NextCursor;
7146 case llvm::BitstreamEntry::Record:
7147 // The interesting case.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007148 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007149 }
7150
7151 // Read a record.
7152 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00007153 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007154 case COMMENTS_RAW_COMMENT: {
7155 unsigned Idx = 0;
7156 SourceRange SR = ReadSourceRange(F, Record, Idx);
7157 RawComment::CommentKind Kind =
7158 (RawComment::CommentKind) Record[Idx++];
7159 bool IsTrailingComment = Record[Idx++];
7160 bool IsAlmostTrailingComment = Record[Idx++];
7161 Comments.push_back(new (Context) RawComment(SR, Kind,
7162 IsTrailingComment,
7163 IsAlmostTrailingComment));
7164 break;
7165 }
7166 }
7167 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007168 NextCursor:;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007169 }
7170 Context.Comments.addCommentsToFront(Comments);
7171}
7172
7173void ASTReader::finishPendingActions() {
7174 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Argyrios Kyrtzidis7640b022013-02-16 00:48:59 +00007175 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007176 // If any identifiers with corresponding top-level declarations have
7177 // been loaded, load those declarations now.
Douglas Gregoraa945902013-02-18 15:53:43 +00007178 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> > TopLevelDecls;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007179 while (!PendingIdentifierInfos.empty()) {
Douglas Gregoraa945902013-02-18 15:53:43 +00007180 // FIXME: std::move
7181 IdentifierInfo *II = PendingIdentifierInfos.back().first;
7182 SmallVector<uint32_t, 4> DeclIDs = PendingIdentifierInfos.back().second;
Douglas Gregorcc9bdcb2013-02-19 18:26:28 +00007183 PendingIdentifierInfos.pop_back();
Douglas Gregoraa945902013-02-18 15:53:43 +00007184
7185 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007186 }
7187
7188 // Load pending declaration chains.
7189 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7190 loadPendingDeclChain(PendingDeclChains[I]);
7191 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
7192 }
7193 PendingDeclChains.clear();
7194
Douglas Gregoraa945902013-02-18 15:53:43 +00007195 // Make the most recent of the top-level declarations visible.
7196 for (llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >::iterator
7197 TLD = TopLevelDecls.begin(), TLDEnd = TopLevelDecls.end();
7198 TLD != TLDEnd; ++TLD) {
7199 IdentifierInfo *II = TLD->first;
7200 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
7201 NamedDecl *ND = cast<NamedDecl>(TLD->second[I]->getMostRecentDecl());
7202 SemaObj->pushExternalDeclIntoScope(ND, II);
7203 }
7204 }
7205
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007206 // Load any pending macro definitions.
7207 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00007208 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
7209 SmallVector<PendingMacroInfo, 2> GlobalIDs;
7210 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
7211 // Initialize the macro history from chained-PCHs ahead of module imports.
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00007212 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7213 ++IDIdx) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00007214 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7215 if (Info.M->Kind != MK_Module)
7216 resolvePendingMacro(II, Info);
7217 }
7218 // Handle module imports.
7219 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7220 ++IDIdx) {
7221 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7222 if (Info.M->Kind == MK_Module)
7223 resolvePendingMacro(II, Info);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007224 }
7225 }
7226 PendingMacroIDs.clear();
Argyrios Kyrtzidis7640b022013-02-16 00:48:59 +00007227
7228 // Wire up the DeclContexts for Decls that we delayed setting until
7229 // recursive loading is completed.
7230 while (!PendingDeclContextInfos.empty()) {
7231 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7232 PendingDeclContextInfos.pop_front();
7233 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7234 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7235 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7236 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007237 }
7238
7239 // If we deserialized any C++ or Objective-C class definitions, any
7240 // Objective-C protocol definitions, or any redeclarable templates, make sure
7241 // that all redeclarations point to the definitions. Note that this can only
7242 // happen now, after the redeclaration chains have been fully wired.
7243 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7244 DEnd = PendingDefinitions.end();
7245 D != DEnd; ++D) {
7246 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7247 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7248 // Make sure that the TagType points at the definition.
7249 const_cast<TagType*>(TagT)->decl = TD;
7250 }
7251
7252 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(*D)) {
7253 for (CXXRecordDecl::redecl_iterator R = RD->redecls_begin(),
7254 REnd = RD->redecls_end();
7255 R != REnd; ++R)
7256 cast<CXXRecordDecl>(*R)->DefinitionData = RD->DefinitionData;
7257
7258 }
7259
7260 continue;
7261 }
7262
7263 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
7264 // Make sure that the ObjCInterfaceType points at the definition.
7265 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7266 ->Decl = ID;
7267
7268 for (ObjCInterfaceDecl::redecl_iterator R = ID->redecls_begin(),
7269 REnd = ID->redecls_end();
7270 R != REnd; ++R)
7271 R->Data = ID->Data;
7272
7273 continue;
7274 }
7275
7276 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7277 for (ObjCProtocolDecl::redecl_iterator R = PD->redecls_begin(),
7278 REnd = PD->redecls_end();
7279 R != REnd; ++R)
7280 R->Data = PD->Data;
7281
7282 continue;
7283 }
7284
7285 RedeclarableTemplateDecl *RTD
7286 = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7287 for (RedeclarableTemplateDecl::redecl_iterator R = RTD->redecls_begin(),
7288 REnd = RTD->redecls_end();
7289 R != REnd; ++R)
7290 R->Common = RTD->Common;
7291 }
7292 PendingDefinitions.clear();
7293
7294 // Load the bodies of any functions or methods we've encountered. We do
7295 // this now (delayed) so that we can be sure that the declaration chains
7296 // have been fully wired up.
7297 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7298 PBEnd = PendingBodies.end();
7299 PB != PBEnd; ++PB) {
7300 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7301 // FIXME: Check for =delete/=default?
7302 // FIXME: Complain about ODR violations here?
7303 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7304 FD->setLazyBody(PB->second);
7305 continue;
7306 }
7307
7308 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7309 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7310 MD->setLazyBody(PB->second);
7311 }
7312 PendingBodies.clear();
7313}
7314
7315void ASTReader::FinishedDeserializing() {
7316 assert(NumCurrentElementsDeserializing &&
7317 "FinishedDeserializing not paired with StartedDeserializing");
7318 if (NumCurrentElementsDeserializing == 1) {
7319 // We decrease NumCurrentElementsDeserializing only after pending actions
7320 // are finished, to avoid recursively re-calling finishPendingActions().
7321 finishPendingActions();
7322 }
7323 --NumCurrentElementsDeserializing;
7324
7325 if (NumCurrentElementsDeserializing == 0 &&
7326 Consumer && !PassingDeclsToConsumer) {
7327 // Guard variable to avoid recursively redoing the process of passing
7328 // decls to consumer.
7329 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7330 true);
7331
7332 while (!InterestingDecls.empty()) {
7333 // We are not in recursive loading, so it's safe to pass the "interesting"
7334 // decls to the consumer.
7335 Decl *D = InterestingDecls.front();
7336 InterestingDecls.pop_front();
7337 PassInterestingDeclToConsumer(D);
7338 }
7339 }
7340}
7341
7342ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7343 StringRef isysroot, bool DisableValidation,
Douglas Gregorf575d6e2013-01-25 00:45:27 +00007344 bool AllowASTWithCompilerErrors, bool UseGlobalIndex)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007345 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7346 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7347 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7348 Consumer(0), ModuleMgr(PP.getFileManager()),
7349 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregore1698072013-01-25 00:38:33 +00007350 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Douglas Gregorf575d6e2013-01-25 00:45:27 +00007351 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007352 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7353 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregore1698072013-01-25 00:38:33 +00007354 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7355 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
7356 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregor95fb36e2013-01-28 17:54:36 +00007357 NumMethodPoolLookups(0), NumMethodPoolHits(0),
7358 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
7359 TotalNumMethodPoolEntries(0),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007360 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
7361 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
7362 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
7363 PassingDeclsToConsumer(false),
7364 NumCXXBaseSpecifiersLoaded(0)
7365{
7366 SourceMgr.setExternalSLocEntrySource(this);
7367}
7368
7369ASTReader::~ASTReader() {
7370 for (DeclContextVisibleUpdatesPending::iterator
7371 I = PendingVisibleUpdates.begin(),
7372 E = PendingVisibleUpdates.end();
7373 I != E; ++I) {
7374 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
7375 F = I->second.end();
7376 J != F; ++J)
7377 delete J->first;
7378 }
7379}