blob: c8b3e93a8706eb23cb9ba9058dca0a0e6e019ba7 [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();
Argyrios Kyrtzidisbd25ff82013-04-03 17:39:30 +00001607 if (NewMI != PrevMI && !PrevMI->isIdenticalTo(*NewMI, PP,
1608 /*Syntactically=*/true)) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001609 // Before marking the macros as ambiguous, check if this is a case where
1610 // the system macro uses a not identical definition compared to a macro
1611 // from the clang headers. For example:
1612 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1613 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
1614 // in which case don't mark them to avoid the "ambiguous macro expansion"
1615 // warning.
1616 // FIXME: This should go away if the system headers get "fixed" to use
1617 // identical definitions.
1618 if (!isSystemAndClangMacro(PrevMI, NewMI, Owner, *this)) {
1619 PrevDef.getDirective()->setAmbiguous(true);
1620 DefMD->setAmbiguous(true);
1621 }
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001622 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001623 }
1624
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001625 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001626}
1627
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001628InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001629 // If this ID is bogus, just return an empty input file.
1630 if (ID == 0 || ID > F.InputFilesLoaded.size())
1631 return InputFile();
1632
1633 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001634 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001635 return F.InputFilesLoaded[ID-1];
1636
1637 // Go find this input file.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001638 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001639 SavedStreamPosition SavedPosition(Cursor);
1640 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1641
1642 unsigned Code = Cursor.ReadCode();
1643 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001644 StringRef Blob;
1645 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001646 case INPUT_FILE: {
1647 unsigned StoredID = Record[0];
1648 assert(ID == StoredID && "Bogus stored ID or offset");
1649 (void)StoredID;
1650 off_t StoredSize = (off_t)Record[1];
1651 time_t StoredTime = (time_t)Record[2];
1652 bool Overridden = (bool)Record[3];
1653
1654 // Get the file entry for this input file.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001655 StringRef OrigFilename = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001656 std::string Filename = OrigFilename;
1657 MaybeAddSystemRootToFilename(F, Filename);
1658 const FileEntry *File
1659 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1660 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1661
1662 // If we didn't find the file, resolve it relative to the
1663 // original directory from which this AST file was created.
1664 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1665 F.OriginalDir != CurrentDir) {
1666 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1667 F.OriginalDir,
1668 CurrentDir);
1669 if (!Resolved.empty())
1670 File = FileMgr.getFile(Resolved);
1671 }
1672
1673 // For an overridden file, create a virtual file with the stored
1674 // size/timestamp.
1675 if (Overridden && File == 0) {
1676 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1677 }
1678
1679 if (File == 0) {
1680 if (Complain) {
1681 std::string ErrorStr = "could not find file '";
1682 ErrorStr += Filename;
1683 ErrorStr += "' referenced by AST file";
1684 Error(ErrorStr.c_str());
1685 }
1686 return InputFile();
1687 }
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001688
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001689 // Check if there was a request to override the contents of the file
1690 // that was part of the precompiled header. Overridding such a file
1691 // can lead to problems when lexing using the source locations from the
1692 // PCH.
1693 SourceManager &SM = getSourceManager();
1694 if (!Overridden && SM.isFileOverridden(File)) {
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001695 if (Complain)
1696 Error(diag::err_fe_pch_file_overridden, Filename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001697 // After emitting the diagnostic, recover by disabling the override so
1698 // that the original file will be used.
1699 SM.disableFileContentsOverride(File);
1700 // The FileEntry is a virtual file entry with the size of the contents
1701 // that would override the original contents. Set it to the original's
1702 // size/time.
1703 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1704 StoredSize, StoredTime);
1705 }
1706
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001707 bool IsOutOfDate = false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001708
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001709 // For an overridden file, there is nothing to validate.
1710 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001711#if !defined(LLVM_ON_WIN32)
1712 // In our regression testing, the Windows file system seems to
1713 // have inconsistent modification times that sometimes
1714 // erroneously trigger this error-handling path.
1715 || StoredTime != File->getModificationTime()
1716#endif
1717 )) {
Douglas Gregor677e15f2013-03-19 00:28:20 +00001718 if (Complain) {
Argyrios Kyrtzidisf8f373f2013-03-08 20:42:38 +00001719 Error(diag::err_fe_pch_file_modified, Filename, F.FileName);
Douglas Gregor677e15f2013-03-19 00:28:20 +00001720 }
1721
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001722 IsOutOfDate = true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001723 }
1724
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001725 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
1726
1727 // Note that we've loaded this input file.
1728 F.InputFilesLoaded[ID-1] = IF;
1729 return IF;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001730 }
1731 }
1732
1733 return InputFile();
1734}
1735
1736const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
1737 ModuleFile &M = ModuleMgr.getPrimaryModule();
1738 std::string Filename = filenameStrRef;
1739 MaybeAddSystemRootToFilename(M, Filename);
1740 const FileEntry *File = FileMgr.getFile(Filename);
1741 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
1742 M.OriginalDir != CurrentDir) {
1743 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1744 M.OriginalDir,
1745 CurrentDir);
1746 if (!resolved.empty())
1747 File = FileMgr.getFile(resolved);
1748 }
1749
1750 return File;
1751}
1752
1753/// \brief If we are loading a relocatable PCH file, and the filename is
1754/// not an absolute path, add the system root to the beginning of the file
1755/// name.
1756void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
1757 std::string &Filename) {
1758 // If this is not a relocatable PCH file, there's nothing to do.
1759 if (!M.RelocatablePCH)
1760 return;
1761
1762 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
1763 return;
1764
1765 if (isysroot.empty()) {
1766 // If no system root was given, default to '/'
1767 Filename.insert(Filename.begin(), '/');
1768 return;
1769 }
1770
1771 unsigned Length = isysroot.size();
1772 if (isysroot[Length - 1] != '/')
1773 Filename.insert(Filename.begin(), '/');
1774
1775 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
1776}
1777
1778ASTReader::ASTReadResult
1779ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001780 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001781 unsigned ClientLoadCapabilities) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001782 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001783
1784 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
1785 Error("malformed block record in AST file");
1786 return Failure;
1787 }
1788
1789 // Read all of the records and blocks in the control block.
1790 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00001791 while (1) {
1792 llvm::BitstreamEntry Entry = Stream.advance();
1793
1794 switch (Entry.Kind) {
1795 case llvm::BitstreamEntry::Error:
1796 Error("malformed block record in AST file");
1797 return Failure;
1798 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001799 // Validate all of the non-system input files.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001800 if (!DisableValidation) {
1801 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001802 // All user input files reside at the index range [0, Record[1]).
1803 // Record is the one from INPUT_FILE_OFFSETS.
1804 for (unsigned I = 0, N = Record[1]; I < N; ++I) {
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001805 InputFile IF = getInputFile(F, I+1, Complain);
1806 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001807 return OutOfDate;
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001808 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001809 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001810 return Success;
Chris Lattner88bde502013-01-19 21:39:22 +00001811
1812 case llvm::BitstreamEntry::SubBlock:
1813 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001814 case INPUT_FILES_BLOCK_ID:
1815 F.InputFilesCursor = Stream;
1816 if (Stream.SkipBlock() || // Skip with the main cursor
1817 // Read the abbreviations
1818 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
1819 Error("malformed block record in AST file");
1820 return Failure;
1821 }
1822 continue;
Chris Lattner88bde502013-01-19 21:39:22 +00001823
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001824 default:
Chris Lattner88bde502013-01-19 21:39:22 +00001825 if (Stream.SkipBlock()) {
1826 Error("malformed block record in AST file");
1827 return Failure;
1828 }
1829 continue;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001830 }
Chris Lattner88bde502013-01-19 21:39:22 +00001831
1832 case llvm::BitstreamEntry::Record:
1833 // The interesting case.
1834 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001835 }
1836
1837 // Read and process a record.
1838 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001839 StringRef Blob;
1840 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001841 case METADATA: {
1842 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1843 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
1844 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1845 : diag::warn_pch_version_too_new);
1846 return VersionMismatch;
1847 }
1848
1849 bool hasErrors = Record[5];
1850 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
1851 Diag(diag::err_pch_with_compiler_errors);
1852 return HadErrors;
1853 }
1854
1855 F.RelocatablePCH = Record[4];
1856
1857 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001858 StringRef ASTBranch = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001859 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
1860 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
1861 Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
1862 return VersionMismatch;
1863 }
1864 break;
1865 }
1866
1867 case IMPORTS: {
1868 // Load each of the imported PCH files.
1869 unsigned Idx = 0, N = Record.size();
1870 while (Idx < N) {
1871 // Read information about the AST file.
1872 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
1873 // The import location will be the local one for now; we will adjust
1874 // all import locations of module imports after the global source
1875 // location info are setup.
1876 SourceLocation ImportLoc =
1877 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor677e15f2013-03-19 00:28:20 +00001878 off_t StoredSize = (off_t)Record[Idx++];
1879 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001880 unsigned Length = Record[Idx++];
1881 SmallString<128> ImportedFile(Record.begin() + Idx,
1882 Record.begin() + Idx + Length);
1883 Idx += Length;
1884
1885 // Load the AST file.
1886 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor677e15f2013-03-19 00:28:20 +00001887 StoredSize, StoredModTime,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001888 ClientLoadCapabilities)) {
1889 case Failure: return Failure;
1890 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregorac39f132013-03-19 00:38:50 +00001891 case Missing:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001892 case OutOfDate: return OutOfDate;
1893 case VersionMismatch: return VersionMismatch;
1894 case ConfigurationMismatch: return ConfigurationMismatch;
1895 case HadErrors: return HadErrors;
1896 case Success: break;
1897 }
1898 }
1899 break;
1900 }
1901
1902 case LANGUAGE_OPTIONS: {
1903 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
1904 if (Listener && &F == *ModuleMgr.begin() &&
1905 ParseLanguageOptions(Record, Complain, *Listener) &&
1906 !DisableValidation)
1907 return ConfigurationMismatch;
1908 break;
1909 }
1910
1911 case TARGET_OPTIONS: {
1912 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1913 if (Listener && &F == *ModuleMgr.begin() &&
1914 ParseTargetOptions(Record, Complain, *Listener) &&
1915 !DisableValidation)
1916 return ConfigurationMismatch;
1917 break;
1918 }
1919
1920 case DIAGNOSTIC_OPTIONS: {
1921 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1922 if (Listener && &F == *ModuleMgr.begin() &&
1923 ParseDiagnosticOptions(Record, Complain, *Listener) &&
1924 !DisableValidation)
1925 return ConfigurationMismatch;
1926 break;
1927 }
1928
1929 case FILE_SYSTEM_OPTIONS: {
1930 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1931 if (Listener && &F == *ModuleMgr.begin() &&
1932 ParseFileSystemOptions(Record, Complain, *Listener) &&
1933 !DisableValidation)
1934 return ConfigurationMismatch;
1935 break;
1936 }
1937
1938 case HEADER_SEARCH_OPTIONS: {
1939 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1940 if (Listener && &F == *ModuleMgr.begin() &&
1941 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
1942 !DisableValidation)
1943 return ConfigurationMismatch;
1944 break;
1945 }
1946
1947 case PREPROCESSOR_OPTIONS: {
1948 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1949 if (Listener && &F == *ModuleMgr.begin() &&
1950 ParsePreprocessorOptions(Record, Complain, *Listener,
1951 SuggestedPredefines) &&
1952 !DisableValidation)
1953 return ConfigurationMismatch;
1954 break;
1955 }
1956
1957 case ORIGINAL_FILE:
1958 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001959 F.ActualOriginalSourceFileName = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001960 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
1961 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
1962 break;
1963
1964 case ORIGINAL_FILE_ID:
1965 F.OriginalSourceFileID = FileID::get(Record[0]);
1966 break;
1967
1968 case ORIGINAL_PCH_DIR:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001969 F.OriginalDir = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001970 break;
1971
1972 case INPUT_FILE_OFFSETS:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001973 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001974 F.InputFilesLoaded.resize(Record[0]);
1975 break;
1976 }
1977 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001978}
1979
1980bool ASTReader::ReadASTBlock(ModuleFile &F) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001981 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001982
1983 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
1984 Error("malformed block record in AST file");
1985 return true;
1986 }
1987
1988 // Read all of the records and blocks for the AST file.
1989 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00001990 while (1) {
1991 llvm::BitstreamEntry Entry = Stream.advance();
1992
1993 switch (Entry.Kind) {
1994 case llvm::BitstreamEntry::Error:
1995 Error("error at end of module block in AST file");
1996 return true;
1997 case llvm::BitstreamEntry::EndBlock: {
Richard Smith43828672013-04-03 22:49:41 +00001998 // Outside of C++, we do not store a lookup map for the translation unit.
1999 // Instead, mark it as needing a lookup map to be built if this module
2000 // contains any declarations lexically within it (which it always does!).
2001 // This usually has no cost, since we very rarely need the lookup map for
2002 // the translation unit outside C++.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002003 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smith43828672013-04-03 22:49:41 +00002004 if (DC->hasExternalLexicalStorage() &&
2005 !getContext().getLangOpts().CPlusPlus)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002006 DC->setMustBuildLookupTable();
Chris Lattner88bde502013-01-19 21:39:22 +00002007
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002008 return false;
2009 }
Chris Lattner88bde502013-01-19 21:39:22 +00002010 case llvm::BitstreamEntry::SubBlock:
2011 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002012 case DECLTYPES_BLOCK_ID:
2013 // We lazily load the decls block, but we want to set up the
2014 // DeclsCursor cursor to point into it. Clone our current bitcode
2015 // cursor to it, enter the block and read the abbrevs in that block.
2016 // With the main cursor, we just skip over it.
2017 F.DeclsCursor = Stream;
2018 if (Stream.SkipBlock() || // Skip with the main cursor.
2019 // Read the abbrevs.
2020 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
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 DECL_UPDATES_BLOCK_ID:
2027 if (Stream.SkipBlock()) {
2028 Error("malformed block record in AST file");
2029 return true;
2030 }
2031 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002032
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002033 case PREPROCESSOR_BLOCK_ID:
2034 F.MacroCursor = Stream;
2035 if (!PP.getExternalSource())
2036 PP.setExternalSource(this);
Chris Lattner88bde502013-01-19 21:39:22 +00002037
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002038 if (Stream.SkipBlock() ||
2039 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2040 Error("malformed block record in AST file");
2041 return true;
2042 }
2043 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2044 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002045
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002046 case PREPROCESSOR_DETAIL_BLOCK_ID:
2047 F.PreprocessorDetailCursor = Stream;
2048 if (Stream.SkipBlock() ||
Chris Lattner88bde502013-01-19 21:39:22 +00002049 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002050 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattner88bde502013-01-19 21:39:22 +00002051 Error("malformed preprocessor detail record in AST file");
2052 return true;
2053 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002054 F.PreprocessorDetailStartOffset
Chris Lattner88bde502013-01-19 21:39:22 +00002055 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2056
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002057 if (!PP.getPreprocessingRecord())
2058 PP.createPreprocessingRecord();
2059 if (!PP.getPreprocessingRecord()->getExternalSource())
2060 PP.getPreprocessingRecord()->SetExternalSource(*this);
2061 break;
2062
2063 case SOURCE_MANAGER_BLOCK_ID:
2064 if (ReadSourceManagerBlock(F))
2065 return true;
2066 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002067
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002068 case SUBMODULE_BLOCK_ID:
2069 if (ReadSubmoduleBlock(F))
2070 return true;
2071 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002072
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002073 case COMMENTS_BLOCK_ID: {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00002074 BitstreamCursor C = Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002075 if (Stream.SkipBlock() ||
2076 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2077 Error("malformed comments block in AST file");
2078 return true;
2079 }
2080 CommentsCursors.push_back(std::make_pair(C, &F));
2081 break;
2082 }
Chris Lattner88bde502013-01-19 21:39:22 +00002083
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002084 default:
Chris Lattner88bde502013-01-19 21:39:22 +00002085 if (Stream.SkipBlock()) {
2086 Error("malformed block record in AST file");
2087 return true;
2088 }
2089 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002090 }
2091 continue;
Chris Lattner88bde502013-01-19 21:39:22 +00002092
2093 case llvm::BitstreamEntry::Record:
2094 // The interesting case.
2095 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002096 }
2097
2098 // Read and process a record.
2099 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002100 StringRef Blob;
2101 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002102 default: // Default behavior: ignore.
2103 break;
2104
2105 case TYPE_OFFSET: {
2106 if (F.LocalNumTypes != 0) {
2107 Error("duplicate TYPE_OFFSET record in AST file");
2108 return true;
2109 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002110 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002111 F.LocalNumTypes = Record[0];
2112 unsigned LocalBaseTypeIndex = Record[1];
2113 F.BaseTypeIndex = getTotalNumTypes();
2114
2115 if (F.LocalNumTypes > 0) {
2116 // Introduce the global -> local mapping for types within this module.
2117 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2118
2119 // Introduce the local -> global mapping for types within this module.
2120 F.TypeRemap.insertOrReplace(
2121 std::make_pair(LocalBaseTypeIndex,
2122 F.BaseTypeIndex - LocalBaseTypeIndex));
2123
2124 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2125 }
2126 break;
2127 }
2128
2129 case DECL_OFFSET: {
2130 if (F.LocalNumDecls != 0) {
2131 Error("duplicate DECL_OFFSET record in AST file");
2132 return true;
2133 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002134 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002135 F.LocalNumDecls = Record[0];
2136 unsigned LocalBaseDeclID = Record[1];
2137 F.BaseDeclID = getTotalNumDecls();
2138
2139 if (F.LocalNumDecls > 0) {
2140 // Introduce the global -> local mapping for declarations within this
2141 // module.
2142 GlobalDeclMap.insert(
2143 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2144
2145 // Introduce the local -> global mapping for declarations within this
2146 // module.
2147 F.DeclRemap.insertOrReplace(
2148 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2149
2150 // Introduce the global -> local mapping for declarations within this
2151 // module.
2152 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2153
2154 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2155 }
2156 break;
2157 }
2158
2159 case TU_UPDATE_LEXICAL: {
2160 DeclContext *TU = Context.getTranslationUnitDecl();
2161 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002162 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002163 Info.NumLexicalDecls
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002164 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002165 TU->setHasExternalLexicalStorage(true);
2166 break;
2167 }
2168
2169 case UPDATE_VISIBLE: {
2170 unsigned Idx = 0;
2171 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2172 ASTDeclContextNameLookupTable *Table =
2173 ASTDeclContextNameLookupTable::Create(
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002174 (const unsigned char *)Blob.data() + Record[Idx++],
2175 (const unsigned char *)Blob.data(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002176 ASTDeclContextNameLookupTrait(*this, F));
2177 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2178 DeclContext *TU = Context.getTranslationUnitDecl();
2179 F.DeclContextInfos[TU].NameLookupTableData = Table;
2180 TU->setHasExternalVisibleStorage(true);
2181 } else
2182 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2183 break;
2184 }
2185
2186 case IDENTIFIER_TABLE:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002187 F.IdentifierTableData = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002188 if (Record[0]) {
2189 F.IdentifierLookupTable
2190 = ASTIdentifierLookupTable::Create(
2191 (const unsigned char *)F.IdentifierTableData + Record[0],
2192 (const unsigned char *)F.IdentifierTableData,
2193 ASTIdentifierLookupTrait(*this, F));
2194
2195 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2196 }
2197 break;
2198
2199 case IDENTIFIER_OFFSET: {
2200 if (F.LocalNumIdentifiers != 0) {
2201 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2202 return true;
2203 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002204 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002205 F.LocalNumIdentifiers = Record[0];
2206 unsigned LocalBaseIdentifierID = Record[1];
2207 F.BaseIdentifierID = getTotalNumIdentifiers();
2208
2209 if (F.LocalNumIdentifiers > 0) {
2210 // Introduce the global -> local mapping for identifiers within this
2211 // module.
2212 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2213 &F));
2214
2215 // Introduce the local -> global mapping for identifiers within this
2216 // module.
2217 F.IdentifierRemap.insertOrReplace(
2218 std::make_pair(LocalBaseIdentifierID,
2219 F.BaseIdentifierID - LocalBaseIdentifierID));
2220
2221 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2222 + F.LocalNumIdentifiers);
2223 }
2224 break;
2225 }
2226
2227 case EXTERNAL_DEFINITIONS:
2228 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2229 ExternalDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2230 break;
2231
2232 case SPECIAL_TYPES:
Douglas Gregorf5cfc892013-02-01 23:45:03 +00002233 if (SpecialTypes.empty()) {
2234 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2235 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2236 break;
2237 }
2238
2239 if (SpecialTypes.size() != Record.size()) {
2240 Error("invalid special-types record");
2241 return true;
2242 }
2243
2244 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2245 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2246 if (!SpecialTypes[I])
2247 SpecialTypes[I] = ID;
2248 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2249 // merge step?
2250 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002251 break;
2252
2253 case STATISTICS:
2254 TotalNumStatements += Record[0];
2255 TotalNumMacros += Record[1];
2256 TotalLexicalDeclContexts += Record[2];
2257 TotalVisibleDeclContexts += Record[3];
2258 break;
2259
2260 case UNUSED_FILESCOPED_DECLS:
2261 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2262 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2263 break;
2264
2265 case DELEGATING_CTORS:
2266 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2267 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2268 break;
2269
2270 case WEAK_UNDECLARED_IDENTIFIERS:
2271 if (Record.size() % 4 != 0) {
2272 Error("invalid weak identifiers record");
2273 return true;
2274 }
2275
2276 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2277 // files. This isn't the way to do it :)
2278 WeakUndeclaredIdentifiers.clear();
2279
2280 // Translate the weak, undeclared identifiers into global IDs.
2281 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2282 WeakUndeclaredIdentifiers.push_back(
2283 getGlobalIdentifierID(F, Record[I++]));
2284 WeakUndeclaredIdentifiers.push_back(
2285 getGlobalIdentifierID(F, Record[I++]));
2286 WeakUndeclaredIdentifiers.push_back(
2287 ReadSourceLocation(F, Record, I).getRawEncoding());
2288 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2289 }
2290 break;
2291
Richard Smith5ea6ef42013-01-10 23:43:47 +00002292 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002293 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith5ea6ef42013-01-10 23:43:47 +00002294 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002295 break;
2296
2297 case SELECTOR_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002298 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002299 F.LocalNumSelectors = Record[0];
2300 unsigned LocalBaseSelectorID = Record[1];
2301 F.BaseSelectorID = getTotalNumSelectors();
2302
2303 if (F.LocalNumSelectors > 0) {
2304 // Introduce the global -> local mapping for selectors within this
2305 // module.
2306 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2307
2308 // Introduce the local -> global mapping for selectors within this
2309 // module.
2310 F.SelectorRemap.insertOrReplace(
2311 std::make_pair(LocalBaseSelectorID,
2312 F.BaseSelectorID - LocalBaseSelectorID));
2313
2314 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2315 }
2316 break;
2317 }
2318
2319 case METHOD_POOL:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002320 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002321 if (Record[0])
2322 F.SelectorLookupTable
2323 = ASTSelectorLookupTable::Create(
2324 F.SelectorLookupTableData + Record[0],
2325 F.SelectorLookupTableData,
2326 ASTSelectorLookupTrait(*this, F));
2327 TotalNumMethodPoolEntries += Record[1];
2328 break;
2329
2330 case REFERENCED_SELECTOR_POOL:
2331 if (!Record.empty()) {
2332 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2333 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2334 Record[Idx++]));
2335 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2336 getRawEncoding());
2337 }
2338 }
2339 break;
2340
2341 case PP_COUNTER_VALUE:
2342 if (!Record.empty() && Listener)
2343 Listener->ReadCounter(F, Record[0]);
2344 break;
2345
2346 case FILE_SORTED_DECLS:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002347 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002348 F.NumFileSortedDecls = Record[0];
2349 break;
2350
2351 case SOURCE_LOCATION_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002352 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002353 F.LocalNumSLocEntries = Record[0];
2354 unsigned SLocSpaceSize = Record[1];
2355 llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2356 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2357 SLocSpaceSize);
2358 // Make our entry in the range map. BaseID is negative and growing, so
2359 // we invert it. Because we invert it, though, we need the other end of
2360 // the range.
2361 unsigned RangeStart =
2362 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2363 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2364 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2365
2366 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2367 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2368 GlobalSLocOffsetMap.insert(
2369 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2370 - SLocSpaceSize,&F));
2371
2372 // Initialize the remapping table.
2373 // Invalid stays invalid.
2374 F.SLocRemap.insert(std::make_pair(0U, 0));
2375 // This module. Base was 2 when being compiled.
2376 F.SLocRemap.insert(std::make_pair(2U,
2377 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2378
2379 TotalNumSLocEntries += F.LocalNumSLocEntries;
2380 break;
2381 }
2382
2383 case MODULE_OFFSET_MAP: {
2384 // Additional remapping information.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002385 const unsigned char *Data = (const unsigned char*)Blob.data();
2386 const unsigned char *DataEnd = Data + Blob.size();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002387
2388 // Continuous range maps we may be updating in our module.
2389 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2390 ContinuousRangeMap<uint32_t, int, 2>::Builder
2391 IdentifierRemap(F.IdentifierRemap);
2392 ContinuousRangeMap<uint32_t, int, 2>::Builder
2393 MacroRemap(F.MacroRemap);
2394 ContinuousRangeMap<uint32_t, int, 2>::Builder
2395 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2396 ContinuousRangeMap<uint32_t, int, 2>::Builder
2397 SubmoduleRemap(F.SubmoduleRemap);
2398 ContinuousRangeMap<uint32_t, int, 2>::Builder
2399 SelectorRemap(F.SelectorRemap);
2400 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2401 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2402
2403 while(Data < DataEnd) {
2404 uint16_t Len = io::ReadUnalignedLE16(Data);
2405 StringRef Name = StringRef((const char*)Data, Len);
2406 Data += Len;
2407 ModuleFile *OM = ModuleMgr.lookup(Name);
2408 if (!OM) {
2409 Error("SourceLocation remap refers to unknown module");
2410 return true;
2411 }
2412
2413 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2414 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2415 uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
2416 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2417 uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
2418 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2419 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2420 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2421
2422 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2423 SLocRemap.insert(std::make_pair(SLocOffset,
2424 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2425 IdentifierRemap.insert(
2426 std::make_pair(IdentifierIDOffset,
2427 OM->BaseIdentifierID - IdentifierIDOffset));
2428 MacroRemap.insert(std::make_pair(MacroIDOffset,
2429 OM->BaseMacroID - MacroIDOffset));
2430 PreprocessedEntityRemap.insert(
2431 std::make_pair(PreprocessedEntityIDOffset,
2432 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2433 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2434 OM->BaseSubmoduleID - SubmoduleIDOffset));
2435 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2436 OM->BaseSelectorID - SelectorIDOffset));
2437 DeclRemap.insert(std::make_pair(DeclIDOffset,
2438 OM->BaseDeclID - DeclIDOffset));
2439
2440 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2441 OM->BaseTypeIndex - TypeIndexOffset));
2442
2443 // Global -> local mappings.
2444 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2445 }
2446 break;
2447 }
2448
2449 case SOURCE_MANAGER_LINE_TABLE:
2450 if (ParseLineTable(F, Record))
2451 return true;
2452 break;
2453
2454 case SOURCE_LOCATION_PRELOADS: {
2455 // Need to transform from the local view (1-based IDs) to the global view,
2456 // which is based off F.SLocEntryBaseID.
2457 if (!F.PreloadSLocEntries.empty()) {
2458 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2459 return true;
2460 }
2461
2462 F.PreloadSLocEntries.swap(Record);
2463 break;
2464 }
2465
2466 case EXT_VECTOR_DECLS:
2467 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2468 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2469 break;
2470
2471 case VTABLE_USES:
2472 if (Record.size() % 3 != 0) {
2473 Error("Invalid VTABLE_USES record");
2474 return true;
2475 }
2476
2477 // Later tables overwrite earlier ones.
2478 // FIXME: Modules will have some trouble with this. This is clearly not
2479 // the right way to do this.
2480 VTableUses.clear();
2481
2482 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2483 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2484 VTableUses.push_back(
2485 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2486 VTableUses.push_back(Record[Idx++]);
2487 }
2488 break;
2489
2490 case DYNAMIC_CLASSES:
2491 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2492 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2493 break;
2494
2495 case PENDING_IMPLICIT_INSTANTIATIONS:
2496 if (PendingInstantiations.size() % 2 != 0) {
2497 Error("Invalid existing PendingInstantiations");
2498 return true;
2499 }
2500
2501 if (Record.size() % 2 != 0) {
2502 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2503 return true;
2504 }
2505
2506 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2507 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2508 PendingInstantiations.push_back(
2509 ReadSourceLocation(F, Record, I).getRawEncoding());
2510 }
2511 break;
2512
2513 case SEMA_DECL_REFS:
2514 // Later tables overwrite earlier ones.
2515 // FIXME: Modules will have some trouble with this.
2516 SemaDeclRefs.clear();
2517 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2518 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2519 break;
2520
2521 case PPD_ENTITIES_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002522 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2523 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2524 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002525
2526 unsigned LocalBasePreprocessedEntityID = Record[0];
2527
2528 unsigned StartingID;
2529 if (!PP.getPreprocessingRecord())
2530 PP.createPreprocessingRecord();
2531 if (!PP.getPreprocessingRecord()->getExternalSource())
2532 PP.getPreprocessingRecord()->SetExternalSource(*this);
2533 StartingID
2534 = PP.getPreprocessingRecord()
2535 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2536 F.BasePreprocessedEntityID = StartingID;
2537
2538 if (F.NumPreprocessedEntities > 0) {
2539 // Introduce the global -> local mapping for preprocessed entities in
2540 // this module.
2541 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2542
2543 // Introduce the local -> global mapping for preprocessed entities in
2544 // this module.
2545 F.PreprocessedEntityRemap.insertOrReplace(
2546 std::make_pair(LocalBasePreprocessedEntityID,
2547 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2548 }
2549
2550 break;
2551 }
2552
2553 case DECL_UPDATE_OFFSETS: {
2554 if (Record.size() % 2 != 0) {
2555 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2556 return true;
2557 }
2558 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2559 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2560 .push_back(std::make_pair(&F, Record[I+1]));
2561 break;
2562 }
2563
2564 case DECL_REPLACEMENTS: {
2565 if (Record.size() % 3 != 0) {
2566 Error("invalid DECL_REPLACEMENTS block in AST file");
2567 return true;
2568 }
2569 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2570 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2571 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2572 break;
2573 }
2574
2575 case OBJC_CATEGORIES_MAP: {
2576 if (F.LocalNumObjCCategoriesInMap != 0) {
2577 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2578 return true;
2579 }
2580
2581 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002582 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002583 break;
2584 }
2585
2586 case OBJC_CATEGORIES:
2587 F.ObjCCategories.swap(Record);
2588 break;
2589
2590 case CXX_BASE_SPECIFIER_OFFSETS: {
2591 if (F.LocalNumCXXBaseSpecifiers != 0) {
2592 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2593 return true;
2594 }
2595
2596 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002597 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002598 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2599 break;
2600 }
2601
2602 case DIAG_PRAGMA_MAPPINGS:
2603 if (F.PragmaDiagMappings.empty())
2604 F.PragmaDiagMappings.swap(Record);
2605 else
2606 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2607 Record.begin(), Record.end());
2608 break;
2609
2610 case CUDA_SPECIAL_DECL_REFS:
2611 // Later tables overwrite earlier ones.
2612 // FIXME: Modules will have trouble with this.
2613 CUDASpecialDeclRefs.clear();
2614 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2615 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2616 break;
2617
2618 case HEADER_SEARCH_TABLE: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002619 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002620 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002621 if (Record[0]) {
2622 F.HeaderFileInfoTable
2623 = HeaderFileInfoLookupTable::Create(
2624 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2625 (const unsigned char *)F.HeaderFileInfoTableData,
2626 HeaderFileInfoTrait(*this, F,
2627 &PP.getHeaderSearchInfo(),
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002628 Blob.data() + Record[2]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002629
2630 PP.getHeaderSearchInfo().SetExternalSource(this);
2631 if (!PP.getHeaderSearchInfo().getExternalLookup())
2632 PP.getHeaderSearchInfo().SetExternalLookup(this);
2633 }
2634 break;
2635 }
2636
2637 case FP_PRAGMA_OPTIONS:
2638 // Later tables overwrite earlier ones.
2639 FPPragmaOptions.swap(Record);
2640 break;
2641
2642 case OPENCL_EXTENSIONS:
2643 // Later tables overwrite earlier ones.
2644 OpenCLExtensions.swap(Record);
2645 break;
2646
2647 case TENTATIVE_DEFINITIONS:
2648 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2649 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2650 break;
2651
2652 case KNOWN_NAMESPACES:
2653 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2654 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2655 break;
Nick Lewycky01a41142013-01-26 00:35:08 +00002656
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002657 case UNDEFINED_BUT_USED:
2658 if (UndefinedButUsed.size() % 2 != 0) {
2659 Error("Invalid existing UndefinedButUsed");
Nick Lewycky01a41142013-01-26 00:35:08 +00002660 return true;
2661 }
2662
2663 if (Record.size() % 2 != 0) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002664 Error("invalid undefined-but-used record");
Nick Lewycky01a41142013-01-26 00:35:08 +00002665 return true;
2666 }
2667 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002668 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
2669 UndefinedButUsed.push_back(
Nick Lewycky01a41142013-01-26 00:35:08 +00002670 ReadSourceLocation(F, Record, I).getRawEncoding());
2671 }
2672 break;
2673
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002674 case IMPORTED_MODULES: {
2675 if (F.Kind != MK_Module) {
2676 // If we aren't loading a module (which has its own exports), make
2677 // all of the imported modules visible.
2678 // FIXME: Deal with macros-only imports.
2679 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2680 if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
2681 ImportedModules.push_back(GlobalID);
2682 }
2683 }
2684 break;
2685 }
2686
2687 case LOCAL_REDECLARATIONS: {
2688 F.RedeclarationChains.swap(Record);
2689 break;
2690 }
2691
2692 case LOCAL_REDECLARATIONS_MAP: {
2693 if (F.LocalNumRedeclarationsInMap != 0) {
2694 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
2695 return true;
2696 }
2697
2698 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002699 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002700 break;
2701 }
2702
2703 case MERGED_DECLARATIONS: {
2704 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
2705 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
2706 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
2707 for (unsigned N = Record[Idx++]; N > 0; --N)
2708 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
2709 }
2710 break;
2711 }
2712
2713 case MACRO_OFFSET: {
2714 if (F.LocalNumMacros != 0) {
2715 Error("duplicate MACRO_OFFSET record in AST file");
2716 return true;
2717 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002718 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002719 F.LocalNumMacros = Record[0];
2720 unsigned LocalBaseMacroID = Record[1];
2721 F.BaseMacroID = getTotalNumMacros();
2722
2723 if (F.LocalNumMacros > 0) {
2724 // Introduce the global -> local mapping for macros within this module.
2725 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
2726
2727 // Introduce the local -> global mapping for macros within this module.
2728 F.MacroRemap.insertOrReplace(
2729 std::make_pair(LocalBaseMacroID,
2730 F.BaseMacroID - LocalBaseMacroID));
2731
2732 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
2733 }
2734 break;
2735 }
2736
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00002737 case MACRO_TABLE: {
2738 // FIXME: Not used yet.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002739 break;
2740 }
2741 }
2742 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002743}
2744
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002745/// \brief Move the given method to the back of the global list of methods.
2746static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
2747 // Find the entry for this selector in the method pool.
2748 Sema::GlobalMethodPool::iterator Known
2749 = S.MethodPool.find(Method->getSelector());
2750 if (Known == S.MethodPool.end())
2751 return;
2752
2753 // Retrieve the appropriate method list.
2754 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
2755 : Known->second.second;
2756 bool Found = false;
2757 for (ObjCMethodList *List = &Start; List; List = List->Next) {
2758 if (!Found) {
2759 if (List->Method == Method) {
2760 Found = true;
2761 } else {
2762 // Keep searching.
2763 continue;
2764 }
2765 }
2766
2767 if (List->Next)
2768 List->Method = List->Next->Method;
2769 else
2770 List->Method = Method;
2771 }
2772}
2773
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00002774void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002775 for (unsigned I = 0, N = Names.size(); I != N; ++I) {
2776 switch (Names[I].getKind()) {
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002777 case HiddenName::Declaration: {
2778 Decl *D = Names[I].getDecl();
2779 bool wasHidden = D->Hidden;
2780 D->Hidden = false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002781
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002782 if (wasHidden && SemaObj) {
2783 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
2784 moveMethodToBackOfGlobalList(*SemaObj, Method);
2785 }
2786 }
2787 break;
2788 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002789 case HiddenName::MacroVisibility: {
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00002790 std::pair<IdentifierInfo *, MacroDirective *> Macro = Names[I].getMacro();
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00002791 installImportedMacro(Macro.first, Macro.second, Owner);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002792 break;
2793 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002794 }
2795 }
2796}
2797
2798void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis5ebcb202013-02-01 16:36:12 +00002799 Module::NameVisibilityKind NameVisibility,
Douglas Gregor906d66a2013-03-20 21:10:35 +00002800 SourceLocation ImportLoc,
2801 bool Complain) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002802 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002803 SmallVector<Module *, 4> Stack;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002804 Stack.push_back(Mod);
2805 while (!Stack.empty()) {
2806 Mod = Stack.back();
2807 Stack.pop_back();
2808
2809 if (NameVisibility <= Mod->NameVisibility) {
2810 // This module already has this level of visibility (or greater), so
2811 // there is nothing more to do.
2812 continue;
2813 }
2814
2815 if (!Mod->isAvailable()) {
2816 // Modules that aren't available cannot be made visible.
2817 continue;
2818 }
2819
2820 // Update the module's name visibility.
2821 Mod->NameVisibility = NameVisibility;
2822
2823 // If we've already deserialized any names from this module,
2824 // mark them as visible.
2825 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
2826 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00002827 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002828 HiddenNamesMap.erase(Hidden);
2829 }
2830
2831 // Push any non-explicit submodules onto the stack to be marked as
2832 // visible.
2833 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2834 SubEnd = Mod->submodule_end();
2835 Sub != SubEnd; ++Sub) {
2836 if (!(*Sub)->IsExplicit && Visited.insert(*Sub))
2837 Stack.push_back(*Sub);
2838 }
2839
2840 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis21a00042013-02-19 19:34:40 +00002841 SmallVector<Module *, 16> Exports;
2842 Mod->getExportedModules(Exports);
2843 for (SmallVectorImpl<Module *>::iterator
2844 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
2845 Module *Exported = *I;
2846 if (Visited.insert(Exported))
2847 Stack.push_back(Exported);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002848 }
Douglas Gregor906d66a2013-03-20 21:10:35 +00002849
2850 // Detect any conflicts.
2851 if (Complain) {
2852 assert(ImportLoc.isValid() && "Missing import location");
2853 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
2854 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
2855 Diag(ImportLoc, diag::warn_module_conflict)
2856 << Mod->getFullModuleName()
2857 << Mod->Conflicts[I].Other->getFullModuleName()
2858 << Mod->Conflicts[I].Message;
2859 // FIXME: Need note where the other module was imported.
2860 }
2861 }
2862 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002863 }
2864}
2865
Douglas Gregor1a49d972013-01-25 01:03:03 +00002866bool ASTReader::loadGlobalIndex() {
2867 if (GlobalIndex)
2868 return false;
2869
2870 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
2871 !Context.getLangOpts().Modules)
2872 return true;
2873
2874 // Try to load the global index.
2875 TriedLoadingGlobalIndex = true;
2876 StringRef ModuleCachePath
2877 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
2878 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor677e15f2013-03-19 00:28:20 +00002879 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregor1a49d972013-01-25 01:03:03 +00002880 if (!Result.first)
2881 return true;
2882
2883 GlobalIndex.reset(Result.first);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00002884 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregor1a49d972013-01-25 01:03:03 +00002885 return false;
2886}
2887
2888bool ASTReader::isGlobalIndexUnavailable() const {
2889 return Context.getLangOpts().Modules && UseGlobalIndex &&
2890 !hasGlobalIndex() && TriedLoadingGlobalIndex;
2891}
2892
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002893ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
2894 ModuleKind Type,
2895 SourceLocation ImportLoc,
2896 unsigned ClientLoadCapabilities) {
2897 // Bump the generation number.
2898 unsigned PreviousGeneration = CurrentGeneration++;
2899
2900 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002901 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002902 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
2903 /*ImportedBy=*/0, Loaded,
Douglas Gregor677e15f2013-03-19 00:28:20 +00002904 0, 0,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002905 ClientLoadCapabilities)) {
2906 case Failure:
Douglas Gregor677e15f2013-03-19 00:28:20 +00002907 case Missing:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002908 case OutOfDate:
2909 case VersionMismatch:
2910 case ConfigurationMismatch:
2911 case HadErrors:
Douglas Gregor677e15f2013-03-19 00:28:20 +00002912 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
2913 Context.getLangOpts().Modules
2914 ? &PP.getHeaderSearchInfo().getModuleMap()
2915 : 0);
Douglas Gregor1a49d972013-01-25 01:03:03 +00002916
2917 // If we find that any modules are unusable, the global index is going
2918 // to be out-of-date. Just remove it.
2919 GlobalIndex.reset();
Douglas Gregor188bdcd2013-01-25 23:32:03 +00002920 ModuleMgr.setGlobalIndex(0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002921 return ReadResult;
2922
2923 case Success:
2924 break;
2925 }
2926
2927 // Here comes stuff that we only do once the entire chain is loaded.
2928
2929 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002930 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
2931 MEnd = Loaded.end();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002932 M != MEnd; ++M) {
2933 ModuleFile &F = *M->Mod;
2934
2935 // Read the AST block.
2936 if (ReadASTBlock(F))
2937 return Failure;
2938
2939 // Once read, set the ModuleFile bit base offset and update the size in
2940 // bits of all files we've seen.
2941 F.GlobalBitOffset = TotalModulesSizeInBits;
2942 TotalModulesSizeInBits += F.SizeInBits;
2943 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
2944
2945 // Preload SLocEntries.
2946 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
2947 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
2948 // Load it through the SourceManager and don't call ReadSLocEntry()
2949 // directly because the entry may have already been loaded in which case
2950 // calling ReadSLocEntry() directly would trigger an assertion in
2951 // SourceManager.
2952 SourceMgr.getLoadedSLocEntryByID(Index);
2953 }
2954 }
2955
Douglas Gregorfa69fc12013-03-22 18:50:14 +00002956 // Setup the import locations and notify the module manager that we've
2957 // committed to these module files.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002958 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
2959 MEnd = Loaded.end();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002960 M != MEnd; ++M) {
2961 ModuleFile &F = *M->Mod;
Douglas Gregorfa69fc12013-03-22 18:50:14 +00002962
2963 ModuleMgr.moduleFileAccepted(&F);
2964
2965 // Set the import location.
Argyrios Kyrtzidis8b136d82013-02-01 16:36:14 +00002966 F.DirectImportLoc = ImportLoc;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002967 if (!M->ImportedBy)
2968 F.ImportLoc = M->ImportLoc;
2969 else
2970 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
2971 M->ImportLoc.getRawEncoding());
2972 }
2973
2974 // Mark all of the identifiers in the identifier table as being out of date,
2975 // so that various accessors know to check the loaded modules when the
2976 // identifier is used.
2977 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
2978 IdEnd = PP.getIdentifierTable().end();
2979 Id != IdEnd; ++Id)
2980 Id->second->setOutOfDate(true);
2981
2982 // Resolve any unresolved module exports.
Douglas Gregor906d66a2013-03-20 21:10:35 +00002983 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
2984 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002985 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
2986 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregor906d66a2013-03-20 21:10:35 +00002987
2988 switch (Unresolved.Kind) {
2989 case UnresolvedModuleRef::Conflict:
2990 if (ResolvedMod) {
2991 Module::Conflict Conflict;
2992 Conflict.Other = ResolvedMod;
2993 Conflict.Message = Unresolved.String.str();
2994 Unresolved.Mod->Conflicts.push_back(Conflict);
2995 }
2996 continue;
2997
2998 case UnresolvedModuleRef::Import:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002999 if (ResolvedMod)
3000 Unresolved.Mod->Imports.push_back(ResolvedMod);
3001 continue;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003002
Douglas Gregor906d66a2013-03-20 21:10:35 +00003003 case UnresolvedModuleRef::Export:
3004 if (ResolvedMod || Unresolved.IsWildcard)
3005 Unresolved.Mod->Exports.push_back(
3006 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3007 continue;
3008 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003009 }
Douglas Gregor906d66a2013-03-20 21:10:35 +00003010 UnresolvedModuleRefs.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003011
3012 InitializeContext();
3013
3014 if (DeserializationListener)
3015 DeserializationListener->ReaderInitialized(this);
3016
3017 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3018 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3019 PrimaryModule.OriginalSourceFileID
3020 = FileID::get(PrimaryModule.SLocEntryBaseID
3021 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3022
3023 // If this AST file is a precompiled preamble, then set the
3024 // preamble file ID of the source manager to the file source file
3025 // from which the preamble was built.
3026 if (Type == MK_Preamble) {
3027 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3028 } else if (Type == MK_MainFile) {
3029 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3030 }
3031 }
3032
3033 // For any Objective-C class definitions we have already loaded, make sure
3034 // that we load any additional categories.
3035 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3036 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3037 ObjCClassesLoaded[I],
3038 PreviousGeneration);
3039 }
Douglas Gregor1a49d972013-01-25 01:03:03 +00003040
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003041 return Success;
3042}
3043
3044ASTReader::ASTReadResult
3045ASTReader::ReadASTCore(StringRef FileName,
3046 ModuleKind Type,
3047 SourceLocation ImportLoc,
3048 ModuleFile *ImportedBy,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003049 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor677e15f2013-03-19 00:28:20 +00003050 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003051 unsigned ClientLoadCapabilities) {
3052 ModuleFile *M;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003053 std::string ErrorStr;
Douglas Gregor677e15f2013-03-19 00:28:20 +00003054 ModuleManager::AddModuleResult AddResult
3055 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3056 CurrentGeneration, ExpectedSize, ExpectedModTime,
3057 M, ErrorStr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003058
Douglas Gregor677e15f2013-03-19 00:28:20 +00003059 switch (AddResult) {
3060 case ModuleManager::AlreadyLoaded:
3061 return Success;
3062
3063 case ModuleManager::NewlyLoaded:
3064 // Load module file below.
3065 break;
3066
3067 case ModuleManager::Missing:
3068 // The module file was missing; if the client handle handle, that, return
3069 // it.
3070 if (ClientLoadCapabilities & ARR_Missing)
3071 return Missing;
3072
3073 // Otherwise, return an error.
3074 {
3075 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3076 + ErrorStr;
3077 Error(Msg);
3078 }
3079 return Failure;
3080
3081 case ModuleManager::OutOfDate:
3082 // We couldn't load the module file because it is out-of-date. If the
3083 // client can handle out-of-date, return it.
3084 if (ClientLoadCapabilities & ARR_OutOfDate)
3085 return OutOfDate;
3086
3087 // Otherwise, return an error.
3088 {
3089 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3090 + ErrorStr;
3091 Error(Msg);
3092 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003093 return Failure;
3094 }
3095
Douglas Gregor677e15f2013-03-19 00:28:20 +00003096 assert(M && "Missing module file");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003097
3098 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3099 // module?
3100 if (FileName != "-") {
3101 CurrentDir = llvm::sys::path::parent_path(FileName);
3102 if (CurrentDir.empty()) CurrentDir = ".";
3103 }
3104
3105 ModuleFile &F = *M;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003106 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003107 Stream.init(F.StreamFile);
3108 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3109
3110 // Sniff for the signature.
3111 if (Stream.Read(8) != 'C' ||
3112 Stream.Read(8) != 'P' ||
3113 Stream.Read(8) != 'C' ||
3114 Stream.Read(8) != 'H') {
3115 Diag(diag::err_not_a_pch_file) << FileName;
3116 return Failure;
3117 }
3118
3119 // This is used for compatibility with older PCH formats.
3120 bool HaveReadControlBlock = false;
3121
Chris Lattner99a5af02013-01-20 00:00:22 +00003122 while (1) {
3123 llvm::BitstreamEntry Entry = Stream.advance();
3124
3125 switch (Entry.Kind) {
3126 case llvm::BitstreamEntry::Error:
3127 case llvm::BitstreamEntry::EndBlock:
3128 case llvm::BitstreamEntry::Record:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003129 Error("invalid record at top-level of AST file");
3130 return Failure;
Chris Lattner99a5af02013-01-20 00:00:22 +00003131
3132 case llvm::BitstreamEntry::SubBlock:
3133 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003134 }
3135
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003136 // We only know the control subblock ID.
Chris Lattner99a5af02013-01-20 00:00:22 +00003137 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003138 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3139 if (Stream.ReadBlockInfoBlock()) {
3140 Error("malformed BlockInfoBlock in AST file");
3141 return Failure;
3142 }
3143 break;
3144 case CONTROL_BLOCK_ID:
3145 HaveReadControlBlock = true;
3146 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
3147 case Success:
3148 break;
3149
3150 case Failure: return Failure;
Douglas Gregor677e15f2013-03-19 00:28:20 +00003151 case Missing: return Missing;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003152 case OutOfDate: return OutOfDate;
3153 case VersionMismatch: return VersionMismatch;
3154 case ConfigurationMismatch: return ConfigurationMismatch;
3155 case HadErrors: return HadErrors;
3156 }
3157 break;
3158 case AST_BLOCK_ID:
3159 if (!HaveReadControlBlock) {
3160 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3161 Diag(diag::warn_pch_version_too_old);
3162 return VersionMismatch;
3163 }
3164
3165 // Record that we've loaded this module.
3166 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3167 return Success;
3168
3169 default:
3170 if (Stream.SkipBlock()) {
3171 Error("malformed block record in AST file");
3172 return Failure;
3173 }
3174 break;
3175 }
3176 }
3177
3178 return Success;
3179}
3180
3181void ASTReader::InitializeContext() {
3182 // If there's a listener, notify them that we "read" the translation unit.
3183 if (DeserializationListener)
3184 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3185 Context.getTranslationUnitDecl());
3186
3187 // Make sure we load the declaration update records for the translation unit,
3188 // if there are any.
3189 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3190 Context.getTranslationUnitDecl());
3191
3192 // FIXME: Find a better way to deal with collisions between these
3193 // built-in types. Right now, we just ignore the problem.
3194
3195 // Load the special types.
3196 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3197 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3198 if (!Context.CFConstantStringTypeDecl)
3199 Context.setCFConstantStringType(GetType(String));
3200 }
3201
3202 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3203 QualType FileType = GetType(File);
3204 if (FileType.isNull()) {
3205 Error("FILE type is NULL");
3206 return;
3207 }
3208
3209 if (!Context.FILEDecl) {
3210 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3211 Context.setFILEDecl(Typedef->getDecl());
3212 else {
3213 const TagType *Tag = FileType->getAs<TagType>();
3214 if (!Tag) {
3215 Error("Invalid FILE type in AST file");
3216 return;
3217 }
3218 Context.setFILEDecl(Tag->getDecl());
3219 }
3220 }
3221 }
3222
3223 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3224 QualType Jmp_bufType = GetType(Jmp_buf);
3225 if (Jmp_bufType.isNull()) {
3226 Error("jmp_buf type is NULL");
3227 return;
3228 }
3229
3230 if (!Context.jmp_bufDecl) {
3231 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3232 Context.setjmp_bufDecl(Typedef->getDecl());
3233 else {
3234 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3235 if (!Tag) {
3236 Error("Invalid jmp_buf type in AST file");
3237 return;
3238 }
3239 Context.setjmp_bufDecl(Tag->getDecl());
3240 }
3241 }
3242 }
3243
3244 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3245 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3246 if (Sigjmp_bufType.isNull()) {
3247 Error("sigjmp_buf type is NULL");
3248 return;
3249 }
3250
3251 if (!Context.sigjmp_bufDecl) {
3252 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3253 Context.setsigjmp_bufDecl(Typedef->getDecl());
3254 else {
3255 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3256 assert(Tag && "Invalid sigjmp_buf type in AST file");
3257 Context.setsigjmp_bufDecl(Tag->getDecl());
3258 }
3259 }
3260 }
3261
3262 if (unsigned ObjCIdRedef
3263 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3264 if (Context.ObjCIdRedefinitionType.isNull())
3265 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3266 }
3267
3268 if (unsigned ObjCClassRedef
3269 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3270 if (Context.ObjCClassRedefinitionType.isNull())
3271 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3272 }
3273
3274 if (unsigned ObjCSelRedef
3275 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3276 if (Context.ObjCSelRedefinitionType.isNull())
3277 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3278 }
3279
3280 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3281 QualType Ucontext_tType = GetType(Ucontext_t);
3282 if (Ucontext_tType.isNull()) {
3283 Error("ucontext_t type is NULL");
3284 return;
3285 }
3286
3287 if (!Context.ucontext_tDecl) {
3288 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3289 Context.setucontext_tDecl(Typedef->getDecl());
3290 else {
3291 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3292 assert(Tag && "Invalid ucontext_t type in AST file");
3293 Context.setucontext_tDecl(Tag->getDecl());
3294 }
3295 }
3296 }
3297 }
3298
3299 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3300
3301 // If there were any CUDA special declarations, deserialize them.
3302 if (!CUDASpecialDeclRefs.empty()) {
3303 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3304 Context.setcudaConfigureCallDecl(
3305 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3306 }
3307
3308 // Re-export any modules that were imported by a non-module AST file.
3309 for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3310 if (Module *Imported = getSubmodule(ImportedModules[I]))
Argyrios Kyrtzidis5ebcb202013-02-01 16:36:12 +00003311 makeModuleVisible(Imported, Module::AllVisible,
Douglas Gregor906d66a2013-03-20 21:10:35 +00003312 /*ImportLoc=*/SourceLocation(),
3313 /*Complain=*/false);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003314 }
3315 ImportedModules.clear();
3316}
3317
3318void ASTReader::finalizeForWriting() {
3319 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3320 HiddenEnd = HiddenNamesMap.end();
3321 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00003322 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003323 }
3324 HiddenNamesMap.clear();
3325}
3326
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003327/// SkipCursorToControlBlock - Given a cursor at the start of an AST file, scan
3328/// ahead and drop the cursor into the start of the CONTROL_BLOCK, returning
3329/// false on success and true on failure.
3330static bool SkipCursorToControlBlock(BitstreamCursor &Cursor) {
3331 while (1) {
3332 llvm::BitstreamEntry Entry = Cursor.advance();
3333 switch (Entry.Kind) {
3334 case llvm::BitstreamEntry::Error:
3335 case llvm::BitstreamEntry::EndBlock:
3336 return true;
3337
3338 case llvm::BitstreamEntry::Record:
3339 // Ignore top-level records.
3340 Cursor.skipRecord(Entry.ID);
3341 break;
3342
3343 case llvm::BitstreamEntry::SubBlock:
3344 if (Entry.ID == CONTROL_BLOCK_ID) {
3345 if (Cursor.EnterSubBlock(CONTROL_BLOCK_ID))
3346 return true;
3347 // Found it!
3348 return false;
3349 }
3350
3351 if (Cursor.SkipBlock())
3352 return true;
3353 }
3354 }
3355}
3356
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003357/// \brief Retrieve the name of the original source file name
3358/// directly from the AST file, without actually loading the AST
3359/// file.
3360std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3361 FileManager &FileMgr,
3362 DiagnosticsEngine &Diags) {
3363 // Open the AST file.
3364 std::string ErrStr;
3365 OwningPtr<llvm::MemoryBuffer> Buffer;
3366 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3367 if (!Buffer) {
3368 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3369 return std::string();
3370 }
3371
3372 // Initialize the stream
3373 llvm::BitstreamReader StreamFile;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003374 BitstreamCursor Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003375 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3376 (const unsigned char *)Buffer->getBufferEnd());
3377 Stream.init(StreamFile);
3378
3379 // Sniff for the signature.
3380 if (Stream.Read(8) != 'C' ||
3381 Stream.Read(8) != 'P' ||
3382 Stream.Read(8) != 'C' ||
3383 Stream.Read(8) != 'H') {
3384 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3385 return std::string();
3386 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003387
Chris Lattner88bde502013-01-19 21:39:22 +00003388 // Scan for the CONTROL_BLOCK_ID block.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003389 if (SkipCursorToControlBlock(Stream)) {
3390 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3391 return std::string();
Chris Lattner88bde502013-01-19 21:39:22 +00003392 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003393
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003394 // Scan for ORIGINAL_FILE inside the control block.
3395 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00003396 while (1) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003397 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattner88bde502013-01-19 21:39:22 +00003398 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3399 return std::string();
3400
3401 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3402 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3403 return std::string();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003404 }
Chris Lattner88bde502013-01-19 21:39:22 +00003405
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003406 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003407 StringRef Blob;
3408 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3409 return Blob.str();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003410 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003411}
3412
3413namespace {
3414 class SimplePCHValidator : public ASTReaderListener {
3415 const LangOptions &ExistingLangOpts;
3416 const TargetOptions &ExistingTargetOpts;
3417 const PreprocessorOptions &ExistingPPOpts;
3418 FileManager &FileMgr;
3419
3420 public:
3421 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3422 const TargetOptions &ExistingTargetOpts,
3423 const PreprocessorOptions &ExistingPPOpts,
3424 FileManager &FileMgr)
3425 : ExistingLangOpts(ExistingLangOpts),
3426 ExistingTargetOpts(ExistingTargetOpts),
3427 ExistingPPOpts(ExistingPPOpts),
3428 FileMgr(FileMgr)
3429 {
3430 }
3431
3432 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
3433 bool Complain) {
3434 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3435 }
3436 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
3437 bool Complain) {
3438 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3439 }
3440 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3441 bool Complain,
3442 std::string &SuggestedPredefines) {
3443 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
3444 SuggestedPredefines);
3445 }
3446 };
3447}
3448
3449bool ASTReader::readASTFileControlBlock(StringRef Filename,
3450 FileManager &FileMgr,
3451 ASTReaderListener &Listener) {
3452 // Open the AST file.
3453 std::string ErrStr;
3454 OwningPtr<llvm::MemoryBuffer> Buffer;
3455 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3456 if (!Buffer) {
3457 return true;
3458 }
3459
3460 // Initialize the stream
3461 llvm::BitstreamReader StreamFile;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003462 BitstreamCursor Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003463 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3464 (const unsigned char *)Buffer->getBufferEnd());
3465 Stream.init(StreamFile);
3466
3467 // Sniff for the signature.
3468 if (Stream.Read(8) != 'C' ||
3469 Stream.Read(8) != 'P' ||
3470 Stream.Read(8) != 'C' ||
3471 Stream.Read(8) != 'H') {
3472 return true;
3473 }
3474
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003475 // Scan for the CONTROL_BLOCK_ID block.
3476 if (SkipCursorToControlBlock(Stream))
3477 return true;
3478
3479 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003480 RecordData Record;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003481 while (1) {
3482 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3483 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3484 return false;
3485
3486 if (Entry.Kind != llvm::BitstreamEntry::Record)
3487 return true;
3488
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003489 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003490 StringRef Blob;
3491 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003492 switch ((ControlRecordTypes)RecCode) {
3493 case METADATA: {
3494 if (Record[0] != VERSION_MAJOR)
3495 return true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003496
Douglas Gregorc544ba02013-03-27 16:47:18 +00003497 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003498 return true;
Douglas Gregorc544ba02013-03-27 16:47:18 +00003499
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003500 break;
3501 }
3502 case LANGUAGE_OPTIONS:
3503 if (ParseLanguageOptions(Record, false, Listener))
3504 return true;
3505 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003506
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003507 case TARGET_OPTIONS:
3508 if (ParseTargetOptions(Record, false, Listener))
3509 return true;
3510 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003511
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003512 case DIAGNOSTIC_OPTIONS:
3513 if (ParseDiagnosticOptions(Record, false, Listener))
3514 return true;
3515 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003516
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003517 case FILE_SYSTEM_OPTIONS:
3518 if (ParseFileSystemOptions(Record, false, Listener))
3519 return true;
3520 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003521
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003522 case HEADER_SEARCH_OPTIONS:
3523 if (ParseHeaderSearchOptions(Record, false, Listener))
3524 return true;
3525 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003526
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003527 case PREPROCESSOR_OPTIONS: {
3528 std::string IgnoredSuggestedPredefines;
3529 if (ParsePreprocessorOptions(Record, false, Listener,
3530 IgnoredSuggestedPredefines))
3531 return true;
3532 break;
3533 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003534
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003535 default:
3536 // No other validation to perform.
3537 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003538 }
3539 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003540}
3541
3542
3543bool ASTReader::isAcceptableASTFile(StringRef Filename,
3544 FileManager &FileMgr,
3545 const LangOptions &LangOpts,
3546 const TargetOptions &TargetOpts,
3547 const PreprocessorOptions &PPOpts) {
3548 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3549 return !readASTFileControlBlock(Filename, FileMgr, validator);
3550}
3551
3552bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
3553 // Enter the submodule block.
3554 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3555 Error("malformed submodule block record in AST file");
3556 return true;
3557 }
3558
3559 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
3560 bool First = true;
3561 Module *CurrentModule = 0;
3562 RecordData Record;
3563 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003564 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
3565
3566 switch (Entry.Kind) {
3567 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
3568 case llvm::BitstreamEntry::Error:
3569 Error("malformed block record in AST file");
3570 return true;
3571 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003572 return false;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003573 case llvm::BitstreamEntry::Record:
3574 // The interesting case.
3575 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003576 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003577
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003578 // Read a record.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003579 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003580 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003581 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003582 default: // Default behavior: ignore.
3583 break;
3584
3585 case SUBMODULE_DEFINITION: {
3586 if (First) {
3587 Error("missing submodule metadata record at beginning of block");
3588 return true;
3589 }
3590
Douglas Gregor970e4412013-03-20 03:59:18 +00003591 if (Record.size() < 8) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003592 Error("malformed module definition");
3593 return true;
3594 }
3595
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003596 StringRef Name = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003597 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
3598 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[1]);
3599 bool IsFramework = Record[2];
3600 bool IsExplicit = Record[3];
3601 bool IsSystem = Record[4];
3602 bool InferSubmodules = Record[5];
3603 bool InferExplicitSubmodules = Record[6];
3604 bool InferExportWildcard = Record[7];
Douglas Gregor970e4412013-03-20 03:59:18 +00003605 bool ConfigMacrosExhaustive = Record[8];
3606
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003607 Module *ParentModule = 0;
3608 if (Parent)
3609 ParentModule = getSubmodule(Parent);
3610
3611 // Retrieve this (sub)module from the module map, creating it if
3612 // necessary.
3613 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
3614 IsFramework,
3615 IsExplicit).first;
3616 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
3617 if (GlobalIndex >= SubmodulesLoaded.size() ||
3618 SubmodulesLoaded[GlobalIndex]) {
3619 Error("too many submodules");
3620 return true;
3621 }
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003622
Douglas Gregor677e15f2013-03-19 00:28:20 +00003623 if (!ParentModule) {
3624 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
3625 if (CurFile != F.File) {
3626 if (!Diags.isDiagnosticInFlight()) {
3627 Diag(diag::err_module_file_conflict)
3628 << CurrentModule->getTopLevelModuleName()
3629 << CurFile->getName()
3630 << F.File->getName();
3631 }
3632 return true;
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003633 }
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003634 }
Douglas Gregor677e15f2013-03-19 00:28:20 +00003635
3636 CurrentModule->setASTFile(F.File);
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003637 }
Douglas Gregor677e15f2013-03-19 00:28:20 +00003638
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003639 CurrentModule->IsFromModuleFile = true;
3640 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
3641 CurrentModule->InferSubmodules = InferSubmodules;
3642 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
3643 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor970e4412013-03-20 03:59:18 +00003644 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003645 if (DeserializationListener)
3646 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
3647
3648 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003649
Douglas Gregor906d66a2013-03-20 21:10:35 +00003650 // Clear out data that will be replaced by what is the module file.
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003651 CurrentModule->LinkLibraries.clear();
Douglas Gregor970e4412013-03-20 03:59:18 +00003652 CurrentModule->ConfigMacros.clear();
Douglas Gregor906d66a2013-03-20 21:10:35 +00003653 CurrentModule->UnresolvedConflicts.clear();
3654 CurrentModule->Conflicts.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003655 break;
3656 }
3657
3658 case SUBMODULE_UMBRELLA_HEADER: {
3659 if (First) {
3660 Error("missing submodule metadata record at beginning of block");
3661 return true;
3662 }
3663
3664 if (!CurrentModule)
3665 break;
3666
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003667 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003668 if (!CurrentModule->getUmbrellaHeader())
3669 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
3670 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
3671 Error("mismatched umbrella headers in submodule");
3672 return true;
3673 }
3674 }
3675 break;
3676 }
3677
3678 case SUBMODULE_HEADER: {
3679 if (First) {
3680 Error("missing submodule metadata record at beginning of block");
3681 return true;
3682 }
3683
3684 if (!CurrentModule)
3685 break;
3686
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00003687 // We lazily associate headers with their modules via the HeaderInfoTable.
3688 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
3689 // of complete filenames or remove it entirely.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003690 break;
3691 }
3692
3693 case SUBMODULE_EXCLUDED_HEADER: {
3694 if (First) {
3695 Error("missing submodule metadata record at beginning of block");
3696 return true;
3697 }
3698
3699 if (!CurrentModule)
3700 break;
3701
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00003702 // We lazily associate headers with their modules via the HeaderInfoTable.
3703 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
3704 // of complete filenames or remove it entirely.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003705 break;
3706 }
3707
3708 case SUBMODULE_TOPHEADER: {
3709 if (First) {
3710 Error("missing submodule metadata record at beginning of block");
3711 return true;
3712 }
3713
3714 if (!CurrentModule)
3715 break;
3716
Argyrios Kyrtzidisc1d22392013-03-13 21:13:43 +00003717 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003718 break;
3719 }
3720
3721 case SUBMODULE_UMBRELLA_DIR: {
3722 if (First) {
3723 Error("missing submodule metadata record at beginning of block");
3724 return true;
3725 }
3726
3727 if (!CurrentModule)
3728 break;
3729
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003730 if (const DirectoryEntry *Umbrella
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003731 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003732 if (!CurrentModule->getUmbrellaDir())
3733 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
3734 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
3735 Error("mismatched umbrella directories in submodule");
3736 return true;
3737 }
3738 }
3739 break;
3740 }
3741
3742 case SUBMODULE_METADATA: {
3743 if (!First) {
3744 Error("submodule metadata record not at beginning of block");
3745 return true;
3746 }
3747 First = false;
3748
3749 F.BaseSubmoduleID = getTotalNumSubmodules();
3750 F.LocalNumSubmodules = Record[0];
3751 unsigned LocalBaseSubmoduleID = Record[1];
3752 if (F.LocalNumSubmodules > 0) {
3753 // Introduce the global -> local mapping for submodules within this
3754 // module.
3755 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
3756
3757 // Introduce the local -> global mapping for submodules within this
3758 // module.
3759 F.SubmoduleRemap.insertOrReplace(
3760 std::make_pair(LocalBaseSubmoduleID,
3761 F.BaseSubmoduleID - LocalBaseSubmoduleID));
3762
3763 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
3764 }
3765 break;
3766 }
3767
3768 case SUBMODULE_IMPORTS: {
3769 if (First) {
3770 Error("missing submodule metadata record at beginning of block");
3771 return true;
3772 }
3773
3774 if (!CurrentModule)
3775 break;
3776
3777 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregor906d66a2013-03-20 21:10:35 +00003778 UnresolvedModuleRef Unresolved;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003779 Unresolved.File = &F;
3780 Unresolved.Mod = CurrentModule;
3781 Unresolved.ID = Record[Idx];
Douglas Gregor906d66a2013-03-20 21:10:35 +00003782 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003783 Unresolved.IsWildcard = false;
Douglas Gregor906d66a2013-03-20 21:10:35 +00003784 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003785 }
3786 break;
3787 }
3788
3789 case SUBMODULE_EXPORTS: {
3790 if (First) {
3791 Error("missing submodule metadata record at beginning of block");
3792 return true;
3793 }
3794
3795 if (!CurrentModule)
3796 break;
3797
3798 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregor906d66a2013-03-20 21:10:35 +00003799 UnresolvedModuleRef Unresolved;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003800 Unresolved.File = &F;
3801 Unresolved.Mod = CurrentModule;
3802 Unresolved.ID = Record[Idx];
Douglas Gregor906d66a2013-03-20 21:10:35 +00003803 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003804 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregor906d66a2013-03-20 21:10:35 +00003805 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003806 }
3807
3808 // Once we've loaded the set of exports, there's no reason to keep
3809 // the parsed, unresolved exports around.
3810 CurrentModule->UnresolvedExports.clear();
3811 break;
3812 }
3813 case SUBMODULE_REQUIRES: {
3814 if (First) {
3815 Error("missing submodule metadata record at beginning of block");
3816 return true;
3817 }
3818
3819 if (!CurrentModule)
3820 break;
3821
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003822 CurrentModule->addRequirement(Blob, Context.getLangOpts(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003823 Context.getTargetInfo());
3824 break;
3825 }
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003826
3827 case SUBMODULE_LINK_LIBRARY:
3828 if (First) {
3829 Error("missing submodule metadata record at beginning of block");
3830 return true;
3831 }
3832
3833 if (!CurrentModule)
3834 break;
3835
3836 CurrentModule->LinkLibraries.push_back(
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003837 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003838 break;
Douglas Gregor63a72682013-03-20 00:22:05 +00003839
3840 case SUBMODULE_CONFIG_MACRO:
3841 if (First) {
3842 Error("missing submodule metadata record at beginning of block");
3843 return true;
3844 }
3845
3846 if (!CurrentModule)
3847 break;
3848
3849 CurrentModule->ConfigMacros.push_back(Blob.str());
3850 break;
Douglas Gregor906d66a2013-03-20 21:10:35 +00003851
3852 case SUBMODULE_CONFLICT: {
3853 if (First) {
3854 Error("missing submodule metadata record at beginning of block");
3855 return true;
3856 }
3857
3858 if (!CurrentModule)
3859 break;
3860
3861 UnresolvedModuleRef Unresolved;
3862 Unresolved.File = &F;
3863 Unresolved.Mod = CurrentModule;
3864 Unresolved.ID = Record[0];
3865 Unresolved.Kind = UnresolvedModuleRef::Conflict;
3866 Unresolved.IsWildcard = false;
3867 Unresolved.String = Blob;
3868 UnresolvedModuleRefs.push_back(Unresolved);
3869 break;
3870 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003871 }
3872 }
3873}
3874
3875/// \brief Parse the record that corresponds to a LangOptions data
3876/// structure.
3877///
3878/// This routine parses the language options from the AST file and then gives
3879/// them to the AST listener if one is set.
3880///
3881/// \returns true if the listener deems the file unacceptable, false otherwise.
3882bool ASTReader::ParseLanguageOptions(const RecordData &Record,
3883 bool Complain,
3884 ASTReaderListener &Listener) {
3885 LangOptions LangOpts;
3886 unsigned Idx = 0;
3887#define LANGOPT(Name, Bits, Default, Description) \
3888 LangOpts.Name = Record[Idx++];
3889#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
3890 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
3891#include "clang/Basic/LangOptions.def"
Will Dietz4f45bc02013-01-18 11:30:38 +00003892#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
3893#include "clang/Basic/Sanitizers.def"
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003894
3895 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
3896 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
3897 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
3898
3899 unsigned Length = Record[Idx++];
3900 LangOpts.CurrentModule.assign(Record.begin() + Idx,
3901 Record.begin() + Idx + Length);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +00003902
3903 Idx += Length;
3904
3905 // Comment options.
3906 for (unsigned N = Record[Idx++]; N; --N) {
3907 LangOpts.CommentOpts.BlockCommandNames.push_back(
3908 ReadString(Record, Idx));
3909 }
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +00003910 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +00003911
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003912 return Listener.ReadLanguageOptions(LangOpts, Complain);
3913}
3914
3915bool ASTReader::ParseTargetOptions(const RecordData &Record,
3916 bool Complain,
3917 ASTReaderListener &Listener) {
3918 unsigned Idx = 0;
3919 TargetOptions TargetOpts;
3920 TargetOpts.Triple = ReadString(Record, Idx);
3921 TargetOpts.CPU = ReadString(Record, Idx);
3922 TargetOpts.ABI = ReadString(Record, Idx);
3923 TargetOpts.CXXABI = ReadString(Record, Idx);
3924 TargetOpts.LinkerVersion = ReadString(Record, Idx);
3925 for (unsigned N = Record[Idx++]; N; --N) {
3926 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
3927 }
3928 for (unsigned N = Record[Idx++]; N; --N) {
3929 TargetOpts.Features.push_back(ReadString(Record, Idx));
3930 }
3931
3932 return Listener.ReadTargetOptions(TargetOpts, Complain);
3933}
3934
3935bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
3936 ASTReaderListener &Listener) {
3937 DiagnosticOptions DiagOpts;
3938 unsigned Idx = 0;
3939#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
3940#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
3941 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
3942#include "clang/Basic/DiagnosticOptions.def"
3943
3944 for (unsigned N = Record[Idx++]; N; --N) {
3945 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
3946 }
3947
3948 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
3949}
3950
3951bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
3952 ASTReaderListener &Listener) {
3953 FileSystemOptions FSOpts;
3954 unsigned Idx = 0;
3955 FSOpts.WorkingDir = ReadString(Record, Idx);
3956 return Listener.ReadFileSystemOptions(FSOpts, Complain);
3957}
3958
3959bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
3960 bool Complain,
3961 ASTReaderListener &Listener) {
3962 HeaderSearchOptions HSOpts;
3963 unsigned Idx = 0;
3964 HSOpts.Sysroot = ReadString(Record, Idx);
3965
3966 // Include entries.
3967 for (unsigned N = Record[Idx++]; N; --N) {
3968 std::string Path = ReadString(Record, Idx);
3969 frontend::IncludeDirGroup Group
3970 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003971 bool IsFramework = Record[Idx++];
3972 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003973 HSOpts.UserEntries.push_back(
Daniel Dunbar59fd6352013-01-30 00:34:26 +00003974 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003975 }
3976
3977 // System header prefixes.
3978 for (unsigned N = Record[Idx++]; N; --N) {
3979 std::string Prefix = ReadString(Record, Idx);
3980 bool IsSystemHeader = Record[Idx++];
3981 HSOpts.SystemHeaderPrefixes.push_back(
3982 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
3983 }
3984
3985 HSOpts.ResourceDir = ReadString(Record, Idx);
3986 HSOpts.ModuleCachePath = ReadString(Record, Idx);
3987 HSOpts.DisableModuleHash = Record[Idx++];
3988 HSOpts.UseBuiltinIncludes = Record[Idx++];
3989 HSOpts.UseStandardSystemIncludes = Record[Idx++];
3990 HSOpts.UseStandardCXXIncludes = Record[Idx++];
3991 HSOpts.UseLibcxx = Record[Idx++];
3992
3993 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
3994}
3995
3996bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
3997 bool Complain,
3998 ASTReaderListener &Listener,
3999 std::string &SuggestedPredefines) {
4000 PreprocessorOptions PPOpts;
4001 unsigned Idx = 0;
4002
4003 // Macro definitions/undefs
4004 for (unsigned N = Record[Idx++]; N; --N) {
4005 std::string Macro = ReadString(Record, Idx);
4006 bool IsUndef = Record[Idx++];
4007 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4008 }
4009
4010 // Includes
4011 for (unsigned N = Record[Idx++]; N; --N) {
4012 PPOpts.Includes.push_back(ReadString(Record, Idx));
4013 }
4014
4015 // Macro Includes
4016 for (unsigned N = Record[Idx++]; N; --N) {
4017 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4018 }
4019
4020 PPOpts.UsePredefines = Record[Idx++];
4021 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4022 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4023 PPOpts.ObjCXXARCStandardLibrary =
4024 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4025 SuggestedPredefines.clear();
4026 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4027 SuggestedPredefines);
4028}
4029
4030std::pair<ModuleFile *, unsigned>
4031ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4032 GlobalPreprocessedEntityMapType::iterator
4033 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4034 assert(I != GlobalPreprocessedEntityMap.end() &&
4035 "Corrupted global preprocessed entity map");
4036 ModuleFile *M = I->second;
4037 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4038 return std::make_pair(M, LocalIndex);
4039}
4040
4041std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4042ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4043 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4044 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4045 Mod.NumPreprocessedEntities);
4046
4047 return std::make_pair(PreprocessingRecord::iterator(),
4048 PreprocessingRecord::iterator());
4049}
4050
4051std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4052ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4053 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4054 ModuleDeclIterator(this, &Mod,
4055 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4056}
4057
4058PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4059 PreprocessedEntityID PPID = Index+1;
4060 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4061 ModuleFile &M = *PPInfo.first;
4062 unsigned LocalIndex = PPInfo.second;
4063 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4064
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004065 if (!PP.getPreprocessingRecord()) {
4066 Error("no preprocessing record");
4067 return 0;
4068 }
4069
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004070 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4071 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4072
4073 llvm::BitstreamEntry Entry =
4074 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4075 if (Entry.Kind != llvm::BitstreamEntry::Record)
4076 return 0;
4077
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004078 // Read the record.
4079 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4080 ReadSourceLocation(M, PPOffs.End));
4081 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004082 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004083 RecordData Record;
4084 PreprocessorDetailRecordTypes RecType =
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004085 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4086 Entry.ID, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004087 switch (RecType) {
4088 case PPD_MACRO_EXPANSION: {
4089 bool isBuiltin = Record[0];
4090 IdentifierInfo *Name = 0;
4091 MacroDefinition *Def = 0;
4092 if (isBuiltin)
4093 Name = getLocalIdentifier(M, Record[1]);
4094 else {
4095 PreprocessedEntityID
4096 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4097 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4098 }
4099
4100 MacroExpansion *ME;
4101 if (isBuiltin)
4102 ME = new (PPRec) MacroExpansion(Name, Range);
4103 else
4104 ME = new (PPRec) MacroExpansion(Def, Range);
4105
4106 return ME;
4107 }
4108
4109 case PPD_MACRO_DEFINITION: {
4110 // Decode the identifier info and then check again; if the macro is
4111 // still defined and associated with the identifier,
4112 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4113 MacroDefinition *MD
4114 = new (PPRec) MacroDefinition(II, Range);
4115
4116 if (DeserializationListener)
4117 DeserializationListener->MacroDefinitionRead(PPID, MD);
4118
4119 return MD;
4120 }
4121
4122 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004123 const char *FullFileNameStart = Blob.data() + Record[0];
4124 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004125 const FileEntry *File = 0;
4126 if (!FullFileName.empty())
4127 File = PP.getFileManager().getFile(FullFileName);
4128
4129 // FIXME: Stable encoding
4130 InclusionDirective::InclusionKind Kind
4131 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4132 InclusionDirective *ID
4133 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004134 StringRef(Blob.data(), Record[0]),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004135 Record[1], Record[3],
4136 File,
4137 Range);
4138 return ID;
4139 }
4140 }
4141
4142 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4143}
4144
4145/// \brief \arg SLocMapI points at a chunk of a module that contains no
4146/// preprocessed entities or the entities it contains are not the ones we are
4147/// looking for. Find the next module that contains entities and return the ID
4148/// of the first entry.
4149PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4150 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4151 ++SLocMapI;
4152 for (GlobalSLocOffsetMapType::const_iterator
4153 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4154 ModuleFile &M = *SLocMapI->second;
4155 if (M.NumPreprocessedEntities)
4156 return M.BasePreprocessedEntityID;
4157 }
4158
4159 return getTotalNumPreprocessedEntities();
4160}
4161
4162namespace {
4163
4164template <unsigned PPEntityOffset::*PPLoc>
4165struct PPEntityComp {
4166 const ASTReader &Reader;
4167 ModuleFile &M;
4168
4169 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4170
4171 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4172 SourceLocation LHS = getLoc(L);
4173 SourceLocation RHS = getLoc(R);
4174 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4175 }
4176
4177 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4178 SourceLocation LHS = getLoc(L);
4179 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4180 }
4181
4182 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4183 SourceLocation RHS = getLoc(R);
4184 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4185 }
4186
4187 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4188 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4189 }
4190};
4191
4192}
4193
4194/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4195PreprocessedEntityID
4196ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4197 if (SourceMgr.isLocalSourceLocation(BLoc))
4198 return getTotalNumPreprocessedEntities();
4199
4200 GlobalSLocOffsetMapType::const_iterator
4201 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00004202 BLoc.getOffset() - 1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004203 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4204 "Corrupted global sloc offset map");
4205
4206 if (SLocMapI->second->NumPreprocessedEntities == 0)
4207 return findNextPreprocessedEntity(SLocMapI);
4208
4209 ModuleFile &M = *SLocMapI->second;
4210 typedef const PPEntityOffset *pp_iterator;
4211 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4212 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4213
4214 size_t Count = M.NumPreprocessedEntities;
4215 size_t Half;
4216 pp_iterator First = pp_begin;
4217 pp_iterator PPI;
4218
4219 // Do a binary search manually instead of using std::lower_bound because
4220 // The end locations of entities may be unordered (when a macro expansion
4221 // is inside another macro argument), but for this case it is not important
4222 // whether we get the first macro expansion or its containing macro.
4223 while (Count > 0) {
4224 Half = Count/2;
4225 PPI = First;
4226 std::advance(PPI, Half);
4227 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4228 BLoc)){
4229 First = PPI;
4230 ++First;
4231 Count = Count - Half - 1;
4232 } else
4233 Count = Half;
4234 }
4235
4236 if (PPI == pp_end)
4237 return findNextPreprocessedEntity(SLocMapI);
4238
4239 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4240}
4241
4242/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4243PreprocessedEntityID
4244ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4245 if (SourceMgr.isLocalSourceLocation(ELoc))
4246 return getTotalNumPreprocessedEntities();
4247
4248 GlobalSLocOffsetMapType::const_iterator
4249 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00004250 ELoc.getOffset() - 1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004251 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4252 "Corrupted global sloc offset map");
4253
4254 if (SLocMapI->second->NumPreprocessedEntities == 0)
4255 return findNextPreprocessedEntity(SLocMapI);
4256
4257 ModuleFile &M = *SLocMapI->second;
4258 typedef const PPEntityOffset *pp_iterator;
4259 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4260 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4261 pp_iterator PPI =
4262 std::upper_bound(pp_begin, pp_end, ELoc,
4263 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4264
4265 if (PPI == pp_end)
4266 return findNextPreprocessedEntity(SLocMapI);
4267
4268 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4269}
4270
4271/// \brief Returns a pair of [Begin, End) indices of preallocated
4272/// preprocessed entities that \arg Range encompasses.
4273std::pair<unsigned, unsigned>
4274 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4275 if (Range.isInvalid())
4276 return std::make_pair(0,0);
4277 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4278
4279 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4280 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4281 return std::make_pair(BeginID, EndID);
4282}
4283
4284/// \brief Optionally returns true or false if the preallocated preprocessed
4285/// entity with index \arg Index came from file \arg FID.
David Blaikiedc84cd52013-02-20 22:23:23 +00004286Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004287 FileID FID) {
4288 if (FID.isInvalid())
4289 return false;
4290
4291 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4292 ModuleFile &M = *PPInfo.first;
4293 unsigned LocalIndex = PPInfo.second;
4294 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4295
4296 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4297 if (Loc.isInvalid())
4298 return false;
4299
4300 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4301 return true;
4302 else
4303 return false;
4304}
4305
4306namespace {
4307 /// \brief Visitor used to search for information about a header file.
4308 class HeaderFileInfoVisitor {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004309 const FileEntry *FE;
4310
David Blaikiedc84cd52013-02-20 22:23:23 +00004311 Optional<HeaderFileInfo> HFI;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004312
4313 public:
Argyrios Kyrtzidis36592b12013-03-06 18:12:44 +00004314 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4315 : FE(FE) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004316
4317 static bool visit(ModuleFile &M, void *UserData) {
4318 HeaderFileInfoVisitor *This
4319 = static_cast<HeaderFileInfoVisitor *>(UserData);
4320
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004321 HeaderFileInfoLookupTable *Table
4322 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4323 if (!Table)
4324 return false;
4325
4326 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00004327 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004328 if (Pos == Table->end())
4329 return false;
4330
4331 This->HFI = *Pos;
4332 return true;
4333 }
4334
David Blaikiedc84cd52013-02-20 22:23:23 +00004335 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004336 };
4337}
4338
4339HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis36592b12013-03-06 18:12:44 +00004340 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004341 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
David Blaikiedc84cd52013-02-20 22:23:23 +00004342 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004343 if (Listener)
4344 Listener->ReadHeaderFileInfo(*HFI, FE->getUID());
4345 return *HFI;
4346 }
4347
4348 return HeaderFileInfo();
4349}
4350
4351void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4352 // FIXME: Make it work properly with modules.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004353 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004354 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4355 ModuleFile &F = *(*I);
4356 unsigned Idx = 0;
4357 DiagStates.clear();
4358 assert(!Diag.DiagStates.empty());
4359 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4360 while (Idx < F.PragmaDiagMappings.size()) {
4361 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4362 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4363 if (DiagStateID != 0) {
4364 Diag.DiagStatePoints.push_back(
4365 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4366 FullSourceLoc(Loc, SourceMgr)));
4367 continue;
4368 }
4369
4370 assert(DiagStateID == 0);
4371 // A new DiagState was created here.
4372 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4373 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4374 DiagStates.push_back(NewState);
4375 Diag.DiagStatePoints.push_back(
4376 DiagnosticsEngine::DiagStatePoint(NewState,
4377 FullSourceLoc(Loc, SourceMgr)));
4378 while (1) {
4379 assert(Idx < F.PragmaDiagMappings.size() &&
4380 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4381 if (Idx >= F.PragmaDiagMappings.size()) {
4382 break; // Something is messed up but at least avoid infinite loop in
4383 // release build.
4384 }
4385 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4386 if (DiagID == (unsigned)-1) {
4387 break; // no more diag/map pairs for this location.
4388 }
4389 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4390 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4391 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4392 }
4393 }
4394 }
4395}
4396
4397/// \brief Get the correct cursor and offset for loading a type.
4398ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4399 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4400 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4401 ModuleFile *M = I->second;
4402 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4403}
4404
4405/// \brief Read and return the type with the given index..
4406///
4407/// The index is the type ID, shifted and minus the number of predefs. This
4408/// routine actually reads the record corresponding to the type at the given
4409/// location. It is a helper routine for GetType, which deals with reading type
4410/// IDs.
4411QualType ASTReader::readTypeRecord(unsigned Index) {
4412 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004413 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004414
4415 // Keep track of where we are in the stream, then jump back there
4416 // after reading this type.
4417 SavedStreamPosition SavedPosition(DeclsCursor);
4418
4419 ReadingKindTracker ReadingKind(Read_Type, *this);
4420
4421 // Note that we are loading a type record.
4422 Deserializing AType(this);
4423
4424 unsigned Idx = 0;
4425 DeclsCursor.JumpToBit(Loc.Offset);
4426 RecordData Record;
4427 unsigned Code = DeclsCursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004428 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004429 case TYPE_EXT_QUAL: {
4430 if (Record.size() != 2) {
4431 Error("Incorrect encoding of extended qualifier type");
4432 return QualType();
4433 }
4434 QualType Base = readType(*Loc.F, Record, Idx);
4435 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4436 return Context.getQualifiedType(Base, Quals);
4437 }
4438
4439 case TYPE_COMPLEX: {
4440 if (Record.size() != 1) {
4441 Error("Incorrect encoding of complex type");
4442 return QualType();
4443 }
4444 QualType ElemType = readType(*Loc.F, Record, Idx);
4445 return Context.getComplexType(ElemType);
4446 }
4447
4448 case TYPE_POINTER: {
4449 if (Record.size() != 1) {
4450 Error("Incorrect encoding of pointer type");
4451 return QualType();
4452 }
4453 QualType PointeeType = readType(*Loc.F, Record, Idx);
4454 return Context.getPointerType(PointeeType);
4455 }
4456
4457 case TYPE_BLOCK_POINTER: {
4458 if (Record.size() != 1) {
4459 Error("Incorrect encoding of block pointer type");
4460 return QualType();
4461 }
4462 QualType PointeeType = readType(*Loc.F, Record, Idx);
4463 return Context.getBlockPointerType(PointeeType);
4464 }
4465
4466 case TYPE_LVALUE_REFERENCE: {
4467 if (Record.size() != 2) {
4468 Error("Incorrect encoding of lvalue reference type");
4469 return QualType();
4470 }
4471 QualType PointeeType = readType(*Loc.F, Record, Idx);
4472 return Context.getLValueReferenceType(PointeeType, Record[1]);
4473 }
4474
4475 case TYPE_RVALUE_REFERENCE: {
4476 if (Record.size() != 1) {
4477 Error("Incorrect encoding of rvalue reference type");
4478 return QualType();
4479 }
4480 QualType PointeeType = readType(*Loc.F, Record, Idx);
4481 return Context.getRValueReferenceType(PointeeType);
4482 }
4483
4484 case TYPE_MEMBER_POINTER: {
4485 if (Record.size() != 2) {
4486 Error("Incorrect encoding of member pointer type");
4487 return QualType();
4488 }
4489 QualType PointeeType = readType(*Loc.F, Record, Idx);
4490 QualType ClassType = readType(*Loc.F, Record, Idx);
4491 if (PointeeType.isNull() || ClassType.isNull())
4492 return QualType();
4493
4494 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4495 }
4496
4497 case TYPE_CONSTANT_ARRAY: {
4498 QualType ElementType = readType(*Loc.F, Record, Idx);
4499 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4500 unsigned IndexTypeQuals = Record[2];
4501 unsigned Idx = 3;
4502 llvm::APInt Size = ReadAPInt(Record, Idx);
4503 return Context.getConstantArrayType(ElementType, Size,
4504 ASM, IndexTypeQuals);
4505 }
4506
4507 case TYPE_INCOMPLETE_ARRAY: {
4508 QualType ElementType = readType(*Loc.F, Record, Idx);
4509 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4510 unsigned IndexTypeQuals = Record[2];
4511 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4512 }
4513
4514 case TYPE_VARIABLE_ARRAY: {
4515 QualType ElementType = readType(*Loc.F, Record, Idx);
4516 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4517 unsigned IndexTypeQuals = Record[2];
4518 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4519 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
4520 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
4521 ASM, IndexTypeQuals,
4522 SourceRange(LBLoc, RBLoc));
4523 }
4524
4525 case TYPE_VECTOR: {
4526 if (Record.size() != 3) {
4527 Error("incorrect encoding of vector type in AST file");
4528 return QualType();
4529 }
4530
4531 QualType ElementType = readType(*Loc.F, Record, Idx);
4532 unsigned NumElements = Record[1];
4533 unsigned VecKind = Record[2];
4534 return Context.getVectorType(ElementType, NumElements,
4535 (VectorType::VectorKind)VecKind);
4536 }
4537
4538 case TYPE_EXT_VECTOR: {
4539 if (Record.size() != 3) {
4540 Error("incorrect encoding of extended vector type in AST file");
4541 return QualType();
4542 }
4543
4544 QualType ElementType = readType(*Loc.F, Record, Idx);
4545 unsigned NumElements = Record[1];
4546 return Context.getExtVectorType(ElementType, NumElements);
4547 }
4548
4549 case TYPE_FUNCTION_NO_PROTO: {
4550 if (Record.size() != 6) {
4551 Error("incorrect encoding of no-proto function type");
4552 return QualType();
4553 }
4554 QualType ResultType = readType(*Loc.F, Record, Idx);
4555 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
4556 (CallingConv)Record[4], Record[5]);
4557 return Context.getFunctionNoProtoType(ResultType, Info);
4558 }
4559
4560 case TYPE_FUNCTION_PROTO: {
4561 QualType ResultType = readType(*Loc.F, Record, Idx);
4562
4563 FunctionProtoType::ExtProtoInfo EPI;
4564 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
4565 /*hasregparm*/ Record[2],
4566 /*regparm*/ Record[3],
4567 static_cast<CallingConv>(Record[4]),
4568 /*produces*/ Record[5]);
4569
4570 unsigned Idx = 6;
4571 unsigned NumParams = Record[Idx++];
4572 SmallVector<QualType, 16> ParamTypes;
4573 for (unsigned I = 0; I != NumParams; ++I)
4574 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
4575
4576 EPI.Variadic = Record[Idx++];
4577 EPI.HasTrailingReturn = Record[Idx++];
4578 EPI.TypeQuals = Record[Idx++];
4579 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
4580 ExceptionSpecificationType EST =
4581 static_cast<ExceptionSpecificationType>(Record[Idx++]);
4582 EPI.ExceptionSpecType = EST;
4583 SmallVector<QualType, 2> Exceptions;
4584 if (EST == EST_Dynamic) {
4585 EPI.NumExceptions = Record[Idx++];
4586 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
4587 Exceptions.push_back(readType(*Loc.F, Record, Idx));
4588 EPI.Exceptions = Exceptions.data();
4589 } else if (EST == EST_ComputedNoexcept) {
4590 EPI.NoexceptExpr = ReadExpr(*Loc.F);
4591 } else if (EST == EST_Uninstantiated) {
4592 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4593 EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4594 } else if (EST == EST_Unevaluated) {
4595 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4596 }
Jordan Rosebea522f2013-03-08 21:51:21 +00004597 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004598 }
4599
4600 case TYPE_UNRESOLVED_USING: {
4601 unsigned Idx = 0;
4602 return Context.getTypeDeclType(
4603 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
4604 }
4605
4606 case TYPE_TYPEDEF: {
4607 if (Record.size() != 2) {
4608 Error("incorrect encoding of typedef type");
4609 return QualType();
4610 }
4611 unsigned Idx = 0;
4612 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
4613 QualType Canonical = readType(*Loc.F, Record, Idx);
4614 if (!Canonical.isNull())
4615 Canonical = Context.getCanonicalType(Canonical);
4616 return Context.getTypedefType(Decl, Canonical);
4617 }
4618
4619 case TYPE_TYPEOF_EXPR:
4620 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
4621
4622 case TYPE_TYPEOF: {
4623 if (Record.size() != 1) {
4624 Error("incorrect encoding of typeof(type) in AST file");
4625 return QualType();
4626 }
4627 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4628 return Context.getTypeOfType(UnderlyingType);
4629 }
4630
4631 case TYPE_DECLTYPE: {
4632 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4633 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
4634 }
4635
4636 case TYPE_UNARY_TRANSFORM: {
4637 QualType BaseType = readType(*Loc.F, Record, Idx);
4638 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4639 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
4640 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
4641 }
4642
4643 case TYPE_AUTO:
4644 return Context.getAutoType(readType(*Loc.F, Record, Idx));
4645
4646 case TYPE_RECORD: {
4647 if (Record.size() != 2) {
4648 Error("incorrect encoding of record type");
4649 return QualType();
4650 }
4651 unsigned Idx = 0;
4652 bool IsDependent = Record[Idx++];
4653 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
4654 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
4655 QualType T = Context.getRecordType(RD);
4656 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4657 return T;
4658 }
4659
4660 case TYPE_ENUM: {
4661 if (Record.size() != 2) {
4662 Error("incorrect encoding of enum type");
4663 return QualType();
4664 }
4665 unsigned Idx = 0;
4666 bool IsDependent = Record[Idx++];
4667 QualType T
4668 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
4669 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4670 return T;
4671 }
4672
4673 case TYPE_ATTRIBUTED: {
4674 if (Record.size() != 3) {
4675 Error("incorrect encoding of attributed type");
4676 return QualType();
4677 }
4678 QualType modifiedType = readType(*Loc.F, Record, Idx);
4679 QualType equivalentType = readType(*Loc.F, Record, Idx);
4680 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
4681 return Context.getAttributedType(kind, modifiedType, equivalentType);
4682 }
4683
4684 case TYPE_PAREN: {
4685 if (Record.size() != 1) {
4686 Error("incorrect encoding of paren type");
4687 return QualType();
4688 }
4689 QualType InnerType = readType(*Loc.F, Record, Idx);
4690 return Context.getParenType(InnerType);
4691 }
4692
4693 case TYPE_PACK_EXPANSION: {
4694 if (Record.size() != 2) {
4695 Error("incorrect encoding of pack expansion type");
4696 return QualType();
4697 }
4698 QualType Pattern = readType(*Loc.F, Record, Idx);
4699 if (Pattern.isNull())
4700 return QualType();
David Blaikiedc84cd52013-02-20 22:23:23 +00004701 Optional<unsigned> NumExpansions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004702 if (Record[1])
4703 NumExpansions = Record[1] - 1;
4704 return Context.getPackExpansionType(Pattern, NumExpansions);
4705 }
4706
4707 case TYPE_ELABORATED: {
4708 unsigned Idx = 0;
4709 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4710 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4711 QualType NamedType = readType(*Loc.F, Record, Idx);
4712 return Context.getElaboratedType(Keyword, NNS, NamedType);
4713 }
4714
4715 case TYPE_OBJC_INTERFACE: {
4716 unsigned Idx = 0;
4717 ObjCInterfaceDecl *ItfD
4718 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
4719 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
4720 }
4721
4722 case TYPE_OBJC_OBJECT: {
4723 unsigned Idx = 0;
4724 QualType Base = readType(*Loc.F, Record, Idx);
4725 unsigned NumProtos = Record[Idx++];
4726 SmallVector<ObjCProtocolDecl*, 4> Protos;
4727 for (unsigned I = 0; I != NumProtos; ++I)
4728 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
4729 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
4730 }
4731
4732 case TYPE_OBJC_OBJECT_POINTER: {
4733 unsigned Idx = 0;
4734 QualType Pointee = readType(*Loc.F, Record, Idx);
4735 return Context.getObjCObjectPointerType(Pointee);
4736 }
4737
4738 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
4739 unsigned Idx = 0;
4740 QualType Parm = readType(*Loc.F, Record, Idx);
4741 QualType Replacement = readType(*Loc.F, Record, Idx);
4742 return
4743 Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
4744 Replacement);
4745 }
4746
4747 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
4748 unsigned Idx = 0;
4749 QualType Parm = readType(*Loc.F, Record, Idx);
4750 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
4751 return Context.getSubstTemplateTypeParmPackType(
4752 cast<TemplateTypeParmType>(Parm),
4753 ArgPack);
4754 }
4755
4756 case TYPE_INJECTED_CLASS_NAME: {
4757 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
4758 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
4759 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
4760 // for AST reading, too much interdependencies.
4761 return
4762 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
4763 }
4764
4765 case TYPE_TEMPLATE_TYPE_PARM: {
4766 unsigned Idx = 0;
4767 unsigned Depth = Record[Idx++];
4768 unsigned Index = Record[Idx++];
4769 bool Pack = Record[Idx++];
4770 TemplateTypeParmDecl *D
4771 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
4772 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
4773 }
4774
4775 case TYPE_DEPENDENT_NAME: {
4776 unsigned Idx = 0;
4777 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4778 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4779 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4780 QualType Canon = readType(*Loc.F, Record, Idx);
4781 if (!Canon.isNull())
4782 Canon = Context.getCanonicalType(Canon);
4783 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
4784 }
4785
4786 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
4787 unsigned Idx = 0;
4788 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4789 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4790 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4791 unsigned NumArgs = Record[Idx++];
4792 SmallVector<TemplateArgument, 8> Args;
4793 Args.reserve(NumArgs);
4794 while (NumArgs--)
4795 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
4796 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
4797 Args.size(), Args.data());
4798 }
4799
4800 case TYPE_DEPENDENT_SIZED_ARRAY: {
4801 unsigned Idx = 0;
4802
4803 // ArrayType
4804 QualType ElementType = readType(*Loc.F, Record, Idx);
4805 ArrayType::ArraySizeModifier ASM
4806 = (ArrayType::ArraySizeModifier)Record[Idx++];
4807 unsigned IndexTypeQuals = Record[Idx++];
4808
4809 // DependentSizedArrayType
4810 Expr *NumElts = ReadExpr(*Loc.F);
4811 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
4812
4813 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
4814 IndexTypeQuals, Brackets);
4815 }
4816
4817 case TYPE_TEMPLATE_SPECIALIZATION: {
4818 unsigned Idx = 0;
4819 bool IsDependent = Record[Idx++];
4820 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
4821 SmallVector<TemplateArgument, 8> Args;
4822 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
4823 QualType Underlying = readType(*Loc.F, Record, Idx);
4824 QualType T;
4825 if (Underlying.isNull())
4826 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
4827 Args.size());
4828 else
4829 T = Context.getTemplateSpecializationType(Name, Args.data(),
4830 Args.size(), Underlying);
4831 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4832 return T;
4833 }
4834
4835 case TYPE_ATOMIC: {
4836 if (Record.size() != 1) {
4837 Error("Incorrect encoding of atomic type");
4838 return QualType();
4839 }
4840 QualType ValueType = readType(*Loc.F, Record, Idx);
4841 return Context.getAtomicType(ValueType);
4842 }
4843 }
4844 llvm_unreachable("Invalid TypeCode!");
4845}
4846
4847class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
4848 ASTReader &Reader;
4849 ModuleFile &F;
4850 const ASTReader::RecordData &Record;
4851 unsigned &Idx;
4852
4853 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
4854 unsigned &I) {
4855 return Reader.ReadSourceLocation(F, R, I);
4856 }
4857
4858 template<typename T>
4859 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
4860 return Reader.ReadDeclAs<T>(F, Record, Idx);
4861 }
4862
4863public:
4864 TypeLocReader(ASTReader &Reader, ModuleFile &F,
4865 const ASTReader::RecordData &Record, unsigned &Idx)
4866 : Reader(Reader), F(F), Record(Record), Idx(Idx)
4867 { }
4868
4869 // We want compile-time assurance that we've enumerated all of
4870 // these, so unfortunately we have to declare them first, then
4871 // define them out-of-line.
4872#define ABSTRACT_TYPELOC(CLASS, PARENT)
4873#define TYPELOC(CLASS, PARENT) \
4874 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
4875#include "clang/AST/TypeLocNodes.def"
4876
4877 void VisitFunctionTypeLoc(FunctionTypeLoc);
4878 void VisitArrayTypeLoc(ArrayTypeLoc);
4879};
4880
4881void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4882 // nothing to do
4883}
4884void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4885 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
4886 if (TL.needsExtraLocalData()) {
4887 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
4888 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
4889 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
4890 TL.setModeAttr(Record[Idx++]);
4891 }
4892}
4893void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
4894 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4895}
4896void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
4897 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4898}
4899void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
4900 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
4901}
4902void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
4903 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
4904}
4905void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
4906 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
4907}
4908void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
4909 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4910 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4911}
4912void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
4913 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
4914 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
4915 if (Record[Idx++])
4916 TL.setSizeExpr(Reader.ReadExpr(F));
4917 else
4918 TL.setSizeExpr(0);
4919}
4920void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
4921 VisitArrayTypeLoc(TL);
4922}
4923void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
4924 VisitArrayTypeLoc(TL);
4925}
4926void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
4927 VisitArrayTypeLoc(TL);
4928}
4929void TypeLocReader::VisitDependentSizedArrayTypeLoc(
4930 DependentSizedArrayTypeLoc TL) {
4931 VisitArrayTypeLoc(TL);
4932}
4933void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
4934 DependentSizedExtVectorTypeLoc TL) {
4935 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4936}
4937void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
4938 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4939}
4940void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
4941 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4942}
4943void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
4944 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
4945 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4946 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4947 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
4948 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
4949 TL.setArg(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
4950 }
4951}
4952void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
4953 VisitFunctionTypeLoc(TL);
4954}
4955void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
4956 VisitFunctionTypeLoc(TL);
4957}
4958void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
4959 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4960}
4961void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
4962 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4963}
4964void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
4965 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
4966 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4967 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4968}
4969void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
4970 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
4971 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4972 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4973 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4974}
4975void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
4976 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4977}
4978void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
4979 TL.setKWLoc(ReadSourceLocation(Record, Idx));
4980 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4981 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4982 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4983}
4984void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
4985 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4986}
4987void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
4988 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4989}
4990void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
4991 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4992}
4993void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4994 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
4995 if (TL.hasAttrOperand()) {
4996 SourceRange range;
4997 range.setBegin(ReadSourceLocation(Record, Idx));
4998 range.setEnd(ReadSourceLocation(Record, Idx));
4999 TL.setAttrOperandParensRange(range);
5000 }
5001 if (TL.hasAttrExprOperand()) {
5002 if (Record[Idx++])
5003 TL.setAttrExprOperand(Reader.ReadExpr(F));
5004 else
5005 TL.setAttrExprOperand(0);
5006 } else if (TL.hasAttrEnumOperand())
5007 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5008}
5009void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5010 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5011}
5012void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5013 SubstTemplateTypeParmTypeLoc TL) {
5014 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5015}
5016void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5017 SubstTemplateTypeParmPackTypeLoc TL) {
5018 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5019}
5020void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5021 TemplateSpecializationTypeLoc TL) {
5022 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5023 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5024 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5025 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5026 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5027 TL.setArgLocInfo(i,
5028 Reader.GetTemplateArgumentLocInfo(F,
5029 TL.getTypePtr()->getArg(i).getKind(),
5030 Record, Idx));
5031}
5032void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5033 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5034 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5035}
5036void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5037 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5038 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5039}
5040void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5041 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5042}
5043void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5044 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5045 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5046 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5047}
5048void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5049 DependentTemplateSpecializationTypeLoc TL) {
5050 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5051 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5052 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5053 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5054 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5055 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5056 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5057 TL.setArgLocInfo(I,
5058 Reader.GetTemplateArgumentLocInfo(F,
5059 TL.getTypePtr()->getArg(I).getKind(),
5060 Record, Idx));
5061}
5062void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5063 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5064}
5065void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5066 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5067}
5068void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5069 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5070 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5071 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5072 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5073 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5074}
5075void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5076 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5077}
5078void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5079 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5080 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5081 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5082}
5083
5084TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5085 const RecordData &Record,
5086 unsigned &Idx) {
5087 QualType InfoTy = readType(F, Record, Idx);
5088 if (InfoTy.isNull())
5089 return 0;
5090
5091 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5092 TypeLocReader TLR(*this, F, Record, Idx);
5093 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5094 TLR.Visit(TL);
5095 return TInfo;
5096}
5097
5098QualType ASTReader::GetType(TypeID ID) {
5099 unsigned FastQuals = ID & Qualifiers::FastMask;
5100 unsigned Index = ID >> Qualifiers::FastWidth;
5101
5102 if (Index < NUM_PREDEF_TYPE_IDS) {
5103 QualType T;
5104 switch ((PredefinedTypeIDs)Index) {
5105 case PREDEF_TYPE_NULL_ID: return QualType();
5106 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5107 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5108
5109 case PREDEF_TYPE_CHAR_U_ID:
5110 case PREDEF_TYPE_CHAR_S_ID:
5111 // FIXME: Check that the signedness of CharTy is correct!
5112 T = Context.CharTy;
5113 break;
5114
5115 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5116 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5117 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5118 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5119 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5120 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5121 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5122 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5123 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5124 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5125 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5126 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5127 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5128 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5129 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5130 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5131 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5132 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5133 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5134 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5135 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5136 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5137 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5138 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5139 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5140 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5141 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5142 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeib13621d2012-12-18 14:38:23 +00005143 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5144 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5145 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5146 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5147 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5148 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei21f18c42013-02-07 10:55:47 +00005149 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00005150 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005151 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5152
5153 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5154 T = Context.getAutoRRefDeductType();
5155 break;
5156
5157 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5158 T = Context.ARCUnbridgedCastTy;
5159 break;
5160
5161 case PREDEF_TYPE_VA_LIST_TAG:
5162 T = Context.getVaListTagType();
5163 break;
5164
5165 case PREDEF_TYPE_BUILTIN_FN:
5166 T = Context.BuiltinFnTy;
5167 break;
5168 }
5169
5170 assert(!T.isNull() && "Unknown predefined type");
5171 return T.withFastQualifiers(FastQuals);
5172 }
5173
5174 Index -= NUM_PREDEF_TYPE_IDS;
5175 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5176 if (TypesLoaded[Index].isNull()) {
5177 TypesLoaded[Index] = readTypeRecord(Index);
5178 if (TypesLoaded[Index].isNull())
5179 return QualType();
5180
5181 TypesLoaded[Index]->setFromAST();
5182 if (DeserializationListener)
5183 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5184 TypesLoaded[Index]);
5185 }
5186
5187 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5188}
5189
5190QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5191 return GetType(getGlobalTypeID(F, LocalID));
5192}
5193
5194serialization::TypeID
5195ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5196 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5197 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5198
5199 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5200 return LocalID;
5201
5202 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5203 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5204 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5205
5206 unsigned GlobalIndex = LocalIndex + I->second;
5207 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5208}
5209
5210TemplateArgumentLocInfo
5211ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5212 TemplateArgument::ArgKind Kind,
5213 const RecordData &Record,
5214 unsigned &Index) {
5215 switch (Kind) {
5216 case TemplateArgument::Expression:
5217 return ReadExpr(F);
5218 case TemplateArgument::Type:
5219 return GetTypeSourceInfo(F, Record, Index);
5220 case TemplateArgument::Template: {
5221 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5222 Index);
5223 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5224 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5225 SourceLocation());
5226 }
5227 case TemplateArgument::TemplateExpansion: {
5228 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5229 Index);
5230 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5231 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5232 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5233 EllipsisLoc);
5234 }
5235 case TemplateArgument::Null:
5236 case TemplateArgument::Integral:
5237 case TemplateArgument::Declaration:
5238 case TemplateArgument::NullPtr:
5239 case TemplateArgument::Pack:
5240 // FIXME: Is this right?
5241 return TemplateArgumentLocInfo();
5242 }
5243 llvm_unreachable("unexpected template argument loc");
5244}
5245
5246TemplateArgumentLoc
5247ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5248 const RecordData &Record, unsigned &Index) {
5249 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5250
5251 if (Arg.getKind() == TemplateArgument::Expression) {
5252 if (Record[Index++]) // bool InfoHasSameExpr.
5253 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5254 }
5255 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5256 Record, Index));
5257}
5258
5259Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5260 return GetDecl(ID);
5261}
5262
5263uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5264 unsigned &Idx){
5265 if (Idx >= Record.size())
5266 return 0;
5267
5268 unsigned LocalID = Record[Idx++];
5269 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5270}
5271
5272CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5273 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00005274 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005275 SavedStreamPosition SavedPosition(Cursor);
5276 Cursor.JumpToBit(Loc.Offset);
5277 ReadingKindTracker ReadingKind(Read_Decl, *this);
5278 RecordData Record;
5279 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00005280 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005281 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5282 Error("Malformed AST file: missing C++ base specifiers");
5283 return 0;
5284 }
5285
5286 unsigned Idx = 0;
5287 unsigned NumBases = Record[Idx++];
5288 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5289 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5290 for (unsigned I = 0; I != NumBases; ++I)
5291 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5292 return Bases;
5293}
5294
5295serialization::DeclID
5296ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5297 if (LocalID < NUM_PREDEF_DECL_IDS)
5298 return LocalID;
5299
5300 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5301 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5302 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5303
5304 return LocalID + I->second;
5305}
5306
5307bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5308 ModuleFile &M) const {
5309 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5310 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5311 return &M == I->second;
5312}
5313
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005314ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005315 if (!D->isFromASTFile())
5316 return 0;
5317 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5318 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5319 return I->second;
5320}
5321
5322SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5323 if (ID < NUM_PREDEF_DECL_IDS)
5324 return SourceLocation();
5325
5326 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5327
5328 if (Index > DeclsLoaded.size()) {
5329 Error("declaration ID out-of-range for AST file");
5330 return SourceLocation();
5331 }
5332
5333 if (Decl *D = DeclsLoaded[Index])
5334 return D->getLocation();
5335
5336 unsigned RawLocation = 0;
5337 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5338 return ReadSourceLocation(*Rec.F, RawLocation);
5339}
5340
5341Decl *ASTReader::GetDecl(DeclID ID) {
5342 if (ID < NUM_PREDEF_DECL_IDS) {
5343 switch ((PredefinedDeclIDs)ID) {
5344 case PREDEF_DECL_NULL_ID:
5345 return 0;
5346
5347 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5348 return Context.getTranslationUnitDecl();
5349
5350 case PREDEF_DECL_OBJC_ID_ID:
5351 return Context.getObjCIdDecl();
5352
5353 case PREDEF_DECL_OBJC_SEL_ID:
5354 return Context.getObjCSelDecl();
5355
5356 case PREDEF_DECL_OBJC_CLASS_ID:
5357 return Context.getObjCClassDecl();
5358
5359 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5360 return Context.getObjCProtocolDecl();
5361
5362 case PREDEF_DECL_INT_128_ID:
5363 return Context.getInt128Decl();
5364
5365 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5366 return Context.getUInt128Decl();
5367
5368 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5369 return Context.getObjCInstanceTypeDecl();
5370
5371 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5372 return Context.getBuiltinVaListDecl();
5373 }
5374 }
5375
5376 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5377
5378 if (Index >= DeclsLoaded.size()) {
5379 assert(0 && "declaration ID out-of-range for AST file");
5380 Error("declaration ID out-of-range for AST file");
5381 return 0;
5382 }
5383
5384 if (!DeclsLoaded[Index]) {
5385 ReadDeclRecord(ID);
5386 if (DeserializationListener)
5387 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5388 }
5389
5390 return DeclsLoaded[Index];
5391}
5392
5393DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5394 DeclID GlobalID) {
5395 if (GlobalID < NUM_PREDEF_DECL_IDS)
5396 return GlobalID;
5397
5398 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5399 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5400 ModuleFile *Owner = I->second;
5401
5402 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5403 = M.GlobalToLocalDeclIDs.find(Owner);
5404 if (Pos == M.GlobalToLocalDeclIDs.end())
5405 return 0;
5406
5407 return GlobalID - Owner->BaseDeclID + Pos->second;
5408}
5409
5410serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5411 const RecordData &Record,
5412 unsigned &Idx) {
5413 if (Idx >= Record.size()) {
5414 Error("Corrupted AST file");
5415 return 0;
5416 }
5417
5418 return getGlobalDeclID(F, Record[Idx++]);
5419}
5420
5421/// \brief Resolve the offset of a statement into a statement.
5422///
5423/// This operation will read a new statement from the external
5424/// source each time it is called, and is meant to be used via a
5425/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5426Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5427 // Switch case IDs are per Decl.
5428 ClearSwitchCaseIDs();
5429
5430 // Offset here is a global offset across the entire chain.
5431 RecordLocation Loc = getLocalBitOffset(Offset);
5432 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5433 return ReadStmtFromStream(*Loc.F);
5434}
5435
5436namespace {
5437 class FindExternalLexicalDeclsVisitor {
5438 ASTReader &Reader;
5439 const DeclContext *DC;
5440 bool (*isKindWeWant)(Decl::Kind);
5441
5442 SmallVectorImpl<Decl*> &Decls;
5443 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5444
5445 public:
5446 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5447 bool (*isKindWeWant)(Decl::Kind),
5448 SmallVectorImpl<Decl*> &Decls)
5449 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5450 {
5451 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5452 PredefsVisited[I] = false;
5453 }
5454
5455 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5456 if (Preorder)
5457 return false;
5458
5459 FindExternalLexicalDeclsVisitor *This
5460 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5461
5462 ModuleFile::DeclContextInfosMap::iterator Info
5463 = M.DeclContextInfos.find(This->DC);
5464 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5465 return false;
5466
5467 // Load all of the declaration IDs
5468 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5469 *IDE = ID + Info->second.NumLexicalDecls;
5470 ID != IDE; ++ID) {
5471 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5472 continue;
5473
5474 // Don't add predefined declarations to the lexical context more
5475 // than once.
5476 if (ID->second < NUM_PREDEF_DECL_IDS) {
5477 if (This->PredefsVisited[ID->second])
5478 continue;
5479
5480 This->PredefsVisited[ID->second] = true;
5481 }
5482
5483 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5484 if (!This->DC->isDeclInLexicalTraversal(D))
5485 This->Decls.push_back(D);
5486 }
5487 }
5488
5489 return false;
5490 }
5491 };
5492}
5493
5494ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
5495 bool (*isKindWeWant)(Decl::Kind),
5496 SmallVectorImpl<Decl*> &Decls) {
5497 // There might be lexical decls in multiple modules, for the TU at
5498 // least. Walk all of the modules in the order they were loaded.
5499 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5500 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
5501 ++NumLexicalDeclContextsRead;
5502 return ELR_Success;
5503}
5504
5505namespace {
5506
5507class DeclIDComp {
5508 ASTReader &Reader;
5509 ModuleFile &Mod;
5510
5511public:
5512 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
5513
5514 bool operator()(LocalDeclID L, LocalDeclID R) const {
5515 SourceLocation LHS = getLocation(L);
5516 SourceLocation RHS = getLocation(R);
5517 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5518 }
5519
5520 bool operator()(SourceLocation LHS, LocalDeclID R) const {
5521 SourceLocation RHS = getLocation(R);
5522 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5523 }
5524
5525 bool operator()(LocalDeclID L, SourceLocation RHS) const {
5526 SourceLocation LHS = getLocation(L);
5527 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5528 }
5529
5530 SourceLocation getLocation(LocalDeclID ID) const {
5531 return Reader.getSourceManager().getFileLoc(
5532 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
5533 }
5534};
5535
5536}
5537
5538void ASTReader::FindFileRegionDecls(FileID File,
5539 unsigned Offset, unsigned Length,
5540 SmallVectorImpl<Decl *> &Decls) {
5541 SourceManager &SM = getSourceManager();
5542
5543 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
5544 if (I == FileDeclIDs.end())
5545 return;
5546
5547 FileDeclsInfo &DInfo = I->second;
5548 if (DInfo.Decls.empty())
5549 return;
5550
5551 SourceLocation
5552 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
5553 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
5554
5555 DeclIDComp DIDComp(*this, *DInfo.Mod);
5556 ArrayRef<serialization::LocalDeclID>::iterator
5557 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5558 BeginLoc, DIDComp);
5559 if (BeginIt != DInfo.Decls.begin())
5560 --BeginIt;
5561
5562 // If we are pointing at a top-level decl inside an objc container, we need
5563 // to backtrack until we find it otherwise we will fail to report that the
5564 // region overlaps with an objc container.
5565 while (BeginIt != DInfo.Decls.begin() &&
5566 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
5567 ->isTopLevelDeclInObjCContainer())
5568 --BeginIt;
5569
5570 ArrayRef<serialization::LocalDeclID>::iterator
5571 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5572 EndLoc, DIDComp);
5573 if (EndIt != DInfo.Decls.end())
5574 ++EndIt;
5575
5576 for (ArrayRef<serialization::LocalDeclID>::iterator
5577 DIt = BeginIt; DIt != EndIt; ++DIt)
5578 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
5579}
5580
5581namespace {
5582 /// \brief ModuleFile visitor used to perform name lookup into a
5583 /// declaration context.
5584 class DeclContextNameLookupVisitor {
5585 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005586 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005587 DeclarationName Name;
5588 SmallVectorImpl<NamedDecl *> &Decls;
5589
5590 public:
5591 DeclContextNameLookupVisitor(ASTReader &Reader,
5592 SmallVectorImpl<const DeclContext *> &Contexts,
5593 DeclarationName Name,
5594 SmallVectorImpl<NamedDecl *> &Decls)
5595 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
5596
5597 static bool visit(ModuleFile &M, void *UserData) {
5598 DeclContextNameLookupVisitor *This
5599 = static_cast<DeclContextNameLookupVisitor *>(UserData);
5600
5601 // Check whether we have any visible declaration information for
5602 // this context in this module.
5603 ModuleFile::DeclContextInfosMap::iterator Info;
5604 bool FoundInfo = false;
5605 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5606 Info = M.DeclContextInfos.find(This->Contexts[I]);
5607 if (Info != M.DeclContextInfos.end() &&
5608 Info->second.NameLookupTableData) {
5609 FoundInfo = true;
5610 break;
5611 }
5612 }
5613
5614 if (!FoundInfo)
5615 return false;
5616
5617 // Look for this name within this module.
5618 ASTDeclContextNameLookupTable *LookupTable =
5619 Info->second.NameLookupTableData;
5620 ASTDeclContextNameLookupTable::iterator Pos
5621 = LookupTable->find(This->Name);
5622 if (Pos == LookupTable->end())
5623 return false;
5624
5625 bool FoundAnything = false;
5626 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
5627 for (; Data.first != Data.second; ++Data.first) {
5628 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
5629 if (!ND)
5630 continue;
5631
5632 if (ND->getDeclName() != This->Name) {
5633 // A name might be null because the decl's redeclarable part is
5634 // currently read before reading its name. The lookup is triggered by
5635 // building that decl (likely indirectly), and so it is later in the
5636 // sense of "already existing" and can be ignored here.
5637 continue;
5638 }
5639
5640 // Record this declaration.
5641 FoundAnything = true;
5642 This->Decls.push_back(ND);
5643 }
5644
5645 return FoundAnything;
5646 }
5647 };
5648}
5649
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005650/// \brief Retrieve the "definitive" module file for the definition of the
5651/// given declaration context, if there is one.
5652///
5653/// The "definitive" module file is the only place where we need to look to
5654/// find information about the declarations within the given declaration
5655/// context. For example, C++ and Objective-C classes, C structs/unions, and
5656/// Objective-C protocols, categories, and extensions are all defined in a
5657/// single place in the source code, so they have definitive module files
5658/// associated with them. C++ namespaces, on the other hand, can have
5659/// definitions in multiple different module files.
5660///
5661/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
5662/// NDEBUG checking.
5663static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
5664 ASTReader &Reader) {
Douglas Gregore0d20662013-01-22 17:08:30 +00005665 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
5666 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005667
5668 return 0;
5669}
5670
Richard Smith3646c682013-02-07 03:30:24 +00005671bool
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005672ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
5673 DeclarationName Name) {
5674 assert(DC->hasExternalVisibleStorage() &&
5675 "DeclContext has no visible decls in storage");
5676 if (!Name)
Richard Smith3646c682013-02-07 03:30:24 +00005677 return false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005678
5679 SmallVector<NamedDecl *, 64> Decls;
5680
5681 // Compute the declaration contexts we need to look into. Multiple such
5682 // declaration contexts occur when two declaration contexts from disjoint
5683 // modules get merged, e.g., when two namespaces with the same name are
5684 // independently defined in separate modules.
5685 SmallVector<const DeclContext *, 2> Contexts;
5686 Contexts.push_back(DC);
5687
5688 if (DC->isNamespace()) {
5689 MergedDeclsMap::iterator Merged
5690 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5691 if (Merged != MergedDecls.end()) {
5692 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5693 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5694 }
5695 }
5696
5697 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005698
5699 // If we can definitively determine which module file to look into,
5700 // only look there. Otherwise, look in all module files.
5701 ModuleFile *Definitive;
5702 if (Contexts.size() == 1 &&
5703 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
5704 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
5705 } else {
5706 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
5707 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005708 ++NumVisibleDeclContextsRead;
5709 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith3646c682013-02-07 03:30:24 +00005710 return !Decls.empty();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005711}
5712
5713namespace {
5714 /// \brief ModuleFile visitor used to retrieve all visible names in a
5715 /// declaration context.
5716 class DeclContextAllNamesVisitor {
5717 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005718 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005719 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > &Decls;
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005720 bool VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005721
5722 public:
5723 DeclContextAllNamesVisitor(ASTReader &Reader,
5724 SmallVectorImpl<const DeclContext *> &Contexts,
5725 llvm::DenseMap<DeclarationName,
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005726 SmallVector<NamedDecl *, 8> > &Decls,
5727 bool VisitAll)
5728 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005729
5730 static bool visit(ModuleFile &M, void *UserData) {
5731 DeclContextAllNamesVisitor *This
5732 = static_cast<DeclContextAllNamesVisitor *>(UserData);
5733
5734 // Check whether we have any visible declaration information for
5735 // this context in this module.
5736 ModuleFile::DeclContextInfosMap::iterator Info;
5737 bool FoundInfo = false;
5738 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5739 Info = M.DeclContextInfos.find(This->Contexts[I]);
5740 if (Info != M.DeclContextInfos.end() &&
5741 Info->second.NameLookupTableData) {
5742 FoundInfo = true;
5743 break;
5744 }
5745 }
5746
5747 if (!FoundInfo)
5748 return false;
5749
5750 ASTDeclContextNameLookupTable *LookupTable =
5751 Info->second.NameLookupTableData;
5752 bool FoundAnything = false;
5753 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregora6b00fc2013-01-23 22:38:11 +00005754 I = LookupTable->data_begin(), E = LookupTable->data_end();
5755 I != E;
5756 ++I) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005757 ASTDeclContextNameLookupTrait::data_type Data = *I;
5758 for (; Data.first != Data.second; ++Data.first) {
5759 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
5760 *Data.first);
5761 if (!ND)
5762 continue;
5763
5764 // Record this declaration.
5765 FoundAnything = true;
5766 This->Decls[ND->getDeclName()].push_back(ND);
5767 }
5768 }
5769
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005770 return FoundAnything && !This->VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005771 }
5772 };
5773}
5774
5775void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
5776 if (!DC->hasExternalVisibleStorage())
5777 return;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005778 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > Decls;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005779
5780 // Compute the declaration contexts we need to look into. Multiple such
5781 // declaration contexts occur when two declaration contexts from disjoint
5782 // modules get merged, e.g., when two namespaces with the same name are
5783 // independently defined in separate modules.
5784 SmallVector<const DeclContext *, 2> Contexts;
5785 Contexts.push_back(DC);
5786
5787 if (DC->isNamespace()) {
5788 MergedDeclsMap::iterator Merged
5789 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5790 if (Merged != MergedDecls.end()) {
5791 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5792 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5793 }
5794 }
5795
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005796 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
5797 /*VisitAll=*/DC->isFileContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005798 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
5799 ++NumVisibleDeclContextsRead;
5800
5801 for (llvm::DenseMap<DeclarationName,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005802 SmallVector<NamedDecl *, 8> >::iterator
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005803 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
5804 SetExternalVisibleDeclsForName(DC, I->first, I->second);
5805 }
5806 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
5807}
5808
5809/// \brief Under non-PCH compilation the consumer receives the objc methods
5810/// before receiving the implementation, and codegen depends on this.
5811/// We simulate this by deserializing and passing to consumer the methods of the
5812/// implementation before passing the deserialized implementation decl.
5813static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
5814 ASTConsumer *Consumer) {
5815 assert(ImplD && Consumer);
5816
5817 for (ObjCImplDecl::method_iterator
5818 I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
5819 Consumer->HandleInterestingDecl(DeclGroupRef(*I));
5820
5821 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
5822}
5823
5824void ASTReader::PassInterestingDeclsToConsumer() {
5825 assert(Consumer);
5826 while (!InterestingDecls.empty()) {
5827 Decl *D = InterestingDecls.front();
5828 InterestingDecls.pop_front();
5829
5830 PassInterestingDeclToConsumer(D);
5831 }
5832}
5833
5834void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
5835 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5836 PassObjCImplDeclToConsumer(ImplD, Consumer);
5837 else
5838 Consumer->HandleInterestingDecl(DeclGroupRef(D));
5839}
5840
5841void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
5842 this->Consumer = Consumer;
5843
5844 if (!Consumer)
5845 return;
5846
5847 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
5848 // Force deserialization of this decl, which will cause it to be queued for
5849 // passing to the consumer.
5850 GetDecl(ExternalDefinitions[I]);
5851 }
5852 ExternalDefinitions.clear();
5853
5854 PassInterestingDeclsToConsumer();
5855}
5856
5857void ASTReader::PrintStats() {
5858 std::fprintf(stderr, "*** AST File Statistics:\n");
5859
5860 unsigned NumTypesLoaded
5861 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
5862 QualType());
5863 unsigned NumDeclsLoaded
5864 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
5865 (Decl *)0);
5866 unsigned NumIdentifiersLoaded
5867 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
5868 IdentifiersLoaded.end(),
5869 (IdentifierInfo *)0);
5870 unsigned NumMacrosLoaded
5871 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
5872 MacrosLoaded.end(),
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00005873 (MacroInfo *)0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005874 unsigned NumSelectorsLoaded
5875 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
5876 SelectorsLoaded.end(),
5877 Selector());
5878
5879 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
5880 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
5881 NumSLocEntriesRead, TotalNumSLocEntries,
5882 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
5883 if (!TypesLoaded.empty())
5884 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
5885 NumTypesLoaded, (unsigned)TypesLoaded.size(),
5886 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
5887 if (!DeclsLoaded.empty())
5888 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
5889 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
5890 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
5891 if (!IdentifiersLoaded.empty())
5892 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
5893 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
5894 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
5895 if (!MacrosLoaded.empty())
5896 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5897 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
5898 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
5899 if (!SelectorsLoaded.empty())
5900 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
5901 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
5902 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
5903 if (TotalNumStatements)
5904 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
5905 NumStatementsRead, TotalNumStatements,
5906 ((float)NumStatementsRead/TotalNumStatements * 100));
5907 if (TotalNumMacros)
5908 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5909 NumMacrosRead, TotalNumMacros,
5910 ((float)NumMacrosRead/TotalNumMacros * 100));
5911 if (TotalLexicalDeclContexts)
5912 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
5913 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
5914 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
5915 * 100));
5916 if (TotalVisibleDeclContexts)
5917 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
5918 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
5919 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
5920 * 100));
5921 if (TotalNumMethodPoolEntries) {
5922 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
5923 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
5924 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
5925 * 100));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005926 }
Douglas Gregor95fb36e2013-01-28 17:54:36 +00005927 if (NumMethodPoolLookups) {
5928 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
5929 NumMethodPoolHits, NumMethodPoolLookups,
5930 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
5931 }
5932 if (NumMethodPoolTableLookups) {
5933 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
5934 NumMethodPoolTableHits, NumMethodPoolTableLookups,
5935 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
5936 * 100.0));
5937 }
5938
Douglas Gregore1698072013-01-25 00:38:33 +00005939 if (NumIdentifierLookupHits) {
5940 std::fprintf(stderr,
5941 " %u / %u identifier table lookups succeeded (%f%%)\n",
5942 NumIdentifierLookupHits, NumIdentifierLookups,
5943 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
5944 }
5945
Douglas Gregor1a49d972013-01-25 01:03:03 +00005946 if (GlobalIndex) {
5947 std::fprintf(stderr, "\n");
5948 GlobalIndex->printStats();
5949 }
5950
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005951 std::fprintf(stderr, "\n");
5952 dump();
5953 std::fprintf(stderr, "\n");
5954}
5955
5956template<typename Key, typename ModuleFile, unsigned InitialCapacity>
5957static void
5958dumpModuleIDMap(StringRef Name,
5959 const ContinuousRangeMap<Key, ModuleFile *,
5960 InitialCapacity> &Map) {
5961 if (Map.begin() == Map.end())
5962 return;
5963
5964 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
5965 llvm::errs() << Name << ":\n";
5966 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
5967 I != IEnd; ++I) {
5968 llvm::errs() << " " << I->first << " -> " << I->second->FileName
5969 << "\n";
5970 }
5971}
5972
5973void ASTReader::dump() {
5974 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
5975 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
5976 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
5977 dumpModuleIDMap("Global type map", GlobalTypeMap);
5978 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
5979 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
5980 dumpModuleIDMap("Global macro map", GlobalMacroMap);
5981 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
5982 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
5983 dumpModuleIDMap("Global preprocessed entity map",
5984 GlobalPreprocessedEntityMap);
5985
5986 llvm::errs() << "\n*** PCH/Modules Loaded:";
5987 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
5988 MEnd = ModuleMgr.end();
5989 M != MEnd; ++M)
5990 (*M)->dump();
5991}
5992
5993/// Return the amount of memory used by memory buffers, breaking down
5994/// by heap-backed versus mmap'ed memory.
5995void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
5996 for (ModuleConstIterator I = ModuleMgr.begin(),
5997 E = ModuleMgr.end(); I != E; ++I) {
5998 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
5999 size_t bytes = buf->getBufferSize();
6000 switch (buf->getBufferKind()) {
6001 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6002 sizes.malloc_bytes += bytes;
6003 break;
6004 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6005 sizes.mmap_bytes += bytes;
6006 break;
6007 }
6008 }
6009 }
6010}
6011
6012void ASTReader::InitializeSema(Sema &S) {
6013 SemaObj = &S;
6014 S.addExternalSource(this);
6015
6016 // Makes sure any declarations that were deserialized "too early"
6017 // still get added to the identifier's declaration chains.
6018 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Douglas Gregoraa945902013-02-18 15:53:43 +00006019 NamedDecl *ND = cast<NamedDecl>(PreloadedDecls[I]->getMostRecentDecl());
6020 SemaObj->pushExternalDeclIntoScope(ND, PreloadedDecls[I]->getDeclName());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006021 }
6022 PreloadedDecls.clear();
6023
6024 // Load the offsets of the declarations that Sema references.
6025 // They will be lazily deserialized when needed.
6026 if (!SemaDeclRefs.empty()) {
6027 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
6028 if (!SemaObj->StdNamespace)
6029 SemaObj->StdNamespace = SemaDeclRefs[0];
6030 if (!SemaObj->StdBadAlloc)
6031 SemaObj->StdBadAlloc = SemaDeclRefs[1];
6032 }
6033
6034 if (!FPPragmaOptions.empty()) {
6035 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6036 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6037 }
6038
6039 if (!OpenCLExtensions.empty()) {
6040 unsigned I = 0;
6041#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6042#include "clang/Basic/OpenCLExtensions.def"
6043
6044 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6045 }
6046}
6047
6048IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6049 // Note that we are loading an identifier.
6050 Deserializing AnIdentifier(this);
Douglas Gregor1a49d972013-01-25 01:03:03 +00006051 StringRef Name(NameStart, NameEnd - NameStart);
6052
6053 // If there is a global index, look there first to determine which modules
6054 // provably do not have any results for this identifier.
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006055 GlobalModuleIndex::HitSet Hits;
6056 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregor1a49d972013-01-25 01:03:03 +00006057 if (!loadGlobalIndex()) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006058 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6059 HitsPtr = &Hits;
Douglas Gregor1a49d972013-01-25 01:03:03 +00006060 }
6061 }
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006062 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregore1698072013-01-25 00:38:33 +00006063 NumIdentifierLookups,
6064 NumIdentifierLookupHits);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006065 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006066 IdentifierInfo *II = Visitor.getIdentifierInfo();
6067 markIdentifierUpToDate(II);
6068 return II;
6069}
6070
6071namespace clang {
6072 /// \brief An identifier-lookup iterator that enumerates all of the
6073 /// identifiers stored within a set of AST files.
6074 class ASTIdentifierIterator : public IdentifierIterator {
6075 /// \brief The AST reader whose identifiers are being enumerated.
6076 const ASTReader &Reader;
6077
6078 /// \brief The current index into the chain of AST files stored in
6079 /// the AST reader.
6080 unsigned Index;
6081
6082 /// \brief The current position within the identifier lookup table
6083 /// of the current AST file.
6084 ASTIdentifierLookupTable::key_iterator Current;
6085
6086 /// \brief The end position within the identifier lookup table of
6087 /// the current AST file.
6088 ASTIdentifierLookupTable::key_iterator End;
6089
6090 public:
6091 explicit ASTIdentifierIterator(const ASTReader &Reader);
6092
6093 virtual StringRef Next();
6094 };
6095}
6096
6097ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6098 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6099 ASTIdentifierLookupTable *IdTable
6100 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6101 Current = IdTable->key_begin();
6102 End = IdTable->key_end();
6103}
6104
6105StringRef ASTIdentifierIterator::Next() {
6106 while (Current == End) {
6107 // If we have exhausted all of our AST files, we're done.
6108 if (Index == 0)
6109 return StringRef();
6110
6111 --Index;
6112 ASTIdentifierLookupTable *IdTable
6113 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6114 IdentifierLookupTable;
6115 Current = IdTable->key_begin();
6116 End = IdTable->key_end();
6117 }
6118
6119 // We have any identifiers remaining in the current AST file; return
6120 // the next one.
Douglas Gregor479633c2013-01-23 18:53:14 +00006121 StringRef Result = *Current;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006122 ++Current;
Douglas Gregor479633c2013-01-23 18:53:14 +00006123 return Result;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006124}
6125
6126IdentifierIterator *ASTReader::getIdentifiers() const {
6127 return new ASTIdentifierIterator(*this);
6128}
6129
6130namespace clang { namespace serialization {
6131 class ReadMethodPoolVisitor {
6132 ASTReader &Reader;
6133 Selector Sel;
6134 unsigned PriorGeneration;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006135 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6136 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006137
6138 public:
6139 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6140 unsigned PriorGeneration)
6141 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) { }
6142
6143 static bool visit(ModuleFile &M, void *UserData) {
6144 ReadMethodPoolVisitor *This
6145 = static_cast<ReadMethodPoolVisitor *>(UserData);
6146
6147 if (!M.SelectorLookupTable)
6148 return false;
6149
6150 // If we've already searched this module file, skip it now.
6151 if (M.Generation <= This->PriorGeneration)
6152 return true;
6153
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006154 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006155 ASTSelectorLookupTable *PoolTable
6156 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6157 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6158 if (Pos == PoolTable->end())
6159 return false;
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006160
6161 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006162 ++This->Reader.NumSelectorsRead;
6163 // FIXME: Not quite happy with the statistics here. We probably should
6164 // disable this tracking when called via LoadSelector.
6165 // Also, should entries without methods count as misses?
6166 ++This->Reader.NumMethodPoolEntriesRead;
6167 ASTSelectorLookupTrait::data_type Data = *Pos;
6168 if (This->Reader.DeserializationListener)
6169 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6170 This->Sel);
6171
6172 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6173 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6174 return true;
6175 }
6176
6177 /// \brief Retrieve the instance methods found by this visitor.
6178 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6179 return InstanceMethods;
6180 }
6181
6182 /// \brief Retrieve the instance methods found by this visitor.
6183 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6184 return FactoryMethods;
6185 }
6186 };
6187} } // end namespace clang::serialization
6188
6189/// \brief Add the given set of methods to the method list.
6190static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6191 ObjCMethodList &List) {
6192 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6193 S.addMethodToGlobalList(&List, Methods[I]);
6194 }
6195}
6196
6197void ASTReader::ReadMethodPool(Selector Sel) {
6198 // Get the selector generation and update it to the current generation.
6199 unsigned &Generation = SelectorGeneration[Sel];
6200 unsigned PriorGeneration = Generation;
6201 Generation = CurrentGeneration;
6202
6203 // Search for methods defined with this selector.
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006204 ++NumMethodPoolLookups;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006205 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6206 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6207
6208 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006209 Visitor.getFactoryMethods().empty())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006210 return;
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006211
6212 ++NumMethodPoolHits;
6213
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006214 if (!getSema())
6215 return;
6216
6217 Sema &S = *getSema();
6218 Sema::GlobalMethodPool::iterator Pos
6219 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6220
6221 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6222 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
6223}
6224
6225void ASTReader::ReadKnownNamespaces(
6226 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6227 Namespaces.clear();
6228
6229 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6230 if (NamespaceDecl *Namespace
6231 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6232 Namespaces.push_back(Namespace);
6233 }
6234}
6235
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006236void ASTReader::ReadUndefinedButUsed(
Nick Lewycky995e26b2013-01-31 03:23:57 +00006237 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006238 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6239 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky01a41142013-01-26 00:35:08 +00006240 SourceLocation Loc =
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006241 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky01a41142013-01-26 00:35:08 +00006242 Undefined.insert(std::make_pair(D, Loc));
6243 }
6244}
Nick Lewycky01a41142013-01-26 00:35:08 +00006245
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006246void ASTReader::ReadTentativeDefinitions(
6247 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6248 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6249 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6250 if (Var)
6251 TentativeDefs.push_back(Var);
6252 }
6253 TentativeDefinitions.clear();
6254}
6255
6256void ASTReader::ReadUnusedFileScopedDecls(
6257 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6258 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6259 DeclaratorDecl *D
6260 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6261 if (D)
6262 Decls.push_back(D);
6263 }
6264 UnusedFileScopedDecls.clear();
6265}
6266
6267void ASTReader::ReadDelegatingConstructors(
6268 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6269 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6270 CXXConstructorDecl *D
6271 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6272 if (D)
6273 Decls.push_back(D);
6274 }
6275 DelegatingCtorDecls.clear();
6276}
6277
6278void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6279 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6280 TypedefNameDecl *D
6281 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6282 if (D)
6283 Decls.push_back(D);
6284 }
6285 ExtVectorDecls.clear();
6286}
6287
6288void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6289 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6290 CXXRecordDecl *D
6291 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6292 if (D)
6293 Decls.push_back(D);
6294 }
6295 DynamicClasses.clear();
6296}
6297
6298void
Richard Smith5ea6ef42013-01-10 23:43:47 +00006299ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6300 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6301 NamedDecl *D
6302 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006303 if (D)
6304 Decls.push_back(D);
6305 }
Richard Smith5ea6ef42013-01-10 23:43:47 +00006306 LocallyScopedExternCDecls.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006307}
6308
6309void ASTReader::ReadReferencedSelectors(
6310 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6311 if (ReferencedSelectorsData.empty())
6312 return;
6313
6314 // If there are @selector references added them to its pool. This is for
6315 // implementation of -Wselector.
6316 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6317 unsigned I = 0;
6318 while (I < DataSize) {
6319 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6320 SourceLocation SelLoc
6321 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6322 Sels.push_back(std::make_pair(Sel, SelLoc));
6323 }
6324 ReferencedSelectorsData.clear();
6325}
6326
6327void ASTReader::ReadWeakUndeclaredIdentifiers(
6328 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6329 if (WeakUndeclaredIdentifiers.empty())
6330 return;
6331
6332 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6333 IdentifierInfo *WeakId
6334 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6335 IdentifierInfo *AliasId
6336 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6337 SourceLocation Loc
6338 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6339 bool Used = WeakUndeclaredIdentifiers[I++];
6340 WeakInfo WI(AliasId, Loc);
6341 WI.setUsed(Used);
6342 WeakIDs.push_back(std::make_pair(WeakId, WI));
6343 }
6344 WeakUndeclaredIdentifiers.clear();
6345}
6346
6347void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6348 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6349 ExternalVTableUse VT;
6350 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6351 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6352 VT.DefinitionRequired = VTableUses[Idx++];
6353 VTables.push_back(VT);
6354 }
6355
6356 VTableUses.clear();
6357}
6358
6359void ASTReader::ReadPendingInstantiations(
6360 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6361 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6362 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6363 SourceLocation Loc
6364 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6365
6366 Pending.push_back(std::make_pair(D, Loc));
6367 }
6368 PendingInstantiations.clear();
6369}
6370
6371void ASTReader::LoadSelector(Selector Sel) {
6372 // It would be complicated to avoid reading the methods anyway. So don't.
6373 ReadMethodPool(Sel);
6374}
6375
6376void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6377 assert(ID && "Non-zero identifier ID required");
6378 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6379 IdentifiersLoaded[ID - 1] = II;
6380 if (DeserializationListener)
6381 DeserializationListener->IdentifierRead(ID, II);
6382}
6383
6384/// \brief Set the globally-visible declarations associated with the given
6385/// identifier.
6386///
6387/// If the AST reader is currently in a state where the given declaration IDs
6388/// cannot safely be resolved, they are queued until it is safe to resolve
6389/// them.
6390///
6391/// \param II an IdentifierInfo that refers to one or more globally-visible
6392/// declarations.
6393///
6394/// \param DeclIDs the set of declaration IDs with the name @p II that are
6395/// visible at global scope.
6396///
Douglas Gregoraa945902013-02-18 15:53:43 +00006397/// \param Decls if non-null, this vector will be populated with the set of
6398/// deserialized declarations. These declarations will not be pushed into
6399/// scope.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006400void
6401ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6402 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregoraa945902013-02-18 15:53:43 +00006403 SmallVectorImpl<Decl *> *Decls) {
6404 if (NumCurrentElementsDeserializing && !Decls) {
6405 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006406 return;
6407 }
6408
6409 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6410 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6411 if (SemaObj) {
Douglas Gregoraa945902013-02-18 15:53:43 +00006412 // If we're simply supposed to record the declarations, do so now.
6413 if (Decls) {
6414 Decls->push_back(D);
6415 continue;
6416 }
6417
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006418 // Introduce this declaration into the translation-unit scope
6419 // and add it to the declaration chain for this identifier, so
6420 // that (unqualified) name lookup will find it.
Douglas Gregoraa945902013-02-18 15:53:43 +00006421 NamedDecl *ND = cast<NamedDecl>(D->getMostRecentDecl());
6422 SemaObj->pushExternalDeclIntoScope(ND, II);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006423 } else {
6424 // Queue this declaration so that it will be added to the
6425 // translation unit scope and identifier's declaration chain
6426 // once a Sema object is known.
6427 PreloadedDecls.push_back(D);
6428 }
6429 }
6430}
6431
Douglas Gregor8222b892013-01-21 16:52:34 +00006432IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006433 if (ID == 0)
6434 return 0;
6435
6436 if (IdentifiersLoaded.empty()) {
6437 Error("no identifier table in AST file");
6438 return 0;
6439 }
6440
6441 ID -= 1;
6442 if (!IdentifiersLoaded[ID]) {
6443 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6444 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
6445 ModuleFile *M = I->second;
6446 unsigned Index = ID - M->BaseIdentifierID;
6447 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
6448
6449 // All of the strings in the AST file are preceded by a 16-bit length.
6450 // Extract that 16-bit length to avoid having to execute strlen().
6451 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6452 // unsigned integers. This is important to avoid integer overflow when
6453 // we cast them to 'unsigned'.
6454 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
6455 unsigned StrLen = (((unsigned) StrLenPtr[0])
6456 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregor8222b892013-01-21 16:52:34 +00006457 IdentifiersLoaded[ID]
6458 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006459 if (DeserializationListener)
6460 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
6461 }
6462
6463 return IdentifiersLoaded[ID];
6464}
6465
Douglas Gregor8222b892013-01-21 16:52:34 +00006466IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
6467 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006468}
6469
6470IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
6471 if (LocalID < NUM_PREDEF_IDENT_IDS)
6472 return LocalID;
6473
6474 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6475 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6476 assert(I != M.IdentifierRemap.end()
6477 && "Invalid index into identifier index remap");
6478
6479 return LocalID + I->second;
6480}
6481
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00006482MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006483 if (ID == 0)
6484 return 0;
6485
6486 if (MacrosLoaded.empty()) {
6487 Error("no macro table in AST file");
6488 return 0;
6489 }
6490
6491 ID -= NUM_PREDEF_MACRO_IDS;
6492 if (!MacrosLoaded[ID]) {
6493 GlobalMacroMapType::iterator I
6494 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
6495 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
6496 ModuleFile *M = I->second;
6497 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00006498 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
6499
6500 if (DeserializationListener)
6501 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
6502 MacrosLoaded[ID]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006503 }
6504
6505 return MacrosLoaded[ID];
6506}
6507
6508MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
6509 if (LocalID < NUM_PREDEF_MACRO_IDS)
6510 return LocalID;
6511
6512 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6513 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
6514 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
6515
6516 return LocalID + I->second;
6517}
6518
6519serialization::SubmoduleID
6520ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
6521 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
6522 return LocalID;
6523
6524 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6525 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
6526 assert(I != M.SubmoduleRemap.end()
6527 && "Invalid index into submodule index remap");
6528
6529 return LocalID + I->second;
6530}
6531
6532Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
6533 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6534 assert(GlobalID == 0 && "Unhandled global submodule ID");
6535 return 0;
6536 }
6537
6538 if (GlobalID > SubmodulesLoaded.size()) {
6539 Error("submodule ID out of range in AST file");
6540 return 0;
6541 }
6542
6543 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
6544}
Douglas Gregorca2ab452013-01-12 01:29:50 +00006545
6546Module *ASTReader::getModule(unsigned ID) {
6547 return getSubmodule(ID);
6548}
6549
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006550Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
6551 return DecodeSelector(getGlobalSelectorID(M, LocalID));
6552}
6553
6554Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
6555 if (ID == 0)
6556 return Selector();
6557
6558 if (ID > SelectorsLoaded.size()) {
6559 Error("selector ID out of range in AST file");
6560 return Selector();
6561 }
6562
6563 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
6564 // Load this selector from the selector table.
6565 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
6566 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
6567 ModuleFile &M = *I->second;
6568 ASTSelectorLookupTrait Trait(*this, M);
6569 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
6570 SelectorsLoaded[ID - 1] =
6571 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
6572 if (DeserializationListener)
6573 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
6574 }
6575
6576 return SelectorsLoaded[ID - 1];
6577}
6578
6579Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
6580 return DecodeSelector(ID);
6581}
6582
6583uint32_t ASTReader::GetNumExternalSelectors() {
6584 // ID 0 (the null selector) is considered an external selector.
6585 return getTotalNumSelectors() + 1;
6586}
6587
6588serialization::SelectorID
6589ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
6590 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
6591 return LocalID;
6592
6593 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6594 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
6595 assert(I != M.SelectorRemap.end()
6596 && "Invalid index into selector index remap");
6597
6598 return LocalID + I->second;
6599}
6600
6601DeclarationName
6602ASTReader::ReadDeclarationName(ModuleFile &F,
6603 const RecordData &Record, unsigned &Idx) {
6604 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
6605 switch (Kind) {
6606 case DeclarationName::Identifier:
Douglas Gregor8222b892013-01-21 16:52:34 +00006607 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006608
6609 case DeclarationName::ObjCZeroArgSelector:
6610 case DeclarationName::ObjCOneArgSelector:
6611 case DeclarationName::ObjCMultiArgSelector:
6612 return DeclarationName(ReadSelector(F, Record, Idx));
6613
6614 case DeclarationName::CXXConstructorName:
6615 return Context.DeclarationNames.getCXXConstructorName(
6616 Context.getCanonicalType(readType(F, Record, Idx)));
6617
6618 case DeclarationName::CXXDestructorName:
6619 return Context.DeclarationNames.getCXXDestructorName(
6620 Context.getCanonicalType(readType(F, Record, Idx)));
6621
6622 case DeclarationName::CXXConversionFunctionName:
6623 return Context.DeclarationNames.getCXXConversionFunctionName(
6624 Context.getCanonicalType(readType(F, Record, Idx)));
6625
6626 case DeclarationName::CXXOperatorName:
6627 return Context.DeclarationNames.getCXXOperatorName(
6628 (OverloadedOperatorKind)Record[Idx++]);
6629
6630 case DeclarationName::CXXLiteralOperatorName:
6631 return Context.DeclarationNames.getCXXLiteralOperatorName(
6632 GetIdentifierInfo(F, Record, Idx));
6633
6634 case DeclarationName::CXXUsingDirective:
6635 return DeclarationName::getUsingDirectiveName();
6636 }
6637
6638 llvm_unreachable("Invalid NameKind!");
6639}
6640
6641void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
6642 DeclarationNameLoc &DNLoc,
6643 DeclarationName Name,
6644 const RecordData &Record, unsigned &Idx) {
6645 switch (Name.getNameKind()) {
6646 case DeclarationName::CXXConstructorName:
6647 case DeclarationName::CXXDestructorName:
6648 case DeclarationName::CXXConversionFunctionName:
6649 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
6650 break;
6651
6652 case DeclarationName::CXXOperatorName:
6653 DNLoc.CXXOperatorName.BeginOpNameLoc
6654 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6655 DNLoc.CXXOperatorName.EndOpNameLoc
6656 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6657 break;
6658
6659 case DeclarationName::CXXLiteralOperatorName:
6660 DNLoc.CXXLiteralOperatorName.OpNameLoc
6661 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6662 break;
6663
6664 case DeclarationName::Identifier:
6665 case DeclarationName::ObjCZeroArgSelector:
6666 case DeclarationName::ObjCOneArgSelector:
6667 case DeclarationName::ObjCMultiArgSelector:
6668 case DeclarationName::CXXUsingDirective:
6669 break;
6670 }
6671}
6672
6673void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
6674 DeclarationNameInfo &NameInfo,
6675 const RecordData &Record, unsigned &Idx) {
6676 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
6677 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
6678 DeclarationNameLoc DNLoc;
6679 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
6680 NameInfo.setInfo(DNLoc);
6681}
6682
6683void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
6684 const RecordData &Record, unsigned &Idx) {
6685 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
6686 unsigned NumTPLists = Record[Idx++];
6687 Info.NumTemplParamLists = NumTPLists;
6688 if (NumTPLists) {
6689 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
6690 for (unsigned i=0; i != NumTPLists; ++i)
6691 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
6692 }
6693}
6694
6695TemplateName
6696ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
6697 unsigned &Idx) {
6698 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
6699 switch (Kind) {
6700 case TemplateName::Template:
6701 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
6702
6703 case TemplateName::OverloadedTemplate: {
6704 unsigned size = Record[Idx++];
6705 UnresolvedSet<8> Decls;
6706 while (size--)
6707 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
6708
6709 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
6710 }
6711
6712 case TemplateName::QualifiedTemplate: {
6713 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6714 bool hasTemplKeyword = Record[Idx++];
6715 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
6716 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
6717 }
6718
6719 case TemplateName::DependentTemplate: {
6720 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6721 if (Record[Idx++]) // isIdentifier
6722 return Context.getDependentTemplateName(NNS,
6723 GetIdentifierInfo(F, Record,
6724 Idx));
6725 return Context.getDependentTemplateName(NNS,
6726 (OverloadedOperatorKind)Record[Idx++]);
6727 }
6728
6729 case TemplateName::SubstTemplateTemplateParm: {
6730 TemplateTemplateParmDecl *param
6731 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6732 if (!param) return TemplateName();
6733 TemplateName replacement = ReadTemplateName(F, Record, Idx);
6734 return Context.getSubstTemplateTemplateParm(param, replacement);
6735 }
6736
6737 case TemplateName::SubstTemplateTemplateParmPack: {
6738 TemplateTemplateParmDecl *Param
6739 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6740 if (!Param)
6741 return TemplateName();
6742
6743 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
6744 if (ArgPack.getKind() != TemplateArgument::Pack)
6745 return TemplateName();
6746
6747 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
6748 }
6749 }
6750
6751 llvm_unreachable("Unhandled template name kind!");
6752}
6753
6754TemplateArgument
6755ASTReader::ReadTemplateArgument(ModuleFile &F,
6756 const RecordData &Record, unsigned &Idx) {
6757 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
6758 switch (Kind) {
6759 case TemplateArgument::Null:
6760 return TemplateArgument();
6761 case TemplateArgument::Type:
6762 return TemplateArgument(readType(F, Record, Idx));
6763 case TemplateArgument::Declaration: {
6764 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
6765 bool ForReferenceParam = Record[Idx++];
6766 return TemplateArgument(D, ForReferenceParam);
6767 }
6768 case TemplateArgument::NullPtr:
6769 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
6770 case TemplateArgument::Integral: {
6771 llvm::APSInt Value = ReadAPSInt(Record, Idx);
6772 QualType T = readType(F, Record, Idx);
6773 return TemplateArgument(Context, Value, T);
6774 }
6775 case TemplateArgument::Template:
6776 return TemplateArgument(ReadTemplateName(F, Record, Idx));
6777 case TemplateArgument::TemplateExpansion: {
6778 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikiedc84cd52013-02-20 22:23:23 +00006779 Optional<unsigned> NumTemplateExpansions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006780 if (unsigned NumExpansions = Record[Idx++])
6781 NumTemplateExpansions = NumExpansions - 1;
6782 return TemplateArgument(Name, NumTemplateExpansions);
6783 }
6784 case TemplateArgument::Expression:
6785 return TemplateArgument(ReadExpr(F));
6786 case TemplateArgument::Pack: {
6787 unsigned NumArgs = Record[Idx++];
6788 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
6789 for (unsigned I = 0; I != NumArgs; ++I)
6790 Args[I] = ReadTemplateArgument(F, Record, Idx);
6791 return TemplateArgument(Args, NumArgs);
6792 }
6793 }
6794
6795 llvm_unreachable("Unhandled template argument kind!");
6796}
6797
6798TemplateParameterList *
6799ASTReader::ReadTemplateParameterList(ModuleFile &F,
6800 const RecordData &Record, unsigned &Idx) {
6801 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
6802 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
6803 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
6804
6805 unsigned NumParams = Record[Idx++];
6806 SmallVector<NamedDecl *, 16> Params;
6807 Params.reserve(NumParams);
6808 while (NumParams--)
6809 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
6810
6811 TemplateParameterList* TemplateParams =
6812 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
6813 Params.data(), Params.size(), RAngleLoc);
6814 return TemplateParams;
6815}
6816
6817void
6818ASTReader::
6819ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
6820 ModuleFile &F, const RecordData &Record,
6821 unsigned &Idx) {
6822 unsigned NumTemplateArgs = Record[Idx++];
6823 TemplArgs.reserve(NumTemplateArgs);
6824 while (NumTemplateArgs--)
6825 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
6826}
6827
6828/// \brief Read a UnresolvedSet structure.
6829void ASTReader::ReadUnresolvedSet(ModuleFile &F, ASTUnresolvedSet &Set,
6830 const RecordData &Record, unsigned &Idx) {
6831 unsigned NumDecls = Record[Idx++];
6832 Set.reserve(Context, NumDecls);
6833 while (NumDecls--) {
6834 NamedDecl *D = ReadDeclAs<NamedDecl>(F, Record, Idx);
6835 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
6836 Set.addDecl(Context, D, AS);
6837 }
6838}
6839
6840CXXBaseSpecifier
6841ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
6842 const RecordData &Record, unsigned &Idx) {
6843 bool isVirtual = static_cast<bool>(Record[Idx++]);
6844 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
6845 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
6846 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
6847 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
6848 SourceRange Range = ReadSourceRange(F, Record, Idx);
6849 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
6850 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
6851 EllipsisLoc);
6852 Result.setInheritConstructors(inheritConstructors);
6853 return Result;
6854}
6855
6856std::pair<CXXCtorInitializer **, unsigned>
6857ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
6858 unsigned &Idx) {
6859 CXXCtorInitializer **CtorInitializers = 0;
6860 unsigned NumInitializers = Record[Idx++];
6861 if (NumInitializers) {
6862 CtorInitializers
6863 = new (Context) CXXCtorInitializer*[NumInitializers];
6864 for (unsigned i=0; i != NumInitializers; ++i) {
6865 TypeSourceInfo *TInfo = 0;
6866 bool IsBaseVirtual = false;
6867 FieldDecl *Member = 0;
6868 IndirectFieldDecl *IndirectMember = 0;
6869
6870 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
6871 switch (Type) {
6872 case CTOR_INITIALIZER_BASE:
6873 TInfo = GetTypeSourceInfo(F, Record, Idx);
6874 IsBaseVirtual = Record[Idx++];
6875 break;
6876
6877 case CTOR_INITIALIZER_DELEGATING:
6878 TInfo = GetTypeSourceInfo(F, Record, Idx);
6879 break;
6880
6881 case CTOR_INITIALIZER_MEMBER:
6882 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
6883 break;
6884
6885 case CTOR_INITIALIZER_INDIRECT_MEMBER:
6886 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
6887 break;
6888 }
6889
6890 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
6891 Expr *Init = ReadExpr(F);
6892 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
6893 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
6894 bool IsWritten = Record[Idx++];
6895 unsigned SourceOrderOrNumArrayIndices;
6896 SmallVector<VarDecl *, 8> Indices;
6897 if (IsWritten) {
6898 SourceOrderOrNumArrayIndices = Record[Idx++];
6899 } else {
6900 SourceOrderOrNumArrayIndices = Record[Idx++];
6901 Indices.reserve(SourceOrderOrNumArrayIndices);
6902 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
6903 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
6904 }
6905
6906 CXXCtorInitializer *BOMInit;
6907 if (Type == CTOR_INITIALIZER_BASE) {
6908 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
6909 LParenLoc, Init, RParenLoc,
6910 MemberOrEllipsisLoc);
6911 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
6912 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
6913 Init, RParenLoc);
6914 } else if (IsWritten) {
6915 if (Member)
6916 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
6917 LParenLoc, Init, RParenLoc);
6918 else
6919 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
6920 MemberOrEllipsisLoc, LParenLoc,
6921 Init, RParenLoc);
6922 } else {
6923 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
6924 LParenLoc, Init, RParenLoc,
6925 Indices.data(), Indices.size());
6926 }
6927
6928 if (IsWritten)
6929 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
6930 CtorInitializers[i] = BOMInit;
6931 }
6932 }
6933
6934 return std::make_pair(CtorInitializers, NumInitializers);
6935}
6936
6937NestedNameSpecifier *
6938ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
6939 const RecordData &Record, unsigned &Idx) {
6940 unsigned N = Record[Idx++];
6941 NestedNameSpecifier *NNS = 0, *Prev = 0;
6942 for (unsigned I = 0; I != N; ++I) {
6943 NestedNameSpecifier::SpecifierKind Kind
6944 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6945 switch (Kind) {
6946 case NestedNameSpecifier::Identifier: {
6947 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
6948 NNS = NestedNameSpecifier::Create(Context, Prev, II);
6949 break;
6950 }
6951
6952 case NestedNameSpecifier::Namespace: {
6953 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
6954 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
6955 break;
6956 }
6957
6958 case NestedNameSpecifier::NamespaceAlias: {
6959 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
6960 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
6961 break;
6962 }
6963
6964 case NestedNameSpecifier::TypeSpec:
6965 case NestedNameSpecifier::TypeSpecWithTemplate: {
6966 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
6967 if (!T)
6968 return 0;
6969
6970 bool Template = Record[Idx++];
6971 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
6972 break;
6973 }
6974
6975 case NestedNameSpecifier::Global: {
6976 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
6977 // No associated value, and there can't be a prefix.
6978 break;
6979 }
6980 }
6981 Prev = NNS;
6982 }
6983 return NNS;
6984}
6985
6986NestedNameSpecifierLoc
6987ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
6988 unsigned &Idx) {
6989 unsigned N = Record[Idx++];
6990 NestedNameSpecifierLocBuilder Builder;
6991 for (unsigned I = 0; I != N; ++I) {
6992 NestedNameSpecifier::SpecifierKind Kind
6993 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6994 switch (Kind) {
6995 case NestedNameSpecifier::Identifier: {
6996 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
6997 SourceRange Range = ReadSourceRange(F, Record, Idx);
6998 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
6999 break;
7000 }
7001
7002 case NestedNameSpecifier::Namespace: {
7003 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7004 SourceRange Range = ReadSourceRange(F, Record, Idx);
7005 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7006 break;
7007 }
7008
7009 case NestedNameSpecifier::NamespaceAlias: {
7010 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7011 SourceRange Range = ReadSourceRange(F, Record, Idx);
7012 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7013 break;
7014 }
7015
7016 case NestedNameSpecifier::TypeSpec:
7017 case NestedNameSpecifier::TypeSpecWithTemplate: {
7018 bool Template = Record[Idx++];
7019 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7020 if (!T)
7021 return NestedNameSpecifierLoc();
7022 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7023
7024 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7025 Builder.Extend(Context,
7026 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7027 T->getTypeLoc(), ColonColonLoc);
7028 break;
7029 }
7030
7031 case NestedNameSpecifier::Global: {
7032 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7033 Builder.MakeGlobal(Context, ColonColonLoc);
7034 break;
7035 }
7036 }
7037 }
7038
7039 return Builder.getWithLocInContext(Context);
7040}
7041
7042SourceRange
7043ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7044 unsigned &Idx) {
7045 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7046 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7047 return SourceRange(beg, end);
7048}
7049
7050/// \brief Read an integral value
7051llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7052 unsigned BitWidth = Record[Idx++];
7053 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7054 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7055 Idx += NumWords;
7056 return Result;
7057}
7058
7059/// \brief Read a signed integral value
7060llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7061 bool isUnsigned = Record[Idx++];
7062 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7063}
7064
7065/// \brief Read a floating-point value
Tim Northover9ec55f22013-01-22 09:46:51 +00007066llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7067 const llvm::fltSemantics &Sem,
7068 unsigned &Idx) {
7069 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007070}
7071
7072// \brief Read a string
7073std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7074 unsigned Len = Record[Idx++];
7075 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7076 Idx += Len;
7077 return Result;
7078}
7079
7080VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7081 unsigned &Idx) {
7082 unsigned Major = Record[Idx++];
7083 unsigned Minor = Record[Idx++];
7084 unsigned Subminor = Record[Idx++];
7085 if (Minor == 0)
7086 return VersionTuple(Major);
7087 if (Subminor == 0)
7088 return VersionTuple(Major, Minor - 1);
7089 return VersionTuple(Major, Minor - 1, Subminor - 1);
7090}
7091
7092CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7093 const RecordData &Record,
7094 unsigned &Idx) {
7095 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7096 return CXXTemporary::Create(Context, Decl);
7097}
7098
7099DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
7100 return Diag(SourceLocation(), DiagID);
7101}
7102
7103DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7104 return Diags.Report(Loc, DiagID);
7105}
7106
7107/// \brief Retrieve the identifier table associated with the
7108/// preprocessor.
7109IdentifierTable &ASTReader::getIdentifierTable() {
7110 return PP.getIdentifierTable();
7111}
7112
7113/// \brief Record that the given ID maps to the given switch-case
7114/// statement.
7115void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7116 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7117 "Already have a SwitchCase with this ID");
7118 (*CurrSwitchCaseStmts)[ID] = SC;
7119}
7120
7121/// \brief Retrieve the switch-case statement with the given ID.
7122SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7123 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7124 return (*CurrSwitchCaseStmts)[ID];
7125}
7126
7127void ASTReader::ClearSwitchCaseIDs() {
7128 CurrSwitchCaseStmts->clear();
7129}
7130
7131void ASTReader::ReadComments() {
7132 std::vector<RawComment *> Comments;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007133 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007134 serialization::ModuleFile *> >::iterator
7135 I = CommentsCursors.begin(),
7136 E = CommentsCursors.end();
7137 I != E; ++I) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007138 BitstreamCursor &Cursor = I->first;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007139 serialization::ModuleFile &F = *I->second;
7140 SavedStreamPosition SavedPosition(Cursor);
7141
7142 RecordData Record;
7143 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007144 llvm::BitstreamEntry Entry =
7145 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
7146
7147 switch (Entry.Kind) {
7148 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7149 case llvm::BitstreamEntry::Error:
7150 Error("malformed block record in AST file");
7151 return;
7152 case llvm::BitstreamEntry::EndBlock:
7153 goto NextCursor;
7154 case llvm::BitstreamEntry::Record:
7155 // The interesting case.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007156 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007157 }
7158
7159 // Read a record.
7160 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00007161 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007162 case COMMENTS_RAW_COMMENT: {
7163 unsigned Idx = 0;
7164 SourceRange SR = ReadSourceRange(F, Record, Idx);
7165 RawComment::CommentKind Kind =
7166 (RawComment::CommentKind) Record[Idx++];
7167 bool IsTrailingComment = Record[Idx++];
7168 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +00007169 Comments.push_back(new (Context) RawComment(
7170 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7171 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007172 break;
7173 }
7174 }
7175 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007176 NextCursor:;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007177 }
7178 Context.Comments.addCommentsToFront(Comments);
7179}
7180
7181void ASTReader::finishPendingActions() {
7182 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Argyrios Kyrtzidis7640b022013-02-16 00:48:59 +00007183 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007184 // If any identifiers with corresponding top-level declarations have
7185 // been loaded, load those declarations now.
Douglas Gregoraa945902013-02-18 15:53:43 +00007186 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> > TopLevelDecls;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007187 while (!PendingIdentifierInfos.empty()) {
Douglas Gregoraa945902013-02-18 15:53:43 +00007188 // FIXME: std::move
7189 IdentifierInfo *II = PendingIdentifierInfos.back().first;
7190 SmallVector<uint32_t, 4> DeclIDs = PendingIdentifierInfos.back().second;
Douglas Gregorcc9bdcb2013-02-19 18:26:28 +00007191 PendingIdentifierInfos.pop_back();
Douglas Gregoraa945902013-02-18 15:53:43 +00007192
7193 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007194 }
7195
7196 // Load pending declaration chains.
7197 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7198 loadPendingDeclChain(PendingDeclChains[I]);
7199 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
7200 }
7201 PendingDeclChains.clear();
7202
Douglas Gregoraa945902013-02-18 15:53:43 +00007203 // Make the most recent of the top-level declarations visible.
7204 for (llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >::iterator
7205 TLD = TopLevelDecls.begin(), TLDEnd = TopLevelDecls.end();
7206 TLD != TLDEnd; ++TLD) {
7207 IdentifierInfo *II = TLD->first;
7208 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
7209 NamedDecl *ND = cast<NamedDecl>(TLD->second[I]->getMostRecentDecl());
7210 SemaObj->pushExternalDeclIntoScope(ND, II);
7211 }
7212 }
7213
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007214 // Load any pending macro definitions.
7215 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00007216 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
7217 SmallVector<PendingMacroInfo, 2> GlobalIDs;
7218 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
7219 // Initialize the macro history from chained-PCHs ahead of module imports.
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00007220 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7221 ++IDIdx) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00007222 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7223 if (Info.M->Kind != MK_Module)
7224 resolvePendingMacro(II, Info);
7225 }
7226 // Handle module imports.
7227 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7228 ++IDIdx) {
7229 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7230 if (Info.M->Kind == MK_Module)
7231 resolvePendingMacro(II, Info);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007232 }
7233 }
7234 PendingMacroIDs.clear();
Argyrios Kyrtzidis7640b022013-02-16 00:48:59 +00007235
7236 // Wire up the DeclContexts for Decls that we delayed setting until
7237 // recursive loading is completed.
7238 while (!PendingDeclContextInfos.empty()) {
7239 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7240 PendingDeclContextInfos.pop_front();
7241 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7242 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7243 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7244 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007245 }
7246
7247 // If we deserialized any C++ or Objective-C class definitions, any
7248 // Objective-C protocol definitions, or any redeclarable templates, make sure
7249 // that all redeclarations point to the definitions. Note that this can only
7250 // happen now, after the redeclaration chains have been fully wired.
7251 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7252 DEnd = PendingDefinitions.end();
7253 D != DEnd; ++D) {
7254 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7255 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7256 // Make sure that the TagType points at the definition.
7257 const_cast<TagType*>(TagT)->decl = TD;
7258 }
7259
7260 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(*D)) {
7261 for (CXXRecordDecl::redecl_iterator R = RD->redecls_begin(),
7262 REnd = RD->redecls_end();
7263 R != REnd; ++R)
7264 cast<CXXRecordDecl>(*R)->DefinitionData = RD->DefinitionData;
7265
7266 }
7267
7268 continue;
7269 }
7270
7271 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
7272 // Make sure that the ObjCInterfaceType points at the definition.
7273 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7274 ->Decl = ID;
7275
7276 for (ObjCInterfaceDecl::redecl_iterator R = ID->redecls_begin(),
7277 REnd = ID->redecls_end();
7278 R != REnd; ++R)
7279 R->Data = ID->Data;
7280
7281 continue;
7282 }
7283
7284 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7285 for (ObjCProtocolDecl::redecl_iterator R = PD->redecls_begin(),
7286 REnd = PD->redecls_end();
7287 R != REnd; ++R)
7288 R->Data = PD->Data;
7289
7290 continue;
7291 }
7292
7293 RedeclarableTemplateDecl *RTD
7294 = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7295 for (RedeclarableTemplateDecl::redecl_iterator R = RTD->redecls_begin(),
7296 REnd = RTD->redecls_end();
7297 R != REnd; ++R)
7298 R->Common = RTD->Common;
7299 }
7300 PendingDefinitions.clear();
7301
7302 // Load the bodies of any functions or methods we've encountered. We do
7303 // this now (delayed) so that we can be sure that the declaration chains
7304 // have been fully wired up.
7305 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7306 PBEnd = PendingBodies.end();
7307 PB != PBEnd; ++PB) {
7308 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7309 // FIXME: Check for =delete/=default?
7310 // FIXME: Complain about ODR violations here?
7311 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7312 FD->setLazyBody(PB->second);
7313 continue;
7314 }
7315
7316 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7317 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7318 MD->setLazyBody(PB->second);
7319 }
7320 PendingBodies.clear();
7321}
7322
7323void ASTReader::FinishedDeserializing() {
7324 assert(NumCurrentElementsDeserializing &&
7325 "FinishedDeserializing not paired with StartedDeserializing");
7326 if (NumCurrentElementsDeserializing == 1) {
7327 // We decrease NumCurrentElementsDeserializing only after pending actions
7328 // are finished, to avoid recursively re-calling finishPendingActions().
7329 finishPendingActions();
7330 }
7331 --NumCurrentElementsDeserializing;
7332
7333 if (NumCurrentElementsDeserializing == 0 &&
7334 Consumer && !PassingDeclsToConsumer) {
7335 // Guard variable to avoid recursively redoing the process of passing
7336 // decls to consumer.
7337 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7338 true);
7339
7340 while (!InterestingDecls.empty()) {
7341 // We are not in recursive loading, so it's safe to pass the "interesting"
7342 // decls to the consumer.
7343 Decl *D = InterestingDecls.front();
7344 InterestingDecls.pop_front();
7345 PassInterestingDeclToConsumer(D);
7346 }
7347 }
7348}
7349
7350ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7351 StringRef isysroot, bool DisableValidation,
Douglas Gregorf575d6e2013-01-25 00:45:27 +00007352 bool AllowASTWithCompilerErrors, bool UseGlobalIndex)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007353 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7354 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7355 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7356 Consumer(0), ModuleMgr(PP.getFileManager()),
7357 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregore1698072013-01-25 00:38:33 +00007358 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Douglas Gregorf575d6e2013-01-25 00:45:27 +00007359 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007360 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7361 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregore1698072013-01-25 00:38:33 +00007362 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7363 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
7364 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregor95fb36e2013-01-28 17:54:36 +00007365 NumMethodPoolLookups(0), NumMethodPoolHits(0),
7366 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
7367 TotalNumMethodPoolEntries(0),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007368 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
7369 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
7370 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
7371 PassingDeclsToConsumer(false),
7372 NumCXXBaseSpecifiersLoaded(0)
7373{
7374 SourceMgr.setExternalSLocEntrySource(this);
7375}
7376
7377ASTReader::~ASTReader() {
7378 for (DeclContextVisibleUpdatesPending::iterator
7379 I = PendingVisibleUpdates.begin(),
7380 E = PendingVisibleUpdates.end();
7381 I != E; ++I) {
7382 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
7383 F = I->second.end();
7384 J != F; ++J)
7385 delete J->first;
7386 }
7387}